text:
//#include "d3dUtil.h"

namespace Vertex
{

	struct SkyBox
	{
		XMFLOAT3 Pos;
		XMFLOAT2 Tex;
	};

	struct TerrainLOD
	{
		XMFLOAT3 Pos;
		XMFLOAT2 TexTess;
	};

	struct PosNormalTexTan
	{
		XMFLOAT3 Position;
		XMFLOAT3 Tangent;
		XMFLOAT3 Normal;
		XMFLOAT2 TexTess;
	};

	struct Body
	{
		XMFLOAT3 Position;
		XMFLOAT3 PositionS;
		XMFLOAT3 PositionT;
		XMFLOAT3 Tangent;
		XMFLOAT3 TangentS;
		XMFLOAT3 TangentT;
		XMFLOAT3 Normal;
		XMFLOAT3 NormalS;
		XMFLOAT3 NormalT;
		XMFLOAT2 Tex;
	};

	struct Billboard
	{
		XMFLOAT3 Position;
		XMFLOAT3 Direct;
		XMFLOAT2 Size;
	};
}

class InputLayoutDesc
{
public:
	static const D3D11_INPUT_ELEMENT_DESC SkyBox[2];
	static const D3D11_INPUT_ELEMENT_DESC TerrainLOD[2];
	static const D3D11_INPUT_ELEMENT_DESC Atmosphere[2];
	static const D3D11_INPUT_ELEMENT_DESC PosNormalTexTan[4];
	static const D3D11_INPUT_ELEMENT_DESC Body[10];
	static const D3D11_INPUT_ELEMENT_DESC Billboard[3];
};

class InputLayouts
{
public:
	static bool InitAll(DX::DeviceResources *resources);
	static void DestroyAll();

	static ID3D11InputLayout* SkyBox;
	static ID3D11InputLayout* TerrainLOD;
	static ID3D11InputLayout* Atmosphere;
	static ID3D11InputLayout* Clouds;
	static ID3D11InputLayout* WaterLOD;
	static ID3D11InputLayout* PosNormalTexTan;
	static ID3D11InputLayout* Body;
	static ID3D11InputLayout* Billboard;
};


text:
/**
 * Created by LinYong on 2016/3/11.
 */
import Main from '../components/main.jsx';
import {Error, Loading} from '../../UI';
import {useDeps, composeWithTracker, composeAll} from 'mantra-core';

const onPropsChange = (props, onData) => {
  console.log('探测props的改变:', props);
  //onData(new Error());
  const handle = setInterval(() => {
    let xname = props.name + ' ' + new Date();
    onData(null, {name: xname});
  }, 3000);
  const cleanup = () => clearInterval(handle);
  return cleanup;
};

export default composeAll(
  composeWithTracker(onPropsChange, Loading, Error),
  useDeps()
)(Main);

redpajama_set_name: RedPajamaGithub


text:
package com.amazonaws.services.elasticloadbalancingv2.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeTargetHealthRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The Amazon Resource Name (ARN) of the target group.
     *

     */
    private String targetGroupArn;
    /**
     *

     * The targets.
     *

     */
    private java.util.List<TargetDescription> targets;

    /**
     *

     * The Amazon Resource Name (ARN) of the target group.
     *

     *
     * @param targetGroupArn
     *        The Amazon Resource Name (ARN) of the target group.
     */

    public void setTargetGroupArn(String targetGroupArn) {
        this.targetGroupArn = targetGroupArn;
    }

    /**
     *

     * The Amazon Resource Name (ARN) of the target group.
     *

     *
     * @return The Amazon Resource Name (ARN) of the target group.
     */

    public String getTargetGroupArn() {
        return this.targetGroupArn;
    }

    /**
     *

     * The Amazon Resource Name (ARN) of the target group.
     *

     *
     * @param targetGroupArn
     *        The Amazon Resource Name (ARN) of the target group.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DescribeTargetHealthRequest withTargetGroupArn(String targetGroupArn) {
        setTargetGroupArn(targetGroupArn);
        return this;
    }

    /**
     *

     * The targets.
     *

     *
     * @return The targets.
     */

    public java.util.List<TargetDescription> getTargets() {
        return targets;
    }

    /**
     *

     * The targets.
     *

     *
     * @param targets
     *        The targets.
     */

    public void setTargets(java.util.Collection<TargetDescription> targets) {
        if (targets == null) {
            this.targets = null;
            return;
        }

        this.targets = new java.util.ArrayList<TargetDescription>(targets);
    }

    /**
     *

     * The targets.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setTargets(java.util.Collection)} or {@link #withTargets(java.util.Collection)} if you want to override
     * the existing values.
     *

     *
     * @param targets
     *        The targets.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DescribeTargetHealthRequest withTargets(TargetDescription... targets) {
        if (this.targets == null) {
            setTargets(new java.util.ArrayList<TargetDescription>(targets.length));
        }
        for (TargetDescription ele : targets) {
            this.targets.add(ele);
        }
        return this;
    }

    /**
     *

     * The targets.
     *

     *
     * @param targets
     *        The targets.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DescribeTargetHealthRequest withTargets(java.util.Collection<TargetDescription> targets) {
        setTargets(targets);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getTargetGroupArn() != null)
            sb.append("TargetGroupArn: ").append(getTargetGroupArn()).append(",");
        if (getTargets() != null)
            sb.append("Targets: ").append(getTargets());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof DescribeTargetHealthRequest == false)
            return false;
        DescribeTargetHealthRequest other = (DescribeTargetHealthRequest) obj;
        if (other.getTargetGroupArn() == null ^ this.getTargetGroupArn() == null)
            return false;
        if (other.getTargetGroupArn() != null && other.getTargetGroupArn().equals(this.getTargetGroupArn()) == false)
            return false;
        if (other.getTargets() == null ^ this.getTargets() == null)
            return false;
        if (other.getTargets() != null && other.getTargets().equals(this.getTargets()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getTargetGroupArn() == null) ? 0 : getTargetGroupArn().hashCode());
        hashCode = prime * hashCode + ((getTargets() == null) ? 0 : getTargets().hashCode());
        return hashCode;
    }

    @Override
    public DescribeTargetHealthRequest clone() {
        return (DescribeTargetHealthRequest) super.clone();
    }

}


text:
class ActivityPackage < ApplicationRecord
  include PaperTrailed
  delegate :project_id, to: :package
  delegate :program_id, to: :package

  belongs_to :package
  belongs_to :activity
end


text:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';

import { Session } from './session.model';

@Injectable()
export class SessionsService {

    private resourceUrl = '<% if (authenticationType === 'uaa') { %><%= uaaBaseName.toLowerCase() %>/<% } %>api/account/sessions/';
    constructor(private http: Http) { }

    findAll(): Observable<Session[]> {
        return this.http.get(this.resourceUrl).map((res: Response) => res.json());
    }

    delete(series: string): Observable<Response> {
        return this.http.delete(`${this.resourceUrl}${series}`);
    }
}


text:
namespace System.ServiceModel.Transactions
{
    using System.Diagnostics.CodeAnalysis;
    using System.Runtime;
    using System.ServiceModel.Security;
    using System.Transactions;
    using Microsoft.Transactions.Wsat.Messaging;

    class WsatTransactionInfo : TransactionInfo
    {
        WsatProxy wsatProxy;
        CoordinationContext context;
        RequestSecurityTokenResponse issuedToken;

        public WsatTransactionInfo(WsatProxy wsatProxy,
                                   CoordinationContext context,
                                   RequestSecurityTokenResponse issuedToken)
        {
            this.wsatProxy = wsatProxy;
            this.context = context;
            this.issuedToken = issuedToken;
        }

        [SuppressMessage(FxCop.Category.Security, FxCop.Rule.AptcaMethodsShouldOnlyCallAptcaMethods, Justification = "The calls into CoordinationContext are safe.")]
        public override Transaction UnmarshalTransaction()
        {
            Transaction tx;

            if (WsatIncomingTransactionCache.Find(this.context.Identifier, out tx))
                return tx;

            tx = this.wsatProxy.UnmarshalTransaction(this);

            // Cache extended information for subsequent marshal operations
            WsatExtendedInformation info = new WsatExtendedInformation(context.Identifier, context.Expires);
            info.TryCache(tx);

            // Cache the unmarshalled transaction for subsequent unmarshal operations
            WsatIncomingTransactionCache.Cache(this.context.Identifier, tx);

            return tx;
        }

        public CoordinationContext Context
        {
            get { return this.context; }
        }

        public RequestSecurityTokenResponse IssuedToken
        {
            get { return this.issuedToken; }
        }
    }
}


text:
// ** I18N

// Calendar pt_BR language
// Author: Adalberto Machado, <betosm@terra.com.br>
// Encoding: any
// Distributed under the same terms as the calendar itself.

// For translators: please use UTF-8 if possible.  We strongly believe that
// Unicode is the answer to a real internationalized world.  Also please
// include your contact information in the header, as can be seen above.

// full day names
Calendar._DN = new Array
("Domingo",
 "Segunda",
 "Terca",
 "Quarta",
 "Quinta",
 "Sexta",
 "Sabado",
 "Domingo");

// Please note that the following array of short day names (and the same goes
// for short month names, _SMN) isn't absolutely necessary.  We give it here
// for exemplification on how one can customize the short day names, but if
// they are simply the first N letters of the full name you can simply say:
//
//   Calendar._SDN_len = N; // short day name length
//   Calendar._SMN_len = N; // short month name length
//
// If N = 3 then this is not needed either since we assume a value of 3 if not
// present, to be compatible with translation files that were written before
// this feature.

// short day names
Calendar._SDN = new Array
("Dom",
 "Seg",
 "Ter",
 "Qua",
 "Qui",
 "Sex",
 "Sab",
 "Dom");

// full month names
Calendar._MN = new Array
("Janeiro",
 "Fevereiro",
 "Marco",
 "Abril",
 "Maio",
 "Junho",
 "Julho",
 "Agosto",
 "Setembro",
 "Outubro",
 "Novembro",
 "Dezembro");

// short month names
Calendar._SMN = new Array
("Jan",
 "Fev",
 "Mar",
 "Abr",
 "Mai",
 "Jun",
 "Jul",
 "Ago",
 "Set",
 "Out",
 "Nov",
 "Dez");

// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "Sobre o calendario";

Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this this ;-)
"Ultima versao visite: http://www.dynarch.com/projects/calendar/\n" +
"Distribuido sobre GNU LGPL.  Veja http://gnu.org/licenses/lgpl.html para detalhes." +
"\n\n" +
"Selecao de data:\n" +
"- Use os botoes \xab, \xbb para selecionar o ano\n" +
"- Use os botoes " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " para selecionar o mes\n" +
"- Segure o botao do mouse em qualquer um desses botoes para selecao rapida.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Selecao de hora:\n" +
"- Clique em qualquer parte da hora para incrementar\n" +
"- ou Shift-click para decrementar\n" +
"- ou clique e segure para selecao rapida.";

Calendar._TT["PREV_YEAR"] = "Ant. ano (segure para menu)";
Calendar._TT["PREV_MONTH"] = "Ant. mes (segure para menu)";
Calendar._TT["GO_TODAY"] = "Hoje";
Calendar._TT["NEXT_MONTH"] = "Prox. mes (segure para menu)";
Calendar._TT["NEXT_YEAR"] = "Prox. ano (segure para menu)";
Calendar._TT["SEL_DATE"] = "Selecione a data";
Calendar._TT["DRAG_TO_MOVE"] = "Arraste para mover";
Calendar._TT["PART_TODAY"] = " (hoje)";

// the following is to inform that "%s" is to be the first day of week
// %s will be replaced with the day name.
Calendar._TT["DAY_FIRST"] = "Mostre %s primeiro";

// This may be locale-dependent.  It specifies the week-end days, as an array
// of comma-separated numbers.  The numbers are from 0 to 6: 0 means Sunday, 1
// means Monday, etc.
Calendar._TT["WEEKEND"] = "0,6";

Calendar._TT["CLOSE"] = "Fechar";
Calendar._TT["TODAY"] = "Hoje";
Calendar._TT["TIME_PART"] = "(Shift-)Click ou arraste para mudar valor";

// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%d/%m/%Y";
Calendar._TT["TT_DATE_FORMAT"] = "%a, %e %b";

Calendar._TT["WK"] = "sm";
Calendar._TT["TIME"] = "Hora:";


text:
#include <iostream>
#include <stack>
#include <string>
using namespace std;

/*

	Solution: as we iterate through the input string, if we see a '(' character, we push its numeric index onto our stack.
	If we see a ')' character, we check if the stack is empty. If it is not, then we know we have a valid pair of parentheses
	and we can remove the index of the corresponding '(' from the stack. If the stack is empty, then we have a mismatched ')'
	character and we mark it with the $ character. After iterating through the string, if the stack is not empty, then we have
	mismatched '(' characters as well. As we pop from the stack, we mark the mismatched '(' character with a $ using its index.
	Finally, we iterate over the original string and append all characters that are not $ to our result string, and return
	the resulting string.

	Time complexity: O(n) [where n is the length of the input string]
	Space conmplexity: O(n)

*/

