text:
package com.tachographStructure.file.vuBlocks;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import com.tachographStructure.file.Block;
import com.tachographStructure.file.certificate.Signature;
import com.tachographStructure.file.driverCardBlock.subBlocks.Certificate;
import com.tachographStructure.file.driverCardBlock.subBlocks.FullCardNumber;
import com.tachographStructure.file.driverCardBlock.subBlocks.Name;
import com.tachographStructure.file.driverCardBlock.subBlocks.VehicleRegistrationIdentification;
import com.tachographStructure.file.vuBlocks.subBlocks.VuCompanyLocksRecord;
import com.tachographStructure.file.vuBlocks.subBlocks.VuControlActivityRecord;
import com.tachographStructure.helpers.IA5String;
import com.tachographStructure.helpers.Number;
import com.tachographStructure.helpers.OctetString;
import com.tachographStructure.helpers.RealTime;

public class Resumen extends Block{

	// 2.68. MemberStateCertificate
	// El certificado de la clave p�blica de un Estado miembro, expedido por la autoridad de certificaci�n europea.
	// MemberStateCertificate::= Certificate

	private Certificate memberStateCertificate;

	// 2.121. VuCertificate
	// Certificado de la clave p�blica de una unidad intravehicular.
	// VuCertificate::= Certificate

	private Certificate VUcertificate;

	// 2.112. VehicleIdentificationNumber
	// N�mero de identificaci�n del veh�culo (VIN) referido al veh�culo completo, generalmente el n�mero de serie del chasis o el n�mero de bastidor.
	// VehicleIdentificationNumber::= IA5String(SIZE(17))
	// Asignaci�n de valor: tal y como se define en la norma ISO 3779.

	private String vehicleIdentificationNumber;

	private VehicleRegistrationIdentification vehicleRegistrationIdentification;

	// 2.45. CurrentDateTime
	// La fecha y la hora actuales del aparato de control.
	// CurrentDateTime::= TimeReal
	// Asignaci�n de valor: no hay m�s especificaciones.

	private Date currentDateTime;

	// 2.129. VuDownloadablePeriod
	// La fecha m�s antigua y la m�s reciente para las que una unidad intravehicular conserva datos relativos a las actividades de los conductores (requisitos 081, 084 o 087).
	// VuDownloadablePeriod::= SEQUENCE {
	// minDownloadableTime TimeReal
	// maxDownloadableTime TimeReal
	// }
	// minDownloadableTime es la fecha y la hora m�s antiguas en que se insert� una tarjeta, ocurri� un cambio de actividad o se introdujo un lugar; seg�n los datos almacenados en la VU.
	// maxDownloadableTime es la fecha y la hora m�s recientes en que se insert� una tarjeta, ocurri� un cambio de actividad o se introdujo un lugar; seg�n los datos almacenados en la VU.
	private Date minDownloableTime;
	private Date maxDonloadbleTime;

	// 2.28. CardSlotsStatus
	// C�digo que indica el tipo de tarjetas insertadas en las dos ranuras de la unidad intravehicular.
	// CardSlotsStatus::= OCTET STRING (SIZE(1))
	// Asignaci�n de valor - Alineaci�n de octeto: 'ccccdddd'B:
	// 'cccc'B Identificaci�n del tipo de tarjeta insertada en la ranura del segundo conductor,
	// 'dddd'B Identificaci�n del tipo de tarjeta insertada en la ranura del conductor,
	// con los siguientes c�digos de identificaci�n:
	// '0000'B no hay tarjeta insertada,
	// '0001'B se ha insertado una tarjeta de conductor,
	// '0010'B se ha insertado una tarjeta del centro de ensayo,
	// '0011'B se ha insertado una tarjeta de control,
	// '0100'B se ha insertado una tarjeta de empresa.

	private byte[] cardSlotsStatus;

	// 2.130. VuDownloadActivityData
	// Informaci�n almacenada en una unidad intravehicular y relativa a la �ltima transferencia de sus datos (requisito 105).
	// VuDownloadActivityData::= SEQUENCE {
	// downloadingTime TimeReal,
	// fullCardNumber FullCardNumber,
	// companyOrWorkshopName Name
	// }
	// downloadingTime es la fecha y la hora de la transferencia.
	// fullCardNumber identifica la tarjeta empleada para autorizar la transferencia.
	// companyOrWorkshopName es el nombre de la empresa o del centro de ensayo.

	private Date downloadingTime;
	private FullCardNumber fullcardNumber;
	private Name companyOrWorkshopName;

	// 2.122. VuCompanyLocksData
	// Informaci�n almacenada en una unidad intravehicular y relativa a bloqueos introducidos por empresas (requisito 104).
	// VuCompanyLocksData::= SEQUENCE {
	// noOfLocks INTEGER(0..20),
	// vuCompanyLocksRecords SET SIZE(noOfLocks) OF VuCompanyLocksRecord
	// }
	// noOfLocks es el n�mero de bloqueos incluidos en el conjunto vuCompanyLocksRecords.
	// vuCompanyLocksRecords es el conjunto de registros de bloqueos introducidos por empresas.
	private int noOfLocks;
	private ArrayList<VuCompanyLocksRecord> vuCompanyLocksRecords;

	// 2.124. VuControlActivityData
	// Informacion almacenada en una unidad intravehicular y relativa a los controles efectuados con dicha VU (requisito 102).
	// VuControlActivityData::= SEQUENCE {
	// noOfControls INTEGER(0..20),
	// vuControlActivityRecords SET SIZE(noOfControls) OF VuControlActivityRecord
	// }
	// noOfControls es el n�mero de controles incluidos en el conjunto vuControlActivityRecords.
	// vuControlActivityRecords es el conjunto de registros sobre actividades de control.
	private int noOfControls;
	private ArrayList<VuControlActivityRecord> vuControlActivityRecord;

	// 2.101. Signature
	// Una firma digital.
	// Signature::= OCTET STRING (SIZE(128))
	// Asignaci�n de valor: con arreglo a lo dispuesto en el Ap�ndice 11 (Mecanismos de seguridad comunes).
	private Signature signature;

	private int size;

	public Resumen(byte[] bytes) throws Exception{

		int start=0; // start in 2 by one byte to id and one byte trep

		this.memberStateCertificate = new Certificate(Arrays.copyOfRange(bytes, start, start+= VuSizes.MEMBERSTATECERTIFICATE.getSize()));

		this.VUcertificate =  new Certificate(Arrays.copyOfRange(bytes, start, start+= VuSizes.MEMBERSTATECERTIFICATE.getSize()));

		IA5String ia5=new IA5String(Arrays.copyOfRange(bytes, start, start+= VuSizes.VEHICLEIDENTIFICATIONNUMBER.getSize()));
		this.vehicleIdentificationNumber= ia5.getiA5String();

		this.vehicleRegistrationIdentification=new VehicleRegistrationIdentification(Arrays.copyOfRange(bytes, start, start+= VuSizes.VEHICLEREGISTRATIONIDENTIFICATION_TREP1.getSize()));

		this.currentDateTime= RealTime.getRealTime(Arrays.copyOfRange(bytes, start, start+= VuSizes.CURRENTDATETIME.getSize()));

		this.minDownloableTime=RealTime.getRealTime(Arrays.copyOfRange(bytes, start, start+= VuSizes.MINDOWNLOADLETIME.getSize()));

		this.maxDonloadbleTime=RealTime.getRealTime(Arrays.copyOfRange(bytes, start, start+= VuSizes.MAXDOWNLOADLETIME.getSize()));
		//tengo que mirar los bytes
		this.cardSlotsStatus=Arrays.copyOfRange(bytes, start, start+= VuSizes.CARDSLOTSSTATUS.getSize());

		this.downloadingTime= RealTime.getRealTime(Arrays.copyOfRange(bytes, start, start+= VuSizes.DOWNLOADINGTIME.getSize()));
		this.fullcardNumber=new FullCardNumber(Arrays.copyOfRange(bytes, start, start+= VuSizes.FULLCARDNUMBER.getSize()));

		this.companyOrWorkshopName= new Name(Arrays.copyOfRange(bytes, start, start+= VuSizes.COMPANYORWORKSHOPNAME.getSize()));
		this.noOfLocks= Number.getShort_8(Arrays.copyOfRange(bytes, start, start+= VuSizes.NOOFLOCKS.getSize()));
		if(this.noOfLocks>0){
			this.vuCompanyLocksRecords=new ArrayList<VuCompanyLocksRecord>();
			this.getListVuCompanyLocksRecords(Arrays.copyOfRange(bytes, start, start+= VuSizes.VUCOMPANYLOCKSRECORD.getSize()*this.noOfLocks));
		}else{
			this.vuCompanyLocksRecords=null;
		}
		 this.noOfControls=Number.getShort_8(Arrays.copyOfRange(bytes, start, start+= VuSizes.NOOFCONTROLS.getSize()));
		 if(this.noOfControls>0){
			 this.vuControlActivityRecord=new ArrayList();
			 this.getListVuControlActivityRecord(Arrays.copyOfRange(bytes, start, start+= VuSizes.VUCONTROLACTIVITYRECORD.getSize()*this.noOfControls));
		 }else{
			 this.vuControlActivityRecord=null;
		 }

		 this.signature = new Signature(Arrays.copyOfRange(bytes, start, start += VuSizes.SIGNATURE_TREP1.getSize()));
		this.size=start;
	}

