text:
package com.google.cloud.notebooks.v1beta1.samples;

// [START notebooks_v1beta1_generated_NotebookService_GetLocation_async]
import com.google.api.core.ApiFuture;
import com.google.cloud.location.GetLocationRequest;
import com.google.cloud.location.Location;
import com.google.cloud.notebooks.v1beta1.NotebookServiceClient;

public class AsyncGetLocation {

  public static void main(String[] args) throws Exception {
    asyncGetLocation();
  }

  public static void asyncGetLocation() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (NotebookServiceClient notebookServiceClient = NotebookServiceClient.create()) {
      GetLocationRequest request = GetLocationRequest.newBuilder().setName("name3373707").build();
      ApiFuture<Location> future = notebookServiceClient.getLocationCallable().futureCall(request);
      // Do something.
      Location response = future.get();
    }
  }
}
// [END notebooks_v1beta1_generated_NotebookService_GetLocation_async]


text:
package com.alibaba.jstorm.flux.test;

import backtype.storm.Config;
import backtype.storm.generated.StormTopology;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Values;
import storm.trident.TridentTopology;
import storm.trident.operation.BaseFunction;
import storm.trident.operation.TridentCollector;
import storm.trident.operation.builtin.Count;
import storm.trident.testing.FixedBatchSpout;
import storm.trident.testing.MemoryMapState;
import storm.trident.tuple.TridentTuple;

/**
 * Basic Trident example that will return a `StormTopology` from a `getTopology()` method.
 */
public class TridentTopologySource {

    private FixedBatchSpout spout;

    public StormTopology getTopology(Config config) {

        this.spout = new FixedBatchSpout(new Fields("sentence"), 20,
                new Values("one two"),
                new Values("two three"),
                new Values("three four"),
                new Values("four five"),
                new Values("five six")
        );

        TridentTopology trident = new TridentTopology();

        trident.newStream("wordcount", spout).name("sentence").parallelismHint(1).shuffle()
                .each(new Fields("sentence"), new Split(), new Fields("word"))
                .parallelismHint(1)
                .groupBy(new Fields("word"))
                .persistentAggregate(new MemoryMapState.Factory(), new Count(), new Fields("count"))
                .parallelismHint(1);
        return trident.build();
    }