class Solution
{
	public:
		string minRemoveToMakeValid(string s)
		{
			if(s.empty())
			{
				return s;
			}

			if(s.find('(')==std::string::npos && s.find(')')==std::string::npos)
			{
				return s;
			}

			stack<int> stk;

			int n=s.size();

			for(int index=0;index<n;index++)
			{
				char letter=s[index];

				if(letter=='(')
				{
					stk.push(index);
				}
				else if(letter==')')
				{
					if(!stk.empty())
					{
						stk.pop();
					}
					else
					{
						s[index]='$';
					}
				}
			}

			while(!stk.empty())
			{
				int index=stk.top();

				s[index]='$';

				stk.pop();
			}

			string result="";

			for(char & letter : s)
			{
				if(letter!='$')
				{
					result+=letter;
				}
			}

			return result;
		}
};


text:
'use strict';
var boundaries = {"districts" : {}, "pre_districts": {},
                  "blocks" : {}, "projects": {},
                  "clusters": {}, "circles": {} };
(function() {

    klp.init = function() {
        klp.router = new KLPRouter();
        klp.router.init();
        klp.router.start();
        initEduSearch("preschool");
        var dataURL = "schools/list/?meetingreport=yes;"//&per_page=20";
        loadData(dataURL);
    }

    $(document).on('click',".next",function () {
        var url = $(this).data('id');
        var rest_url = url.split('api/v1/')[1];
        console.log(rest_url);
        loadData(rest_url);
    });

    $(document).on('click',".prev",function () {
        var url = $(this).data('id');
        var rest_url = url.split('api/v1/')[1];
        console.log(rest_url);
        loadData(rest_url);
    });

    function loadData(dataURL) {
        var params = {};
        var $dataXHR = klp.api.do(dataURL, params);
        $dataXHR.done(function(data) {
            var $countXHR = klp.api.do("schools/meeting-reports/", params);
            $countXHR.done(function(mr) {
                data['report_count'] = mr.count;
                 renderSummary(data);
            });

        });
    }

    function transformData(schools) {
        var schoolMap = {};
        for (var i in schools) {
            var school = schools[i]
            schoolMap[school.id.toString()] = {
                "pdfs":{},
                "name": school.name,
                "id": school.id, //data.name,
                "admin3": school.admin3,
                "admin2": school.admin2,
                "admin1": school.admin1,
                "school_type" : school.type.name
            };
            for (var each in school.meeting_reports) {
                var report = school.meeting_reports[each];
                schoolMap[school.id.toString()]["pdfs"][report.pdf] = {
                    "path":report.pdf,
                    "lang":report.language,
                    "is_archived": (report.generated_at == null)? true : false,
                    "year": (report.generated_at != null)? moment(report.generated_at, "YYYY-MM-DD").format("YYYY") : null,
                    "month": (report.generated_at != null)? moment(report.generated_at, "YYYY-MM-DD").format("MMMM") : null
                };
            }
        }
        console.log(schoolMap);
        return schoolMap;
    }

    function renderSummary(data) {
        var transformed = transformData(data['features'])
        //console.log(transformed);
        var tplButtons = swig.compile($('#tpl-buttons').html());
        var buttonHTML =  tplButtons({'next':data.next,'previous': data.previous });
        $('#buttons').html(buttonHTML)
        var tplCountSummary = swig.compile($('#tpl-countSummary').html());
        var countHTML =  tplCountSummary({'school_count':data.count,'report_count':data.report_count});
        $('#count_summary').html(countHTML)
        var tplResponseTable = swig.compile($('#tpl-responseTable').html());
        var tableHTML = tplResponseTable({'data':transformed});
        $('#response_summary').html(tableHTML);
    }

    function makeLookupArrays(){
        var districtXHR = klp.api.do('boundary/admin1s?meetingreport=yes&per_page=0',{});
        districtXHR.done(function (data) {
            for(var i in data["features"]) {
                var boundary = data["features"][i];
                if (boundary.school_type == "preschool")
                    boundaries ["pre_districts"][boundary.id.toString()] = boundary;
                else
                    boundaries ["districts"][boundary.id.toString()] = boundary;
            }
            var blockXHR = klp.api.do('boundary/admin2s?meetingreport=yes&per_page=0',{});
            blockXHR.done(function (data) {
                for(var i in data["features"]) {
                    var boundary = data["features"][i];
                    if (boundary.school_type == "preschool")
                        boundaries ["projects"][boundary.id.toString()] = boundary;
                    else
                        boundaries ["blocks"][boundary.id.toString()] = boundary;
                }
                var clusterXHR = klp.api.do('boundary/admin3s?meetingreport=yes&per_page=0',{});
                clusterXHR.done(function (data) {
                    for(var i in data["features"]) {
                        var boundary = data["features"][i];
                        if (boundary.school_type == "preschool")
                            boundaries ["circles"][boundary.id.toString()] = boundary;
                        else
                            boundaries ["clusters"][boundary.id.toString()] = boundary;
                    }
                });
            });
        });
        //console.log(boundaries);

    }

    function format(item) {
        if (item.properties != undefined)
            return _.str.titleize(item.properties.name);
        else
            return _.str.titleize(item.name);
    }

    function populateSelect(container,data) {
        // data.forEach(function(d) {
        //     if(d.properties !=undefined)
        //         d.id = d.properties.id;
        // });
        container.select2({
            sortResults: function(results) {
                return _.sortBy(results, function(result) {
                    return result.name;
                });
            },
            data: {
                results: data,
                text: function(item) {
                    return item.name;
                }
            },
            formatSelection: format,
            formatResult: format,
        });
    }

    function getSubset(type,parent) {
        var subset = {}
        for(var i in boundaries[type]) {
            if(boundaries[type][i].parent.id == parent) {
                subset[boundaries[type][i].id] = boundaries[type][i]
            }
        }
        return subset;
    }

    function initEduSearch(school_type) {
        makeLookupArrays();
        console.log(boundaries);
        var $select_type = $("#select-type");
        var $select_district = $("#select-district");
        var $select_block = $("#select-block");
        var $select_cluster = $("#select-cluster");
        $select_type.select2("val","");
        $select_district.select2("val","");
        $select_block.select2("val","");
        $select_cluster.select2("val","");

        populateSelect($select_type, {
            "primaryschool":{"id":1,"name":"Primary School"},
            "preschool":{"id":2,"name":"Preschool"},
        })

        $select_type.on("change", function(selected) {
            var selection ="districts"
            if(selected.val == 2) {
                selection = "pre_districts"
            }
            populateSelect($select_district, boundaries[selection]);
        });

        $select_district.on("change", function(selected) {
            populateSelect($select_block, getSubset(selected.added.school_type=="preschool"?"projects":"blocks",selected.val));
            var dataURL = "schools/list/?admin1=" + selected.val + "&meetingreport=yes&per_page=20";
            loadData(dataURL);
        });

        $select_block.on("change", function(selected) {
            populateSelect($select_cluster, getSubset(selected.added.school_type=="preschool"?"circles":"clusters",selected.val));
            var dataURL = "schools/list/?admin2=" + selected.val + "&meetingreport=yes&per_page=20";
            loadData(dataURL);
        });

        $select_cluster.on("change", function(selected) {
            var dataURL = "schools/list/?admin3=" + selected.val + "&meetingreport=yes&per_page=20";
            loadData(dataURL);
        });
    }

})();

// function transformData(meetingreports) {
//     var schoolMap = {};
//     for (var i in meetingreports) {
//         var report = meetingreports[i]
//         if (_.keys(schoolMap).indexOf(report.school.id.toString())==-1) {
//             schoolMap[report.school.id.toString()] = {
//                             "pdfs":{},
//                             "name": report.school.name,
//                             "id": report.school.id //data.name,
//                             // "admin3": data.admin3.name,
//                             // "admin2": data.admin2.name,
//                             // "admin1": data.admin1.name
//                         };
//         }
//         schoolMap[report.school.id.toString()]["pdfs"][report.id.toString()] = {
//             "path":report.pdf,
//             "lang":report.language,
//             "is_archived": (report.generated_at == null)? true : false,
//             "year": (report.generated_at != null)? moment(report.generated_at, "YYYY-MM-DD").format("YYYY") : null,
//             "month": (report.generated_at != null)? moment(report.generated_at, "YYYY-MM-DD").format("MMMM") : null
//         };
//     }
//     return schoolMap;
// }

// function searchTable() {
//     // Declare variables
//     var id, name, year, id_filter, name_filter, yr_filter;
//     // id = document.getElementById("search-id");
//     // if(id.value != null) {
//     //     id_filter = id.value.toUpperCase();
//     //     searchLoop(0,id_filter);
//     // }
//     name = document.getElementById("search-name");
//     if(name.value != null && name.value != "") {
//         name_filter = name.value.toUpperCase();
//         searchLoop(1,name_filter);
//     }

//     // year = document.getElementById("search-year");
//     // if(year.value != null) {
//     //    yr_filter = year.value.toUpperCase();
//     //     searchLoop(2,yr_filter);
//     // }
// }

//  // Loop through all table rows, and hide those who don't match the search query

// function searchLoop(col_num, filter) {
//     var table, tr, td, i;
//     table = document.getElementById("sdmc-table");
//     tr = table.getElementsByTagName("tr");
//     for (i = 0; i < tr.length; i++) {
//         td = tr[i].getElementsByTagName("td")[col_num];
//         if (td) {
//             if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
//                 tr[i].style.display = "";
//                 // console.log("display");
//             } else {
//                 tr[i].style.display = "none";
//                 // console.log("don't display");
//             }
//         }
//     }
// }


text:
/**
 *
 */
package com.baosight.iplat4j.ee.dm.service;

import com.baosight.iplat4j.common.constant.EPResource;
import com.baosight.iplat4j.common.ee.domain.TEEDM01;
import com.baosight.iplat4j.common.ee.domain.TEEDM03;
import com.baosight.iplat4j.core.ei.EiBlockMeta;
import com.baosight.iplat4j.core.ei.EiConstant;
import com.baosight.iplat4j.core.ei.EiInfo;
import com.baosight.iplat4j.ee.dm.utils.EEDMUtils;
import com.baosight.iplat4j.el.PlatMessageLogger;
import com.baosight.iplat4j.ep.ServiceEPBase;
import com.baosight.iplat4j.ep.util.MethodParamConstants;