	private void getListVuControlActivityRecord(byte[] bytes) throws UnsupportedEncodingException {
		VuControlActivityRecord vcar=null;
		int end=bytes.length/ VuSizes.VUCONTROLACTIVITYRECORD.getSize();
		int start=0;
				for (int i=0; i<this.noOfControls;i++){
					vcar=new VuControlActivityRecord(Arrays.copyOfRange(bytes, start, start+= VuSizes.VUCONTROLACTIVITYRECORD.getSize()));
					this.vuControlActivityRecord.add(vcar);
				}

	}

	private void getListVuCompanyLocksRecords(byte[] bytes) throws UnsupportedEncodingException {

		VuCompanyLocksRecord vclr=null;
		int start=0;
		for(int i=0; i<this.noOfLocks; i++){
			vclr=new VuCompanyLocksRecord(Arrays.copyOfRange(bytes, start, start+= VuSizes.VUCOMPANYLOCKSRECORD.getSize()));
			this.vuCompanyLocksRecords.add(vclr);
		}

	}

	/**
	 * @return the memberStateCertificate
	 */
	public Certificate getMemberStateCertificate() {
		return memberStateCertificate;
	}

	/**
	 * @param memberStateCertificate the memberStateCertificate to set
	 */
	public void setMemberStateCertificate(Certificate memberStateCertificate) {
		this.memberStateCertificate = memberStateCertificate;
	}

	/**
	 * @return the vUcertificate
	 */
	public Certificate getVUcertificate() {
		return VUcertificate;
	}

	/**
	 * @param vUcertificate the vUcertificate to set
	 */
	public void setVUcertificate(Certificate vUcertificate) {
		VUcertificate = vUcertificate;
	}

	/**
	 * @return the vehicleIdentificationNumber
	 */
	public String getVehicleIdentificationNumber() {
		return vehicleIdentificationNumber;
	}

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

	/**
	 * @return the vehicleRegistrationIdentification
	 */
	public VehicleRegistrationIdentification getVehicleRegistrationIdentification() {
		return vehicleRegistrationIdentification;
	}

	/**
	 * @param vehicleRegistrationIdentification the vehicleRegistrationIdentification to set
	 */
	public void setVehicleRegistrationIdentification(VehicleRegistrationIdentification vehicleRegistrationIdentification) {
		this.vehicleRegistrationIdentification = vehicleRegistrationIdentification;
	}

	/**
	 * @return the currentDateTime
	 */
	public Date getCurrentDateTime() {
		return currentDateTime;
	}

	/**
	 * @param currentDateTime the currentDateTime to set
	 */
	public void setCurrentDateTime(Date currentDateTime) {
		this.currentDateTime = currentDateTime;
	}

	/**
	 * @return the minDownloableTime
	 */
	public Date getMinDownloableTime() {
		return minDownloableTime;
	}

	/**
	 * @param minDownloableTime the minDownloableTime to set
	 */
	public void setMinDownloableTime(Date minDownloableTime) {
		this.minDownloableTime = minDownloableTime;
	}

	/**
	 * @return the maxDonloadbleTime
	 */
	public Date getMaxDonloadbleTime() {
		return maxDonloadbleTime;
	}

	/**
	 * @param maxDonloadbleTime the maxDonloadbleTime to set
	 */
	public void setMaxDonloadbleTime(Date maxDonloadbleTime) {
		this.maxDonloadbleTime = maxDonloadbleTime;
	}

	/**
	 * @return the cardSlotsStatus
	 */
	public byte[] getCardSlotsStatus() {
		return cardSlotsStatus;
	}

	/**
	 * @param cardSlotsStatus the cardSlotsStatus to set
	 */
	public void setCardSlotsStatus(byte[] cardSlotsStatus) {
		this.cardSlotsStatus = cardSlotsStatus;
	}

	/**
	 * @return the downloadingTime
	 */
	public Date getDownloadingTime() {
		return downloadingTime;
	}

	/**
	 * @param downloadingTime the downloadingTime to set
	 */
	public void setDownloadingTime(Date downloadingTime) {
		this.downloadingTime = downloadingTime;
	}

	/**
	 * @return the fullcardNumber
	 */
	public FullCardNumber getFullcardNumber() {
		return fullcardNumber;
	}

	/**
	 * @param fullcardNumber the fullcardNumber to set
	 */
	public void setFullcardNumber(FullCardNumber fullcardNumber) {
		this.fullcardNumber = fullcardNumber;
	}

	/**
	 * @return the companyOrWorkshopName
	 */
	public Name getCompanyOrWorkshopName() {
		return companyOrWorkshopName;
	}

	/**
	 * @param companyOrWorkshopName the companyOrWorkshopName to set
	 */
	public void setCompanyOrWorkshopName(Name companyOrWorkshopName) {
		this.companyOrWorkshopName = companyOrWorkshopName;
	}

	/**
	 * @return the noOfLocks
	 */
	public int getNoOfLocks() {
		return noOfLocks;
	}

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

	/**
	 * @return the vuCompanyLocksRecords
	 */
	public ArrayList<VuCompanyLocksRecord> getVuCompanyLocksRecords() {
		return vuCompanyLocksRecords;
	}

	/**
	 * @param vuCompanyLocksRecords the vuCompanyLocksRecords to set
	 */
	public void setVuCompanyLocksRecords(ArrayList<VuCompanyLocksRecord> vuCompanyLocksRecords) {
		this.vuCompanyLocksRecords = vuCompanyLocksRecords;
	}

	/**
	 * @return the noOfControls
	 */
	public int getNoOfControls() {
		return noOfControls;
	}

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

	/**
	 * @return the vuControlActivityRecord
	 */
	public ArrayList<VuControlActivityRecord> getVuControlActivityRecord() {
		return vuControlActivityRecord;
	}

	/**
	 * @param vuControlActivityRecord the vuControlActivityRecord to set
	 */
	public void setVuControlActivityRecord(ArrayList<VuControlActivityRecord> vuControlActivityRecord) {
		this.vuControlActivityRecord = vuControlActivityRecord;
	}

	/**
	 * @return the signature
	 */
	public Signature getSignature() {
		return signature;
	}

	/**
	 * @param signature the signature to set
	 */
	public void setSignature(Signature signature) {
		this.signature = signature;
	}

	/**
	 * @return the size
	 */
	public int getSize() {
		return size;
	}

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

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "Resumen [memberStateCertificate=" + memberStateCertificate.toString() + "\n, VUcertificate=" + VUcertificate.toString()
				+ "\n, vehicleIdentificationNumber=" + vehicleIdentificationNumber
				+ "\n, vehicleRegistrationIdentification=" + vehicleRegistrationIdentification + "\n, currentDateTime="
				+ currentDateTime + "\n, minDownloableTime=" + minDownloableTime + "\n, maxDonloadbleTime="
				+ maxDonloadbleTime + "\n, cardSlotsStatus=" + Arrays.toString(cardSlotsStatus) + "\n, downloadingTime="
				+ downloadingTime + "\n, fullcardNumber=" + fullcardNumber + "\n, companyOrWorkshopName="
				+ companyOrWorkshopName + "\n, noOfLocks=" + noOfLocks + "\n, vuCompanyLocksRecords="
				+ vuCompanyLocksRecords + "\n, noOfControls=" + noOfControls + "\n, vuControlActivityRecord="
				+ vuControlActivityRecord + "\n, signature=" + signature + "]";
	}

}