    public static class Split extends BaseFunction {
        @Override
        public void execute(TridentTuple tuple, TridentCollector collector) {
            String sentence = tuple.getString(0);
            for (String word : sentence.split(" ")) {
                collector.emit(new Values(word));
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.facebook.LinkBench;

// Various operation types for which we want to gather stats
public enum LinkBenchOp {
  ADD_NODE,
  UPDATE_NODE,
  DELETE_NODE,
  GET_NODE,
  ADD_LINK,
  DELETE_LINK,
  UPDATE_LINK,
  COUNT_LINK,
  MULTIGET_LINK,
  GET_LINKS_LIST,
  LOAD_NODE_BULK,
  LOAD_LINK,
  LOAD_LINKS_BULK,
  LOAD_COUNTS_BULK,
  // Although the following are not truly operations, we need stats
  // for them
  RANGE_SIZE,    // how big range scans are
  LOAD_LINKS_BULK_NLINKS, // how many links inserted in bulk
  LOAD_COUNTS_BULK_NLINKS, // how many counts inserted in bulk
  UNKNOWN;

  public String displayName() {
    return name();
  }
}


text:
/**
 */
package CIM15.IEC61968.PaymentMetering;

import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;

import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;

/**
 *
 * A representation of the model object 'Bank Account Detail'.
 *
 *
 *

 * The following features are supported:
 *

 *
{@link CIM15.IEC61968.PaymentMetering.BankAccountDetail#getHolderID Holder ID}

 *
{@link CIM15.IEC61968.PaymentMetering.BankAccountDetail#getHolderName Holder Name}

 *
{@link CIM15.IEC61968.PaymentMetering.BankAccountDetail#getBankName Bank Name}

 *
{@link CIM15.IEC61968.PaymentMetering.BankAccountDetail#getBranchCode Branch Code}

 *
{@link CIM15.IEC61968.PaymentMetering.BankAccountDetail#getAccountNumber Account Number}

 *

 *

 *
 * @generated
 */
public class BankAccountDetail extends MinimalEObjectImpl.Container implements EObject {
	/**
	 * The default value of the '{@link #getHolderID() Holder ID}' attribute.
	 *
	 *
	 * @see #getHolderID()
	 * @generated
	 * @ordered
	 */
	protected static final String HOLDER_ID_EDEFAULT = null;

	/**
	 * The cached value of the '{@link #getHolderID() Holder ID}' attribute.
	 *
	 *
	 * @see #getHolderID()
	 * @generated
	 * @ordered
	 */
	protected String holderID = HOLDER_ID_EDEFAULT;

	/**
	 * This is true if the Holder ID attribute has been set.
	 *
	 *
	 * @generated
	 * @ordered
	 */
	protected boolean holderIDESet;

	/**
	 * The default value of the '{@link #getHolderName() Holder Name}' attribute.
	 *
	 *
	 * @see #getHolderName()
	 * @generated
	 * @ordered
	 */
	protected static final String HOLDER_NAME_EDEFAULT = null;

	/**
	 * The cached value of the '{@link #getHolderName() Holder Name}' attribute.
	 *
	 *
	 * @see #getHolderName()
	 * @generated
	 * @ordered
	 */
	protected String holderName = HOLDER_NAME_EDEFAULT;

	/**
	 * This is true if the Holder Name attribute has been set.
	 *
	 *
	 * @generated
	 * @ordered
	 */
	protected boolean holderNameESet;

	/**
	 * The default value of the '{@link #getBankName() Bank Name}' attribute.
	 *
	 *
	 * @see #getBankName()
	 * @generated
	 * @ordered
	 */
	protected static final String BANK_NAME_EDEFAULT = null;

	/**
	 * The cached value of the '{@link #getBankName() Bank Name}' attribute.
	 *
	 *
	 * @see #getBankName()
	 * @generated
	 * @ordered
	 */
	protected String bankName = BANK_NAME_EDEFAULT;

	/**
	 * This is true if the Bank Name attribute has been set.
	 *
	 *
	 * @generated
	 * @ordered
	 */
	protected boolean bankNameESet;

	/**
	 * The default value of the '{@link #getBranchCode() Branch Code}' attribute.
	 *
	 *
	 * @see #getBranchCode()
	 * @generated
	 * @ordered
	 */
	protected static final String BRANCH_CODE_EDEFAULT = null;

	/**
	 * The cached value of the '{@link #getBranchCode() Branch Code}' attribute.
	 *
	 *
	 * @see #getBranchCode()
	 * @generated
	 * @ordered
	 */
	protected String branchCode = BRANCH_CODE_EDEFAULT;

	/**
	 * This is true if the Branch Code attribute has been set.
	 *
	 *
	 * @generated
	 * @ordered
	 */
	protected boolean branchCodeESet;

	/**
	 * The default value of the '{@link #getAccountNumber() Account Number}' attribute.
	 *
	 *
	 * @see #getAccountNumber()
	 * @generated
	 * @ordered
	 */
	protected static final String ACCOUNT_NUMBER_EDEFAULT = null;

	/**
	 * The cached value of the '{@link #getAccountNumber() Account Number}' attribute.
	 *
	 *
	 * @see #getAccountNumber()
	 * @generated
	 * @ordered
	 */
	protected String accountNumber = ACCOUNT_NUMBER_EDEFAULT;

	/**
	 * This is true if the Account Number attribute has been set.
	 *
	 *
	 * @generated
	 * @ordered
	 */
	protected boolean accountNumberESet;

	/**
	 *
	 *
	 * @generated
	 */
	protected BankAccountDetail() {
		super();
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	protected EClass eStaticClass() {
		return PaymentMeteringPackage.Literals.BANK_ACCOUNT_DETAIL;
	}

	/**
	 * Returns the value of the 'Holder ID' attribute.
	 *
	 *

	 * If the meaning of the 'Holder ID' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Holder ID' attribute.
	 * @see #isSetHolderID()
	 * @see #unsetHolderID()
	 * @see #setHolderID(String)
	 * @generated
	 */
	public String getHolderID() {
		return holderID;
	}

	/**
	 * Sets the value of the '{@link CIM15.IEC61968.PaymentMetering.BankAccountDetail#getHolderID Holder ID}' attribute.
	 *
	 *
	 * @param value the new value of the 'Holder ID' attribute.
	 * @see #isSetHolderID()
	 * @see #unsetHolderID()
	 * @see #getHolderID()
	 * @generated
	 */
	public void setHolderID(String newHolderID) {
		holderID = newHolderID;
		holderIDESet = true;
	}

	/**
	 * Unsets the value of the '{@link CIM15.IEC61968.PaymentMetering.BankAccountDetail#getHolderID Holder ID}' attribute.
	 *
	 *
	 * @see #isSetHolderID()
	 * @see #getHolderID()
	 * @see #setHolderID(String)
	 * @generated
	 */
	public void unsetHolderID() {
		holderID = HOLDER_ID_EDEFAULT;
		holderIDESet = false;
	}

	/**
	 * Returns whether the value of the '{@link CIM15.IEC61968.PaymentMetering.BankAccountDetail#getHolderID Holder ID}' attribute is set.
	 *
	 *
	 * @return whether the value of the 'Holder ID' attribute is set.
	 * @see #unsetHolderID()
	 * @see #getHolderID()
	 * @see #setHolderID(String)
	 * @generated
	 */
	public boolean isSetHolderID() {
		return holderIDESet;
	}

	/**
	 * Returns the value of the 'Holder Name' attribute.
	 *
	 *

	 * If the meaning of the 'Holder Name' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Holder Name' attribute.
	 * @see #isSetHolderName()
	 * @see #unsetHolderName()
	 * @see #setHolderName(String)
	 * @generated
	 */
	public String getHolderName() {
		return holderName;
	}

	/**
	 * Sets the value of the '{@link CIM15.IEC61968.PaymentMetering.BankAccountDetail#getHolderName Holder Name}' attribute.
	 *
	 *
	 * @param value the new value of the 'Holder Name' attribute.
	 * @see #isSetHolderName()
	 * @see #unsetHolderName()
	 * @see #getHolderName()
	 * @generated
	 */
	public void setHolderName(String newHolderName) {
		holderName = newHolderName;
		holderNameESet = true;
	}

	/**
	 * Unsets the value of the '{@link CIM15.IEC61968.PaymentMetering.BankAccountDetail#getHolderName Holder Name}' attribute.
	 *
	 *
	 * @see #isSetHolderName()
	 * @see #getHolderName()
	 * @see #setHolderName(String)
	 * @generated
	 */
	public void unsetHolderName() {
		holderName = HOLDER_NAME_EDEFAULT;
		holderNameESet = false;
	}

	/**
	 * Returns whether the value of the '{@link CIM15.IEC61968.PaymentMetering.BankAccountDetail#getHolderName Holder Name}' attribute is set.
	 *
	 *
	 * @return whether the value of the 'Holder Name' attribute is set.
	 * @see #unsetHolderName()
	 * @see #getHolderName()
	 * @see #setHolderName(String)
	 * @generated
	 */
	public boolean isSetHolderName() {
		return holderNameESet;
	}

	/**
	 * Returns the value of the 'Bank Name' attribute.
	 *
	 *

	 * If the meaning of the 'Bank Name' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Bank Name' attribute.
	 * @see #isSetBankName()
	 * @see #unsetBankName()
	 * @see #setBankName(String)
	 * @generated
	 */
	public String getBankName() {
		return bankName;
	}

	/**
	 * Sets the value of the '{@link CIM15.IEC61968.PaymentMetering.BankAccountDetail#getBankName Bank Name}' attribute.
	 *
	 *
	 * @param value the new value of the 'Bank Name' attribute.
	 * @see #isSetBankName()
	 * @see #unsetBankName()
	 * @see #getBankName()
	 * @generated
	 */
	public void setBankName(String newBankName) {
		bankName = newBankName;
		bankNameESet = true;
	}

	/**
	 * Unsets the value of the '{@link CIM15.IEC61968.PaymentMetering.BankAccountDetail#getBankName Bank Name}' attribute.
	 *
	 *
	 * @see #isSetBankName()
	 * @see #getBankName()
	 * @see #setBankName(String)
	 * @generated
	 */
	public void unsetBankName() {
		bankName = BANK_NAME_EDEFAULT;
		bankNameESet = false;
	}

	/**
	 * Returns whether the value of the '{@link CIM15.IEC61968.PaymentMetering.BankAccountDetail#getBankName Bank Name}' attribute is set.
	 *
	 *
	 * @return whether the value of the 'Bank Name' attribute is set.
	 * @see #unsetBankName()
	 * @see #getBankName()
	 * @see #setBankName(String)
	 * @generated
	 */
	public boolean isSetBankName() {
		return bankNameESet;
	}

	/**
	 * Returns the value of the 'Branch Code' attribute.
	 *
	 *

	 * If the meaning of the 'Branch Code' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Branch Code' attribute.
	 * @see #isSetBranchCode()
	 * @see #unsetBranchCode()
	 * @see #setBranchCode(String)
	 * @generated
	 */
	public String getBranchCode() {
		return branchCode;
	}

	/**
	 * Sets the value of the '{@link CIM15.IEC61968.PaymentMetering.BankAccountDetail#getBranchCode Branch Code}' attribute.
	 *
	 *
	 * @param value the new value of the 'Branch Code' attribute.
	 * @see #isSetBranchCode()
	 * @see #unsetBranchCode()
	 * @see #getBranchCode()
	 * @generated
	 */
	public void setBranchCode(String newBranchCode) {
		branchCode = newBranchCode;
		branchCodeESet = true;
	}

	/**
	 * Unsets the value of the '{@link CIM15.IEC61968.PaymentMetering.BankAccountDetail#getBranchCode Branch Code}' attribute.
	 *
	 *
	 * @see #isSetBranchCode()
	 * @see #getBranchCode()
	 * @see #setBranchCode(String)
	 * @generated
	 */
	public void unsetBranchCode() {
		branchCode = BRANCH_CODE_EDEFAULT;
		branchCodeESet = false;
	}

	/**
	 * Returns whether the value of the '{@link CIM15.IEC61968.PaymentMetering.BankAccountDetail#getBranchCode Branch Code}' attribute is set.
	 *
	 *
	 * @return whether the value of the 'Branch Code' attribute is set.
	 * @see #unsetBranchCode()
	 * @see #getBranchCode()
	 * @see #setBranchCode(String)
	 * @generated
	 */
	public boolean isSetBranchCode() {
		return branchCodeESet;
	}

	/**
	 * Returns the value of the 'Account Number' attribute.
	 *
	 *

	 * If the meaning of the 'Account Number' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Account Number' attribute.
	 * @see #isSetAccountNumber()
	 * @see #unsetAccountNumber()
	 * @see #setAccountNumber(String)
	 * @generated
	 */
	public String getAccountNumber() {
		return accountNumber;
	}

	/**
	 * Sets the value of the '{@link CIM15.IEC61968.PaymentMetering.BankAccountDetail#getAccountNumber Account Number}' attribute.
	 *
	 *
	 * @param value the new value of the 'Account Number' attribute.
	 * @see #isSetAccountNumber()
	 * @see #unsetAccountNumber()
	 * @see #getAccountNumber()
	 * @generated
	 */
	public void setAccountNumber(String newAccountNumber) {
		accountNumber = newAccountNumber;
		accountNumberESet = true;
	}

	/**
	 * Unsets the value of the '{@link CIM15.IEC61968.PaymentMetering.BankAccountDetail#getAccountNumber Account Number}' attribute.
	 *
	 *
	 * @see #isSetAccountNumber()
	 * @see #getAccountNumber()
	 * @see #setAccountNumber(String)
	 * @generated
	 */
	public void unsetAccountNumber() {
		accountNumber = ACCOUNT_NUMBER_EDEFAULT;
		accountNumberESet = false;
	}

	/**
	 * Returns whether the value of the '{@link CIM15.IEC61968.PaymentMetering.BankAccountDetail#getAccountNumber Account Number}' attribute is set.
	 *
	 *
	 * @return whether the value of the 'Account Number' attribute is set.
	 * @see #unsetAccountNumber()
	 * @see #getAccountNumber()
	 * @see #setAccountNumber(String)
	 * @generated
	 */
	public boolean isSetAccountNumber() {
		return accountNumberESet;
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public Object eGet(int featureID, boolean resolve, boolean coreType) {
		switch (featureID) {
			case PaymentMeteringPackage.BANK_ACCOUNT_DETAIL__HOLDER_ID:
				return getHolderID();
			case PaymentMeteringPackage.BANK_ACCOUNT_DETAIL__HOLDER_NAME:
				return getHolderName();
			case PaymentMeteringPackage.BANK_ACCOUNT_DETAIL__BANK_NAME:
				return getBankName();
			case PaymentMeteringPackage.BANK_ACCOUNT_DETAIL__BRANCH_CODE:
				return getBranchCode();
			case PaymentMeteringPackage.BANK_ACCOUNT_DETAIL__ACCOUNT_NUMBER:
				return getAccountNumber();
		}
		return super.eGet(featureID, resolve, coreType);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eSet(int featureID, Object newValue) {
		switch (featureID) {
			case PaymentMeteringPackage.BANK_ACCOUNT_DETAIL__HOLDER_ID:
				setHolderID((String)newValue);
				return;
			case PaymentMeteringPackage.BANK_ACCOUNT_DETAIL__HOLDER_NAME:
				setHolderName((String)newValue);
				return;
			case PaymentMeteringPackage.BANK_ACCOUNT_DETAIL__BANK_NAME:
				setBankName((String)newValue);
				return;
			case PaymentMeteringPackage.BANK_ACCOUNT_DETAIL__BRANCH_CODE:
				setBranchCode((String)newValue);
				return;
			case PaymentMeteringPackage.BANK_ACCOUNT_DETAIL__ACCOUNT_NUMBER:
				setAccountNumber((String)newValue);
				return;
		}
		super.eSet(featureID, newValue);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eUnset(int featureID) {
		switch (featureID) {
			case PaymentMeteringPackage.BANK_ACCOUNT_DETAIL__HOLDER_ID:
				unsetHolderID();
				return;
			case PaymentMeteringPackage.BANK_ACCOUNT_DETAIL__HOLDER_NAME:
				unsetHolderName();
				return;
			case PaymentMeteringPackage.BANK_ACCOUNT_DETAIL__BANK_NAME:
				unsetBankName();
				return;
			case PaymentMeteringPackage.BANK_ACCOUNT_DETAIL__BRANCH_CODE:
				unsetBranchCode();
				return;
			case PaymentMeteringPackage.BANK_ACCOUNT_DETAIL__ACCOUNT_NUMBER:
				unsetAccountNumber();
				return;
		}
		super.eUnset(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case PaymentMeteringPackage.BANK_ACCOUNT_DETAIL__HOLDER_ID:
				return isSetHolderID();
			case PaymentMeteringPackage.BANK_ACCOUNT_DETAIL__HOLDER_NAME:
				return isSetHolderName();
			case PaymentMeteringPackage.BANK_ACCOUNT_DETAIL__BANK_NAME:
				return isSetBankName();
			case PaymentMeteringPackage.BANK_ACCOUNT_DETAIL__BRANCH_CODE:
				return isSetBranchCode();
			case PaymentMeteringPackage.BANK_ACCOUNT_DETAIL__ACCOUNT_NUMBER:
				return isSetAccountNumber();
		}
		return super.eIsSet(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public String toString() {
		if (eIsProxy()) return super.toString();

		StringBuffer result = new StringBuffer(super.toString());
		result.append(" (holderID: ");
		if (holderIDESet) result.append(holderID); else result.append("<unset>");
		result.append(", holderName: ");
		if (holderNameESet) result.append(holderName); else result.append("<unset>");
		result.append(", bankName: ");
		if (bankNameESet) result.append(bankName); else result.append("<unset>");
		result.append(", branchCode: ");
		if (branchCodeESet) result.append(branchCode); else result.append("<unset>");
		result.append(", accountNumber: ");
		if (accountNumberESet) result.append(accountNumber); else result.append("<unset>");
		result.append(')');
		return result.toString();
	}

} // BankAccountDetail


text:
package com.coderevisited.bits;

/**
 * binary to gray : n XOR n/2
 * gray to binary : n ^ n/2 ^ n/4 ^ n/8 ... 1
 */
public class GrayCodeConversion
{
    public static void main(String[] args)
    {
        int n = binaryToGrayCode(10);
        System.out.println("binary to gray " + n);
        System.out.println("gray to binary " + grayToBinary(n));
    }

    public static int binaryToGrayCode(int n)
    {
        return (n >> 1) ^ n;
    }

    public static int grayToBinary(int n)
    {
        for (int mask = n >> 1; mask != 0; mask = mask >> 1) {
            n = n ^ mask;
        }
        return n;
    }
}


text:
module Cryptoexchange::Exchanges
  module Trademn
    module Services
      class Market < Cryptoexchange::Services::Market
        class << self
          def supports_individual_ticker_query?
            true
          end
        end

        def fetch(market_pair)
          output = super(ticker_url(market_pair))
          adapt(market_pair, output)
        end

        def ticker_url(market_pair)
          "#{Cryptoexchange::Exchanges::Trademn::Market::API_URL}/ticker/#{market_pair.base}"
        end

        def adapt(market_pair, output)
          ticker = Cryptoexchange::Models::Ticker.new
          ticker.base = market_pair.base
          ticker.target = market_pair.target
          ticker.market = Trademn::Market::NAME
          ticker.ask = NumericHelper.to_d(output['data']['sell_price'])
          ticker.bid = NumericHelper.to_d(output['data']['buy_price'])
          ticker.last = NumericHelper.to_d(output['data']['last_price'])
          ticker.high = NumericHelper.to_d(output['data']['max_price'])
          ticker.low = NumericHelper.to_d(output['data']['min_price'])
          ticker.volume = NumericHelper.to_d(output['data']['units_traded'])
          ticker.timestamp = nil
          ticker.payload = output
          ticker
        end
      end
    end
  end
end


text:
package com.android.dexdeps;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;

/**
 * Data extracted from a DEX file.
 */
public class DexData {
    private RandomAccessFile mDexFile;
    private HeaderItem mHeaderItem;
    private String[] mStrings;              // strings from string_data_*
    private TypeIdItem[] mTypeIds;
    private ProtoIdItem[] mProtoIds;
    private FieldIdItem[] mFieldIds;
    private MethodIdItem[] mMethodIds;
    private ClassDefItem[] mClassDefs;

    private byte tmpBuf[] = new byte[4];
    private boolean isBigEndian = false;

    /**
     * Constructs a new DexData for this file.
     */
    public DexData(RandomAccessFile raf) {
        mDexFile = raf;
    }

    /**
     * Loads the contents of the DEX file into our data structures.
     *
     * @throws IOException if we encounter a problem while reading
     * @throws DexDataException if the DEX contents look bad
     */
    public void load() throws IOException {
        parseHeaderItem();

        loadStrings();
        loadTypeIds();
        loadProtoIds();
        loadFieldIds();
        loadMethodIds();
        loadClassDefs();

        markInternalClasses();
    }

    /**
     * Verifies the given magic number.
     */
    private static boolean verifyMagic(byte[] magic) {
        return Arrays.equals(magic, HeaderItem.DEX_FILE_MAGIC) ||
            Arrays.equals(magic, HeaderItem.DEX_FILE_MAGIC_API_13);
    }

    /**
     * Parses the interesting bits out of the header.
     */
    void parseHeaderItem() throws IOException {
        mHeaderItem = new HeaderItem();

        seek(0);

        byte[] magic = new byte[8];
        readBytes(magic);
        if (!verifyMagic(magic)) {
            System.err.println("Magic number is wrong -- are you sure " +
                "this is a DEX file?");
            throw new DexDataException("Magic number is wrong -- are you sure this is a DEX file?");
        }

        /*
         * Read the endian tag, so we properly swap things as we read
         * them from here on.
         */
        seek(8 + 4 + 20 + 4 + 4);
        mHeaderItem.endianTag = readInt();
        if (mHeaderItem.endianTag == HeaderItem.ENDIAN_CONSTANT) {
            /* do nothing */
        } else if (mHeaderItem.endianTag == HeaderItem.REVERSE_ENDIAN_CONSTANT) {
            /* file is big-endian (!), reverse future reads */
            isBigEndian = true;
        } else {
            System.err.println("Endian constant has unexpected value" +
                Integer.toHexString(mHeaderItem.endianTag));
            throw new DexDataException("Endian constant has unexpected value" +
                Integer.toHexString(mHeaderItem.endianTag));
        }

        seek(8 + 4 + 20);  // magic, checksum, signature
        mHeaderItem.fileSize = readInt();
        mHeaderItem.headerSize = readInt();
        /*mHeaderItem.endianTag =*/
        readInt();
        /*mHeaderItem.linkSize =*/
        readInt();
        /*mHeaderItem.linkOff =*/
        readInt();
        /*mHeaderItem.mapOff =*/
        readInt();
        mHeaderItem.stringIdsSize = readInt();
        mHeaderItem.stringIdsOff = readInt();
        mHeaderItem.typeIdsSize = readInt();
        mHeaderItem.typeIdsOff = readInt();
        mHeaderItem.protoIdsSize = readInt();
        mHeaderItem.protoIdsOff = readInt();
        mHeaderItem.fieldIdsSize = readInt();
        mHeaderItem.fieldIdsOff = readInt();
        mHeaderItem.methodIdsSize = readInt();
        mHeaderItem.methodIdsOff = readInt();
        mHeaderItem.classDefsSize = readInt();
        mHeaderItem.classDefsOff = readInt();
        /*mHeaderItem.dataSize =*/
        readInt();
        /*mHeaderItem.dataOff =*/
        readInt();
    }

    /**
     * Loads the string table out of the DEX.
     *
     * First we read all of the string_id_items, then we read all of the
     * string_data_item.  Doing it this way should allow us to avoid
     * seeking around in the file.
     */
    void loadStrings() throws IOException {
        int count = mHeaderItem.stringIdsSize;
        int stringOffsets[] = new int[count];

        //System.out.println("reading " + count + " strings");

        seek(mHeaderItem.stringIdsOff);
        for (int i = 0; i < count; i++) {
            stringOffsets[i] = readInt();
        }

        mStrings = new String[count];

        seek(stringOffsets[0]);
        for (int i = 0; i < count; i++) {
            seek(stringOffsets[i]);         // should be a no-op
            mStrings[i] = readString();
            //System.out.println("STR: " + i + ": " + mStrings[i]);
        }
    }

    /**
     * Loads the type ID list.
     */
    void loadTypeIds() throws IOException {
        int count = mHeaderItem.typeIdsSize;
        mTypeIds = new TypeIdItem[count];

        //System.out.println("reading " + count + " typeIds");
        seek(mHeaderItem.typeIdsOff);
        for (int i = 0; i < count; i++) {
            mTypeIds[i] = new TypeIdItem();
            mTypeIds[i].descriptorIdx = readInt();

            //System.out.println(i + ": " + mTypeIds[i].descriptorIdx +
            //    " " + mStrings[mTypeIds[i].descriptorIdx]);
        }
    }

    /**
     * Loads the proto ID list.
     */
    void loadProtoIds() throws IOException {
        int count = mHeaderItem.protoIdsSize;
        mProtoIds = new ProtoIdItem[count];

        //System.out.println("reading " + count + " protoIds");
        seek(mHeaderItem.protoIdsOff);

        /*
         * Read the proto ID items.
         */
        for (int i = 0; i < count; i++) {
            mProtoIds[i] = new ProtoIdItem();
            mProtoIds[i].shortyIdx = readInt();
            mProtoIds[i].returnTypeIdx = readInt();
            mProtoIds[i].parametersOff = readInt();

            //System.out.println(i + ": " + mProtoIds[i].shortyIdx +
            //    " " + mStrings[mProtoIds[i].shortyIdx]);
        }

        /*
         * Go back through and read the type lists.
         */
        for (int i = 0; i < count; i++) {
            ProtoIdItem protoId = mProtoIds[i];

            int offset = protoId.parametersOff;

            if (offset == 0) {
                protoId.types = new int[0];
                continue;
            } else {
                seek(offset);
                int size = readInt();       // #of entries in list
                protoId.types = new int[size];

                for (int j = 0; j < size; j++) {
                    protoId.types[j] = readShort() & 0xffff;
                }
            }
        }
    }

    /**
     * Loads the field ID list.
     */
    void loadFieldIds() throws IOException {
        int count = mHeaderItem.fieldIdsSize;
        mFieldIds = new FieldIdItem[count];

        //System.out.println("reading " + count + " fieldIds");
        seek(mHeaderItem.fieldIdsOff);
        for (int i = 0; i < count; i++) {
            mFieldIds[i] = new FieldIdItem();
            mFieldIds[i].classIdx = readShort() & 0xffff;
            mFieldIds[i].typeIdx = readShort() & 0xffff;
            mFieldIds[i].nameIdx = readInt();

            //System.out.println(i + ": " + mFieldIds[i].nameIdx +
            //    " " + mStrings[mFieldIds[i].nameIdx]);
        }
    }

    /**
     * Loads the method ID list.
     */
    void loadMethodIds() throws IOException {
        int count = mHeaderItem.methodIdsSize;
        mMethodIds = new MethodIdItem[count];

        //System.out.println("reading " + count + " methodIds");
        seek(mHeaderItem.methodIdsOff);
        for (int i = 0; i < count; i++) {
            mMethodIds[i] = new MethodIdItem();
            mMethodIds[i].classIdx = readShort() & 0xffff;
            mMethodIds[i].protoIdx = readShort() & 0xffff;
            mMethodIds[i].nameIdx = readInt();

            //System.out.println(i + ": " + mMethodIds[i].nameIdx +
            //    " " + mStrings[mMethodIds[i].nameIdx]);
        }
    }

    /**
     * Loads the class defs list.
     */
    void loadClassDefs() throws IOException {
        int count = mHeaderItem.classDefsSize;
        mClassDefs = new ClassDefItem[count];

        //System.out.println("reading " + count + " classDefs");
        seek(mHeaderItem.classDefsOff);
        for (int i = 0; i < count; i++) {
            mClassDefs[i] = new ClassDefItem();
            mClassDefs[i].classIdx = readInt();

            /* access_flags = */
            readInt();
            /* superclass_idx = */
            readInt();
            /* interfaces_off = */
            readInt();
            /* source_file_idx = */
            readInt();
            /* annotations_off = */
            readInt();
            /* class_data_off = */
            readInt();
            /* static_values_off = */
            readInt();

            //System.out.println(i + ": " + mClassDefs[i].classIdx + " " +
            //    mStrings[mTypeIds[mClassDefs[i].classIdx].descriptorIdx]);
        }
    }

    /**
     * Sets the "internal" flag on type IDs which are defined in the
     * DEX file or within the VM (e.g. primitive classes and arrays).
     */
    void markInternalClasses() {
        for (int i = mClassDefs.length - 1; i >= 0; i--) {
            mTypeIds[mClassDefs[i].classIdx].internal = true;
        }

        for (int i = 0; i < mTypeIds.length; i++) {
            String className = mStrings[mTypeIds[i].descriptorIdx];

            if (className.length() == 1) {
                // primitive class
                mTypeIds[i].internal = true;
            } else if (className.charAt(0) == '[') {
                mTypeIds[i].internal = true;
            }

            //System.out.println(i + " " +
            //    (mTypeIds[i].internal ? "INTERNAL" : "external") + " - " +
            //    mStrings[mTypeIds[i].descriptorIdx]);
        }
    }

    /*
     * =======================================================================
     *      Queries
     * =======================================================================
     */

    /**
     * Returns the class name, given an index into the type_ids table.
     */
    private String classNameFromTypeIndex(int idx) {
        return mStrings[mTypeIds[idx].descriptorIdx];
    }

    /**
     * Returns an array of method argument type strings, given an index
     * into the proto_ids table.
     */
    private String[] argArrayFromProtoIndex(int idx) {
        ProtoIdItem protoId = mProtoIds[idx];
        String[] result = new String[protoId.types.length];

        for (int i = 0; i < protoId.types.length; i++) {
            result[i] = mStrings[mTypeIds[protoId.types[i]].descriptorIdx];
        }

        return result;
    }

    /**
     * Returns a string representing the method's return type, given an
     * index into the proto_ids table.
     */
    private String returnTypeFromProtoIndex(int idx) {
        ProtoIdItem protoId = mProtoIds[idx];
        return mStrings[mTypeIds[protoId.returnTypeIdx].descriptorIdx];
    }

    /**
     * Returns an array with all of the class references that don't
     * correspond to classes in the DEX file.  Each class reference has
     * a list of the referenced fields and methods associated with
     * that class.
     */
    public ClassRef[] getExternalReferences() {
        // create a sparse array of ClassRef that parallels mTypeIds
        ClassRef[] sparseRefs = new ClassRef[mTypeIds.length];

        // create entries for all externally-referenced classes
        int count = 0;
        for (int i = 0; i < mTypeIds.length; i++) {
            if (!mTypeIds[i].internal) {
                sparseRefs[i] =
                    new ClassRef(mStrings[mTypeIds[i].descriptorIdx]);
                count++;
            }
        }

        // add fields and methods to the appropriate class entry
        addExternalFieldReferences(sparseRefs);
        addExternalMethodReferences(sparseRefs);

        // crunch out the sparseness
        ClassRef[] classRefs = new ClassRef[count];
        int idx = 0;
        for (int i = 0; i < mTypeIds.length; i++) {
            if (sparseRefs[i] != null) {
                classRefs[idx++] = sparseRefs[i];
            }
        }

        assert idx == count;

        return classRefs;
    }

    /**
     * Runs through the list of field references, inserting external
     * references into the appropriate ClassRef.
     */
    private void addExternalFieldReferences(ClassRef[] sparseRefs) {
        for (int i = 0; i < mFieldIds.length; i++) {
            if (!mTypeIds[mFieldIds[i].classIdx].internal) {
                FieldIdItem fieldId = mFieldIds[i];
                FieldRef newFieldRef = new FieldRef(
                    classNameFromTypeIndex(fieldId.classIdx),
                    classNameFromTypeIndex(fieldId.typeIdx),
                    mStrings[fieldId.nameIdx]);
                sparseRefs[mFieldIds[i].classIdx].addField(newFieldRef);
            }
        }
    }

    /**
     * Runs through the list of method references, inserting external
     * references into the appropriate ClassRef.
     */
    private void addExternalMethodReferences(ClassRef[] sparseRefs) {
        for (int i = 0; i < mMethodIds.length; i++) {
            if (!mTypeIds[mMethodIds[i].classIdx].internal) {
                MethodIdItem methodId = mMethodIds[i];
                MethodRef newMethodRef = new MethodRef(
                    classNameFromTypeIndex(methodId.classIdx),
                    argArrayFromProtoIndex(methodId.protoIdx),
                    returnTypeFromProtoIndex(methodId.protoIdx),
                    mStrings[methodId.nameIdx]);
                sparseRefs[mMethodIds[i].classIdx].addMethod(newMethodRef);
            }
        }
    }

    /**
     * Returns the list of all method references.
     */
    public MethodRef[] getMethodRefs() {
        MethodRef[] methodRefs = new MethodRef[mMethodIds.length];
        for (int i = 0; i < mMethodIds.length; i++) {
            MethodIdItem methodId = mMethodIds[i];
            methodRefs[i] = new MethodRef(
                classNameFromTypeIndex(methodId.classIdx),
                argArrayFromProtoIndex(methodId.protoIdx),
                returnTypeFromProtoIndex(methodId.protoIdx),
                mStrings[methodId.nameIdx]);
        }
        return methodRefs;
    }

    /**
     * Returns the list of all field references.
     */
    public FieldRef[] getFieldRefs() {
        FieldRef[] fieldRefs = new FieldRef[mFieldIds.length];
        for (int i = 0; i < mFieldIds.length; i++) {
            FieldIdItem fieldId = mFieldIds[i];
            fieldRefs[i] = new FieldRef(
                classNameFromTypeIndex(fieldId.classIdx),
                classNameFromTypeIndex(fieldId.typeIdx),
                mStrings[fieldId.nameIdx]);
        }
        return fieldRefs;
    }

    /*
     * =======================================================================
     *      Basic I/O functions
     * =======================================================================
     */

    /**
     * Seeks the DEX file to the specified absolute position.
     */
    void seek(int position) throws IOException {
        mDexFile.seek(position);
    }

    /**
     * Fills the buffer by reading bytes from the DEX file.
     */
    void readBytes(byte[] buffer) throws IOException {
        mDexFile.readFully(buffer);
    }

    /**
     * Reads a single signed byte value.
     */
    byte readByte() throws IOException {
        mDexFile.readFully(tmpBuf, 0, 1);
        return tmpBuf[0];
    }

    /**
     * Reads a signed 16-bit integer, byte-swapping if necessary.
     */
    short readShort() throws IOException {
        mDexFile.readFully(tmpBuf, 0, 2);
        if (isBigEndian) {
            return (short) ((tmpBuf[1] & 0xff) | ((tmpBuf[0] & 0xff) << 8));
        } else {
            return (short) ((tmpBuf[0] & 0xff) | ((tmpBuf[1] & 0xff) << 8));
        }
    }

    /**
     * Reads a signed 32-bit integer, byte-swapping if necessary.
     */
    int readInt() throws IOException {
        mDexFile.readFully(tmpBuf, 0, 4);

        if (isBigEndian) {
            return (tmpBuf[3] & 0xff) | ((tmpBuf[2] & 0xff) << 8) |
                ((tmpBuf[1] & 0xff) << 16) | ((tmpBuf[0] & 0xff) << 24);
        } else {
            return (tmpBuf[0] & 0xff) | ((tmpBuf[1] & 0xff) << 8) |
                ((tmpBuf[2] & 0xff) << 16) | ((tmpBuf[3] & 0xff) << 24);
        }
    }

    /**
     * Reads a variable-length unsigned LEB128 value.  Does not attempt to
     * verify that the value is valid.
     *
     * @throws IOException if we run off the end of the file
     */
    int readUnsignedLeb128() throws IOException {
        int result = 0;
        byte val;

        do {
            val = readByte();
            result = (result << 7) | (val & 0x7f);
        } while (val < 0);

        return result;
    }

    /**
     * Reads a UTF-8 string.
     *
     * We don't know how long the UTF-8 string is, so we have to read one
     * byte at a time.  We could make an educated guess based on the
     * utf16_size and seek back if we get it wrong, but seeking backward
     * may cause the underlying implementation to reload I/O buffers.
     */
    String readString() throws IOException {
        int utf16len = readUnsignedLeb128();
        byte inBuf[] = new byte[utf16len * 3];      // worst case
        int idx;

        for (idx = 0; idx < inBuf.length; idx++) {
            byte val = readByte();
            if (val == 0) {
                break;
            }
            inBuf[idx] = val;
        }

        return new String(inBuf, 0, idx, "UTF-8");
    }

    /*
     * =======================================================================
     *      Internal "structure" declarations
     * =======================================================================
     */

    /**
     * Holds the contents of a header_item.
     */
    static class HeaderItem {
        public int fileSize;
        public int headerSize;
        public int endianTag;
        public int stringIdsSize, stringIdsOff;
        public int typeIdsSize, typeIdsOff;
        public int protoIdsSize, protoIdsOff;
        public int fieldIdsSize, fieldIdsOff;
        public int methodIdsSize, methodIdsOff;
        public int classDefsSize, classDefsOff;

        /* expected magic values */
        public static final byte[] DEX_FILE_MAGIC = {
            0x64, 0x65, 0x78, 0x0a, 0x30, 0x33, 0x36, 0x00 };
        public static final byte[] DEX_FILE_MAGIC_API_13 = {
            0x64, 0x65, 0x78, 0x0a, 0x30, 0x33, 0x35, 0x00 };
        public static final int ENDIAN_CONSTANT = 0x12345678;
        public static final int REVERSE_ENDIAN_CONSTANT = 0x78563412;
    }

    /**
     * Holds the contents of a type_id_item.
     *
     * This is chiefly a list of indices into the string table.  We need
     * some additional bits of data, such as whether or not the type ID
     * represents a class defined in this DEX, so we use an object for
     * each instead of a simple integer.  (Could use a parallel array, but
     * since this is a desktop app it's not essential.)
     */
    static class TypeIdItem {
        public int descriptorIdx;       // index into string_ids

        public boolean internal;        // defined within this DEX file?
    }

    /**
     * Holds the contents of a proto_id_item.
     */
    static class ProtoIdItem {
        public int shortyIdx;           // index into string_ids
        public int returnTypeIdx;       // index into type_ids
        public int parametersOff;       // file offset to a type_list

        public int types[];             // contents of type list
    }

    /**
     * Holds the contents of a field_id_item.
     */
    static class FieldIdItem {
        public int classIdx;            // index into type_ids (defining class)
        public int typeIdx;             // index into type_ids (field type)
        public int nameIdx;             // index into string_ids
    }

    /**
     * Holds the contents of a method_id_item.
     */
    static class MethodIdItem {
        public int classIdx;            // index into type_ids
        public int protoIdx;            // index into proto_ids
        public int nameIdx;             // index into string_ids
    }

    /**
     * Holds the contents of a class_def_item.
     *
     * We don't really need a class for this, but there's some stuff in
     * the class_def_item that we might want later.
     */
    static class ClassDefItem {
        public int classIdx;            // index into type_ids
    }
}


text:
require 'spec_helper'

describe Puppet::Type.type(:cs_property).provider(:crm) do
  before do
    described_class.stubs(:command).with(:crm).returns 'crm'
  end

  context 'when getting instances' do
    let :instances do

      test_cib = <<-EOS
        <cib>
          <configuration>
            <crm_config>
              <cluster_property_set>
                <nvpair name="apples" value="red"/>
                <nvpair name="oranges" value="orange"/>
              </cluster_property_set>
            </crm_config>
          </configuration>
        </cib>
      EOS

      described_class.expects(:block_until_ready).returns(nil)
      if Puppet::PUPPETVERSION.to_f < 3.4
        Puppet::Util::SUIDManager.expects(:run_and_capture).with(['crm', 'configure', 'show', 'xml']).at_least_once.returns([test_cib, 0])
      else
        Puppet::Util::Execution.expects(:execute).with(['crm', 'configure', 'show', 'xml']).at_least_once.returns(
          Puppet::Util::Execution::ProcessOutput.new(test_cib, 0)
        )
      end
      instances = described_class.instances
    end

    it 'should have an instance for each <nvpair> in <cluster_property_set>' do
      expect(instances.count).to eq(2)
    end

    describe 'each instance' do
      let :instance do
        instances.first
      end

      it "is a kind of #{described_class.name}" do
        expect(instance).to be_a_kind_of(described_class)
      end

      it "is named by the <nvpair>'s name attribute" do
        expect(instance.name).to eq("apples")
      end

      it "has a value corresponding to the <nvpair>'s value attribute" do
        expect(instance.value).to eq("red")
      end
    end
  end
end


text:
webapp module
-------------
A REST webapp responsible for accepting HTTP REST/SOAP requests, and routing the calls to the correct CTS2 Profile Service Interface.


text:
<?php

class UsersModelTable {

	/**
	*@tablename
	*@var
	*/
	public $table = 'users';

	/**
	 *@column
	 *@primary
	 *@type autonumber
	 */
	protected $id;

	/**
	 *@column
	 *@type datetime
	 *@add deleted
	 */
	protected $date_created;

	/**
	 *@column
	 *@type datetime
	 *@index
	 *@update
	 */
	protected $date_modified;

	/**
	 *@var string The query used to generate this model table
	 */
	protected $query_string;

}


text:
<?php

namespace Sprint\Migration\Helpers\Traits\Iblock;

use Bitrix\Iblock\Model\PropertyFeature;
use Bitrix\Iblock\PropertyFeatureTable;
use CIBlockProperty;
use CIBlockPropertyEnum;
use Exception;
use Sprint\Migration\Exceptions\HelperException;
use Sprint\Migration\Locale;

trait IblockPropertyTrait
{
    /**
     * Сохраняет свойство инфоблока
     * Создаст если не было, обновит если существует и отличается
     *
     * @param       $iblockId
     * @param array $fields
     *
     * @throws HelperException
     * @return bool|mixed
     */
    public function saveProperty($iblockId, $fields)
    {
        $this->checkRequiredKeys(__METHOD__, $fields, ['CODE']);

        $exists = $this->getProperty($iblockId, $fields['CODE']);
        $exportExists = $this->prepareExportProperty($exists);
        $fields = $this->prepareExportProperty($fields);

        if (empty($exists)) {
            $ok = $this->getMode('test') ? true : $this->addProperty($iblockId, $fields);
            $this->outNoticeIf(
                $ok,
                Locale::getMessage(
                    'IB_PROPERTY_CREATED',
                    [
                        '#IBLOCK_ID#' => $iblockId,
                        '#NAME#'      => $fields['CODE'],
                    ]
                )
            );
            return $ok;
        }

        if ($this->hasDiff($exportExists, $fields)) {
            $ok = $this->getMode('test') ? true : $this->updatePropertyById($exists['ID'], $fields);
            $this->outNoticeIf(
                $ok,
                Locale::getMessage(
                    'IB_PROPERTY_UPDATED',
                    [
                        '#IBLOCK_ID#' => $iblockId,
                        '#NAME#'      => $fields['CODE'],
                    ]
                )
            );
            $this->outDiffIf($ok, $exportExists, $fields);
            return $ok;
        }

        $ok = $this->getMode('test') ? true : $exists['ID'];
        if ($this->getMode('out_equal')) {
            $this->outIf(
                $ok,
                Locale::getMessage(
                    'IB_PROPERTY_EQUAL',
                    [
                        '#IBLOCK_ID#' => $iblockId,
                        '#NAME#'      => $fields['CODE'],
                    ]
                )
            );
        }
        return $ok;
    }

    /**
     * Получает свойство инфоблока
     *
     * @param $iblockId
     * @param $code int|array - код или фильтр
     *
     * @return array|bool
     */
    public function getProperty($iblockId, $code)
    {
        /** @compatibility filter or code */
        $filter = is_array($code)
            ? $code
            : [
                'CODE' => $code,
            ];

        $filter['IBLOCK_ID'] = $iblockId;
        $filter['CHECK_PERMISSIONS'] = 'N';
        /* do not use =CODE in filter */
        $property = CIBlockProperty::GetList(['SORT' => 'ASC'], $filter)->Fetch();
        return $this->prepareProperty($property);
    }

    /**
     * Получает значения списков для свойств инфоблоков
     *
     * @param array $filter
     *
     * @return array
     */
    public function getPropertyEnums($filter = [])
    {
        $result = [];
        $dbres = CIBlockPropertyEnum::GetList(
            [
                'SORT'  => 'ASC',
                'VALUE' => 'ASC',
            ], $filter
        );
        while ($item = $dbres->Fetch()) {
            $result[] = $item;
        }
        return $result;
    }

    public function getPropertyFeatures($propertyId)
    {
        if (!class_exists('\Bitrix\Iblock\Model\PropertyFeature')) {
            return [];
        }
        if (!class_exists('\Bitrix\Iblock\PropertyFeatureTable')) {
            return [];
        }

        $features = [];
        try {
            if (PropertyFeature::isEnabledFeatures()) {
                $features = PropertyFeatureTable::getList([
                    'select' => ['ID', 'MODULE_ID', 'FEATURE_ID', 'IS_ENABLED'],
                    'filter' => ['=PROPERTY_ID' => (int)$propertyId],
                ])->fetchAll();
            }
        } catch (Exception $e) {
        }

        return $features;
    }

    /**
     * Получает значения списков для свойства инфоблока
     *
     * @param $iblockId
     * @param $propertyId
     *
     * @return array
     */
    public function getPropertyEnumValues($iblockId, $propertyId)
    {
        return $this->getPropertyEnums(
            [
                'IBLOCK_ID'   => $iblockId,
                'PROPERTY_ID' => $propertyId,
            ]
        );
    }

    /**
     * Получает свойство инфоблока
     *
     * @param $iblockId
     * @param $code int|array - код или фильтр
     *
     * @return int
     */
    public function getPropertyId($iblockId, $code)
    {
        $item = $this->getProperty($iblockId, $code);
        return ($item && isset($item['ID'])) ? $item['ID'] : 0;
    }

    /**
     * Получает свойства инфоблока
     *
     * @param       $iblockId
     * @param array $filter
     *
     * @return array
     */
    public function getProperties($iblockId, $filter = [])
    {
        $filter['IBLOCK_ID'] = $iblockId;
        $filter['CHECK_PERMISSIONS'] = 'N';

        $filterIds = false;
        if (isset($filter['ID']) && is_array($filter['ID'])) {
            $filterIds = $filter['ID'];
            unset($filter['ID']);
        }

        $dbres = CIBlockProperty::GetList(['SORT' => 'ASC'], $filter);

        $result = [];

        while ($property = $dbres->Fetch()) {
            if ($filterIds) {
                if (in_array($property['ID'], $filterIds)) {
                    $result[] = $this->prepareProperty($property);
                }
            } else {
                $result[] = $this->prepareProperty($property);
            }
        }
        return $result;
    }

    /**
     * Добавляет свойство инфоблока если его не существует
     *
     * @param int   $iblockId
     * @param array $fields
     *
     * @throws HelperException
     * @return bool
     */
    public function addPropertyIfNotExists($iblockId, $fields)
    {
        $this->checkRequiredKeys(__METHOD__, $fields, ['CODE']);

        $property = $this->getProperty($iblockId, $fields['CODE']);
        if ($property) {
            return $property['ID'];
        }

        return $this->addProperty($iblockId, $fields);
    }

    /**
     * Добавляет свойство инфоблока
     *
     * @param $iblockId
     * @param $fields
     *
     * @throws HelperException
     * @return int|void
     */
    public function addProperty($iblockId, $fields)
    {
        $default = [
            'NAME'           => '',
            'ACTIVE'         => 'Y',
            'SORT'           => '500',
            'CODE'           => '',
            'PROPERTY_TYPE'  => 'S',
            'USER_TYPE'      => '',
            'ROW_COUNT'      => '1',
            'COL_COUNT'      => '30',
            'LIST_TYPE'      => 'L',
            'MULTIPLE'       => 'N',
            'IS_REQUIRED'    => 'N',
            'FILTRABLE'      => 'Y',
            'LINK_IBLOCK_ID' => 0,
        ];

        if (!empty($fields['VALUES'])) {
            $default['PROPERTY_TYPE'] = 'L';
        }

        if (!empty($fields['LINK_IBLOCK_ID'])) {
            $default['PROPERTY_TYPE'] = 'E';
        }

        $fields = array_replace_recursive($default, $fields);

        if (false !== strpos($fields['PROPERTY_TYPE'], ':')) {
            list($ptype, $utype) = explode(':', $fields['PROPERTY_TYPE']);
            $fields['PROPERTY_TYPE'] = $ptype;
            $fields['USER_TYPE'] = $utype;
        }

        if (false !== strpos($fields['LINK_IBLOCK_ID'], ':')) {
            $fields['LINK_IBLOCK_ID'] = $this->getIblockIdByUid($fields['LINK_IBLOCK_ID']);
        }

        $fields['IBLOCK_ID'] = $iblockId;

        $ib = new CIBlockProperty;
        $propertyId = $ib->Add($fields);

        if ($propertyId) {
            return $propertyId;
        }

        $this->throwException(__METHOD__, $ib->LAST_ERROR);
    }

    /**
     * Удаляет свойство инфоблока если оно существует
     *
     * @param $iblockId
     * @param $code
     *
     * @throws HelperException
     * @return bool|void
     */
    public function deletePropertyIfExists($iblockId, $code)
    {
        $property = $this->getProperty($iblockId, $code);
        if (!$property) {
            return false;
        }

        return $this->deletePropertyById($property['ID']);
    }

    /**
     * Удаляет свойство инфоблока
     *
     * @param $propertyId
     *
     * @throws HelperException
     * @return bool|void
     */
    public function deletePropertyById($propertyId)
    {
        $ib = new CIBlockProperty;
        if ($ib->Delete($propertyId)) {
            return true;
        }

        $this->throwException(__METHOD__, $ib->LAST_ERROR);
    }

    /**
     * Обновляет свойство инфоблока если оно существует
     *
     * @param $iblockId
     * @param $code
     * @param $fields
     *
     * @throws HelperException
     * @return bool|int|void
     */
    public function updatePropertyIfExists($iblockId, $code, $fields)
    {
        $property = $this->getProperty($iblockId, $code);
        if (!$property) {
            return false;
        }
        return $this->updatePropertyById($property['ID'], $fields);
    }

    /**
     * Обновляет свойство инфоблока
     *
     * @param $propertyId
     * @param $fields
     *
     * @throws HelperException
     * @return int|void
     */
    public function updatePropertyById($propertyId, $fields)
    {
        if (!empty($fields['VALUES']) && !isset($fields['PROPERTY_TYPE'])) {
            $fields['PROPERTY_TYPE'] = 'L';
        }

        if (!empty($fields['LINK_IBLOCK_ID']) && !isset($fields['PROPERTY_TYPE'])) {
            $fields['PROPERTY_TYPE'] = 'E';
        }

        if (false !== strpos($fields['PROPERTY_TYPE'], ':')) {
            list($ptype, $utype) = explode(':', $fields['PROPERTY_TYPE']);
            $fields['PROPERTY_TYPE'] = $ptype;
            $fields['USER_TYPE'] = $utype;
        }

        if (false !== strpos($fields['LINK_IBLOCK_ID'], ':')) {
            $fields['LINK_IBLOCK_ID'] = $this->getIblockIdByUid($fields['LINK_IBLOCK_ID']);
        }

        if (isset($fields['VALUES']) && is_array($fields['VALUES'])) {
            $existsEnums = $this->getPropertyEnums(
                [
                    'PROPERTY_ID' => $propertyId,
                ]
            );

            $newValues = [];
            foreach ($fields['VALUES'] as $index => $item) {
                foreach ($existsEnums as $existsEnum) {
                    if ($existsEnum['XML_ID'] == $item['XML_ID']) {
                        $item['ID'] = $existsEnum['ID'];
                        break;
                    }
                }

                if (!empty($item['ID'])) {
                    $newValues[$item['ID']] = $item;
                } else {
                    $newValues['n' . $index] = $item;
                }
            }

            $fields['VALUES'] = $newValues;
        }

        $ib = new CIBlockProperty();
        if ($ib->Update($propertyId, $fields)) {
            return $propertyId;
        }

        $this->throwException(__METHOD__, $ib->LAST_ERROR);
    }

    /**
     * Получает свойство инфоблока
     * Данные подготовлены для экспорта в миграцию или схему
     *
     * @param      $iblockId
     * @param bool $code
     *
     * @throws HelperException
     * @return array|void
     */
    public function exportProperty($iblockId, $code = false)
    {
        $export = $this->prepareExportProperty(
            $this->getProperty($iblockId, $code)
        );

        if (!empty($export['CODE'])) {
            return $export;
        }

        $this->throwException(
            __METHOD__,
            Locale::getMessage(
                'ERR_IB_PROPERTY_CODE_NOT_FOUND'
            )
        );
    }

    /**
     * Получает свойства инфоблока
     * Данные подготовлены для экспорта в миграцию или схему
     *
     * @param       $iblockId
     * @param array $filter
     *
     * @return array
     */
    public function exportProperties($iblockId, $filter = [])
    {
        $exports = [];
        $items = $this->getProperties($iblockId, $filter);
        foreach ($items as $item) {
            if (!empty($item['CODE'])) {
                if (!empty($item['LINK_IBLOCK_ID'])) {
                    try {
                        $item['LINK_IBLOCK_ID'] = $this->getIblockUid($item['LINK_IBLOCK_ID']);
                    } catch (HelperException $e) {
                        continue;
                    }
                }
                $exports[] = $this->prepareExportProperty($item);
            }
        }
        return $exports;
    }

    /**
     * @param $iblockId
     * @param $code
     *
     * @throws HelperException
     * @return bool
     * @deprecated
     */
    public function deleteProperty($iblockId, $code)
    {
        return $this->deletePropertyIfExists($iblockId, $code);
    }

    /**
     * @param $iblockId
     * @param $code
     * @param $fields
     *
     * @throws HelperException
     * @return bool|mixed
     * @deprecated
     */
    public function updateProperty($iblockId, $code, $fields)
    {
        return $this->updatePropertyIfExists($iblockId, $code, $fields);
    }

    public function getPropertyType($iblockId, $code)
    {
        $prop = $this->getProperty($iblockId, $code);
        return $prop['PROPERTY_TYPE'];
    }

    public function getPropertyLinkIblockId($iblockId, $code)
    {
        $prop = $this->getProperty($iblockId, $code);
        return $prop['LINK_IBLOCK_ID'];
    }

    public function isPropertyMultiple($iblockId, $code)
    {
        $prop = $this->getProperty($iblockId, $code);
        return ($prop['MULTIPLE'] == 'Y');
    }

    public function getPropertyEnumIdByXmlId($iblockId, $code, $xmlId)
    {
        $prop = $this->getProperty($iblockId, $code);
        if (empty($prop['VALUES']) || !is_array($prop['VALUES'])) {
            return '';
        }

        foreach ($prop['VALUES'] as $val) {
            if ($val['XML_ID'] == $xmlId) {
                return $val['ID'];
            }
        }
        return '';
    }

    protected function prepareProperty($property)
    {
        if (!empty($property['ID']) && !empty($property['IBLOCK_ID'])) {
            if ($property['PROPERTY_TYPE'] == 'L') {
                $property['VALUES'] = $this->getPropertyEnums(
                    [
                        'IBLOCK_ID'   => $property['IBLOCK_ID'],
                        'PROPERTY_ID' => $property['ID'],
                    ]
                );
            }

            $features = $this->getPropertyFeatures($property['ID']);
            if (!empty($features)) {
                $property['FEATURES'] = $features;
            }
        }

        return $property;
    }

    protected function prepareExportProperty($prop)
    {
        if (empty($prop)) {
            return $prop;
        }

        if (!empty($prop['VALUES']) && is_array($prop['VALUES'])) {
            $exportValues = [];

            foreach ($prop['VALUES'] as $item) {
                $exportValues[] = [
                    'VALUE'  => $item['VALUE'],
                    'DEF'    => $item['DEF'],
                    'SORT'   => $item['SORT'],
                    'XML_ID' => $item['XML_ID'],
                ];
            }

            $prop['VALUES'] = $exportValues;
        }

        if (!empty($prop['FEATURES']) && is_array($prop['FEATURES'])) {
            $exportFeatures = [];
            foreach ($prop['FEATURES'] as $item) {
                $exportFeatures[] = [
                    'MODULE_ID'  => $item['MODULE_ID'],
                    'FEATURE_ID' => $item['FEATURE_ID'],
                    'IS_ENABLED' => $item['IS_ENABLED'],
                ];
            }

            $prop['FEATURES'] = $exportFeatures;
        }

        if (!empty($prop['LINK_IBLOCK_ID'])) {
            $prop['LINK_IBLOCK_ID'] = $this->getIblockUid($prop['LINK_IBLOCK_ID']);
        }

        unset($prop['ID']);
        unset($prop['IBLOCK_ID']);
        unset($prop['TIMESTAMP_X']);
        unset($prop['TMP_ID']);

        return $prop;
    }
}


text:
'use strict';

angular.module('directives.date-range-picker', [])

  .directive('dateRangePicker', function () {
    return {
      restrict: 'E',
      templateUrl: 'views/components/date-range-picker.html',
      scope: {
        startDate: '=',
        endDate: '=',
        onRangeChange: '&onRangeChange'
      },
      replace: true,
      link: function ($scope, elem, attr) {

        angular.element('#date-range-start').datetimepicker();
        angular.element('#date-range-end').datetimepicker();
        angular.element('#date-range-start').on("dp.change",function (e) {
          angular.element('#date-range-end').data("DateTimePicker").setMinDate(e.date);
          $scope.startDate = new Date(e.date);
        });
        angular.element('#date-range-end').on("dp.change",function (e) {
          angular.element('#date-range-start').data("DateTimePicker").setMaxDate(e.date);
          $scope.endDate = new Date(e.date);
        });

        $scope.$watch(function () {
          return $scope.startDate;
        }, function () {
          $scope.onRangeChange();
        }, true);
        $scope.$watch(function () {
          return $scope.endDate;
        }, function () {
          $scope.onRangeChange();
        }, true);

        $scope.openDateRangePicker = function() {

        }
      }
    }
  });


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

public class BReceptionRoom : BuildableRoom{

    public List<BuildableReception> frontdesks = new List<BuildableReception>();
    protected Dictionary<int, AIBase> receptionists = new Dictionary<int, AIBase>();

    public List<Type> placeableItems = new List<Type>
    {
        typeof(BuildableReception)
    };

    public BuildableReception assignReceptionist(ReceptionistAI ai)
    {
        for(int i = 0; i < frontdesks.Count; i++)
        {
            if( !receptionists.ContainsKey(i))
            {
                receptionists.Add(i, ai);
                return frontdesks[i];
            }
        }

        return null;
    }

    public AIBase getReceptionist(int index)
    {
        if (receptionists.ContainsKey(index))
        {
            return receptionists[index];
        }
        else
        {
            return null;
        }
    }

    public Dictionary<Type, int> requiredItems = new Dictionary<Type, int>
    {
        { typeof(BuildableReception),1 } // Requires 1 front desk
    };

    public override bool canBeBuilt()
    {
        return doors.Count > 0 && selectionScript.isValid();
    }

    public override List<Type> getPlaceableItems()
    {
        return placeableItems;
    }

    public override void RemoveItem(BuildableItem item)
    {
        base.RemoveItem(item);
        if (item is BuildableReception)
        {
            frontdesks.Remove((BuildableReception)item);
        }

    }

    public override Dictionary<Type, int> getRequiredItems()
    {
        return requiredItems;
    }

    public BuildableReception getFrontDesk(int index)
    {
        return frontdesks[index];
    }

    protected override void addItem(BuildableItem item)
    {
        Debug.Log("Added item " + item);
        base.addItem(item);
        Debug.Log("Added item2 " + item);
        if (item is BuildableReception)
        {
            Debug.Log("Was Reception");
            frontdesks.Add((BuildableReception)item);
        }
    }

    public static BReceptionRoom Create(int x, int y, int width, int height, int frontDeskX, int frontDeskY, int frontDeskRotation, List<DDoor> doorPositions)
    {
        Vector3 position = new Vector3(x, 0, y);
        Vector3 size = new Vector3(width, 0, height);
        BReceptionRoom room = (BReceptionRoom)ScriptableObject.CreateInstance<BReceptionRoom>().Create(position, size);

        BuildableReception frontDesk = (BuildableReception)ScriptableObject.CreateInstance<BuildableReception>().Create(frontDeskX,frontDeskY);
        frontDesk.rotation = Quaternion.Euler(0, frontDeskRotation, 0);
        room.addItem(frontDesk);

        room.doors.AddRange(doorPositions);

        return room;
    }
}


text:
'use strict';
module.exports = {
    config: {
        modifierKeys: {altIsMeta: true},

        windowSize: [1000, 600],

        // default font size in pixels for all tabs
        fontSize: 16,

        // font family with optional fallbacks
        fontFamily: '"ADejaVuSansMonoForPowerline Nerd Font", PingFangSC-Regular, DejaVuSansMono, Consolas',
        uiFontFamily: '"ADejaVuSansMonoForPowerline Nerd Font", PingFangSC-Regular, DejaVuSansMono, Consolas',

        // `BEAM` for |, `UNDERLINE` for _, `BLOCK` for █
        cursorShape: 'BEAM',
        cursorBlink: true,

        // terminal cursor background color and opacity (hex, rgb, hsl, hsv, hwb or cmyk)
        cursorColor: 'rgba(255, 255, 255, 0.8)',
        foregroundColor: '#cdcdcd',
        backgroundColor: '#0b0b0ce6',

        // border color (window, tabs)
        borderColor: '#222',

        // custom css to embed in the main window
        css: '',

        // custom css to embed in the terminal window
        // termCSS: '',
        // termCSS: '.wc-node.unicode-node{width: 1em}',

        // set to `true` if you're using a Linux set up
        // that doesn't shows native menus
        // default: `false` on Linux, `true` on Windows (ignored on macOS)
        showHamburgerMenu: '',

        // set to `false` if you want to hide the minimize, maximize and close buttons
        // additionally, set to `'left'` if you want them on the left, like in Ubuntu
        // default: `true` on windows and Linux (ignored on macOS)
        showWindowControls: '',

        // custom padding (css format, i.e.: `top right bottom left`)
        padding: '0px 8px 0px 8px',

        // the full list. if you're going to provide the full color palette,
        // including the 6 x 6 color cubes and the grayscale map, just provide
        // an array here instead of a color map object
        colors: {
            black: '#000000',
            red: '#e12000',
            green: '#00db1a',
            yellow: '#e1c731',
            blue: '#6980ff',
            magenta: '#bf6ee1',
            cyan: '#5dd9e1',
            white: '#e6e6e6',
            lightBlack: '#666666',
            lightRed: '#ff2600',
            lightGreen: '#00f91e',
            lightYellow: '#ffe037',
            lightBlue: '#afbaff',
            lightMagenta: '#e7afff',
            lightCyan: '#9bf9ff',
            lightWhite: '#ffffff',
            // colorCubes,
            // grayscale,
        },

        // the shell to run when spawning a new session (i.e. /usr/local/bin/fish)
        // if left empty, your system's login shell will be used by default
        shell: '/usr/local/bin/bash',

        // for setting shell arguments (i.e. for using interactive shellArgs: ['-i'])
        // by default ['--login'] will be used
        shellArgs: ['--login'],

        // for environment variables
        env: {
            // PS1_SIGNATURE: '$',
        },

        // set to false for no bell
        bell: 'SOUND',

        // if true, selected text will automatically be copied to the clipboard
        copyOnSelect: false,

        // URL to custom bell
        // bellSoundURL: 'http://example.com/bell.mp3',

        // for advanced config flags please refer to https://hyper.is/#cfg

        // plugin configs:
        confirmQuit: true,
        hyperCat: {
            staggerHeight: 2, // The number of pixels the cat and rainbow should jump up and down.
            rainbowMaxAlpha: 0.6, // The max opacity of the rainbow.
            audioEnabled: false, // Whether audio should play while typing.
        },
        catCursor: {
            speed: 4000, // length of the sequence in milliseconds
            // fontSize: 60, // font size of the cat in css pixels
            // cats: ['😐', '😑'],
            cats: ['😺', '😸'],
            // cats: ['🌎', '🌍', '🌏'],
            // cats: ['🐱', '🙀', '😾', '😿', '😹', '😼', '😺', '😻', '😸', '😽'] // custom cat sequence. only cats are accepted, of course
        },
    },

    // a list of plugins to fetch and install from npm
    // format: [@org/]project[#version]
    // examples:
    //   `hyperpower`
    //   `@company/project`
    //   `project#1.0.1`
    plugins: [
        // 'prop-types',
        // 'react',
        // 'hyperline',  // 依赖 prop-types, react
        'hypergravity',
        // 'hyper-cat-cursor',
        'hyper-match',
        'hyper-search',
        // 'hyper-cat',  // 警告:有猫
        'hypercwd',
        // 'hyper-confirm',
        // 'hyperpower',
    ],

    npmRegistry: 'https://registry.npm.taobao.org/',

    // in development, you can create a directory under
    // `~/.hyper_plugins/local/` and include it here
    // to load it and avoid it being `npm install`ed
    localPlugins: [],
};


text:
package org.synyx.urlaubsverwaltung.workingtime;

import de.focus_shift.HolidayManager;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.synyx.urlaubsverwaltung.absence.DateRange;
import org.synyx.urlaubsverwaltung.person.Person;
import org.synyx.urlaubsverwaltung.publicholiday.PublicHolidaysServiceImpl;
import org.synyx.urlaubsverwaltung.settings.Settings;
import org.synyx.urlaubsverwaltung.settings.SettingsService;

import java.math.BigDecimal;
import java.net.URL;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;

import static de.focus_shift.ManagerParameters.create;
import static java.math.BigDecimal.TEN;
import static java.time.DayOfWeek.FRIDAY;
import static java.time.DayOfWeek.MONDAY;
import static java.time.DayOfWeek.SATURDAY;
import static java.time.DayOfWeek.THURSDAY;
import static java.time.DayOfWeek.TUESDAY;
import static java.time.DayOfWeek.WEDNESDAY;
import static java.time.Month.DECEMBER;
import static java.time.Month.JANUARY;
import static java.time.Month.NOVEMBER;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
import static org.synyx.urlaubsverwaltung.period.DayLength.FULL;
import static org.synyx.urlaubsverwaltung.period.DayLength.MORNING;
import static org.synyx.urlaubsverwaltung.period.DayLength.NOON;
import static org.synyx.urlaubsverwaltung.workingtime.FederalState.GERMANY_BADEN_WUERTTEMBERG;

@ExtendWith(MockitoExtension.class)
class WorkDaysCountServiceTest {

    private WorkDaysCountService sut;

    @Mock
    private WorkingTimeService workingTimeService;
    @Mock
    private SettingsService settingsService;

    @BeforeEach
    void setUp() {
        final var publicHolidaysService = new PublicHolidaysServiceImpl(settingsService, Map.of("de", getHolidayManager()));
        sut = new WorkDaysCountService(publicHolidaysService, workingTimeService);
    }

    @Test
    void getWeekDays() {

        final LocalDate startDate = LocalDate.of(2011, 11, 16);
        final LocalDate endDate = LocalDate.of(2011, 11, 28);

        final double weekDaysCount = sut.getWeekDaysCount(startDate, endDate);
        assertThat(weekDaysCount).isEqualTo(9.0);
    }

    @Test
    void getWorkDaysWithPublicHolidaysAndBothOnWeekend() {

        when(settingsService.getSettings()).thenReturn(new Settings());

        final Person person = new Person("muster", "Muster", "Marlene", "muster@example.org");
        final LocalDate startDate = LocalDate.of(2010, 12, 17);
        final LocalDate endDate = LocalDate.of(2010, 12, 31);

        final WorkingTime workingTime = createWorkingTime(person, startDate, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY);
        when(workingTimeService.getWorkingTimesByPersonAndDateRange(eq(person), any(DateRange.class))).thenReturn(Map.of(new DateRange(startDate, endDate), workingTime));

        // Testing for 2010: 17.12. is Friday, 31.12. is Friday
        // between these dates:
        //   Public Holidays : 2 (25., 26.) and 2*0.5 (24., 31.) => 3
        //   Weekends : 2 (18-19 and 25-26 - already public holidays)) => 2
        // total days: 15
        // netto days: 10 (considering public holidays and weekends)
        final BigDecimal workDaysCount = sut.getWorkDaysCount(FULL, startDate, endDate, person);
        assertThat(workDaysCount).isEqualByComparingTo(TEN);
    }

    @Test
    void getWorkDaysWithPublicHolidaysAndOneOnWeekend() {

        when(settingsService.getSettings()).thenReturn(new Settings());

        final Person person = new Person("muster", "Muster", "Marlene", "muster@example.org");
        final LocalDate startDate = LocalDate.of(2009, 12, 17);
        final LocalDate endDate = LocalDate.of(2009, 12, 31);

        final WorkingTime workingTime = createWorkingTime(person, startDate, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY);
        when(workingTimeService.getWorkingTimesByPersonAndDateRange(eq(person), any(DateRange.class))).thenReturn(Map.of(new DateRange(startDate, endDate), workingTime));

        // Testing for 2009: 17.12. is Thursday, 31.12. ist Thursday
        // between these dates:
        //   Public Holidays : 2 (25., 26.) and 2*0.5 (24., 31.) => 3
        //   Weekends : 2 (19-20 and 26-27 - one is already public holidays)) => 3
        // total days: 15
        // netto days: 9 (considering public holidays and weekends)
        final BigDecimal workDaysCount = sut.getWorkDaysCount(FULL, startDate, endDate, person);
        assertThat(workDaysCount).isEqualByComparingTo(BigDecimal.valueOf(9));
    }

    @Test
    void getWorkDaysWithMultipleWorkingTimesOverOneAbsence() {

        when(settingsService.getSettings()).thenReturn(new Settings());

        final Person person = new Person("muster", "Muster", "Marlene", "muster@example.org");
        final LocalDate startDate = LocalDate.of(2022, 1, 10);
        final LocalDate midDate = LocalDate.of(2022, 1, 17);
        final LocalDate endDate = LocalDate.of(2022, 1, 23);

        final WorkingTime workingTimeFullWeek = createWorkingTime(person, startDate, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY);
        final WorkingTime workingTimeHalfWeek = createWorkingTime(person, midDate, MONDAY, TUESDAY, WEDNESDAY);
        when(workingTimeService.getWorkingTimesByPersonAndDateRange(eq(person), any(DateRange.class)))
            .thenReturn(Map.of(
                new DateRange(startDate, midDate.minusDays(1)), workingTimeFullWeek,
                new DateRange(midDate, endDate), workingTimeHalfWeek
            ));

        final BigDecimal workDaysCount = sut.getWorkDaysCount(FULL, startDate, endDate, person);
        assertThat(workDaysCount).isEqualByComparingTo(BigDecimal.valueOf(8));
    }

    @Test
    void getWorkDaysWithHalfDayMorning() {

        when(settingsService.getSettings()).thenReturn(new Settings());

        final Person person = new Person("muster", "Muster", "Marlene", "muster@example.org");
        final LocalDate startDate = LocalDate.of(2011, 1, 4);
        final LocalDate endDate = LocalDate.of(2011, 1, 4);

        final WorkingTime workingTime = createWorkingTime(person, startDate, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY);
        when(workingTimeService.getWorkingTimesByPersonAndDateRange(eq(person), any(DateRange.class))).thenReturn(Map.of(new DateRange(startDate, endDate), workingTime));

        final BigDecimal workDaysCount = sut.getWorkDaysCount(MORNING, startDate, endDate, person);
        assertThat(workDaysCount).isEqualByComparingTo(BigDecimal.valueOf(0.5));
    }

    @Test
    void getWorkDaysWithHalfDaysMorning() {

        when(settingsService.getSettings()).thenReturn(new Settings());

        final Person person = new Person("muster", "Muster", "Marlene", "muster@example.org");
        final LocalDate startDate = LocalDate.of(2011, 1, 4);
        final LocalDate endDate = LocalDate.of(2011, 1, 8);

        final WorkingTime workingTime = createWorkingTime(person, startDate, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY);
        when(workingTimeService.getWorkingTimesByPersonAndDateRange(eq(person), any(DateRange.class))).thenReturn(Map.of(new DateRange(startDate, endDate), workingTime));

        final BigDecimal workDaysCount = sut.getWorkDaysCount(MORNING, startDate, endDate, person);
        assertThat(workDaysCount).isEqualByComparingTo(BigDecimal.valueOf(1.5));
    }

    @Test
    void getWorkDaysWithHalfDayNoon() {

        when(settingsService.getSettings()).thenReturn(new Settings());

        final Person person = new Person("muster", "Muster", "Marlene", "muster@example.org");
        final LocalDate startDate = LocalDate.of(2011, 1, 4);
        final LocalDate endDate = LocalDate.of(2011, 1, 4);

        final WorkingTime workingTime = createWorkingTime(person, startDate, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY);
        when(workingTimeService.getWorkingTimesByPersonAndDateRange(eq(person), any(DateRange.class))).thenReturn(Map.of(new DateRange(startDate, endDate), workingTime));

        final BigDecimal workDaysCount = sut.getWorkDaysCount(NOON, startDate, endDate, person);
        assertThat(workDaysCount).isEqualByComparingTo(BigDecimal.valueOf(0.5));
    }

    @Test
    void getWorkDaysWithHalfDaysNoon() {

        when(settingsService.getSettings()).thenReturn(new Settings());

        final Person person = new Person("muster", "Muster", "Marlene", "muster@example.org");
        final LocalDate startDate = LocalDate.of(2011, 1, 4);
        final LocalDate endDate = LocalDate.of(2011, 1, 8);

        final WorkingTime workingTime = createWorkingTime(person, startDate, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY);
        when(workingTimeService.getWorkingTimesByPersonAndDateRange(eq(person), any(DateRange.class))).thenReturn(Map.of(new DateRange(startDate, endDate), workingTime));

        final BigDecimal workDaysCount = sut.getWorkDaysCount(NOON, startDate, endDate, person);
        assertThat(workDaysCount).isEqualByComparingTo(BigDecimal.valueOf(1.5));
    }

    @Test
    void getWorkDaysWithSundayToSaturday() {

        when(settingsService.getSettings()).thenReturn(new Settings());

        final Person person = new Person("muster", "Muster", "Marlene", "muster@example.org");
        // start date is Sunday, end date Saturday
        final LocalDate startDate = LocalDate.of(2011, 1, 2);
        final LocalDate endDate = LocalDate.of(2011, 1, 8);

        final WorkingTime workingTime = createWorkingTime(person, startDate, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY);
        when(workingTimeService.getWorkingTimesByPersonAndDateRange(eq(person), any(DateRange.class))).thenReturn(Map.of(new DateRange(startDate, endDate), workingTime));

        final BigDecimal workDaysCount = sut.getWorkDaysCount(FULL, startDate, endDate, person);
        assertThat(workDaysCount).isEqualByComparingTo(BigDecimal.valueOf(4));
    }

    @Test
    void getWorkDaysWithPublicHolidaysOverLabourDay() {

        when(settingsService.getSettings()).thenReturn(new Settings());

        final Person person = new Person("muster", "Muster", "Marlene", "muster@example.org");
        // Labour Day (1st May)
        final LocalDate startDate = LocalDate.of(2009, 4, 27);
        final LocalDate endDate = LocalDate.of(2009, 5, 2);

        final WorkingTime workingTime = createWorkingTime(person, startDate, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY);
        when(workingTimeService.getWorkingTimesByPersonAndDateRange(eq(person), any(DateRange.class))).thenReturn(Map.of(new DateRange(startDate, endDate), workingTime));

        final BigDecimal workDaysCount = sut.getWorkDaysCount(FULL, startDate, endDate, person);
        assertThat(workDaysCount).isEqualByComparingTo(BigDecimal.valueOf(4));
    }

    @Test
    void getWorkDaysWithPublicHolidaysOverYears() {

        when(settingsService.getSettings()).thenReturn(new Settings());

        final Person person = new Person("muster", "Muster", "Marlene", "muster@example.org");
        // start date and end date are not in the same year
        final LocalDate startDate = LocalDate.of(2011, 12, 26);
        final LocalDate endDate = LocalDate.of(2012, 1, 15);

        final WorkingTime workingTime = createWorkingTime(person, startDate, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY);
        when(workingTimeService.getWorkingTimesByPersonAndDateRange(eq(person), any(DateRange.class))).thenReturn(Map.of(new DateRange(startDate, endDate), workingTime));

        final BigDecimal workDaysCount = sut.getWorkDaysCount(FULL, startDate, endDate, person);
        assertThat(workDaysCount).isEqualByComparingTo(BigDecimal.valueOf(13));
    }

    @Test
    void testGetWorkDaysForTeilzeitPersons() {

        when(settingsService.getSettings()).thenReturn(new Settings());

        final Person person = new Person("muster", "Muster", "Marlene", "muster@example.org");

        final LocalDate startDate = LocalDate.of(2013, DECEMBER, 16);
        final LocalDate endDate = LocalDate.of(2013, DECEMBER, 31);

        final WorkingTime workingTime = createWorkingTime(person, startDate, MONDAY, WEDNESDAY, FRIDAY, SATURDAY);
        when(workingTimeService.getWorkingTimesByPersonAndDateRange(eq(person), any(DateRange.class))).thenReturn(Map.of(new DateRange(startDate, endDate), workingTime));

        final BigDecimal workDaysCount = sut.getWorkDaysCount(FULL, startDate, endDate, person);
        assertThat(workDaysCount).isEqualByComparingTo(BigDecimal.valueOf(8));
    }

    @Test
    void testGetWorkDaysForVollzeitPersons() {

        when(settingsService.getSettings()).thenReturn(new Settings());

        final Person person = new Person("muster", "Muster", "Marlene", "muster@example.org");
        final LocalDate startDate = LocalDate.of(2013, DECEMBER, 16);
        final LocalDate endDate = LocalDate.of(2013, DECEMBER, 31);

        final WorkingTime workingTime = createWorkingTime(person, startDate, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY);
        when(workingTimeService.getWorkingTimesByPersonAndDateRange(eq(person), any(DateRange.class))).thenReturn(Map.of(new DateRange(startDate, endDate), workingTime));

        final BigDecimal workDaysCount = sut.getWorkDaysCount(FULL, startDate, endDate, person);
        assertThat(workDaysCount).isEqualByComparingTo(BigDecimal.valueOf(9));
    }

    @Test
    void testGetWorkDaysHalfDay() {

        when(settingsService.getSettings()).thenReturn(new Settings());

        final Person person = new Person("muster", "Muster", "Marlene", "muster@example.org");

        // monday
        final LocalDate startDate = LocalDate.of(2013, NOVEMBER, 25);
        final LocalDate endDate = LocalDate.of(2013, NOVEMBER, 25);

        final WorkingTime workingTime = createWorkingTime(person, startDate, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY);
        when(workingTimeService.getWorkingTimesByPersonAndDateRange(eq(person), any(DateRange.class))).thenReturn(Map.of(new DateRange(startDate, endDate), workingTime));

        final BigDecimal workDaysCount = sut.getWorkDaysCount(MORNING, startDate, endDate, person);
        assertThat(workDaysCount).isEqualByComparingTo(BigDecimal.valueOf(0.5));
    }

    @Test
    void testGetWorkDaysZero() {

        when(settingsService.getSettings()).thenReturn(new Settings());

        final Person person = new Person("muster", "Muster", "Marlene", "muster@example.org");

        // saturday
        final LocalDate startDate = LocalDate.of(2013, NOVEMBER, 23);
        final LocalDate endDate = LocalDate.of(2013, NOVEMBER, 23);

        final WorkingTime workingTime = createWorkingTime(person, startDate, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY);
        when(workingTimeService.getWorkingTimesByPersonAndDateRange(eq(person), any(DateRange.class))).thenReturn(Map.of(new DateRange(startDate, endDate), workingTime));

        final BigDecimal workDaysCount = sut.getWorkDaysCount(FULL, startDate, endDate, person);
        assertThat(workDaysCount).isEqualByComparingTo(BigDecimal.ZERO);
    }

    @Test
    void testGetWorkDaysHalfDayZero() {

        when(settingsService.getSettings()).thenReturn(new Settings());

        final Person person = new Person("muster", "Muster", "Marlene", "muster@example.org");

        // Saturday
        final LocalDate date = LocalDate.of(2013, NOVEMBER, 23);

        final WorkingTime workingTime = createWorkingTime(person, date, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY);
        when(workingTimeService.getWorkingTimesByPersonAndDateRange(eq(person), any(DateRange.class))).thenReturn(Map.of(new DateRange(date, date), workingTime));

        final BigDecimal workDaysCount = sut.getWorkDaysCount(MORNING, date, date, person);
        assertThat(workDaysCount).isEqualByComparingTo(BigDecimal.ZERO);
    }

    @Test
    void testGetWorkDaysForChristmasEve() {

        when(settingsService.getSettings()).thenReturn(new Settings());

        final Person person = new Person("muster", "Muster", "Marlene", "muster@example.org");
        final LocalDate date = LocalDate.of(2013, DECEMBER, 24);

        final WorkingTime workingTime = createWorkingTime(person, date, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY);
        when(workingTimeService.getWorkingTimesByPersonAndDateRange(eq(person), any(DateRange.class))).thenReturn(Map.of(new DateRange(date, date), workingTime));

        final BigDecimal workDaysCount = sut.getWorkDaysCount(FULL, date, date, person);
        assertThat(workDaysCount).isEqualByComparingTo(BigDecimal.valueOf(0.5));
    }

    @Test
    void testGetWorkDaysForChristmasEveDayLengthMorning() {

        when(settingsService.getSettings()).thenReturn(new Settings());

        final Person person = new Person("muster", "Muster", "Marlene", "muster@example.org");
        final LocalDate date = LocalDate.of(2013, DECEMBER, 24);

        final WorkingTime workingTime = createWorkingTime(person, date, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY);
        when(workingTimeService.getWorkingTimesByPersonAndDateRange(eq(person), any(DateRange.class))).thenReturn(Map.of(new DateRange(date, date), workingTime));

        final BigDecimal workDaysCount = sut.getWorkDaysCount(MORNING, date, date, person);
        assertThat(workDaysCount).isEqualByComparingTo(BigDecimal.valueOf(0.5));
    }

    @Test
    void testGetWorkDaysForNewYearsEve() {

        when(settingsService.getSettings()).thenReturn(new Settings());

        final Person person = new Person("muster", "Muster", "Marlene", "muster@example.org");
        final LocalDate date = LocalDate.of(2013, DECEMBER, 31);

        final WorkingTime workingTime = createWorkingTime(person, date, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY);
        when(workingTimeService.getWorkingTimesByPersonAndDateRange(eq(person), any(DateRange.class))).thenReturn(Map.of(new DateRange(date, date), workingTime));

        final BigDecimal workDaysCount = sut.getWorkDaysCount(FULL, date, date, person);
        assertThat(workDaysCount).isEqualByComparingTo(BigDecimal.valueOf(0.5));
    }

    @Test
    void testGetWorkDaysForNewYearsEveDayLengthMorning() {

        when(settingsService.getSettings()).thenReturn(new Settings());

        final Person person = new Person("muster", "Muster", "Marlene", "muster@example.org");
        final LocalDate date = LocalDate.of(2013, DECEMBER, 31);

        final WorkingTime workingTime = createWorkingTime(person, date, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY);
        when(workingTimeService.getWorkingTimesByPersonAndDateRange(eq(person), any(DateRange.class))).thenReturn(Map.of(new DateRange(date, date), workingTime));

        final BigDecimal workDaysCount = sut.getWorkDaysCount(MORNING, date, date, person);
        assertThat(workDaysCount).isEqualByComparingTo(BigDecimal.valueOf(0.5));
    }

    @Test
    void testGetWorkDaysForChristmasEveAndNewYearsHoliday() {

        when(settingsService.getSettings()).thenReturn(new Settings());

        final Person person = new Person("muster", "Muster", "Marlene", "muster@example.org");
        final LocalDate startDate = LocalDate.of(2013, DECEMBER, 23);
        final LocalDate endDate = LocalDate.of(2014, JANUARY, 2);

        final WorkingTime workingTime = createWorkingTime(person, startDate, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY);
        when(workingTimeService.getWorkingTimesByPersonAndDateRange(eq(person), any(DateRange.class))).thenReturn(Map.of(new DateRange(startDate, endDate), workingTime));

        final BigDecimal workDaysCount = sut.getWorkDaysCount(FULL, startDate, endDate, person);
        assertThat(workDaysCount).isEqualByComparingTo(BigDecimal.valueOf(5));
    }

    @Test
    void testGetWorkDaysForChristmasEveAndNewYearsHolidayDayLengthMorning() {

        when(settingsService.getSettings()).thenReturn(new Settings());

        final Person person = new Person("muster", "Muster", "Marlene", "muster@example.org");
        final LocalDate startDate = LocalDate.of(2013, DECEMBER, 23);
        final LocalDate endDate = LocalDate.of(2014, JANUARY, 2);

        final WorkingTime workingTime = createWorkingTime(person, startDate, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY);
        when(workingTimeService.getWorkingTimesByPersonAndDateRange(eq(person), any(DateRange.class))).thenReturn(Map.of(new DateRange(startDate, endDate), workingTime));

        final BigDecimal workDaysCount = sut.getWorkDaysCount(MORNING, startDate, endDate, person);
        assertThat(workDaysCount).isEqualByComparingTo(BigDecimal.valueOf(2.5));
    }

    private HolidayManager getHolidayManager() {
        final ClassLoader cl = Thread.currentThread().getContextClassLoader();
        final URL url = cl.getResource("Holidays_de.xml");
        return HolidayManager.getInstance(create(url));
    }

    public static WorkingTime createWorkingTime(Person person, LocalDate validFrom, DayOfWeek... daysOfWeek) {
        final WorkingTime workingTime = new WorkingTime(person, validFrom, GERMANY_BADEN_WUERTTEMBERG, false);
        workingTime.setWorkingDays(List.of(daysOfWeek), FULL);
        return workingTime;
    }

}


text:
/*	$NetBSD: test.c,v 1.4 2011/08/30 20:29:41 joerg Exp $	*/

/*-
 * Copyright (c) 2002 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Christos Zoulas.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/cdefs.h>
#ifndef lint
__RCSID("$NetBSD: test.c,v 1.4 2011/08/30 20:29:41 joerg Exp $");
#endif

#include <stdio.h>
#include <netdb.h>
#include <string.h>
#include <err.h>

#include <rpc/rpc.h>
#include <rpcsvc/bootparam_prot.h>

/* Default timeout can be changed using clnt_control() */
static struct timeval TIMEOUT = {25, 0};

bp_whoami_res *
bootparamproc_whoami_1(bp_whoami_arg *argp, CLIENT *clnt)
{
	static bp_whoami_res res;
	enum clnt_stat st;

	(void)memset(&res, 0, sizeof(res));
	if ((st = clnt_call(clnt, BOOTPARAMPROC_WHOAMI, xdr_bp_whoami_arg, argp,
	    xdr_bp_whoami_res, &res, TIMEOUT)) != RPC_SUCCESS) {
		warnx("clnt_call returned %s", clnt_sperrno(st));
		return NULL;
	}
	return &res;
}

int
main(int argc, char **argv)
{
	CLIENT *cli;
	bp_whoami_res *out;
	bp_whoami_arg bp;
	struct hostent *hp;
	uint32_t addr;

	if (argc < 2) {
		warnx("usage: test <hostname>");
		errx(1, "Always talks to bootparamd at localhost");
	}
	if ((hp = gethostbyname(argv[1])) == NULL)
		errx(1, "Cannot resolve `%s'", argv[1]);

	printf("Creating client for localhost\n");
	cli = clnt_create("localhost", BOOTPARAMPROG, BOOTPARAMVERS, "udp");
	if (!cli)
		errx(1, "Failed to create client");
	memcpy(&addr, hp->h_addr_list[0], sizeof(addr));
	addr = htonl(addr);
	bp.client_address.address_type = IP_ADDR_TYPE;
	bp.client_address.bp_address_u.ip_addr.net = (addr >> 24) & 0xff;
	bp.client_address.bp_address_u.ip_addr.host = (addr >> 16) & 0xff;
	bp.client_address.bp_address_u.ip_addr.lh = (addr >> 8) & 0xff;
	bp.client_address.bp_address_u.ip_addr.impno = (addr >> 0) & 0xff;

	if ((out = bootparamproc_whoami_1(&bp, cli)) != NULL) {
		printf("Success [host=%s, domain=%s, gw=%d.%d.%d.%d]\n",
		    out->client_name, out->domain_name,
		    out->router_address.bp_address_u.ip_addr.net & 0xff,
		    out->router_address.bp_address_u.ip_addr.host & 0xff,
		    out->router_address.bp_address_u.ip_addr.lh & 0xff,
		    out->router_address.bp_address_u.ip_addr.impno & 0xff);
	} else
		printf("Fail\n");

	return 0;
}