/**
 * 复杂主从表、明细表
 * @author wangyuqiu
 *
 */
public class ServiceEEDM14 extends ServiceEPBase {

	private static String INQU_COUNTRY_CODE = "inqu_status-0-countryCode";
	private static String COUNTRY_CODE = "countryCode";

	/**
	 * Service 初始化函数
	 */
	public EiInfo initLoad(EiInfo inInfo) {

		TEEDM01 teedm01 = new TEEDM01();
		EiInfo outInfo = super.initLoad(inInfo, teedm01);
		//outInfo.getBlock(EiConstant.resultBlock).setRows(new ArrayList());
		outInfo.addBlock(EEDMUtils.generateBlock("country",new TEEDM03(),"teedm03.query"));
	//	outInfo.addBlock(EEDMUtils.generateBlock("company",new TEEDM01(),"teedm01.query"));
		return outInfo;
	}
	/**
	 * 查询方法函数
	 * 返回公司查询信息的eiinfo
	 */
	public EiInfo query(EiInfo inInfo){
		inInfo.setMethodParam(MethodParamConstants.sqlName, "EEDM01.query");
		inInfo.setMethodParam(MethodParamConstants.daoEPBaseBean, new TEEDM01());
		EiInfo outInfo = super.query(inInfo,true);
		outInfo.addBlock(EEDMUtils.generateBlock("country",new TEEDM03(),"teedm03.query"));
	//	outInfo.addBlock(EEDMUtils.generateBlock("company",new TEEDM01(),"teedm01.query"));
		return outInfo;
	}

	/**
	 * 删除公司信息
	 * 返回删除后的公司查询信息的eiinfo
	 */
	public EiInfo delete(EiInfo inInfo) {
		TEEDM01 teedm01 = new TEEDM01();
		inInfo.getBlock(EiConstant.resultBlock).setBlockMeta(teedm01.eiMetadata);
		inInfo.set(EiConstant.sqlName, "teedm01.delete");
		super.delete(inInfo);
		return query(inInfo);
	}

	/**
	 * 插入公司信息
	 */
	public EiInfo insert(EiInfo inInfo) {
		TEEDM01 teedm01 = new TEEDM01();
		inInfo.getBlock(EiConstant.resultBlock).setBlockMeta(teedm01.eiMetadata);
		PlatMessageLogger.logMessage(EPResource.EP_1000, new String[] {
				"dd", "新增" });
		int i = 0;
		for (i = 0; i < inInfo.getBlock(EiConstant.resultBlock).getRowCount(); i++) {
			teedm01.fromMap(inInfo.getBlock(EiConstant.resultBlock).getRow(i));
			dao.update("teedm01.insert", teedm01);
		}
		inInfo.setMsgByKey(EPResource.EP_1000, new String[] {
				String.valueOf(i), "新增" });
		return query(inInfo);
	}

	/**
	 * 更新公司信息
	 */
	public EiInfo update(EiInfo inInfo) {
		TEEDM01 teedm01 = new TEEDM01();
		inInfo.getBlock(EiConstant.resultBlock).setBlockMeta(teedm01.eiMetadata);
		int i = 0;
		for (i = 0; i < inInfo.getBlock(EiConstant.resultBlock).getRowCount(); i++) {
			teedm01.fromMap(inInfo.getBlock(EiConstant.resultBlock).getRow(i));
			dao.update("teedm01.update", teedm01);
		}
		inInfo.setMsgByKey(EPResource.EP_1000, new String[] {
				String.valueOf(i), "更新" });
		return query(inInfo);
	}

	/**
	 * 查询国家信息
	 * @param inInfo
	 * @return outInfo 返回国家查询信息的eiinfo
	 */
	public EiInfo queryCountry(EiInfo inInfo){
		TEEDM03 teedm03 = new TEEDM03();
		inInfo.set(INQU_COUNTRY_CODE, inInfo.get(COUNTRY_CODE));
		inInfo.setMethodParam(MethodParamConstants.sqlName, "EEDM03.query");
		inInfo.setMethodParam(MethodParamConstants.daoEPBaseBean, teedm03);
		EiInfo outInfo = super.query(inInfo,true);
		EiBlockMeta meta = teedm03.eiMetadata;
		meta.getMeta(COUNTRY_CODE).setPrimaryKey(false);
		outInfo.getBlock(EiConstant.resultBlock).setBlockMeta(meta);
		return outInfo;
	}
}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.createReducer = exports.createPageMiddleware = exports.pageConst = exports.createPageAction = exports.connectPage = exports.config = undefined;

var _config = require('./config');

var _config2 = _interopRequireDefault(_config);

var _connectPage = require('./connectPage');

var _connectPage2 = _interopRequireDefault(_connectPage);

var _createPageAction = require('./createPageAction');

var _createPageAction2 = _interopRequireDefault(_createPageAction);

var _const = require('./const');

var _const2 = _interopRequireDefault(_const);

var _createPageMiddleware = require('./createPageMiddleware');

var _createPageMiddleware2 = _interopRequireDefault(_createPageMiddleware);

var _createReducer = require('./createReducer');

var _createReducer2 = _interopRequireDefault(_createReducer);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.config = _config2.default;
exports.connectPage = _connectPage2.default;
exports.createPageAction = _createPageAction2.default;
exports.pageConst = _const2.default;
exports.createPageMiddleware = _createPageMiddleware2.default;
exports.createReducer = _createReducer2.default;


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
  <!-- FIXME is there a way to avoid using the condensed titles here, perhaps by stacking the items? -->
    <item android:id="@+id/add_mi" android:title="Add" android:visible="true" android:enabled="true" android:titleCondensed="+"/>
    <item android:id="@+id/remove_all_checked_mi" android:enabled="true" android:titleCondensed="X" android:title="Remove Checked" android:visible="true"/>
</menu>


text:
@implementation DateObject

-(void)dealloc{

}

+(id)initWithYMDString:(NSString*)ymdStr{
    return [self initWithYMDHMSString:[NSString stringWithFormat:@"%@ %02d:%02d:%02d",ymdStr, 0,0,0]];
}

+(id)initWithYMDHMSString:(NSString*)ymdhmsStr{
    DateObject* date = [[DateObject alloc] init];

    ymdhmsStr = [ymdhmsStr stringByReplacingOccurrencesOfString:@"-" withString:@""];
    ymdhmsStr = [ymdhmsStr stringByReplacingOccurrencesOfString:@"." withString:@""];
    ymdhmsStr = [ymdhmsStr stringByReplacingOccurrencesOfString:@"_" withString:@""];
    ymdhmsStr = [ymdhmsStr stringByReplacingOccurrencesOfString:@":" withString:@""];
    ymdhmsStr = [ymdhmsStr stringByReplacingOccurrencesOfString:@" " withString:@""];

    date.Year = [[ymdhmsStr substringToIndex:4] integerValue];
    date.Month = [[[ymdhmsStr substringFromIndex:4] substringToIndex:2] integerValue];
    date.Day = [[[ymdhmsStr substringFromIndex:6] substringToIndex:2] integerValue];

    date.Hour = [[[ymdhmsStr substringFromIndex:8] substringToIndex:2] integerValue];
    date.Minute = [[[ymdhmsStr substringFromIndex:10] substringToIndex:2] integerValue];
    date.Second = [[[ymdhmsStr substringFromIndex:12] substringToIndex:2] integerValue];

    if (ymdhmsStr.length > 14) {
        NSString* mili = [ymdhmsStr substringFromIndex:14];
        if(mili.length > 3) mili = [mili substringToIndex:4];
        date.MiliSecond = [mili integerValue];
    }

    return date;
}

+(id)initWithYear: (NSInteger) year month: (NSInteger) month day:(NSInteger) day{
    return [self initWithYMDString:[NSString stringWithFormat:@"%d-%02d-%02d", (int)year, (int)month, (int)day]];
}

+(id)initWithYear: (NSInteger) year month: (NSInteger) month day:(NSInteger) day hour:(NSInteger) hour minute:(NSInteger) minute second:(NSInteger) second
{
    return [self initWithYMDHMSString:[NSString stringWithFormat:@"%d-%02d-%02d %02d:%02d:%02d", (int)year, (int)month, (int)day, (int)hour, (int)minute, (int)second]];
}

+(id)initWithYear: (NSInteger) year month: (NSInteger) month day:(NSInteger) day hour:(NSInteger) hour minute:(NSInteger) minute second:(NSInteger) second milisecond:(NSInteger)milisecond
{
    return [self initWithYMDHMSString:[NSString stringWithFormat:@"%d-%02d-%02d %02d:%02d:%02d.%d", (int)year, (int)month, (int)day, (int)hour, (int)minute, (int)second, (int)milisecond]];
}

+(DateObject*)initWithNSDate:(NSDate*) date
{

    NSDateComponents *components;

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000 // iOS 8.0 and later supported
    components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSCalendarUnitNanosecond fromDate:date];
#else
    components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit } fromDate:date];
#endif

    return [self initWithYear:components.year
                        month:components.month
                          day:components.day
                         hour:components.hour
                       minute:components.minute
                       second:components.second
                   milisecond:components.nanosecond];
}

+(DateObject*)initToday
{
    return [self initWithNSDate:[NSDate date]];
}

//============================================================================================================

-(NSString*)toHMSTimeString{
    return [self toHMSTimeStringWithFormat:@"%02d:%02d:%02d"];
}

-(NSString*)toHMSTimeStringWithFormat:(NSString*) format{
    return [NSString stringWithFormat:format, _Hour, _Minute, _Second];
}

-(NSString*)toHMTimeString{
    return [self toHMTimeStringWithFormat:@"%02d:%02d"];
}

-(NSString*)toHMTimeStringWithFormat:(NSString*) format{
    return [NSString stringWithFormat:format, _Hour, _Minute];
}

-(NSString*)toDMYString{
    return [self toDMYStringWithFormat:@"%02d/%02d/%02d"];
}

-(NSString*)toDMYStringWithFormat:(NSString*) format{
    return [NSString stringWithFormat:format, _Day, _Month, _Year];
}

-(NSString*)toYMDString{
    return [self toYMDStringWithFormat:@"%d-%02d-%02d"];
}

-(NSString*)toYMDStringWithFormat:(NSString*) format{
    return [NSString stringWithFormat:format, _Year, _Month, _Day];
}

-(NSString*)toYMDHMSLogFormatString{
    return [self toYMDHMSStringWithFormat:@"%d-%02d-%02d %02d:%02d:%02d"];
}

-(NSString*)toYMDHMSFileFormatString{
    return [self toYMDHMSStringWithFormat:@"%d%02d%02d_%02d%02d%02d"];
}

-(NSString*)toYMDHMSStringWithFormat:(NSString*) format{
    return [NSString stringWithFormat:format, _Year, _Month, _Day, _Hour, _Minute, _Second];
}

-(NSString*)toDMonYString{
    return [NSString stringWithFormat:@"%02ld %@ %ld", (long)_Day, [self getMonthName:YES], (long)_Year];
}

-(NSString*)toTimeAgoString
{
    return [[self toNSDate] formattedAsTimeAgo];
}

-(BOOL)equalDate:(DateObject*)date{
    return [[self toYMDString] isEqualToString:[date toYMDString]];
}

-(BOOL)equalExactDate:(DateObject*)date{
    return [[self toYMDHMSLogFormatString] isEqualToString:[date toYMDHMSLogFormatString]];
}