text:
package org.hogel.batchsan.core.job.result;

public interface JobResult {
    boolean isSuccess();

    String getBody();
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<CustomFieldTranslation xmlns="http://soap.sforce.com/2006/04/metadata">
    <name>Grading_Period_Sequence__c</name>
    <help>Ilmaisee mikä jakso tämä on. Kirjoita esimerkiksi "1" ensimmäiselle vuosineljännekselle tai lukukaudelle, "2" toiselle vuosineljännekselle tai lukukaudelle jne.</help>
    <label>Arvostelujakson sijoitus</label>
</CustomFieldTranslation>


text:
<?php
namespace common\widgets\Wcalendar;

use yii\base\Widget;
use common\models\DateForm;
use Yii;

class calendar extends Widget
{
    public function run()
    {
        $dtForm = new DateForm;
        $dtForm->load(Yii::$app->request->post());

        return $this->render('vcalendar',[
                                            'model' => $dtForm,
                                            'date'  => (!empty($dtForm->startdate)? $dtForm->startdate: date('d-m-Y')),
                                        ]);
    }
}
?>


text:
package com.google.test.metric.collection;

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

import com.google.common.base.Supplier;
import com.google.common.collect.ForwardingMap;

/**
 * Wrap a Map to provide lazy creation of its values.
 * @author alexeagle@google.com (Alex Eagle)
 */
public class LazyHashMap<K, V> extends ForwardingMap<K,V> {
  private final Map<K, V> delegate;
  private final Supplier<V> supplier;

  public LazyHashMap(Supplier<V> supplier) {
    this.delegate = new HashMap<K,V>();
    this.supplier = supplier;
  }

  protected Map<K, V> delegate() {
    return delegate;
  }

  @Override
  public V get(Object o) {
    V value = delegate.get(o);
    if (value == null) {
      value = supplier.get();
      delegate.put((K)o, value);
    }
    return value;
  }

  public static <K,V> Map<K, V> newLazyHashMap(Supplier<V> supplier) {
    return new LazyHashMap<K,V>(supplier);
  }

}


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.init;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.support.annotation.CallSuper;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.Display;
import android.view.Menu;
import android.view.Surface;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.view.WindowManager;

import org.chromium.base.ApiCompatibilityUtils;
import org.chromium.base.TraceEvent;
import org.chromium.base.VisibleForTesting;
import org.chromium.base.library_loader.LibraryLoader;
import org.chromium.base.library_loader.LoaderErrors;
import org.chromium.base.library_loader.ProcessInitException;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.ChromeApplication;
import org.chromium.chrome.browser.WarmupManager;
import org.chromium.chrome.browser.firstrun.FirstRunFlowSequencer;
import org.chromium.chrome.browser.metrics.MemoryUma;
import org.chromium.chrome.browser.profiles.Profile;
import org.chromium.chrome.browser.tabmodel.DocumentModeAssassin;
import org.chromium.chrome.browser.upgrade.UpgradeActivity;
import org.chromium.ui.base.ActivityWindowAndroid;
import org.chromium.ui.base.DeviceFormFactor;
import org.chromium.ui.base.WindowAndroid;

import java.lang.reflect.Field;

/**
 * An activity that talks with application and activity level delegates for async initialization.
 */
public abstract class AsyncInitializationActivity extends AppCompatActivity implements
        ChromeActivityNativeDelegate, BrowserParts {
    protected final Handler mHandler;

    private final NativeInitializationController mNativeInitializationController =
            new NativeInitializationController(this);

    /** Time at which onCreate is called. This is realtime, counted in ms since device boot. */
    private long mOnCreateTimestampMs;

    /** Time at which onCreate is called. This is uptime, to be sent to native code. */
    private long mOnCreateTimestampUptimeMs;

    private ActivityWindowAndroid mWindowAndroid;
    private Bundle mSavedInstanceState;
    private int mCurrentOrientation = Surface.ROTATION_0;
    private boolean mDestroyed;
    private MemoryUma mMemoryUma;
    private long mLastUserInteractionTime;
    private boolean mIsTablet;
    private boolean mHadWarmStart;
    private boolean mIsWarmOnResume;

    // Stores whether the activity was not resumed yet. Always false after the
    // first |onResume| call.
    private boolean mFirstResumePending = true;

    private boolean mStartupDelayed;
    private boolean mFirstDrawComplete;

    public AsyncInitializationActivity() {
        mHandler = new Handler();
    }

    @Override
    protected void onDestroy() {
        mDestroyed = true;

        if (mWindowAndroid != null) {
            mWindowAndroid.destroy();
            mWindowAndroid = null;
        }

        super.onDestroy();
    }

    @Override
    @TargetApi(Build.VERSION_CODES.N)
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(newBase);

        // On N+, Chrome should always retain the tab strip layout on tablets. Normally in
        // multi-window, if Chrome is launched into a smaller screen Android will load the tab
        // switcher resources. Overriding the smallestScreenWidthDp in the Configuration ensures
        // Android will load the tab strip resources. See crbug.com/588838.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            int smallestDeviceWidthDp = DeviceFormFactor.getSmallestDeviceWidthDp();

            if (smallestDeviceWidthDp >= DeviceFormFactor.MINIMUM_TABLET_WIDTH_DP) {
                Configuration overrideConfiguration = new Configuration();
                overrideConfiguration.smallestScreenWidthDp = smallestDeviceWidthDp;
                applyOverrideConfiguration(overrideConfiguration);
            }
        }
    }

    @Override
    public void preInflationStartup() {
        mHadWarmStart = LibraryLoader.isInitialized();
        // On some devices, OEM modifications have been made to the resource loader that cause the
        // DeviceFormFactor calculation of whether a device is using tablet resources to be
        // incorrect. Check which resources were actually loaded and set the DeviceFormFactor
        // values. See crbug.com/662338.
        boolean isTablet = getResources().getBoolean(R.bool.is_tablet);
        boolean isLargeTablet = getResources().getBoolean(R.bool.is_large_tablet);
        DeviceFormFactor.setIsTablet(isTablet, isLargeTablet);
        mIsTablet = isTablet;
    }

    @Override
    public final void setContentViewAndLoadLibrary() {
        // Unless it was called before, {@link #setContentView} inflates the decorView and the basic
        // UI hierarchy as stubs. This is done here before kicking long running I/O because
        // inflation accesses resource files (XML, etc) even if we are inflating views defined by
        // the framework. If this operation gets blocked because other long running I/O are running,
        // we delay onCreate(), onStart() and first draw consequently.

        setContentView();
        if (mLaunchBehindWorkaround != null) mLaunchBehindWorkaround.onSetContentView();

        if (!mStartupDelayed) {
            // Kick off long running IO tasks that can be done in parallel.
            mNativeInitializationController.startBackgroundTasks(shouldAllocateChildConnection());
        }
    }

    /** Controls the parameter of {@link NativeInitializationController#startBackgroundTasks()}.*/
    @VisibleForTesting
    public boolean shouldAllocateChildConnection() {
        return true;
    }

    @CallSuper
    @Override
    public void postInflationStartup() {
        final View firstDrawView = getViewToBeDrawnBeforeInitializingNative();
        assert firstDrawView != null;
        ViewTreeObserver.OnPreDrawListener firstDrawListener =
                new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                firstDrawView.getViewTreeObserver().removeOnPreDrawListener(this);
                mFirstDrawComplete = true;
                if (!mStartupDelayed) {
                    onFirstDrawComplete();
                }
                return true;
            }
        };
        firstDrawView.getViewTreeObserver().addOnPreDrawListener(firstDrawListener);
    }

    /**
     * @return The primary view that must have completed at least one draw before initializing
     *         native.  This must be non-null.
     */
    protected View getViewToBeDrawnBeforeInitializingNative() {
        return findViewById(android.R.id.content);
    }

    @Override
    public void maybePreconnect() {
        TraceEvent.begin("maybePreconnect");
        Intent intent = getIntent();
        if (intent != null && Intent.ACTION_VIEW.equals(intent.getAction())) {
            final String url = intent.getDataString();
            WarmupManager.getInstance()
                .maybePreconnectUrlAndSubResources(Profile.getLastUsedProfile(), url);
        }
        TraceEvent.end("maybePreconnect");
    }

    @Override
    public void initializeCompositor() { }

    @Override
    public void initializeState() { }

    @Override
    public void finishNativeInitialization() {
        // Set up the initial orientation of the device.
        checkOrientation();
        findViewById(android.R.id.content).addOnLayoutChangeListener(
                new View.OnLayoutChangeListener() {
                    @Override
                    public void onLayoutChange(View v, int left, int top, int right, int bottom,
                            int oldLeft, int oldTop, int oldRight, int oldBottom) {
                        checkOrientation();
                    }
                });
        mMemoryUma = new MemoryUma();
        mNativeInitializationController.onNativeInitializationComplete();
    }

    @Override
    public void onStartupFailure() {
        ProcessInitException e =
                new ProcessInitException(LoaderErrors.LOADER_ERROR_NATIVE_STARTUP_FAILED);
        ChromeApplication.reportStartupErrorAndExit(e);
    }

    /**
     * Extending classes should override {@link AsyncInitializationActivity#preInflationStartup()},
     * {@link AsyncInitializationActivity#setContentView()} and
     * {@link AsyncInitializationActivity#postInflationStartup()} instead of this call which will
     * be called on that order.
     */
    @Override
    @SuppressLint("MissingSuperCall")  // Called in onCreateInternal.
    protected final void onCreate(Bundle savedInstanceState) {
        TraceEvent.begin("AsyncInitializationActivity.onCreate()");
        onCreateInternal(savedInstanceState);
        TraceEvent.end("AsyncInitializationActivity.onCreate()");
    }

    private final void onCreateInternal(Bundle savedInstanceState) {
        if (DocumentModeAssassin.getInstance().isMigrationNecessary()) {
            super.onCreate(null);

            // Kick the user to the MigrationActivity.
            UpgradeActivity.launchInstance(this, getIntent());

            // Don't remove this task -- it may be a DocumentActivity that exists only in Recents.
            finish();
            return;
        }

        if (!isStartedUpCorrectly(getIntent())) {
            abortLaunch();
            return;
        }

        if (requiresFirstRunToBeCompleted(getIntent())
                && FirstRunFlowSequencer.launch(this, getIntent(), false)) {
            abortLaunch();
            return;
        }

        super.onCreate(transformSavedInstanceStateForOnCreate(savedInstanceState));
        mOnCreateTimestampMs = SystemClock.elapsedRealtime();
        mOnCreateTimestampUptimeMs = SystemClock.uptimeMillis();
        mSavedInstanceState = savedInstanceState;

        mWindowAndroid = createWindowAndroid();
        if (mWindowAndroid != null) {
            getWindowAndroid().restoreInstanceState(getSavedInstanceState());
        }

        mStartupDelayed = shouldDelayBrowserStartup();
        ChromeBrowserInitializer.getInstance(this).handlePreNativeStartup(this);
    }

    private void abortLaunch() {
        super.onCreate(null);
        ApiCompatibilityUtils.finishAndRemoveTask(this);
    }

    /**
     * Call to begin loading the library, if it was delayed.
     */
    protected void startDelayedNativeInitialization() {
        assert mStartupDelayed;
        mStartupDelayed = false;

        // Kick off long running IO tasks that can be done in parallel.
        mNativeInitializationController.startBackgroundTasks(shouldAllocateChildConnection());

        if (mFirstDrawComplete) onFirstDrawComplete();
    }

    /**
     * Creates an {@link ActivityWindowAndroid} to delegate calls to, if the Activity requires it.
     */
    @Nullable
    protected ActivityWindowAndroid createWindowAndroid() {
        return null;
    }

    /**
     * @return Whether the browser startup should be delayed. Note that changing this return value
     *         will have direct impact on startup performance.
     */
    protected boolean shouldDelayBrowserStartup() {
        return false;
    }

    /**
     * Allows subclasses to override the instance state passed to super.onCreate().
     * The original instance state will still be available via getSavedInstanceState().
     */
    protected Bundle transformSavedInstanceStateForOnCreate(Bundle savedInstanceState) {
        return savedInstanceState;
    }

    /**
     * Overriding this function is almost always wrong.
     * @return Whether or not the user needs to go through First Run before using this Activity.
     */
    protected boolean requiresFirstRunToBeCompleted(Intent intent) {
        return true;
    }

    /**
     * Whether or not the Activity was started up via a valid Intent.
     */
    protected boolean isStartedUpCorrectly(Intent intent) {
        return true;
    }

    /**
     * @return The elapsed real time for the activity creation in ms.
     */
    protected long getOnCreateTimestampUptimeMs() {
        return mOnCreateTimestampUptimeMs;
    }

    /**
     * @return The uptime for the activity creation in ms.
     */
    protected long getOnCreateTimestampMs() {
        return mOnCreateTimestampMs;
    }

    /**
     * @return The saved bundle for the last recorded state.
     */
    protected Bundle getSavedInstanceState() {
        return mSavedInstanceState;
    }

    /**
     * Resets the saved state and makes it unavailable for the rest of the activity lifecycle.
     */
    protected void resetSavedInstanceState() {
        mSavedInstanceState = null;
    }

    @Override
    public void onStart() {
        super.onStart();
        mNativeInitializationController.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();
        mNativeInitializationController.onResume();
        if (mLaunchBehindWorkaround != null) mLaunchBehindWorkaround.onResume();
        mIsWarmOnResume = !mFirstResumePending || hadWarmStart();
        mFirstResumePending = false;
    }

    @Override
    public void onPause() {
        mNativeInitializationController.onPause();
        super.onPause();
        if (mLaunchBehindWorkaround != null) mLaunchBehindWorkaround.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mMemoryUma != null) mMemoryUma.onStop();
        mNativeInitializationController.onStop();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        if (intent == null) return;
        mNativeInitializationController.onNewIntent(intent);
        setIntent(intent);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        mNativeInitializationController.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public final void onCreateWithNative() {
        try {
            ChromeBrowserInitializer.getInstance(this).handlePostNativeStartup(true, this);
        } catch (ProcessInitException e) {
            ChromeApplication.reportStartupErrorAndExit(e);
        }
    }

    @Override
    public void onStartWithNative() { }

    @Override
    public void onResumeWithNative() { }

    @Override
    public void onPauseWithNative() { }

    @Override
    public void onStopWithNative() { }

    @Override
    public boolean isActivityDestroyed() {
        return mDestroyed;
    }

    @Override
    public boolean isActivityFinishing() {
        return isFinishing();
    }

    @Override
    public abstract boolean shouldStartGpuProcess();

    @Override
    public void onContextMenuClosed(Menu menu) {
        if (mWindowAndroid != null) mWindowAndroid.onContextMenuClosed();
    }

    private void onFirstDrawComplete() {
        assert mFirstDrawComplete;
        assert !mStartupDelayed;

        mHandler.post(new Runnable() {
            @Override
            public void run() {
                mNativeInitializationController.firstDrawComplete();
            }
        });
    }

    @Override
    public void onNewIntentWithNative(Intent intent) { }

    @Override
    public Intent getInitialIntent() {
        return getIntent();
    }

    /**
     * @return A {@link ActivityWindowAndroid} instance.  May be null if one was not created.
     */
    @Nullable
    public ActivityWindowAndroid getWindowAndroid() {
        return mWindowAndroid;
    }

    /**
     * This will handle passing {@link Intent} results back to the {@link WindowAndroid}.  It will
     * return whether or not the {@link WindowAndroid} has consumed the event or not.
     */
    @Override
    public boolean onActivityResultWithNative(int requestCode, int resultCode, Intent intent) {
        if (mWindowAndroid != null) {
            return mWindowAndroid.onActivityResult(requestCode, resultCode, intent);
        } else {
            return false;
        }
    }

    @Override
    public void onRequestPermissionsResult(
            int requestCode, String[] permissions, int[] grantResults) {
        if (mWindowAndroid != null) {
            if (mWindowAndroid.onRequestPermissionsResult(requestCode, permissions, grantResults)) {
                return;
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mWindowAndroid != null) mWindowAndroid.saveInstanceState(outState);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        if (mMemoryUma != null) mMemoryUma.onLowMemory();
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        if (mMemoryUma != null) mMemoryUma.onTrimMemory(level);
    }

    /**
     * @return Whether the activity is running in tablet mode.
     */
    public boolean isTablet() {
        return mIsTablet;
    }

    /**
     * @return Whether the activity had a warm start because the native library was already fully
     *     loaded and initialized.
     */
    public boolean hadWarmStart() {
        return mHadWarmStart;
    }

    /**
     * This returns true if the activity was started warm (native library loaded and initialized) or
     * if a cold starts have been completed by the time onResume is/will be called.
     * This is useful to distinguish between the case where an already running instance of Chrome is
     * being brought back to the foreground from the case where Chrome is started, in order to avoid
     * contention on browser startup
     * @return Whether the activity is warm in onResume.
     */
    public boolean isWarmOnResume() {
        return mIsWarmOnResume;
    }

    @Override
    public void onUserInteraction() {
        mLastUserInteractionTime = SystemClock.elapsedRealtime();
    }

    /**
     * @return timestamp when the last user interaction was made.
     */
    public long getLastUserInteractionTime() {
        return mLastUserInteractionTime;
    }

    /**
     * Called when the orientation of the device changes.  The orientation is checked/detected on
     * root view layouts.
     * @param orientation One of {@link Surface#ROTATION_0} (no rotation),
     *                    {@link Surface#ROTATION_90}, {@link Surface#ROTATION_180}, or
     *                    {@link Surface#ROTATION_270}.
     */
    protected void onOrientationChange(int orientation) {
    }

    private void checkOrientation() {
        WindowManager wm = getWindowManager();
        if (wm == null) return;

        Display display = wm.getDefaultDisplay();
        if (display == null) return;

        int oldOrientation = mCurrentOrientation;
        mCurrentOrientation = display.getRotation();

        if (oldOrientation != mCurrentOrientation) onOrientationChange(mCurrentOrientation);
    }

    /**
     * Removes the window background.
     */
    protected void removeWindowBackground() {
        boolean removeWindowBackground = true;
        try {
            Field field = Settings.Secure.class.getField(
                    "ACCESSIBILITY_DISPLAY_MAGNIFICATION_ENABLED");
            field.setAccessible(true);

            if (field.getType() == String.class) {
                String accessibilityMagnificationSetting = (String) field.get(null);
                // When Accessibility magnification is turned on, setting a null window
                // background causes the overlaid android views to stretch when panning.
                // (crbug/332994)
                if (Settings.Secure.getInt(
                        getContentResolver(), accessibilityMagnificationSetting) == 1) {
                    removeWindowBackground = false;
                }
            }
        } catch (SettingNotFoundException e) {
            // Window background is removed if an exception occurs.
        } catch (NoSuchFieldException e) {
            // Window background is removed if an exception occurs.
        } catch (IllegalAccessException e) {
            // Window background is removed if an exception occurs.
        } catch (IllegalArgumentException e) {
            // Window background is removed if an exception occurs.
        }
        if (removeWindowBackground) getWindow().setBackgroundDrawable(null);
    }

    /**
     * Extending classes should implement this and call {@link Activity#setContentView(int)} in it.
     */
    protected abstract void setContentView();

    /**
     * Lollipop (pre-MR1) makeTaskLaunchBehind() workaround.
     *
     * Our activity's surface is destroyed at the end of the new activity animation
     * when ActivityOptions.makeTaskLaunchBehind() is used, which causes a crash.
     * Making everything invisible when paused prevents the crash, since view changes
     * will not trigger draws to the missing surface. However, we need to wait until
     * after the first draw to make everything invisible, as the activity launch
     * animation needs a full frame (or it will delay the animation excessively).
     */
    private final LaunchBehindWorkaround mLaunchBehindWorkaround =
            (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP)
                    ? new LaunchBehindWorkaround()
                    : null;

    private class LaunchBehindWorkaround {
        private boolean mPaused;

        private View getDecorView() {
            return getWindow().getDecorView();
        }

        private ViewTreeObserver getViewTreeObserver() {
            return getDecorView().getViewTreeObserver();
        }

        private void onPause() {
            mPaused = true;
        }

        public void onResume() {
            mPaused = false;
            getDecorView().setVisibility(View.VISIBLE);
        }

        public void onSetContentView() {
            getViewTreeObserver().addOnPreDrawListener(mPreDrawListener);
        }

        // Note, we probably want onDrawListener here, but it isn't being called
        // when I add this to the decorView. However, it should be the same for
        // this purpose as long as no other pre-draw listener returns false.
        private final OnPreDrawListener mPreDrawListener = new OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (mPaused) {
                            getDecorView().setVisibility(View.GONE);
                        }
                        getViewTreeObserver().removeOnPreDrawListener(mPreDrawListener);
                    }
                });
                return true;
            }
        };
    }
}