-(NSDate*)toNSDate
{
    NSDateComponents * date = [[NSDateComponents alloc] init] ;
    date.timeZone = [NSTimeZone defaultTimeZone];

    [date setDay:[self Day]];
    [date setMonth:[self Month]];
    [date setYear:[self Year]];
    [date setHour:[self Hour]];
    [date setMinute:[self Minute]];
    [date setSecond:[self Second]];
    [date setNanosecond:[self MiliSecond]];

    NSCalendar *gregorian = [self getCalendar];

    NSDate *today = [gregorian dateFromComponents:date];

    return today;
}

-(NSDate*)toNSDateUTC
{
    return [[self addTimeWithYear:0 month:0 day:0 hour:0 minute:0 second:[[NSTimeZone localTimeZone] secondsFromGMT]] toNSDate];
}

-(DateObject*)addTimeWithYear: (NSInteger) year month: (NSInteger) month day:(NSInteger) day hour:(NSInteger) hour minute:(NSInteger) minute second:(NSInteger) second
{
    // set up date components
    NSDateComponents *date = [[NSDateComponents alloc] init];
    [date setDay:day];
    [date setMonth:month];
    [date setYear:year];
    [date setHour:hour];
    [date setMinute:minute];
    [date setSecond:second];

    // create a calendar
    NSCalendar *gregorian = [self getCalendar];

    NSDate *result = [gregorian dateByAddingComponents:date toDate:[self toNSDate] options:0];

    return [DateObject initWithNSDate:result];
}

-(DateObject*)addTimeWithYear: (NSInteger) year month: (NSInteger) month day:(NSInteger) day
{
    return [self addTimeWithYear:year month:month day:day hour:0 minute:0 second:0];
}

-(NSCalendar*) getCalendar
{
    NSCalendar *gregorian;
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000 // iOS 8.0 and later supported
    gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSCalendarIdentifierGregorian];
#else
    gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
#endif
    return gregorian;
}

-(int)getWeekday
{
    NSCalendar *gregorian = [self getCalendar];

    NSDateComponents *weekdayComponents;
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000 // iOS 8.0 and later supported
    weekdayComponents = [gregorian components:(NSCalendarUnitDay | NSCalendarUnitWeekday) fromDate:[self toNSDate]];
#else
    weekdayComponents = [gregorian components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:[self toNSDate]];
#endif

    int weekday = (int)[weekdayComponents weekday];

    return weekday;
}

-(NSString*)getWeekdayName{
    NSArray* daynames = @[ @"Sunday", @"Monday", @"Tuesday", @"Wednesday", @"Thursday", @"Friday", @"Saturday"];
    return daynames[ [self getWeekday] - 1 ];
}

-(NSString*)getMonthName:(BOOL) isInShortName{
    NSArray* months = @[@"January", @"Febuary", @"March", @"April", @"May", @"June", @"July", @"August", @"September", @"October", @"November", @"December"];
    return isInShortName? [months[_Month-1] substringToIndex:3] : months[_Month-1];
}

-(double)getYMDInterval{
    NSString* str = [NSString stringWithFormat:@"%ld",(long)_Year];
    str = [str stringByAppendingFormat: @"%02ld" ,(long)_Month];
    str = [str stringByAppendingFormat: @"%02ld" ,(long)_Day];
    str = [str stringByAppendingFormat: @"%02ld" ,(long)_Hour];
    str = [str stringByAppendingFormat: @"%02ld" ,(long)_Minute];
    str = [str stringByAppendingFormat: @"%02ld" ,(long)_Second];

    return [str doubleValue];
}

#pragma mark - LUNAR FUNCTION==========================================================

-(DateObject*)toLunarDateWithTimeZone: (double) timeZone{

    double k = 0, dayNumber = 0, monthStart = 0, a11 = 0, b11 = 0, lunarDay = 0, lunarMonth = 0, lunarYear = 0, lunarLeap = 0, leapMonthDiff = 0, diff = 0;

    dayNumber = [self jdFromDate:_Day mm:_Month yy:_Year];

    k = floor((dayNumber - 2415021.076998695) / 29.530588853);
    monthStart = [self getNewMoonDay:(k+1) timeZone: timeZone];

    if (monthStart > dayNumber) {
        monthStart = [self getNewMoonDay:k timeZone: timeZone];
    }

    a11 = [self getLunarMonth11:_Year timeZone:timeZone];
    b11 = a11;

    if (a11 >= monthStart) {
        lunarYear = _Year;
        a11 = [self getLunarMonth11:(_Year-1) timeZone:timeZone];
    } else {
        lunarYear = _Year+1;
        b11 = [self getLunarMonth11:(_Year+1) timeZone:timeZone];
    }

    lunarDay = dayNumber-monthStart+1;
    diff = floor((monthStart - a11)/29);
    lunarLeap = 0;
    lunarMonth = diff+11;

    if (b11 - a11 > 365) {
        leapMonthDiff = [self getLeapMonthOffset:a11 timeZone:timeZone];
        if (diff >= leapMonthDiff) {
            lunarMonth = diff + 10;
            if (diff == leapMonthDiff) {
                lunarLeap = 1;
            }
        }
    }
    if (lunarMonth > 12) {
        lunarMonth = lunarMonth - 12;
    }
    if (lunarMonth >= 11 && diff < 4) {
        lunarYear -= 1;
    }

    return [DateObject initWithYear:lunarYear month:lunarMonth day:lunarDay];
}

-(DateObject*)toSolarDateWithLunarLeap:(double)lunarLeap timeZone:(double) timeZone
{
    double k, a11, b11, off, leapOff, leapMonth, monthStart;
    if (_Month < 11) {

        a11 = [self getLunarMonth11:_Year-1 timeZone:timeZone];
        b11 = [self getLunarMonth11:_Year timeZone: timeZone];
    } else {
        a11 = [self getLunarMonth11:_Year timeZone: timeZone];
        b11 = [self getLunarMonth11:_Year+1 timeZone: timeZone];
    }

    off = _Month - 11;

    if (off < 0) {
        off += 12;
    }
    if (b11 - a11 > 365) {
        leapOff = [self getLeapMonthOffset:a11 timeZone: timeZone];
        leapMonth = leapOff - 2;
        if (leapMonth < 0) {
            leapMonth += 12;
        }
        if (lunarLeap != 0 && _Month != leapMonth) {
            return nil;
        } else if (lunarLeap != 0 || off >= leapOff)
        {
            off += 1;
        }
    }
    k = floor(0.5 + (a11 - 2415021.076998695) / 29.530588853);
    monthStart = [self getNewMoonDay:k+off timeZone:timeZone];
    return [self jdToDate:monthStart+_Day-1];
}

-(DateObject*)jdToDate: (double) jd
{
    double a, b, c, d, e, m, day, month, year;
    if (jd > 2299160) { // After 5/10/1582, Gregorian calendar
        a = jd + 32044;
        b = floor((4*a+3)/146097);
        c = a - floor((b*146097)/4);
    } else {
        b = 0;
        c = jd + 32082;
    }

    d = floor((4*c+3)/1461);
    e = c - floor((1461*d)/4);
    m = floor((5*e+2)/153);
    day = e - floor((153*m+2)/5) + 1;
    month = m + 3 - 12*floor(m/10);
    year = b*100 + d - 4800 + floor(m/10);

    return [DateObject initWithYear:year month:month day:day];
}

-(double)jdFromDate: (double) dd mm:(double) mm yy:(double) yy
{
    double a = 0, y = 0, m = 0, jd = 0;
    a = floor((14 - mm) / 12);

    y = yy+4800-a;
    m = mm+12*a-3;
    jd = dd + floor((153*m+2)/5) + 365*y + floor(y/4) - floor(y/100) + floor(y/400) - 32045;
    if (jd < 2299161) {
        jd = dd + floor((153*m+2)/5) + 365*y + floor(y/4) - 32083;
    }
    return jd;
}

-(double)getNewMoonDay:(double)k timeZone:(double)timeZone
{

    double T, T2, T3, dr, Jd1, M, Mpr, F, C1, deltat, JdNew;
    T = k/1236.85; // Time in Julian centuries from 1900 January 0.5
    T2 = T * T;
    T3 = T2 * T;
    dr = M_PI /180;
    Jd1 = 2415020.75933 + 29.53058868*k + 0.0001178*T2 - 0.000000155*T3;
    Jd1 = Jd1 + 0.00033*sin((166.56 + 132.87*T - 0.009173*T2)*dr); // Mean new moon
    M = 359.2242 + 29.10535608*k - 0.0000333*T2 - 0.00000347*T3; // Sun's mean anomaly
    Mpr = 306.0253 + 385.81691806*k + 0.0107306*T2 + 0.00001236*T3; // Moon's mean anomaly
    F = 21.2964 + 390.67050646*k - 0.0016528*T2 - 0.00000239*T3; // Moon's argument of latitude
    C1=(0.1734 - 0.000393*T)*sin(M*dr) + 0.0021*sin(2*dr*M);
    C1 = C1 - 0.4068*sin(Mpr*dr) + 0.0161*sin(dr*2*Mpr);
    C1 = C1 - 0.0004*sin(dr*3*Mpr);
    C1 = C1 + 0.0104*sin(dr*2*F) - 0.0051*sin(dr*(M+Mpr));
    C1 = C1 - 0.0074*sin(dr*(M-Mpr)) + 0.0004*sin(dr*(2*F+M));
    C1 = C1 - 0.0004*sin(dr*(2*F-M)) - 0.0006*sin(dr*(2*F+Mpr));
    C1 = C1 + 0.0010*sin(dr*(2*F-Mpr)) + 0.0005*sin(dr*(2*Mpr+M));

    if (T < -11) {
        deltat= 0.001 + 0.000839*T + 0.0002261*T2 - 0.00000845*T3 - 0.000000081*T*T3;
    } else {
        deltat= -0.000278 + 0.000265*T + 0.000262*T2;
    };

    JdNew = Jd1 + C1 - deltat;

    return floor(JdNew + 0.5 + timeZone/24);
}

-(double)getLunarMonth11: (double) yy timeZone: (double) timeZone
{
    double k, off, nm, sunLong;
    off = [self jdFromDate:31 mm:12 yy:yy] - 2415021;

    k = floor(off / 29.530588853);

    nm = [self getNewMoonDay:k timeZone:timeZone];

    sunLong = [self getSunLongitude:nm timeZone:timeZone]; // sun longitude at local midnight

    if (sunLong >= 9) {
        nm = [self getNewMoonDay:(k-1) timeZone:timeZone];
    }
    return nm;
}

-(double)getSunLongitude:(double)jdn timeZone: (double) timeZone
{
    double T, T2, dr, M, L0, DL, L;
    T = (jdn - 2451545.5 - timeZone/24) / 36525; // Time in Julian centuries from 2000-01-01 12:00:00 GMT
    T2 = T*T;
    dr = M_PI/180; // degree to radian
    M = 357.52910 + 35999.05030*T - 0.0001559*T2 - 0.00000048*T*T2; // mean anomaly, degree
    L0 = 280.46645 + 36000.76983*T + 0.0003032*T2; // mean longitude, degree
    DL = (1.914600 - 0.004817*T - 0.000014*T2)*sin(dr*M);
    DL = DL + (0.019993 - 0.000101*T)*sin(dr*2*M) + 0.000290*sin(dr*3*M);
    L = L0 + DL; // true longitude, degree
    L = L*dr;
    L = L - M_PI*2*(floor(L/(M_PI*2))); // Normalize to (0, 2*PI)
    return floor(L / M_PI * 6);
}