text:
package pusher

import (
	"encoding/json"
	"errors"
	"fmt"
	"net"
	"net/http"
	"net/http/httptest"
	"reflect"
	"runtime"
	"strconv"
	"strings"
	"sync"
	"testing"
	"time"

	"golang.org/x/net/websocket"
)

// TODO Implement Client.Error channel in all tests and fail the test if any
// errors occur

func TestUnmarshalDataString(t *testing.T) {
	dest := map[string]interface{}{}
	err := UnmarshalDataString(json.RawMessage(`"{\"foo\":\"A\",\"bar\":1}"`), &dest)
	if err != nil {
		t.Errorf("Expected error to be `nil`, got %v", err)
	}

	wantData := map[string]interface{}{
		"foo": "A",
		"bar": 1.0,
	}
	if !reflect.DeepEqual(dest, wantData) {
		t.Errorf("Expected dest to deep-equal %+v, got %+v", wantData, dest)
	}
}

func TestClientIsConnected(t *testing.T) {
	t.Run("false", func(t *testing.T) {
		client := &Client{connected: false}
		if isConnected := client.isConnected(); isConnected != false {
			t.Errorf("Expected isConnected to return false, got %v", isConnected)
		}
	})
	t.Run("true", func(t *testing.T) {
		client := &Client{connected: true}
		if isConnected := client.isConnected(); isConnected != true {
			t.Errorf("Expected isConnected to return true, got %v", isConnected)
		}
	})
}

func TestClientResetActivityTimer(t *testing.T) {
	client := &Client{
		activityTimerReset: make(chan struct{}, 1),
	}

	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		<-client.activityTimerReset
		wg.Done()
	}()

	client.resetActivityTimer()

	wg.Wait()
}

func TestClientSendError(t *testing.T) {
	errChan := make(chan error)
	wantErr := errors.New("foo")
	client := &Client{Errors: errChan}

	var gotErr error
	wg := &sync.WaitGroup{}
	wg.Add(1)
	go func() { gotErr = <-errChan; wg.Done() }()
	runtime.Gosched()
	client.sendError(wantErr)
	wg.Wait()

	if !reflect.DeepEqual(gotErr, wantErr) {
		t.Errorf("Expected to value from error chan to be %+v, got %+v", wantErr, gotErr)
	}
}

func TestClientBind(t *testing.T) {
	wantChan := "foo"
	client := Client{boundEvents: map[string]boundEventChans{}}
	boundChan := client.Bind(wantChan)

	eventBoundChans, ok := client.boundEvents[wantChan]
	if !ok {
		t.Errorf("Expected client bound events to contain %q, got %+v instead", wantChan, client.boundEvents)
	}
	_, ok = eventBoundChans[boundChan]
	if !ok {
		t.Errorf("Expected event bound channels to contain returned channel, got %+v instead", eventBoundChans)
	}
}

func TestClientUnbind(t *testing.T) {
	wantChan := "foo"
	t.Run("eventOnly", func(t *testing.T) {
		client := Client{boundEvents: map[string]boundEventChans{
			wantChan: {make(chan Event): struct{}{}},
		}}
		client.Unbind(wantChan)

		if _, ok := client.boundEvents[wantChan]; ok {
			t.Errorf("Expected client bound events not to contain %q, got %+v instead", wantChan, client.boundEvents)
		}
	})

	t.Run("eventWithChans", func(t *testing.T) {
		wantChan := "foo"
		ch1 := make(chan Event)
		ch2 := make(chan Event)
		ch3 := make(chan Event)
		client := Client{boundEvents: map[string]boundEventChans{
			wantChan: {
				ch1: struct{}{},
				ch2: struct{}{},
				ch3: struct{}{},
			},
		}}
		client.Unbind(wantChan, ch1, ch3)

		eventBoundChans, ok := client.boundEvents[wantChan]
		if !ok {
			t.Errorf("Expected client bound events to contain %q, got %+v instead", wantChan, client.boundEvents)
		}
		_, ok = eventBoundChans[ch1]
		if ok {
			t.Errorf("Expected event bound channels not to contain ch1, got %+v instead", eventBoundChans)
		}
		_, ok = eventBoundChans[ch3]
		if ok {
			t.Errorf("Expected event bound channels not to contain ch3, got %+v instead", eventBoundChans)
		}
		_, ok = eventBoundChans[ch2]
		if !ok {
			t.Errorf("Expected event bound channels to contain ch3, got %+v instead", eventBoundChans)
		}
	})
}

func TestClientSendEvent(t *testing.T) {
	wantEvent := Event{
		Channel: "foo",
		Event:   "bar",
		Data:    json.RawMessage(`{"bar":1,"foo":"A"}`),
	}

	wg := &sync.WaitGroup{}
	wg.Add(1)
	srv := httptest.NewServer(websocket.Handler(func(ws *websocket.Conn) {
		event := Event{}
		err := websocket.JSON.Receive(ws, &event)
		if err != nil {
			panic(err)
		}
		if !reflect.DeepEqual(event, wantEvent) {
			t.Errorf("Expected received event to deep-equal %+v, got %+v", wantEvent, event)
		}
		wg.Done()
	}))
	defer srv.Close()
	wsURL := strings.Replace(srv.URL, "http", "ws", 1)
	ws, err := websocket.Dial(wsURL, "ws", localOrigin)
	if err != nil {
		panic(err)
	}

	client := &Client{
		ws:                 ws,
		activityTimerReset: make(chan struct{}, 1),
	}
	defer client.Disconnect()

	err = client.SendEvent(wantEvent.Event, wantEvent.Data, wantEvent.Channel)
	if err != nil {
		panic(err)
	}
	wg.Wait()

	<-client.activityTimerReset
}

func TestClientSubscribe(t *testing.T) {
	t.Run("existingSubscription", func(t *testing.T) {
		srv := httptest.NewServer(websocket.Handler(func(ws *websocket.Conn) {}))
		defer srv.Close()
		wsURL := strings.Replace(srv.URL, "http", "ws", 1)
		ws, err := websocket.Dial(wsURL, "ws", localOrigin)
		if err != nil {
			panic(err)
		}

		channelName := "foo"
		ch := &channel{name: channelName, subscribed: true}
		client := &Client{
			subscribedChannels: map[string]internalChannel{channelName: ch},
			ws:                 ws,
		}
		defer client.Disconnect()
		ch.client = client
		subCh, err := client.Subscribe(channelName)
		if err != nil {
			panic(err)
		}

		if ch != subCh.(*channel) {
			t.Errorf("Expected subCh to be %+v, got %+v", ch, subCh)
		}
	})

	t.Run("newPublicChannel", func(t *testing.T) {
		channelName := "foo"

		srv := httptest.NewServer(websocket.Handler(func(ws *websocket.Conn) {
			var evt Event
			err := websocket.JSON.Receive(ws, &evt)
			if err != nil {
				panic(err)
			}
			if evt.Event != pusherSubscribe {
				t.Errorf("Expected event to be %q, got %q", pusherSubscribe, evt.Event)
			}

			err = websocket.JSON.Send(ws, Event{
				Event:   pusherInternalSubSucceeded,
				Channel: channelName,
			})
			if err != nil {
				panic(err)
			}
		}))
		defer srv.Close()
		wsURL := strings.Replace(srv.URL, "http", "ws", 1)
		ws, err := websocket.Dial(wsURL, "ws", localOrigin)
		if err != nil {
			panic(err)
		}

		client := &Client{
			subscribedChannels: map[string]internalChannel{},
			ws:                 ws,
			connected:          true,
		}
		defer client.Disconnect()

		go client.listen()

		subCh, err := client.Subscribe(channelName)
		if err != nil {
			panic(err)
		}

		baseCh := subCh.(*channel)
		if baseCh.name != channelName {
			t.Errorf("Expected channel name to be %q, got %q", channelName, baseCh.name)
		}
	})

	t.Run("newPrivateChannel", func(t *testing.T) {
		channelName := "private-foo"

		srv := httptest.NewServer(websocket.Handler(func(ws *websocket.Conn) {
			var evt Event
			err := websocket.JSON.Receive(ws, &evt)
			if err != nil {
				panic(err)
			}
			if evt.Event != pusherSubscribe {
				t.Errorf("Expected event to be %q, got %q", pusherSubscribe, evt.Event)
			}

			err = websocket.JSON.Send(ws, Event{
				Event:   pusherInternalSubSucceeded,
				Channel: channelName,
			})
			if err != nil {
				panic(err)
			}
		}))
		defer srv.Close()
		wsURL := strings.Replace(srv.URL, "http", "ws", 1)
		ws, err := websocket.Dial(wsURL, "ws", localOrigin)
		if err != nil {
			panic(err)
		}

		authSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			w.Write([]byte(`{}`))
		}))

		client := &Client{
			subscribedChannels: map[string]internalChannel{},
			ws:                 ws,
			connected:          true,
			AuthURL:            authSrv.URL,
		}
		defer client.Disconnect()

		go client.listen()

		subCh, err := client.Subscribe(channelName)
		if err != nil {
			panic(err)
		}

		baseCh := subCh.(*privateChannel)
		if baseCh.name != channelName {
			t.Errorf("Expected channel name to be %q, got %q", channelName, baseCh.name)
		}
	})

	t.Run("newPresenceChannel", func(t *testing.T) {
		channelName := "presence-foo"

		srv := httptest.NewServer(websocket.Handler(func(ws *websocket.Conn) {
			var evt Event
			err := websocket.JSON.Receive(ws, &evt)
			if err != nil {
				panic(err)
			}
			if evt.Event != pusherSubscribe {
				t.Errorf("Expected event to be %q, got %q", pusherSubscribe, evt.Event)
			}

			data, err := json.Marshal(`
				{
					"presence": {
						"ids": ["1", "2"],
						"hash": {
							"1": { "name": "name-1" },
							"2": { "name": "name-2" }
						},
						"count": 2
					}
				}
			`)
			if err != nil {
				t.Fatal("error marshaling data: ", err)
			}

			err = websocket.JSON.Send(ws, Event{
				Event:   pusherInternalSubSucceeded,
				Channel: channelName,
				Data:    data,
			})
			if err != nil {
				panic(err)
			}
		}))
		defer srv.Close()
		wsURL := strings.Replace(srv.URL, "http", "ws", 1)
		ws, err := websocket.Dial(wsURL, "ws", localOrigin)
		if err != nil {
			panic(err)
		}

		authSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			w.Write([]byte(`{}`))
		}))

		client := &Client{
			subscribedChannels: map[string]internalChannel{},
			ws:                 ws,
			connected:          true,
			AuthURL:            authSrv.URL,
		}
		defer client.Disconnect()

		go client.listen()

		subCh, err := client.SubscribePresence(channelName)
		if err != nil {
			panic(err)
		}

		baseCh := subCh.(*presenceChannel)
		if baseCh.name != channelName {
			t.Errorf("Expected channel name to be %q, got %q", channelName, baseCh.name)
		}
	})
}

func TestClientUnsubscribe(t *testing.T) {
	srv := httptest.NewServer(websocket.Handler(func(ws *websocket.Conn) {}))
	defer srv.Close()
	wsURL := strings.Replace(srv.URL, "http", "ws", 1)
	ws, err := websocket.Dial(wsURL, "ws", localOrigin)
	if err != nil {
		panic(err)
	}

	ch := &channel{name: "foo"}
	client := &Client{
		subscribedChannels: map[string]internalChannel{"foo": ch},
		ws:                 ws,
	}
	defer client.Disconnect()
	ch.client = client
	err = client.Unsubscribe("foo")
	if err != nil {
		panic(err)
	}

	if _, ok := client.subscribedChannels["foo"]; ok {
		t.Errorf("Expected client subscribed channels not to contain 'foo', got %+v", client.subscribedChannels)
	}
}

func TestClientDisconnect(t *testing.T) {
	srv := httptest.NewServer(websocket.Handler(func(ws *websocket.Conn) {}))
	defer srv.Close()
	wsURL := strings.Replace(srv.URL, "http", "ws", 1)
	ws, err := websocket.Dial(wsURL, "ws", localOrigin)
	if err != nil {
		panic(err)
	}

	client := &Client{
		connected: true,
		ws:        ws,
	}

	err = client.Disconnect()
	if err != nil {
		panic(err)
	}

	if client.connected {
		t.Errorf("Expected client connected to be false, got true")
	}
	if err = ws.Close(); err == nil {
		t.Errorf("Expected websocket connection to have been closed, got no error closing again")
	}
}