-(double)getLeapMonthOffset:(double) a11 timeZone: (double)timeZone
{
    double k, last, arc, i;
    k = floor((a11 - 2415021.076998695) / 29.530588853 + 0.5);
    last = 0;
    i = 1; // We start with the month following lunar month 11
    arc = [self getSunLongitude: [self getNewMoonDay:(k+i) timeZone:timeZone] timeZone:timeZone];
    do {
        last = arc;
        i++;
        arc = [self getSunLongitude:[self getNewMoonDay:(k+i) timeZone:timeZone] timeZone:timeZone];
    } while (arc != last && i < 14);
    return i-1;
}

@end


text:
Try
=====

[![Language](http://img.shields.io/badge/language-swift-brightgreen.svg?style=flat
)](https://developer.apple.com/swift)
[![CocoaPods](https://img.shields.io/cocoapods/v/Future.svg)]()
[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)]
(https://github.com/Carthage/Carthage)
[![License](http://img.shields.io/badge/license-MIT-lightgrey.svg?style=flat
)](http://mit-license.org)
[![Issues](https://img.shields.io/github/issues/nghialv/Try.svg?style=flat
)](https://github.com/nghialv/Try/issues?state=open)

Swift µframework providing Try<T>.

This library is inspired by the `Try` implementation in Scala.

##### Without `Try`

``` swift
enum FileError: ErrorType {
	case FileNotFound
	case Unknown
}

func lineCountOfFile(filename: String) throws -> Int {
	if exists(filename) {
		let file = open(filename)
		return file.lineCount
	} else {
		throw FileError.FileNotFound
	}
}

// traditional way with Swift 2.0
do {
	let lineCount = try lineCountOfFile("data.text")
	// do something
} catch {
	// error handling
}

```

##### Code with `Try`

``` swift
let t = Try(try lineCountOfFile("data.text"))

switch t {
 	case .Success(let lines): print(lines)
	case .Failure(let error): print(error)
}
```

- `map` `<^>`

```swift
let t = Try(try lineCountOfFile("data.text")).map { $0 * 5 }

switch t {
	case .Success(let lines): print(lines)
	case .Failure(let error): print(error)
}
```

- `flatMap` `>>-`

```swift
let t = Try(try lineCountOfFile("data.text")).flapMap { Try(try doSomething($0)) }

switch t {
 	case .Success(let lines): print(lines)
	case .Failure(let error): print(error)
}
```

- Operators

``` swift
let t = Try(try lineCountOfFile("data.text")) <^> { $0 * 5} >>- { Try(try doSomething($0)) }

switch t {
	case .Success(let lines): print(lines)
	case .Failure(let error): print(error)
}
```

Installation
-----

- Using Carthage
>	- Insert `github "nghialv/Try"` to your Cartfile
>	- Run `carthage update`

- Using Cocoapods
>	- Insert `use_frameworks!` to your Podfile
>	- Insert `pod "Try"` to your Podfile
>	- Run `pod install`

- Using Submodule

Requirements
-----

- Swift 2.0 (Xcode 7.0 or later)
- iOS 8.0 or later


text:
<?php

namespace Google\AdsApi\AdManager\v202211;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class BreakdownForecast
{

    /**
     * @var int $matched
     */
    protected $matched = null;

    /**
     * @var int $available
     */
    protected $available = null;

    /**
     * @var int $possible
     */
    protected $possible = null;

    /**
     * @param int $matched
     * @param int $available
     * @param int $possible
     */
    public function __construct($matched = null, $available = null, $possible = null)
    {
      $this->matched = $matched;
      $this->available = $available;
      $this->possible = $possible;
    }

    /**
     * @return int
     */
    public function getMatched()
    {
      return $this->matched;
    }

    /**
     * @param int $matched
     * @return \Google\AdsApi\AdManager\v202211\BreakdownForecast
     */
    public function setMatched($matched)
    {
      $this->matched = (!is_null($matched) && PHP_INT_SIZE === 4)
          ? floatval($matched) : $matched;
      return $this;
    }

    /**
     * @return int
     */
    public function getAvailable()
    {
      return $this->available;
    }

    /**
     * @param int $available
     * @return \Google\AdsApi\AdManager\v202211\BreakdownForecast
     */
    public function setAvailable($available)
    {
      $this->available = (!is_null($available) && PHP_INT_SIZE === 4)
          ? floatval($available) : $available;
      return $this;
    }

    /**
     * @return int
     */
    public function getPossible()
    {
      return $this->possible;
    }

    /**
     * @param int $possible
     * @return \Google\AdsApi\AdManager\v202211\BreakdownForecast
     */
    public function setPossible($possible)
    {
      $this->possible = (!is_null($possible) && PHP_INT_SIZE === 4)
          ? floatval($possible) : $possible;
      return $this;
    }

}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace Klinkby.Calendar
{
    /// <summary>Extension methods for an ascending ordered <see cref="T:IEnumerable`1"/>
    /// using <see cref="IEvent"/> as generic type parameter.</summary>
    public static class EnumerableIEventsExtensions
    {
        /// <summary>
        /// Get the commands needed for inserting a new time slot into an existing ascending ordered collection.
        /// Will join adjacent events and prevent overlapping.
        /// </summary>
        /// <typeparam name="T"><see cref="IEvent"/> implementation</typeparam>
        /// <param name="orderedEvents">Collection of ascending ordered events.</param>
        /// <param name="evt">Event to add</param>
        /// <returns>Collection of <see cref="DataCommand"/>.</returns>
        public static IEnumerable<IDataCommand> AddEvent<T>(this IEnumerable<T> orderedEvents, IEvent evt)
            where T: IEvent
        {
            var position = ResolvePosition(orderedEvents, evt);
            // does the new slot conver entire slots (C in Y)
            // tested by OverlapsCompletely()
            foreach (var e in position.OverlapsCompletely)
            {
                yield return new DataCommand(e, DataCommandVerb.Delete);
            }
            IEvent extendEnd = position.StartsAdjacentTo ?? position.OverlapsEndOf;
            IEvent prependStart = position.EndsAdjacentTo ?? position.OverlapsStartOf;
            // does the new slot fill the entire space between two other slots (B, C)
            // tested by MergeBC()
            if (null != extendEnd && null != prependStart)
            {
                extendEnd.Duration = (prependStart.Start + prependStart.Duration)
                    - extendEnd.Start;
                Debug.Assert(extendEnd.Duration.Ticks > 0);
                yield return new DataCommand(prependStart, DataCommandVerb.Delete);
                yield return new DataCommand(extendEnd, DataCommandVerb.Update);
                yield break;
            }
            // does the new slot extend the end time of a preceding slot (B)
            // tested by ExtendBEnd()
            if (null != extendEnd)
            {
                extendEnd.Duration = (evt.Start + evt.Duration) - extendEnd.Start;
                Debug.Assert(extendEnd.Duration.Ticks > 0);
                yield return new DataCommand(extendEnd, DataCommandVerb.Update);
                yield break;
            }
            // does the new slot prepend the start time of a following slot (C)
            // tested by ExtendCStartAdjacent()
            if (null != prependStart)
            {
                prependStart.Duration = (prependStart.Start + prependStart.Duration) - evt.Start;
                Debug.Assert(prependStart.Duration.Ticks > 0);
                prependStart.Start = evt.Start;
                yield return new DataCommand(prependStart, DataCommandVerb.Update);
                yield break;
            }
            // this is completely new territory
            // tested by AddNew()
            yield return new DataCommand(evt, DataCommandVerb.Insert);
        }

        /// <summary>
        /// Get the commands needed for removing time slot from an existing ascending ordered collection.
        /// Will clip existing events if they overlap the given time slot.
        /// </summary>
        /// <typeparam name="T"><see cref="IEvent"/> implementation</typeparam>
        /// <param name="orderedEvents">Collection of ascending ordered events.</param>
        /// <param name="evt">Time slot to remove</param>
        /// <returns>Collection of <see cref="DataCommand"/>.</returns>
        public static IEnumerable<IDataCommand> RemoveEvent<T>(this IEnumerable<T> orderedEvents, IEvent evt)
            where T : IEvent
        {
            var position = ResolvePosition(orderedEvents, evt);
            var overlapsEndOf = position.OverlapsEndOf;
            var overlapsStartOf = position.OverlapsStartOf;
            // does this slot conver entire slots (C in Y)
            // tested by OverlapsCompletely()
            foreach (var e in position.OverlapsCompletely)
            {
                yield return new DataCommand(e, DataCommandVerb.Delete);
            }
            // does this slot overlap the end time of a preceding slot (B)
            // tested by OverlapsEndOf()
            if (null != overlapsEndOf)
            {
                overlapsEndOf.Duration = evt.Start - overlapsEndOf.Start;
                Debug.Assert(overlapsEndOf.Duration.Ticks > 0);
                yield return new DataCommand(overlapsEndOf, DataCommandVerb.Update);
            }
            // does the new slot overlap the start time of a following slot (C)
            // tested by OverlapsStartOf()
            if (null != overlapsStartOf)
            {
                overlapsStartOf.Duration = (overlapsStartOf.Start + overlapsStartOf.Duration)- (evt.Start + evt.Duration);
                Debug.Assert(overlapsStartOf.Duration.Ticks > 0);
                overlapsStartOf.Start = evt.Start + evt.Duration;
                yield return new DataCommand(overlapsStartOf, DataCommandVerb.Update);
                yield break;
            }
        }

        /// <summary>
        /// Does a sanity check on the events to ensure none are null, have positive durations, are ordered ascending and does not overlap.
        /// Throws on first error found.
        /// </summary>
        /// <typeparam name="T"><see cref="IEvent"/> implementation</typeparam>
        /// <param name="orderedEvents">Collection of ascending ordered events.</param>
        /// <exception cref="InvalidOperationException">Thrown if there is an issue with the event list.</exception>
        public static void Validate<T>(this IEnumerable<T> orderedEvents)
            where T: IEvent
        {
            if (null == orderedEvents) throw new ArgumentNullException("orderedEvents");
            DateTime lastEnd = DateTime.MinValue;
            int i = 0;
            foreach (var item in orderedEvents)
            {
                if (null == item)
                {
                    throw new InvalidOperationException("Event index " + i + " is null");
                }
                if (0 >= item.Duration.Ticks)
                {
                    throw new InvalidOperationException("Event index " + i + " starting at " + item.Start + " ends in the past");
                }
                if (item.Start <= lastEnd)
                {
                    throw new InvalidOperationException("Event index " + i + " starts at " + item.Start + " before or when previous event ends at " + lastEnd);
                }
                i++;
                lastEnd = item.Start + item.Duration;
            }
        }

        /// <summary>
        /// Enumerates the orderedEvents to determine how evt fits in.
        /// </summary>
        /// <typeparam name="T"><see cref="IEvent"/> implementation</typeparam>
        /// <param name="orderedEvents">Collection of ascending ordered events.</param>
        /// <param name="evt">The time slot to fit in.</param>
        /// <returns>See <see cref="IEventPosition"/></returns>
        public static IEventPosition ResolvePosition<T>(this IEnumerable<T> orderedEvents, IEvent evt)
            where T: IEvent
        {
            if (null == orderedEvents) throw new ArgumentNullException("orderedEvents");
            if (null == evt) throw new ArgumentNullException("newEvent");
            var newItem = new EventWrapper(evt);
            var result = new EventPosition();
            using (var enumerator = orderedEvents.GetEnumerator())
            {
                /*

                    |  A   |%|   B   |%%%%%%%|   C   |%|   D  |%%%%%%%%%|  E  |
                                   |<--- x --->|
                                     |<-------- y -------->|
                                                                |<- z ->|
                */
                EventWrapper listItem;
                // skip preceding past events (A)
                do
                {
                    if (!enumerator.MoveNext()) return result;
                    listItem = new EventWrapper(enumerator.Current);
                } while (listItem.IsWayBefore(newItem));
                // does newItem start adjacent (Y to B)
                if (newItem.StartsAdjacentTo(listItem))
                {
                    result.StartsAdjacentTo = listItem.Event;
                    if (!enumerator.MoveNext()) return result;
                    listItem = new EventWrapper(enumerator.Current);
                }
                // or overlaps the end of an event (Y on B)
                else if (listItem.EndOverlappedBy(newItem))
                {
                    result.OverlapsEndOf = listItem.Event;
                    if (!enumerator.MoveNext()) return result;
                    listItem = new EventWrapper(enumerator.Current);
                }
                // is the following events contained in this one (C in Y)
                while (listItem.CompletelyOverlappedBy(newItem))
                {
                    result.OverlapsCompletely.Enqueue(listItem.Event);
                    if (!enumerator.MoveNext()) return result;
                    listItem = new EventWrapper(enumerator.Current);
                }
                // does the following event start exactly where this one ends (Y to E)
                if (newItem.EndsAdjacentTo(listItem))
                {
                    result.EndsAdjacentTo = listItem.Event;
                }
                // or overlaps the start of an event (Y on D)
                else if (newItem.EndOverlappedBy(listItem))
                {
                    result.OverlapsStartOf = listItem.Event;
                }
                // skip the rest
            }
            return result;
        }
    }
}


text:
(function(module) {
  mifosX.controllers = _.extend(module, {
    CreateOfficeController: function(scope, resourceFactory, location,dateFilter) {
        scope.offices = [];
        scope.first = {};
        scope.first.date = new Date();
        scope.restrictDate = new Date();
        resourceFactory.officeResource.getAllOffices(function(data) {
            scope.offices = data;
            scope.formData = {
              parentId : scope.offices[0].id
            }
        });

        scope.submit = function() {
          this.formData.locale = scope.optlang.code;
          var reqDate = dateFilter(scope.first.date,scope.df);
          this.formData.dateFormat = scope.df;
          this.formData.openingDate = reqDate;
          resourceFactory.officeResource.save(this.formData,function(data){
            location.path('/viewoffice/' + data.resourceId);
          });
        };
    }
  });
  mifosX.ng.application.controller('CreateOfficeController', ['$scope', 'ResourceFactory', '$location','dateFilter', mifosX.controllers.CreateOfficeController]).run(function($log) {
    $log.info("CreateOfficeController initialized");
  });
}(mifosX.controllers || {}));


text:
package ${package}.server;

public interface ${artifactId} {
	public void function();
	public abstract String read(String key);
	public abstract int updata(String key);
}


text:
package org.apache.olingo.fit.tecsvc.client;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.net.URI;

import org.apache.olingo.client.api.communication.ODataClientErrorException;
import org.apache.olingo.client.api.communication.request.retrieve.ODataEntitySetRequest;
import org.apache.olingo.client.api.communication.response.ODataRetrieveResponse;
import org.apache.olingo.client.api.domain.ClientEntity;
import org.apache.olingo.client.api.domain.ClientEntitySet;
import org.apache.olingo.commons.api.http.HttpHeader;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.junit.Test;

public class SystemQueryOptionITCase extends AbstractParamTecSvcITCase {
  private static final String PROPERTY_INT16 = "PropertyInt16";
  private static final String ES_SERVER_SIDE_PAGING = "ESServerSidePaging";
  private static final String ES_ALL_PRIM = "ESAllPrim";

  @Test
  public void countSimple() {
    ODataEntitySetRequest<ClientEntitySet> request = getClient().getRetrieveRequestFactory()
        .getEntitySetRequest(getClient().newURIBuilder(SERVICE_URI)
            .appendEntitySetSegment(ES_ALL_PRIM)
            .count(true)
            .build());
    setCookieHeader(request);
    ODataRetrieveResponse<ClientEntitySet> response = request.execute();
    saveCookieHeader(response);

    assertEquals(Integer.valueOf(4), response.getBody().getCount());
    assertEquals(4, response.getBody().getEntities().size());
  }

  @Test
  public void serverSidePagingCount() {
    ODataEntitySetRequest<ClientEntitySet> request = getClient().getRetrieveRequestFactory()
        .getEntitySetRequest(getClient().newURIBuilder(SERVICE_URI)
            .appendEntitySetSegment(ES_SERVER_SIDE_PAGING)
            .count(true)
            .build());
    setCookieHeader(request);
    ODataRetrieveResponse<ClientEntitySet> response = request.execute();
    saveCookieHeader(response);

    assertEquals(10, response.getBody().getEntities().size());
    assertEquals(Integer.valueOf(503), response.getBody().getCount());
  }

  @Test
  public void topSimple() {
    ODataEntitySetRequest<ClientEntitySet> request = getClient().getRetrieveRequestFactory()
        .getEntitySetRequest(getClient().newURIBuilder(SERVICE_URI)
            .appendEntitySetSegment(ES_SERVER_SIDE_PAGING)
            .top(5)
            .build());
    setCookieHeader(request);
    ODataRetrieveResponse<ClientEntitySet> response = request.execute();
    saveCookieHeader(response);

    assertEquals(5, response.getBody().getEntities().size());

    for (int i = 0; i < 5; i++) {
      ClientEntity entity = response.getBody().getEntities().get(i);
      assertShortOrInt(i + 1, entity.getProperty(PROPERTY_INT16).getPrimitiveValue().toValue());
    }
  }

  @Test
  public void skipSimple() {
    ODataEntitySetRequest<ClientEntitySet> request = getClient().getRetrieveRequestFactory()
        .getEntitySetRequest(getClient().newURIBuilder(SERVICE_URI)
            .appendEntitySetSegment(ES_SERVER_SIDE_PAGING)
            .skip(5)
            .build());
    setCookieHeader(request);
    ODataRetrieveResponse<ClientEntitySet> response = request.execute();
    saveCookieHeader(response);

    assertEquals(10, response.getBody().getEntities().size());

    for (int i = 0; i < 10; i++) {
      ClientEntity entity = response.getBody().getEntities().get(i);
      assertShortOrInt(i + 6, entity.getProperty(PROPERTY_INT16).getPrimitiveValue().toValue());
    }
  }

  @Test
  public void topNothing() {
    ODataEntitySetRequest<ClientEntitySet> request = getClient().getRetrieveRequestFactory()
        .getEntitySetRequest(getClient().newURIBuilder(SERVICE_URI)
            .appendEntitySetSegment(ES_SERVER_SIDE_PAGING)
            .top(20)
            .skip(503)
            .build());
    setCookieHeader(request);
    ODataRetrieveResponse<ClientEntitySet> response = request.execute();
    saveCookieHeader(response);

    assertTrue(response.getBody().getEntities().isEmpty());
  }

  @Test
  public void skipNothing() {
    ODataEntitySetRequest<ClientEntitySet> request = getClient().getRetrieveRequestFactory()
        .getEntitySetRequest(getClient().newURIBuilder(SERVICE_URI)
            .appendEntitySetSegment(ES_SERVER_SIDE_PAGING)
            .skip(10000)
            .build());
    setCookieHeader(request);
    ODataRetrieveResponse<ClientEntitySet> response = request.execute();
    saveCookieHeader(response);

    assertTrue(response.getBody().getEntities().isEmpty());
  }

  @Test
  public void searchAndFilterWithTopSkipOrderByAndServerSidePaging() {
    ODataEntitySetRequest<ClientEntitySet> request = getClient().getRetrieveRequestFactory()
        .getEntitySetRequest(getClient().newURIBuilder(SERVICE_URI)
            .appendEntitySetSegment(ES_SERVER_SIDE_PAGING)
            .search("\"Number:\" AND NOT \"106\"") // 1, 2, ..., 105, 107, ...
            .filter("PropertyInt16 le 106") // 1, 2, ..., 105
            .orderBy("PropertyInt16 desc") // 105, 104, ..., 2, 1
            .count(true) // 105
            .skip(3) // 102, 101, ..., 2, 1
            .top(43) // 102, 101, ...., 59
            .build());
    setCookieHeader(request);
    ODataRetrieveResponse<ClientEntitySet> response = request.execute();
    saveCookieHeader(response);

    assertEquals(Integer.valueOf(105), response.getBody().getCount());
    assertEquals(10, response.getBody().getEntities().size());

    int id = 102;

    // Check first 10 entities.
    for (int i = 0; i < 10; i++) {
      ClientEntity entity = response.getBody().getEntities().get(i);
      assertShortOrInt(id, entity.getProperty(PROPERTY_INT16).getPrimitiveValue().toValue());
      id--;
    }

    // Get 3 * 10 = 30 Entities and check the key.
    for (int j = 0; j < 3; j++) {
      request = getClient().getRetrieveRequestFactory().getEntitySetRequest(response.getBody().getNext());
      setCookieHeader(request);
      response = request.execute();
      saveCookieHeader(response);
      assertEquals(Integer.valueOf(105), response.getBody().getCount());
      assertEquals(10, response.getBody().getEntities().size());
      for (int i = 0; i < 10; i++) {
        ClientEntity entity = response.getBody().getEntities().get(i);
        assertShortOrInt(id, entity.getProperty(PROPERTY_INT16).getPrimitiveValue().toValue());
        id--;
      }
    }

    // Get the last 3 items.
    request = getClient().getRetrieveRequestFactory().getEntitySetRequest(response.getBody().getNext());
    setCookieHeader(request);
    response = request.execute();
    saveCookieHeader(response);
    assertEquals(Integer.valueOf(105), response.getBody().getCount());
    assertEquals(3, response.getBody().getEntities().size());
    for (int i = 0; i < 3; i++) {
      ClientEntity entity = response.getBody().getEntities().get(i);
      assertShortOrInt(id, entity.getProperty(PROPERTY_INT16).getPrimitiveValue().toValue());
      id--;
    }

    // Make sure that the body no not contain a next link
    assertNull(response.getBody().getNext());
  }

  @Test
  public void nextLinkFormat() {
    ODataEntitySetRequest<ClientEntitySet> request = getClient().getRetrieveRequestFactory()
        .getEntitySetRequest(getClient().newURIBuilder(SERVICE_URI)
            .appendEntitySetSegment(ES_SERVER_SIDE_PAGING)
            .build());
    setCookieHeader(request);
    ODataRetrieveResponse<ClientEntitySet> response = request.execute();
    saveCookieHeader(response);

    // Check initial next link format
    URI nextLink = response.getBody().getNext();
    assertEquals(SERVICE_URI + "ESServerSidePaging?%24skiptoken=1%2A10", nextLink.toASCIIString());

    // Check subsequent next links.
    request = getClient().getRetrieveRequestFactory().getEntitySetRequest(nextLink);
    setCookieHeader(request);
    response = request.execute();
    saveCookieHeader(response);

    nextLink = response.getBody().getNext();
    assertEquals(SERVICE_URI + "ESServerSidePaging?%24skiptoken=2%2A10", nextLink.toASCIIString());
  }

  @Test
  public void nextLinkFormatWithQueryOptions() {
    ODataEntitySetRequest<ClientEntitySet> request = getClient().getRetrieveRequestFactory()
        .getEntitySetRequest(getClient().newURIBuilder(SERVICE_URI)
            .appendEntitySetSegment(ES_SERVER_SIDE_PAGING)
            .count(true)
            .build());
    setCookieHeader(request);
    ODataRetrieveResponse<ClientEntitySet> response = request.execute();
    saveCookieHeader(response);

    // Check initial next link format
    URI nextLink = response.getBody().getNext();
    assertEquals(SERVICE_URI + "ESServerSidePaging?%24count=true&%24skiptoken=1%2A10",
        nextLink.toASCIIString());

    int token = 1;
    while (nextLink != null) {
      token++;

      // Check subsequent next links.
      request = getClient().getRetrieveRequestFactory().getEntitySetRequest(nextLink);
      setCookieHeader(request);
      response = request.execute();
      saveCookieHeader(response);

      nextLink = response.getBody().getNext();
      if (nextLink != null) {
        assertEquals(SERVICE_URI + "ESServerSidePaging?%24count=true&%24skiptoken=" + token + "%2A10",
            nextLink.toASCIIString());
      }
    }

    assertEquals(50 + 1, token);
  }

  @Test
  public void nextLinkFormatWithClientPageSize() {
    final URI uri = getClient().newURIBuilder(SERVICE_URI).appendEntitySetSegment(ES_SERVER_SIDE_PAGING).build();
    ODataEntitySetRequest<ClientEntitySet> request = getClient().getRetrieveRequestFactory().getEntitySetRequest(uri);
    request.setPrefer(getClient().newPreferences().maxPageSize(7));
    setCookieHeader(request);

    final ODataRetrieveResponse<ClientEntitySet> response = request.execute();
    saveCookieHeader(response);
    assertEquals("odata.maxpagesize=7", response.getHeader(HttpHeader.PREFERENCE_APPLIED).iterator().next());
    assertEquals(SERVICE_URI + ES_SERVER_SIDE_PAGING + "?%24skiptoken=1%2A" + 7,
        response.getBody().getNext().toASCIIString());
  }

  @Test
  public void negativeSkip() {
    ODataEntitySetRequest<ClientEntitySet> request = getClient().getRetrieveRequestFactory()
        .getEntitySetRequest(getClient().newURIBuilder(SERVICE_URI)
            .appendEntitySetSegment(ES_ALL_PRIM)
            .skip(-5)
            .build());
    setCookieHeader(request);
    try {
      request.execute();
      fail();
    } catch (ODataClientErrorException e) {
      assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), e.getStatusLine().getStatusCode());
    }
  }

  @Test
  public void negativeTop() {
    ODataEntitySetRequest<ClientEntitySet> request = getClient().getRetrieveRequestFactory()
        .getEntitySetRequest(getClient().newURIBuilder(SERVICE_URI)
            .appendEntitySetSegment(ES_ALL_PRIM)
            .top(-5)
            .build());
    setCookieHeader(request);
    try {
      request.execute();
      fail();
    } catch (ODataClientErrorException e) {
      assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), e.getStatusLine().getStatusCode());
    }
  }

  @Test
  public void basicSearch() {
    ODataEntitySetRequest<ClientEntitySet> request = getClient().getRetrieveRequestFactory()
        .getEntitySetRequest(getClient().newURIBuilder(SERVICE_URI)
            .appendEntitySetSegment(ES_ALL_PRIM)
            .search("Second")
            .build());
    setCookieHeader(request);
    final ODataRetrieveResponse<ClientEntitySet> response = request.execute();
    assertEquals(1, response.getBody().getEntities().size());
  }

  @Test
  public void basicSearchPhrase() {
    ODataEntitySetRequest<ClientEntitySet> request = getClient().getRetrieveRequestFactory()
        .getEntitySetRequest(getClient().newURIBuilder(SERVICE_URI)
            .appendEntitySetSegment(ES_ALL_PRIM)
            .search("\"This is a \\\"$imple\\\"\\\\Phras~\" AND "
                + "AnUnicodeWordLl\u01E3Lm\u02B5Lo\u00AALt\u01F2Lu\u03D3Nl\u216F")
            .build());
    setCookieHeader(request);
    final ODataRetrieveResponse<ClientEntitySet> response = request.execute();
    assertTrue(response.getBody().getEntities().isEmpty());
  }

  @Test
  public void andSearch() {
    ODataEntitySetRequest<ClientEntitySet> request = getClient().getRetrieveRequestFactory()
        .getEntitySetRequest(getClient().newURIBuilder(SERVICE_URI)
            .appendEntitySetSegment(ES_ALL_PRIM)
            .search("Second AND positive")
            .build());
    setCookieHeader(request);
    final ODataRetrieveResponse<ClientEntitySet> response = request.execute();
    assertTrue(response.getBody().getEntities().isEmpty());
  }

  @Test
  public void orSearch() {
    ODataEntitySetRequest<ClientEntitySet> request = getClient().getRetrieveRequestFactory()
        .getEntitySetRequest(getClient().newURIBuilder(SERVICE_URI)
            .appendEntitySetSegment(ES_ALL_PRIM)
            .search("Second OR positive")
            .build());
    setCookieHeader(request);
    ODataRetrieveResponse<ClientEntitySet> response = request.execute();
    assertEquals(2, response.getBody().getEntities().size());
  }
}


text:
CREATE TABLE staging.wiki_info (
    wiki VARCHAR(100),
    code VARCHAR(100),
    sitename VARCHAR(100),
    url VARCHAR(255),
    lang_id INT,
    lang_code VARCHAR(100),
    lang_name VARBINARY(255),
    lang_local_name VARBINARY(255),
    PRIMARY KEY(wiki)
);


text:
define( "JBrowse/Store/SeqFeature/BAM/LazyFeature", ['dojo/_base/array',
         'JBrowse/Util',
         './Util',
         'JBrowse/Model/SimpleFeature'
        ],
        function( array, Util, BAMUtil, SimpleFeature ) {

var SEQRET_DECODER = ['=', 'A', 'C', 'x', 'G', 'x', 'x', 'x', 'T', 'x', 'x', 'x', 'x', 'x', 'x', 'N'];
var CIGAR_DECODER  = ['M', 'I', 'D', 'N', 'S', 'H', 'P', '=', 'X', '?', '?', '?', '?', '?', '?', '?'];

var readInt   = BAMUtil.readInt;
var readShort = BAMUtil.readShort;
var readFloat = BAMUtil.readFloat;
var readByte  = BAMUtil.readByte;

var Feature = Util.fastDeclare(
{
    constructor: function( args ) {
        this.file  = args.file;
        this.data  = {
            type: 'match',
            source: args.store.source
        };
        this.bytes = {
            start: args.bytes.start,
            end: args.bytes.end,
            byteArray: args.bytes.byteArray
        };

        this._coreParse();
    },

    get: function( field) {
        return this._get( field.toLowerCase() );
    },

    // same as get(), except requires lower-case arguments.  used
    // internally to save lots of calls to field.toLowerCase()
    _get: function( field ) {
        return field in this.data ? this.data[field] : // have we already parsed it out?
            function(field) {
                var v = this.data[field] =
                    this[field]            ? this[field]()            : // maybe we have a special parser for it
                    this._flagMasks[field] ? this._parseFlag( field ) : // or is it a flag?
                                             this._parseTag( field );   // otherwise, look for it in the tags
                return v;
            }.call(this,field);
    },

    tags: function() {
        return this._get('_tags');
    },

    _tags: function() {
        this._parseAllTags();

        var tags = [ 'seq', 'seq_reverse_complemented', 'unmapped','qc_failed','duplicate','secondary_alignment','supplementary_alignment' ];

        if( ! this._get('unmapped') )
            tags.push( 'start', 'end', 'strand', 'score', 'qual', 'MQ', 'CIGAR', 'length_on_ref', 'template_length' );
        if( this._get('multi_segment_template') ) {
            tags.push( 'multi_segment_all_correctly_aligned',
                       'multi_segment_next_segment_unmapped',
                       'multi_segment_next_segment_reversed',
                       'multi_segment_first',
                       'multi_segment_last',
                       'next_segment_position'
                     );
        }
        tags = tags.concat( this._tagList || [] );

        var d = this.data;
        for( var k in d ) {
            if( d.hasOwnProperty( k ) && k[0] != '_'
                && k != 'multi_segment_all_aligned'
                && k != 'next_seq_id')
                tags.push( k );
        }

        var seen = {};
        tags = array.filter( tags, function(t) {
            if( t in this.data && this.data[t] === undefined )
                return false;

            var lt = t.toLowerCase();
            var s = seen[lt];
            seen[lt] = true;
            return ! s;
        },this);

        return tags;
    },

    parent: function() {
        return undefined;
    },

    children: function() {
        return this._get('subfeatures');
    },

    id: function() {
        return this._get('name')+'/'+this._get('md')+'/'+this._get('cigar')+'/'+this._get('start')+'/'+this._get('multi_segment_next_segment_reversed');
    },

    multi_segment_all_aligned: function() {
        return this._get('multi_segment_all_correctly_aligned');
    },

    // special parsers
    /**
     * Mapping quality score.
     */
    mq: function() {
        var mq = (this._get('_bin_mq_nl') & 0xff00) >> 8;
        return mq == 255 ? undefined : mq;
    },
    score: function() {
        return this._get('mq');
    },
    qual: function() {
        if( this._get('unmapped') )
            return undefined;

        var qseq = [];
        var byteArray = this.bytes.byteArray;
        var p = this.bytes.start + 36 + this._get('_l_read_name') + this._get('_n_cigar_op')*4 + this._get('_seq_bytes');
        var lseq = this._get('seq_length');
        for (var j = 0; j < lseq; ++j) {
            qseq.push( byteArray[p + j] );
        }
        return qseq.join(' ');
    },
    strand: function() {
        return this._get('seq_reverse_complemented') ? -1 :  1;
    },
    multi_segment_next_segment_strand: function() {
      if(this._get('multi_segment_next_segment_unmapped'))
        return undefined;
      return this._get('multi_segment_next_segment_reversed') ? -1 : 1;
    },

    /**
     * Length in characters of the read name.
     */
    _l_read_name: function() {
        return this._get('_bin_mq_nl') & 0xff;
    },
    /**
     * number of bytes in the sequence field
     */
    _seq_bytes: function() {
        return (this._get('seq_length') + 1) >> 1;
    },
    seq: function() {
        var seq = '';
        var byteArray = this.bytes.byteArray;
        var p = this.bytes.start + 36 + this._get('_l_read_name') + this._get('_n_cigar_op')*4;
        var seqBytes = this._get('_seq_bytes');
        for (var j = 0; j < seqBytes; ++j) {
            var sb = byteArray[p + j];
            seq += SEQRET_DECODER[(sb & 0xf0) >> 4];
            if (seq.length < this.get('seq_length'))
                seq += SEQRET_DECODER[(sb & 0x0f)];
        }
        return seq;
    },
    name: function() {
        return this._get('_read_name');
    },
    _read_name: function() {
        var byteArray = this.bytes.byteArray;
        var readName = '';
        var nl = this._get('_l_read_name');
        var p = this.bytes.start + 36;
        for (var j = 0; j < nl-1; ++j) {
            readName += String.fromCharCode(byteArray[p+j]);
        }
        return readName;
    },
    _n_cigar_op: function() {
        return this._get('_flag_nc') & 0xffff;
    },
    cigar: function() {
        if( this._get('unmapped') )
            return undefined;

        var byteArray   = this.bytes.byteArray;
        var numCigarOps = this._get('_n_cigar_op');
        var p = this.bytes.start + 36 + this._get('_l_read_name');
        var cigar = '';
        var lref = 0;
        for (var c = 0; c < numCigarOps; ++c) {
            var cigop = readInt(byteArray, p);
            var lop = cigop >> 4;
            var op = CIGAR_DECODER[cigop & 0xf];
            cigar += lop + op;

            // soft clip, hard clip, and insertion don't count toward
            // the length on the reference
            if( op != 'H' && op != 'S' && op != 'I' )
                lref += lop;

            p += 4;
        }

        this.data.length_on_ref = lref;
        return cigar;
    },
    next_segment_position: function() {
        var nextSegment = this.file.indexToChr[this._get('_next_refid')];
        if( nextSegment )
            return nextSegment.name+':'+this._get('_next_pos');
        else
            return undefined;
    },
    subfeatures: function() {
        var cigar = this._get('cigar');
        if( cigar )
            return this._cigarToSubfeats( cigar );

        return undefined;
    },
    length_on_ref: function() {
        var c = this._get('cigar'); // the length_on_ref is set as a
                                   // side effect of the CIGAR parsing
        return this.data.length_on_ref;
    },
    _flags: function() {
        return (this.get('_flag_nc') & 0xffff0000) >> 16;
    },
    end: function() {
        return this._get('start') + ( this._get('length_on_ref') || this._get('seq_length') || undefined );
    },

    seq_id: function() {
        if( this._get('unmapped') )
            return undefined;

        return ( this.file.indexToChr[ this._refID ] || {} ).name;
    },

    next_seq_id: function() {
        if( this._get('multi_segment_next_segment_unmapped') )
            return undefined;
        return ( this.file.indexToChr[this._get('_next_refid')] || {} ).name;
    },

    _bin_mq_nl: function() {
        return readInt( this.bytes.byteArray, this.bytes.start + 12  );
    },
    _flag_nc: function() {
        return readInt( this.bytes.byteArray, this.bytes.start + 16 );
    },
    seq_length: function() {
        return readInt( this.bytes.byteArray, this.bytes.start + 20 );
    },
    _next_refid: function() {
        return readInt( this.bytes.byteArray, this.bytes.start + 24 );
    },
    _next_pos: function() {
        return readInt( this.bytes.byteArray, this.bytes.start + 28 );
    },
    template_length: function() {
        return readInt( this.bytes.byteArray, this.bytes.start + 32 );
    },

    /**
     * parse the core data: ref ID and start
     */
    _coreParse: function() {
        this._refID      = readInt( this.bytes.byteArray, this.bytes.start + 4 );
        this.data.start  = readInt( this.bytes.byteArray, this.bytes.start + 8 );
    },

    /**
     * Get the value of a tag, parsing the tags as far as necessary.
     * Only called if we have not already parsed that field.
     */
    _parseTag: function( tagName ) {
        // if all of the tags have been parsed and we're still being
        // called, we already know that we have no such tag, because
        // it would already have been cached.
        if( this._allTagsParsed )
            return undefined;

        this._tagList = this._tagList || [];
        var byteArray = this.bytes.byteArray;
        var p = this._tagOffset || this.bytes.start + 36 + this._get('_l_read_name') + this._get('_n_cigar_op')*4 + this._get('_seq_bytes') + this._get('seq_length');

        var blockEnd = this.bytes.end;
        while( p < blockEnd && lcTag != tagName ) {
            var tag      = String.fromCharCode( byteArray[p], byteArray[ p+1 ] );
            var lcTag    = tag.toLowerCase();
            var type = String.fromCharCode( byteArray[ p+2 ] );
            p += 3;

            var value;
            switch( type.toLowerCase() ) {
            case 'a':
                value = String.fromCharCode( byteArray[p] );
                p += 1;
                break;
            case 'i':
                value = readInt(byteArray, p );
                p += 4;
                break;
            case 'c':
                value = byteArray[p];
                p += 1;
                break;
            case 's':
                value = readShort(byteArray, p);
                p += 2;
                break;
            case 'f':
                value = readFloat( byteArray, p );
                p += 4;
                break;
            case 'z':
            case 'h':
                value = '';
                while( p <= blockEnd ) {
                    var cc = byteArray[p++];
                    if( cc == 0 ) {
                        break;
                    }
                    else {
                        value += String.fromCharCode(cc);
                    }
                }
                break;
            case 'b':
                value = '';
                var cc = byteArray[p++];
                var Btype = String.fromCharCode(cc);
                if( Btype == 'i'|| Btype == 'I' ) {
                    var limit = readInt( byteArray, p )
                    p += 4;
                    for( var k = 0; k < limit; k++ ) {
                        value += readInt( byteArray, p );
                        if(k+1<limit) value += ',';
                        p += 4;
                    }
                }
                if( Btype == 's'|| Btype == 'S' ) {
                    var limit = readInt( byteArray, p )
                    p += 4;
                    for( var k = 0; k < limit; k++ ) {
                        value += readShort( byteArray, p );
                        if(k+1<limit) value += ',';
                        p += 2;
                    }
                }
                if( Btype == 'c'|| Btype == 'C' ) {
                    var limit = readInt( byteArray, p )
                    p += 4;
                    for( var k = 0; k < limit; k++ ) {
                        value += readByte( byteArray, p );
                        if(k+1<limit) value += ',';
                        p += 1;
                    }
                }
                if( Btype == 'f' ) {
                    var limit = readInt( byteArray, p )
                    p += 4;
                    for( var k = 0; k < limit; k++ ) {
                        value += readFloat( byteArray, p );
                        if(k+1<limit) value += ',';
                        p += 4;
                    }
                }
                break;
            default:
                console.warn( "Unknown BAM tag type '"+type
                              +"', tags may be incomplete"
                            );
                value = undefined;
                p = blockEnd; // stop parsing tags
            }

            this._tagOffset = p;

            this._tagList.push( tag );
            if( lcTag == tagName )
                return value;
            else {
                this.data[ lcTag ] = value;
            }
        }
        this._allTagsParsed = true;
        return undefined;
    },
    _parseAllTags: function() {
        this._parseTag(); // calling _parseTag with no arg just parses
        // all the tags and returns the last one
    },

    _flagMasks: {
        multi_segment_template:              0x1,
        multi_segment_all_correctly_aligned: 0x2,
        unmapped:                            0x4,
        multi_segment_next_segment_unmapped: 0x8,
        seq_reverse_complemented:            0x10,
        multi_segment_next_segment_reversed: 0x20,
        multi_segment_first:                 0x40,
        multi_segment_last:                  0x80,
        secondary_alignment:                 0x100,
        qc_failed:                           0x200,
        duplicate:                           0x400,
        supplementary_alignment:             0x800
    },

    _parseFlag: function( flagName ) {
        return !!( this._get('_flags') & this._flagMasks[flagName] );
    },

    _parseCigar: function( cigar ) {
        return array.map( cigar.match(/\d+\D/g), function( op ) {
           return [ op.match(/\D/)[0].toUpperCase(), parseInt( op ) ];
        });
    },

    /**
     *  take a cigar string, and initial position, return an array of subfeatures
     */
    _cigarToSubfeats: function(cigar)    {
        var subfeats = [];
        var min = this._get('start');
        var max;
        var ops = this._parseCigar( cigar );
        for (var i = 0; i < ops.length; i++)  {
            var lop = ops[i][1];
            var op = ops[i][0];  // operation type
            // converting "=" to "E" to avoid possible problems later with non-alphanumeric type name
            if (op === "=")  { op = "E"; }

            switch (op) {
            case 'M':
            case 'D':
            case 'N':
            case 'E':
            case 'X':
                max = min + lop;
                break;
            case 'I':
                max = min;
                break;
            case 'P':  // not showing padding deletions (possibly change this later -- could treat same as 'I' ?? )
            case 'H':  // not showing hard clipping (since it's unaligned, and offset arg meant to be beginning of aligned part)
            case 'S':  // not showing soft clipping (since it's unaligned, and offset arg meant to be beginning of aligned part)
                break;
                // other possible cases
            }
            if( op !== 'N' ) {
                subfeats.push(
                    new SimpleFeature(
                        {
                            data: {
                                type: op,
                                start: min,
                                end: max,
                                strand: this._get('strand'),
                                cigar_op: lop+op
                            },
                            parent: this
                        })
                );
            }
            min = max;
        }
        return subfeats;
    }

});

return Feature;
});


text:
'use strict'

var http = require('http')
  , assert = require('assert')
  , request = require('../index')
  , tape = require('tape')

var server = http.createServer(function(req, resp) {
  resp.statusCode = 200
  if (req.url === '/get') {
    assert.equal(req.method, 'GET')
    resp.write('content')
    resp.end()
    return
  }
  if (req.url === '/put') {
    var x = ''
    assert.equal(req.method, 'PUT')
    req.on('data', function(chunk) {
      x += chunk
    })
    req.on('end', function() {
      assert.equal(x, 'content')
      resp.write('success')
      resp.end()
    })
    return
  }
  if (req.url === '/proxy') {
    assert.equal(req.method, 'PUT')
    req.pipe(request(server.url + '/put')).pipe(resp)
    return
  }
  if (req.url === '/test') {
    request(server.url + '/get').pipe(request.put(server.url + '/proxy')).pipe(resp)
    return
  }
  throw new Error('Unknown url', req.url)
})

tape('setup', function(t) {
  server.listen(0, function() {
    server.url = 'http://localhost:' + this.address().port
    t.end()
  })
})

tape('chained one-line proxying', function(t) {
  request(server.url + '/test', function(err, res, body) {
    t.equal(err, null)
    t.equal(res.statusCode, 200)
    t.equal(body, 'success')
    t.end()
  })
})

tape('cleanup', function(t) {
  server.close(function() {
    t.end()
  })
})


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace YAF.Pages.Admin {

    public partial class boards {

        /// <summary>
        /// PageLinks control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::VZF.Controls.PageLinks PageLinks;

        /// <summary>
        /// LocalizedLabel1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::VZF.Controls.LocalizedLabel LocalizedLabel1;

        /// <summary>
        /// LocalizedLabel4 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::VZF.Controls.LocalizedLabel LocalizedLabel4;

        /// <summary>
        /// LocalizedLabel5 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::VZF.Controls.LocalizedLabel LocalizedLabel5;

        /// <summary>
        /// List control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Repeater List;

        /// <summary>
        /// New control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button New;

        /// <summary>
        /// SmartScroller1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::VZF.Controls.SmartScroller SmartScroller1;
    }
}


text:
using System;
using System.Linq;
using DevLab.JmesPath.Utils;
using Newtonsoft.Json.Linq;

namespace DevLab.JmesPath.Functions
{
    public class MapFunction : JmesPathFunction
    {
        public MapFunction()
            : base("map", 2)
        {
        }

        public override void Validate(params JmesPathFunctionArgument[] args)
        {
            if (!args[0].IsExpressionType)
                throw new Exception($"Error: invalid-type, function {Name} expects its first argument to be an expression type.");

            var array = args[1].Token;
            if (array.Type != JTokenType.Array)
                throw new Exception($"Error: invalid-type, function {Name} expects its second argument to be an array.");
        }

        public override JToken Execute(params JmesPathFunctionArgument[] args)
        {
            var expression = args[0].Expression;
            var elements = (JArray) (args[1].Token);

            var items = elements.Select(e =>
                expression.Transform(e).AsJToken()
                ).ToArray();

            return new JArray().AddRange(items);
        }
    }
}


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
es5id: 15.2.3.3-4-180
description: >
    Object.getOwnPropertyDescriptor returns data desc (all false) for
    properties on built-ins (Global.undefined)
includes: [fnGlobalObject.js]
---*/

  // in non-strict mode, 'this' is bound to the global object.
  var desc = Object.getOwnPropertyDescriptor(fnGlobalObject(),  "undefined");

assert.sameValue(desc.writable, false, 'desc.writable');
assert.sameValue(desc.enumerable, false, 'desc.enumerable');
assert.sameValue(desc.configurable, false, 'desc.configurable');
assert.sameValue(desc.hasOwnProperty('get'), false, 'desc.hasOwnProperty("get")');
assert.sameValue(desc.hasOwnProperty('set'), false, 'desc.hasOwnProperty("set")');