func TestClientHeartbeat(t *testing.T) {
	t.Run("notConnected", func(t *testing.T) {
		timeChan := make(chan time.Time)
		client := &Client{
			connected:          false,
			activityTimerReset: make(chan struct{}, 1),
			activityTimer:      &time.Timer{C: timeChan},
		}

		go func() {
			client.activityTimerReset <- struct{}{}
			client.activityTimerReset <- struct{}{}
			t.Errorf("Expected not to block on send to activityTimerReset, but message was received")
		}()
		go func() {
			timeChan <- time.Now()
			t.Errorf("Expected not to block on send to activityTimer chan, but message was received")
		}()

		client.heartbeat()
	})

	t.Run("timerReset", func(t *testing.T) {
		srv := httptest.NewServer(websocket.Handler(func(ws *websocket.Conn) {}))
		defer srv.Close()
		wsURL := strings.Replace(srv.URL, "http", "ws", 1)
		ws, err := websocket.Dial(wsURL, "ws", localOrigin)
		if err != nil {
			panic(err)
		}

		client := &Client{
			connected:          true,
			activityTimerReset: make(chan struct{}, 1),
			activityTimer:      time.NewTimer(1 * time.Hour),
			activityTimeout:    0,
			ws:                 ws,
		}

		go client.heartbeat()
		runtime.Gosched()

		client.Disconnect()
		client.activityTimerReset <- struct{}{}

		<-client.activityTimer.C
	})

	t.Run("timerExpire", func(t *testing.T) {
		wg := &sync.WaitGroup{}
		wg.Add(1)
		srv := httptest.NewServer(websocket.Handler(func(ws *websocket.Conn) {
			var event Event
			err := websocket.JSON.Receive(ws, &event)
			if err != nil {
				panic(err)
			}

			if event.Event != pusherPing {
				t.Errorf("Expected to get ping event, got %+v", event)
			}
			wg.Done()
		}))
		defer srv.Close()
		wsURL := strings.Replace(srv.URL, "http", "ws", 1)
		ws, err := websocket.Dial(wsURL, "ws", localOrigin)
		if err != nil {
			panic(err)
		}

		client := &Client{
			connected:     true,
			activityTimer: time.NewTimer(0),
			ws:            ws,
		}
		defer client.Disconnect()

		go client.heartbeat()

		wg.Wait()
	})

	t.Run("timerReset doesn't block", func(t *testing.T) {
		srv := httptest.NewServer(websocket.Handler(func(ws *websocket.Conn) {}))
		defer srv.Close()

		wsURL := strings.Replace(srv.URL, "http", "ws", 1)
		ws, err := websocket.Dial(wsURL, "ws", localOrigin)
		if err != nil {
			panic(err)
		}

		client := &Client{
			connected:          true,
			activityTimerReset: make(chan struct{}, 1),
			activityTimer:      time.NewTimer(1024 * time.Hour),
			activityTimeout:    0,
			ws:                 ws,
		}

		go client.heartbeat()
		runtime.Gosched()

		// If there's a bug in the implementation, this will block forever.
		// The test should timeout.
		done := make(chan struct{})
		go func() {
			client.resetActivityTimer()
			close(done)
		}()

		select {
		case <-done:
			// test passed
		case <-time.After(3 * time.Second):
			t.Errorf("Timeout waiting for resetActivityTimer to finish")
		}
	})
}

func TestClientListen(t *testing.T) {
	t.Run("notConnected", func(t *testing.T) {
		client := &Client{
			connected: false,
		}

		client.heartbeat()
	})

	t.Run("receivePing", func(t *testing.T) {
		wg := &sync.WaitGroup{}
		wg.Add(1)
		srv := httptest.NewServer(websocket.Handler(func(ws *websocket.Conn) {
			websocket.Message.Send(ws, pingPayload)

			var event Event
			err := websocket.JSON.Receive(ws, &event)
			if err != nil {
				panic(err)
			}

			if event.Event != pusherPong {
				t.Errorf("Expected to get pong event, got %+v", event)
			}
			wg.Done()
		}))
		defer srv.Close()
		wsURL := strings.Replace(srv.URL, "http", "ws", 1)
		ws, err := websocket.Dial(wsURL, "ws", localOrigin)
		if err != nil {
			panic(err)
		}

		client := &Client{
			connected: true,
			ws:        ws,
		}
		defer client.Disconnect()

		go client.listen()

		wg.Wait()
	})

	t.Run("receiveEvent", func(t *testing.T) {
		wantData := json.RawMessage(`{"hello":"world"}`)
		wantEvent := Event{
			Event:   "foo",
			Channel: "bar",
			Data:    wantData,
		}
		srv := httptest.NewServer(websocket.Handler(func(ws *websocket.Conn) {
			websocket.JSON.Send(ws, wantEvent)
		}))
		defer srv.Close()
		wsURL := strings.Replace(srv.URL, "http", "ws", 1)
		ws, err := websocket.Dial(wsURL, "ws", localOrigin)
		if err != nil {
			panic(err)
		}

		eventChan := make(chan Event)
		dataChan := make(chan json.RawMessage)
		client := &Client{
			connected: true,
			ws:        ws,
			boundEvents: map[string]boundEventChans{
				wantEvent.Event: {eventChan: struct{}{}},
			},
			subscribedChannels: map[string]internalChannel{
				wantEvent.Channel: &channel{
					boundEvents: map[string]boundDataChans{
						wantEvent.Event: {dataChan: make(chan struct{})},
					},
				},
			},
		}
		defer client.Disconnect()

		wg := &sync.WaitGroup{}
		wg.Add(1)
		go func() {
			if gotEvent := <-eventChan; !reflect.DeepEqual(gotEvent, wantEvent) {
				t.Errorf("Expected to receive event %+v, got %+v", wantEvent, gotEvent)
			}
			if gotData := <-dataChan; !reflect.DeepEqual(gotData, wantData) {
				t.Errorf("Expected to receive data %+v, got %+v", wantData, gotData)
			}
			wg.Done()
		}()

		go client.listen()

		wg.Wait()
	})

	t.Run("receiveError", func(t *testing.T) {
		wantError := EventError{
			Code:    1234,
			Message: "foo",
		}
		errData, err := json.Marshal(wantError)
		if err != nil {
			panic(err)
		}
		srv := httptest.NewServer(websocket.Handler(func(ws *websocket.Conn) {
			for {
				websocket.JSON.Send(ws, Event{Event: pusherError, Data: errData})
			}
		}))
		defer srv.Close()
		wsURL := strings.Replace(srv.URL, "http", "ws", 1)
		ws, err := websocket.Dial(wsURL, "ws", localOrigin)
		if err != nil {
			panic(err)
		}

		client := &Client{
			connected: true,
			ws:        ws,
			Errors:    make(chan error),
		}
		defer client.Disconnect()

		wg := &sync.WaitGroup{}
		wg.Add(1)
		go func() {
			if gotError := <-client.Errors; !reflect.DeepEqual(gotError, wantError) {
				t.Errorf("Expected to receive event %+v, got %+v", wantError, gotError)
			}
			wg.Done()
		}()

		go client.listen()

		wg.Wait()
	})
}

func TestClientGenerateConnURL(t *testing.T) {
	t.Run("defaults", func(t *testing.T) {
		wantAppKey := "foo"
		client := &Client{}
		gotURL := client.generateConnURL(wantAppKey)
		if !strings.Contains(gotURL, secureScheme) {
			t.Errorf("Expected connection URL to have secure scheme, got %q", gotURL)
		}
		if !strings.Contains(gotURL, fmt.Sprint(securePort)) {
			t.Errorf("Expected connection URL to have secure port, got %q", gotURL)
		}
		if !strings.Contains(gotURL, defaultHost) {
			t.Errorf("Expected connection URL to have default host, got %q", gotURL)
		}
		if !strings.Contains(gotURL, wantAppKey) {
			t.Errorf("Expected connection URL to have app key, got %q", gotURL)
		}
	})

	t.Run("custom", func(t *testing.T) {
		wantAppKey := "foo"
		client := &Client{
			Insecure: true,
			Cluster:  "bar",
		}
		gotURL := client.generateConnURL(wantAppKey)
		if !strings.Contains(gotURL, insecureScheme) {
			t.Errorf("Expected connection URL to have insecure scheme, got %q", gotURL)
		}
		if !strings.Contains(gotURL, fmt.Sprint(insecurePort)) {
			t.Errorf("Expected connection URL to have insecure port, got %q", gotURL)
		}
		if !strings.Contains(gotURL, "pusher.com") {
			t.Errorf("Expected connection URL to have pusher.com, got %q", gotURL)
		}
		if !strings.Contains(gotURL, client.Cluster) {
			t.Errorf("Expected connection URL to have custom cluster, got %q", gotURL)
		}
		if !strings.Contains(gotURL, wantAppKey) {
			t.Errorf("Expected connection URL to have app key, got %q", gotURL)
		}
	})

	t.Run("override", func(t *testing.T) {
		client := &Client{
			overrideHost: "foo.bar",
			overridePort: 1234,
		}

		gotURL := client.generateConnURL("")
		if !strings.Contains(gotURL, client.overrideHost) {
			t.Errorf("Expected connection URL to have override host, got %q", gotURL)
		}
		if !strings.Contains(gotURL, fmt.Sprint(client.overridePort)) {
			t.Errorf("Expected connection URL to have override port, got %q", gotURL)
		}
	})
}

func TestClientConnect(t *testing.T) {
	t.Run("pusherError", func(t *testing.T) {
		wantError := EventError{
			Code:    1234,
			Message: "foo",
		}
		errData, err := json.Marshal(wantError)
		if err != nil {
			panic(err)
		}
		srv := httptest.NewServer(websocket.Handler(func(ws *websocket.Conn) {
			for {
				websocket.JSON.Send(ws, Event{Event: pusherError, Data: errData})
			}
		}))
		defer srv.Close()

		host, port, err := net.SplitHostPort(strings.TrimPrefix(srv.URL, "http://"))
		if err != nil {
			panic(err)
		}
		portNum, err := strconv.Atoi(port)
		if err != nil {
			panic(err)
		}

		client := &Client{
			Insecure:     true,
			overrideHost: host,
			overridePort: portNum,
		}
		defer client.Disconnect()

		connectErr := client.Connect("")
		if !reflect.DeepEqual(connectErr, wantError) {
			t.Errorf("Expected error to deep-equal %+v, got %+v", wantError, connectErr)
		}
	})

	t.Run("connectionEstablished", func(t *testing.T) {
		wantConnData := connectionData{
			SocketID:        "foo",
			ActivityTimeout: 1234,
		}
		connData, err := json.Marshal(wantConnData)
		if err != nil {
			panic(err)
		}
		connDataStr, err := json.Marshal(string(connData))
		if err != nil {
			panic(err)
		}
		srv := httptest.NewServer(websocket.Handler(func(ws *websocket.Conn) {
			for {
				websocket.JSON.Send(ws, Event{Event: pusherConnEstablished, Data: connDataStr})
			}
		}))
		defer srv.Close()

		host, port, err := net.SplitHostPort(strings.TrimPrefix(srv.URL, "http://"))
		if err != nil {
			panic(err)
		}
		portNum, err := strconv.Atoi(port)
		if err != nil {
			panic(err)
		}

		client := &Client{
			Insecure:     true,
			overrideHost: host,
			overridePort: portNum,
		}
		defer client.Disconnect()

		err = client.Connect("")
		if err != nil {
			panic(err)
		}

		if client.connected != true {
			t.Errorf("Expected client connected to be true, got false")
		}
		if client.socketID != wantConnData.SocketID {
			t.Errorf("Expected client socket ID to be %v, got %v", wantConnData.SocketID, client.socketID)
		}
		wantTimeout := time.Duration(wantConnData.ActivityTimeout) * time.Second
		if client.activityTimeout != wantTimeout {
			t.Errorf("Expected client activity timeout to be %v, got %v", wantTimeout, client.activityTimeout)
		}
		if client.activityTimer == nil {
			t.Errorf("Expected client activity timer to be non-nil")
		}
		if client.activityTimerReset == nil {
			t.Errorf("Expected client activity timer reset channel to be non-nil")
		}
		if cap(client.activityTimerReset) != 1 {
			t.Errorf("Expected client activity timer reset channel to have capacity 1, got %v",
				cap(client.activityTimerReset))
		}
		if client.boundEvents == nil {
			t.Errorf("Expected client bound events to be non-nil")
		}
		if client.subscribedChannels == nil {
			t.Errorf("Expected client subscribed channels to be non-nil")
		}
	})
}


text:
package daoBean;

import javax.ejb.Local;
import javax.ejb.Stateless;

import model.PopisnaKomisija;
import rs.ac.uns.ftn.xws.sessionbeans.common.GenericDaoBean;

@Stateless
@Local(PopisnaKomisijaDaoLocal.class)
public class PopisnaKomisijaItemDao extends GenericDaoBean<PopisnaKomisija, Integer> implements PopisnaKomisijaDaoLocal{

}


text:
namespace librealsense
{
    const size_t PRESISTENCY_LUT_SIZE = 256;

    class temporal_filter : public depth_processing_block
    {
    public:
        temporal_filter();

    protected:
        void    update_configuration(const rs2::frame& f);
        rs2::frame process_frame(const rs2::frame_source& source, const rs2::frame& f) override;

        rs2::frame prepare_target_frame(const rs2::frame& f, const rs2::frame_source& source);

        template<typename T>
        void temp_jw_smooth(void* frame_data, void * _last_frame_data, uint8_t *history)
        {
            static_assert((std::is_arithmetic<T>::value), "temporal filter assumes numeric types");

            const bool fp = (std::is_floating_point<T>::value);

            T delta_z = static_cast<T>(_delta_param);

            auto frame          = reinterpret_cast<T*>(frame_data);
            auto _last_frame    = reinterpret_cast<T*>(_last_frame_data);

            unsigned char mask = 1 << _cur_frame_index;

            // pass one -- go through image and update all
            for (size_t i = 0; i < _current_frm_size_pixels; i++)
            {
                T cur_val = frame[i];
                T prev_val = _last_frame[i];

                if (cur_val)
                {
                    if (!prev_val)
                    {
                        _last_frame[i] = cur_val;
                        history[i] = mask;
                    }
                    else
                    {  // old and new val
                        T diff = static_cast<T>(fabs(cur_val - prev_val));

                        if (diff < delta_z)
                        {  // old and new val agree
                            history[i] |= mask;
                            float filtered = _alpha_param * cur_val + _one_minus_alpha * prev_val;
                            T result = static_cast<T>(filtered);
                            frame[i] = result;
                            _last_frame[i] = result;
                        }
                        else
                        {
                            _last_frame[i] = cur_val;
                            history[i] = mask;
                        }
                    }
                }
                else
                {  // no cur_val
                    if (prev_val)
                    { // only case we can help
                        unsigned char hist = history[i];
                        unsigned char classification = _persistence_map[hist];
                        if (classification & mask)
                        { // we have had enough samples lately
                            frame[i] = prev_val;
                        }
                    }
                    history[i] &= ~mask;
                }
            }

            _cur_frame_index = (_cur_frame_index + 1) % 8;  // at end of cycle
        }

    private:
        void on_set_persistence_control(uint8_t val);
        void on_set_alpha(float val);
        void on_set_delta(float val);

        void recalc_persistence_map();
        uint8_t                 _persistence_param;

        float                   _alpha_param;               // The normalized weight of the current pixel
        float                   _one_minus_alpha;
        uint8_t                 _delta_param;               // A threshold when a filter is invoked
        size_t                  _width, _height, _stride;
        size_t                  _bpp;
        rs2_extension           _extension_type;            // Strictly Depth/Disparity
        size_t                  _current_frm_size_pixels;
        rs2::stream_profile     _source_stream_profile;
        rs2::stream_profile     _target_stream_profile;
        std::vector<uint8_t>    _last_frame;                // Hold the last frame received for the current profile
        std::vector<uint8_t>    _history;                   // represents the history over the last 8 frames, 1 bit per frame
        uint8_t                 _cur_frame_index;
        // encodes whether a particular 8 bit history is good enough for all 8 phases of storage
        std::array<uint8_t, PRESISTENCY_LUT_SIZE> _persistence_map;
    };
    MAP_EXTENSION(RS2_EXTENSION_TEMPORAL_FILTER, librealsense::temporal_filter);
}