text:
def isPalindrome(iSequence):
    if len(iSequence)> 0:
        first = 0
        last  = len(iSequence) - 1
        pivot = (len(iSequence) /2 )
        while(first <= pivot):
            if(iSequence[first] != iSequence[last]):
                return False
            else:
                first += 1
                last  -= 1
        return True
    return False

def isPal(iSequence):
    return iSequence[0:len(iSequence)/2] == iSequence[len(iSequence)/2:][::-1]

if __name__ == "__main__":
    palindromes = ["", "aa", "abba", "aba", "abbb"]
    for p in palindromes:
        print p, isPalindrome(p)
        print p, isPal(p)

redpajama_set_name: RedPajamaGithub


text:
import numpy as np
import warnings
#Everything else is imported locally when needed

class LinReg:
#########################################################################################
#                                   Linear regression                                   #
#                                                                                #
#        Louis-Francois Arsenault, Columbia University la2518@columbia.edu (2016)       #
#########################################################################################
#                                                                                #
#       INPUTS:                                                                         #
#       	X : A ndarray representing a matrix with Nlearn lines with all known	#
#		    examples and the columns are the dimension of one x			#
#   		y : a 1d array representing a NlearnX1 vector with values for each known#
#		    examples								#
#	OUTPUTS: 									#

#Verify multiple outputs

	def __init__(self):
		pass

	def train(self,X,y):
		#We treat the constant term as part of the coeffs. w and thus
		#need to add 1 at the end of every input
		OneVec = np.ones((X.shape[0],1))
		XX = np.concatenate((X, OneVec), axis=1)

		#How many intances, dimensions of the inputs and how many outputs
		SizeXX = XX.shape
		self.pdim = SizeXX[1]
		self.Nlearn = SizeXX[0]
		if y.ndim == 2:
			self.Nout = y.shape[1]
		else:
			self.Nout = 1

		if self.pdim <= self.Nlearn:
			A = np.dot(XX.transpose(),XX)
			self.w = np.linalg.solve(A,XX.transpose().dot(y))
			self.method = "pxp"
		else:
			A = np.dot(XX,XX.transpose())
			wp = np.linalg.solve(A,y)
			self.w = wp.dot(XX)
			self.method = "NxN"

	def query(self,Xt):
		OneVec = np.ones((Xt.shape[0],1))
                XX = np.concatenate((Xt, OneVec), axis=1)
                return XX.dot(self.w)

	def score(self,Xt,ytrue,metric='MAE'):
	#Calculate the mean absolute error MAE by default, mean square error MSE or
	# correlation coeff CORR
		ypredic = self.query(Xt)
		if metric == 'MAE':
			return np.sum(np.absolute(ypredic-ytrue),axis=0)/len(ytrue)
		elif metric == 'MSE':
			ydiff = (ypredic-ytrue)
                        return np.sum(ydiff**2,axis=0)/len(ytrue)

#########################################################################################

class RidgeReg:
#########################################################################################
#                                   Ridge regression	                                #
#                                                                                #
#        Louis-Francois Arsenault, Columbia University la2518@columbia.edu (2016)       #
#########################################################################################
#                                                                                #
#       INPUTS:                                                                         #
#	   train:									#
#               X      : A ndarray representing a matrix with Nlearn lines with all	#
#			 known examples and the columns are the dimension of one x      #
#               y      : a 1d array representing a NlearnX1 vector with values for each	#
#		         known examples                                                 #
#		lam    : Regularization parameter					#
#	   query:									#
#		Xt     : A ndarray representing a matrix with Ntest lines with all the 	#
#			 test examples and the columns are the dimension of one x	#
#	   score:									#
#		Xt     : Same as in query						#
#		ytrue  : A 1d array with the values for the test set			#
#		metric : The error metric 'MAE' (default) or 'MSE'			#
#											#
#       OUTPUTS:                                                                        #

	def __init__(self,solver='exact',eta=None,tol=None,Nbatch=None,epochMax=None):
		self.solver=solver
		if solver is 'sg':
			self.Nbatch=Nbatch
                        self.eta=eta
                        self.epochMax=epochMax
                        self.tol=tol
		elif solver is not 'exact':
			raise ValueError('solver must be exact or sg only')

	def __deriv_forSG(self,w,XX,y,lam):
		nfeat=len(XX)
		Imat = np.identity(nfeat)
                Imat[nfeat-1][nfeat-1] = 0.
		return -y*XX + (np.outer(XX,XX)+lam*Imat).dot(w)

	def __deriv(self,w,XX,y,lam):
		nfeat=XX.shape[1]
		Imat = np.identity(nfeat)
                Imat[nfeat-1][nfeat-1] = 0.
		return -np.dot(XX.T,y) + (np.dot(XX.T,XX)+lam*Imat ).dot(w)

	def train(self,X,y,lam):
                #We treat the constant term as part of the coeffs. w and thus
                #need to add 1 at the end of every input
                OneVec = np.ones((X.shape[0],1))
                XX = np.concatenate((X, OneVec), axis=1)

		#How many intances, dimensions of the inputs and how many outputs
                SizeXX = XX.shape
                self.pdim = SizeXX[1]
                self.Nlearn = SizeXX[0]
		self.lam=lam

		if self.solver is 'exact':
			if y.ndim == 2:
                        	self.Nout = y.shape[1]
                	else:
                        	self.Nout = 1

                	if self.pdim <= self.Nlearn:
                        	Imat = np.identity(self.pdim)
                        	Imat[self.pdim-1][self.pdim-1] = 0.
                        	A = np.dot(XX.transpose(),XX) + lam*Imat
                        	self.w = np.linalg.solve(A,XX.transpose().dot(y))
                        	self.method = "pxp"
                	else:
			#In the case where there are less examples N than features dimensions
			#p, switch to a NxN approach, giving the solution with the smallest l2
			#norm among the infinite possible solutions
                        	Imat = np.identity(self.Nlearn)
                        	Imat[self.Nlearn-1][self.Nlearn-1] = 0.
                        	A = np.dot(XX,XX.transpose()) + lam*Imat
                        	wp = np.linalg.solve(A,y)
                        	self.w = wp.dot(XX)
                        	self.method = "NxN"
		else:
			#Using stochastic gradient descent found in NumMethos directory
                        from NumMethods import StochGrad
                        if self.Nbatch==1:
                                w_0,ep,ite,mess=StochGrad(self.__deriv_forSG,w_0,XX,y,self.Nlearn,(lam/self.Nlearn),lam/self.Nlearn,eta=self.eta,tol=self.tol,epochMax=self.epochMax,Nbatch=self.Nbatch)
                        else:
                                w_0,ep,ite,mess=StochGrad(self.__deriv,w_0,XX,y,self.Nlearn,(lam/self.Nlearn),lam/self.Nlearn,eta=self.eta,tol=self.tol,epochMax=self.epochMax,Nbatch=self.Nbatch)
                        self.w=w_0
                        self.epoch=ep

        def query(self,Xt):
		OneVec = np.ones((Xt.shape[0],1))
                XX = np.concatenate((Xt, OneVec), axis=1)
                return XX.dot(self.w)

	def score(self,Xt,ytrue,metric='MAE'):
        #Calculate the mean absolute error MAE by default, mean square error MSE or
	#correlation coeff CORR
                ypredic = self.query(Xt)
                if metric == 'MAE':
                        return np.sum(np.absolute(ypredic-ytrue),axis=0)/len(ytrue)
                elif metric == 'MSE':
                        ydiff = (ypredic-ytrue)
                        return np.sum(ydiff**2,axis=0)/len(ytrue)

#########################################################################################


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

public class PlayerStats : MonoBehaviour {

	public bool playerIsAlive = true;
	public bool playerHelmet = false;
	public Vector3 position = new Vector3(1000f, 1000f, 1000f);
	[HideInInspector] public Vector3 resetPosition = new Vector3(1000f, 1000f, 1000f);
	public float playerHealth = 100.0f;
	[Header("Supply the list of available damage types:")]
	public List<string> damageType = new List<string>();
	[Header("Supply the corresponding list of blood effects")]
	public List<GameObject> bloodEffect = new List<GameObject> ();
	[Header("Supply the corresponding list of death animations:")]
	public List<Rigidbody> deadPlayer = new List<Rigidbody>();
	//public Rigidbody deadPlayer;
	private Rigidbody dropWeapon;
	private PlayerWeaponChange playerWeaponChange;
	private UsableWeapons usableWeapons;
	[HideInInspector] public Vector3 damageForce = Vector3.zero;
	private GameObject playerGO;
	private Vector3 dropPoint;
	private Rigidbody deadBody;
	[HideInInspector] public float explosionForce = 0.0f;
	[HideInInspector] public Vector3 explosionLocation = Vector3.zero;
	private int damageTypeIndex;

	private CenterMessageController centerMessageController;

	void Awake(){
		playerGO = GameObject.FindGameObjectWithTag(Tags.player);
		centerMessageController = GameObject.FindGameObjectWithTag (Tags.canvas).GetComponentInChildren<CenterMessageController> ();
	}

	void Update(){
		//If the player health is <= 0, destroy the player
		if(playerHealth <= 0.0f){
			if(playerIsAlive){ //Test to see if the player health has just crossed below 0.0

				centerMessageController.UpdateCenterMessage("Press Tab to Restart");
				centerMessageController.FlashCenterMessageAfterSeconds(0.5f);

				playerWeaponChange = playerGO.GetComponent<PlayerWeaponChange>();

				dropPoint = playerWeaponChange.dropPoint.position;
				//Test to see if the dropPoint is being blocked by an obstacle...
				RaycastHit wallHit;
				if(Physics.Raycast (playerWeaponChange.transform.position, (dropPoint - playerWeaponChange.transform.position), out wallHit, (dropPoint - playerWeaponChange.transform.position).magnitude, 1 << LayerMask.NameToLayer("Environment_Collision"))){
					dropPoint = playerWeaponChange.transform.position+(wallHit.point-playerWeaponChange.transform.position)*0.8f;
				}

				usableWeapons = GameObject.FindGameObjectWithTag(Tags.gameController).GetComponent<UsableWeapons>();

				if(playerWeaponChange.hasPrimaryWeap == true){
					string equippedWeaponName = playerWeaponChange.primaryEquipped.gameObject.GetComponent<weaponIndex> ().weaponName;
					int equippedWeaponIndex = usableWeapons.primaryUsableWeapons.IndexOf (equippedWeaponName);
					dropWeapon = Instantiate(usableWeapons.worldPrimaryUsableWeapons [equippedWeaponIndex], dropPoint, playerWeaponChange.primarySpawnpoint.rotation) as Rigidbody;
					dropWeapon.AddForce(playerGO.GetComponent<Rigidbody>().velocity*playerWeaponChange.dropForce);
					dropWeapon.AddTorque (transform.up*playerWeaponChange.dropForce*Random.Range(-0.5f, 0.5f));
					dropWeapon.GetComponent<weaponIndex>().ammoCount = playerWeaponChange.primaryEquipped.gameObject.GetComponent<weaponIndex> ().ammoCount;
				}
				if(playerWeaponChange.hasSecondaryWeap == true){
					string equippedWeaponName = playerWeaponChange.secondaryEquipped.gameObject.GetComponent<weaponIndex> ().weaponName;
					int equippedWeaponIndex = usableWeapons.secondaryUsableWeapons.IndexOf (equippedWeaponName);
					dropWeapon = Instantiate(usableWeapons.worldSecondaryUsableWeapons [equippedWeaponIndex], dropPoint, playerWeaponChange.secondarySpawnpoint.rotation) as Rigidbody;
					dropWeapon.AddForce(playerGO.GetComponent<Rigidbody>().velocity*playerWeaponChange.dropForce);
					dropWeapon.AddTorque (transform.up*playerWeaponChange.dropForce*Random.Range(-0.5f, 0.5f));
					dropWeapon.GetComponent<weaponIndex>().ammoCount = playerWeaponChange.secondaryEquipped.gameObject.GetComponent<weaponIndex> ().ammoCount;
				}
				deadBody = Instantiate (deadPlayer[damageTypeIndex], playerGO.transform.position, playerWeaponChange.primarySpawnpoint.rotation) as Rigidbody;

				//Check for helmet...
				if(deadBody.GetComponent<Animator>()){
					Animator[] anims = playerGO.GetComponentsInChildren<Animator> ();
					Animator deadBodyAnim = deadBody.GetComponent<Animator>();
					foreach (Animator a in anims) {
						AnimatorControllerParameter[] acps = a.parameters;
						foreach (AnimatorControllerParameter acp in acps){
							if(acp.name == "helmetEquipped"){
								bool currentValue = a.GetBool ("helmetEquipped");
								deadBodyAnim.SetBool ("helmetEquipped", currentValue);
								break;
							}
						}
					}
					AnimatorControllerParameter[] deadBodyAcp = deadBodyAnim.parameters;
					AnimatorControllerParameterType paramType = AnimatorControllerParameterType.Bool;
					int randomIndex = 0;
					while (paramType != AnimatorControllerParameterType.Trigger){
						randomIndex = Random.Range (0, deadBodyAcp.Length); //Random.Range is exclusive for the 2nd value
						paramType = deadBodyAcp[randomIndex].type;
					}
					deadBodyAnim.SetTrigger (deadBodyAcp [randomIndex].name);
				}
				//End check for helmet

				if(damageForce != Vector3.zero){
					deadBody.AddForce (damageForce);
				}
				if(explosionForce != 0.0f){
					//deadBody.AddExplosionForce(explosionForce, explosionLocation, explosionRadius);
					deadBody.AddForce (explosionForce*((playerGO.transform.position - explosionLocation).normalized));
				}
			}
			playerIsAlive = false;
			Destroy(playerGO);

		}

	}

	public void BloodEffects(string damType, Vector3 damPosition, Quaternion damRotation){
		damageTypeIndex = damageType.IndexOf(damType);
		Instantiate (bloodEffect [damageTypeIndex], damPosition, damRotation);

	}

}


text:
class Event {
    constructor(start, end) {
        this.start = start;
        this.end = end;
        this.next = null;
    }
}

class MyCalendar {
    constructor() {
        this.eventHead = new Event(Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY);
    }
    /**
     * @param {number} start
     * @param {number} end
     * @return {boolean}
     */
    book(start, end) {
        let curr = this.eventHead;
        while (curr.next != null && curr.next.end <= start) {
            curr = curr.next;
        }
        if (curr.next === null) {
            curr.next = new Event(start, end);
            return true;
        }
        if (curr.next.start < end) {
            return false;
        }
        let newEvent = new Event(start, end);
        newEvent.next = curr.next;
        curr.next = newEvent;
        return true;
    }
};

module.exports = MyCalendar;

/**
 * Your MyCalendar object will be instantiated and called as such:
 * var obj = Object.create(MyCalendar).createNew()
 * var param_1 = obj.book(start,end)
 */


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.api.integration.aws;

import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.HostName;
import com.yahoo.config.provision.zone.ZoneApi;
import com.yahoo.config.provision.zone.ZoneId;

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

/**
 * @author olaa
 */
public class MockResourceTagger implements ResourceTagger {

    Map<ZoneId, Map<HostName, ApplicationId>> values = new HashMap<>();

    @Override
    public int tagResources(ZoneApi zone, Map<HostName, ApplicationId> ownerOfHosts) {
        values.put(zone.getId(), ownerOfHosts);
        return 0;
    }

    public Map<ZoneId, Map<HostName, ApplicationId>> getValues() {
        return values;
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Proc. Linn. Soc. N. S. W. 82: 14 (1957)

#### Original name
Guignardia acaciae Hansf.

### Remarks
null


text:
package etong.lineanimation;

import android.graphics.PorterDuff;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.view.DraweeTransition;
import com.facebook.drawee.view.SimpleDraweeView;

import java.util.ArrayList;
import java.util.List;

public class DetailActivity extends AppCompatActivity implements AppBarLayout.OnOffsetChangedListener {

    public final static String VIEW_NAME_HEADER_IMAGE = "header_image";
    public final static String VIEW_NAME_HEADER_TITLE = "header_title";

    public final static String TITLE = "titleTextView";
    public final static String SUBTITLE = "subTitleView";
    public final static String IMAGEURL = "imageUrl";

    AppBarLayout appBar;
    CollapsingToolbarLayout collapsingToolbar;
    SimpleDraweeView bgImageView;
    SubtitleView subtitleView;
    TextView titleTextView;
    Toolbar toolbar;
    RecyclerView recyclerView;

    String title;
    String backgroundImage;
    String subTitle;

    Button button;

    List<String> list = new ArrayList<>();

    private int subtitleMargin;
    private int minLength;
    private int maxTitleWidth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        appBar = (AppBarLayout) findViewById(R.id.app_bar);
        collapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsingToolbar);
        bgImageView = (SimpleDraweeView) findViewById(R.id.bgImageView);
        subtitleView = (SubtitleView) findViewById(R.id.subTitle);
        titleTextView = (TextView) findViewById(R.id.title);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);

        title = getIntent().getStringExtra(TITLE);
        subTitle = getIntent().getStringExtra(SUBTITLE);
        backgroundImage = getIntent().getStringExtra(IMAGEURL);

        button = (Button) findViewById(R.id.button);

        list.add("123");
        list.add("123");
        list.add("123");
        list.add("123");
        list.add("123");
        list.add("123");
        list.add("123");
        list.add("123");
        list.add("123");
        list.add("123");
        list.add("123");
        list.add("123");
        list.add("123");
        list.add("123");
        list.add("123");
        list.add("123");

        subtitleMargin = getResources().getDimensionPixelSize(R.dimen.subtitle_margin);
        minLength = getResources().getDimensionPixelSize(R.dimen.min_length);
        maxTitleWidth = ScreenUtils.screenWidth - subtitleMargin * 2 - minLength * 2;
        onAfterViews();
    }

    void onAfterViews() {
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.getNavigationIcon().setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.MULTIPLY);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });

        ViewCompat.setTransitionName(bgImageView, VIEW_NAME_HEADER_IMAGE);
        ViewCompat.setTransitionName(titleTextView, VIEW_NAME_HEADER_TITLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//解决SimpleDraweeView不能加载图片问题
            getWindow().setSharedElementEnterTransition(
                    DraweeTransition.createTransitionSet(ScalingUtils.ScaleType.CENTER_CROP,
                            ScalingUtils.ScaleType.CENTER_CROP)); // 进入
            getWindow().setSharedElementReturnTransition(
                    DraweeTransition.createTransitionSet(ScalingUtils.ScaleType.CENTER_CROP,
                            ScalingUtils.ScaleType.CENTER_CROP)); // 返回
        }

        collapsingToolbar.setTitle(" ");

        titleTextView.setText(title);
        if (!TextUtils.isEmpty(subTitle)) {
            ((CollapsingToolbarLayout.LayoutParams) titleTextView.getLayoutParams()).setParallaxMultiplier(0.65f);
            subtitleView.setVisibility(View.VISIBLE);
            subtitleView.setText(subTitle);
            subtitleView.setTextColor(0x00ffffff);
            subtitleView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    subtitleView.animate(1);
                    appBar.addOnOffsetChangedListener(DetailActivity.this);
                }
            }, 500);

            titleTextView.post(new Runnable() {
                @Override
                public void run() {
                    calculateSubTitle();
                }
            });
        } else {
            titleTextView.setY(ScreenUtils.dip2px(16));
            ((CollapsingToolbarLayout.LayoutParams) titleTextView.getLayoutParams()).setParallaxMultiplier(0.5f);
            subtitleView.setVisibility(View.GONE);
        }

        bgImageView.setImageURI(backgroundImage);

        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(new SimpleAdapter(list));

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                subtitleView.setPercent(0);
                subtitleView.animate(1);
            }
        });
    }

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        if (!TextUtils.isEmpty(subTitle)) {
            float value = appBar.getHeight() - toolbar.getHeight() * 2;
            float p = (value + verticalOffset) / value;
            if (p < 0) {
                p = 0;
            }
            subtitleView.setPercent(p);
        }

//        if (Math.abs(verticalOffset) > appBarLayout.getHeight() / 2) {
//            int color = getResources().getColor(R.color.colorPrimary);
//            titleTextView.setTextColor(color);
//            toolbar.getNavigationIcon().setColorFilter(color, PorterDuff.Mode.MULTIPLY);
//        } else {
//            int white = getResources().getColor(R.color.white);
//            toolbar.getNavigationIcon().setColorFilter(white, PorterDuff.Mode.MULTIPLY);
//            titleTextView.setTextColor(white);
//        }

    }

    public void calculateSubTitle() {
        int titleWidth = titleTextView.getWidth();

        if (titleWidth > maxTitleWidth) {
            titleTextView.getLayoutParams().width = maxTitleWidth;
            subtitleView.getLayoutParams().width = maxTitleWidth + minLength * 2;
            subtitleView.setLength(minLength * 2);
            subtitleView.requestLayout();
            titleTextView.requestLayout();
        } else if (subtitleView.getWidth() > ScreenUtils.screenWidth - subtitleMargin * 2) {
            subtitleView.getLayoutParams().width = ScreenUtils.screenWidth - subtitleMargin * 2;
            subtitleView.setLength(subtitleView.getLayoutParams().width - titleWidth);
            subtitleView.requestLayout();
        } else if (subtitleView.getWidth() < titleWidth + minLength * 2) {
            subtitleView.getLayoutParams().width = titleWidth + minLength * 2;
            subtitleView.setLength(subtitleView.getLayoutParams().width - titleWidth);
            subtitleView.requestLayout();
        } else {
            subtitleView.setLength(subtitleView.getLayoutParams().width - titleWidth);
            subtitleView.requestLayout();
        }
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        subtitleView.setVisibility(View.GONE);
    }
}


text:
namespace net {

// Provides the core logic needed for randomized exponential back-off
// on requests to a given resource, given a back-off policy.
//
// This utility class knows nothing about network specifics; it is
// intended for reuse in various networking scenarios.
class NET_EXPORT_PRIVATE BackoffEntry
    : NON_EXPORTED_BASE(public base::NonThreadSafe) {
 public:
  // The set of parameters that define a back-off policy.
  struct Policy {
    // Number of initial errors (in sequence) to ignore before applying
    // exponential back-off rules.
    int num_errors_to_ignore;

    // Initial delay for exponential back-off.
    int initial_backoff_ms;

    // Factor by which the waiting time will be multiplied.
    double multiply_factor;

    // Fuzzing percentage. ex: 10% will spread requests randomly
    // between 90%-100% of the calculated time.
    double jitter_factor;

    // Maximum amount of time we are willing to delay our request, -1
    // for no maximum.
    int64 maximum_backoff_ms;

    // Time to keep an entry from being discarded even when it
    // has no significant state, -1 to never discard.
    int64 entry_lifetime_ms;
  };

  // Lifetime of policy must enclose lifetime of BackoffEntry. The
  // pointer must be valid but is not dereferenced during construction.
  explicit BackoffEntry(const Policy* const policy);
  virtual ~BackoffEntry();

  // Inform this item that a request for the network resource it is
  // tracking was made, and whether it failed or succeeded.
  void InformOfRequest(bool succeeded);

  // Returns true if a request for the resource this item tracks should
  // be rejected at the present time due to exponential back-off policy.
  bool ShouldRejectRequest() const;

  // Returns the absolute time after which this entry (given its present
  // state) will no longer reject requests.
  base::TimeTicks GetReleaseTime() const;

  // Causes this object reject requests until the specified absolute time.
  // This can be used to e.g. implement support for a Retry-After header.
  void SetCustomReleaseTime(const base::TimeTicks& release_time);

  // Returns true if this object has no significant state (i.e. you could
  // just as well start with a fresh BackoffEntry object), and hasn't
  // had for Policy::entry_lifetime_ms_.
  bool CanDiscard() const;

  // Resets this entry to a fresh (as if just constructed) state.
  void Reset();

  // Returns the failure count for this entry.
  int failure_count() const { return failure_count_; }

 protected:
  // Equivalent to TimeTicks::Now(), virtual so unit tests can override.
  virtual base::TimeTicks ImplGetTimeNow() const;

 private:
  // Calculates when requests should again be allowed through.
  base::TimeTicks CalculateReleaseTime() const;

  // Timestamp calculated by the exponential back-off algorithm at which we are
  // allowed to start sending requests again.
  base::TimeTicks exponential_backoff_release_time_;

  // Counts request errors; reset on success.
  int failure_count_;

  const Policy* const policy_;

  DISALLOW_COPY_AND_ASSIGN(BackoffEntry);
};

}  // namespace net

#endif  // NET_BASE_BACKOFF_ITEM_H_


text:
<!DOCTYPE html>

  <title>background.coffee</title>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <meta name="viewport" content="width=device-width, target-densitydpi=160dpi, initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">
  <link rel="stylesheet" media="all" href="docco.css" />

          Jump To …
          +

                analytics.coffee

                background.coffee

                i18n.coffee

                install.coffee

                log.coffee

                notification.coffee

                options.coffee

                popup.coffee

                store.coffee

                utils.coffee

background.coffee

                ¶

iOrder
(c) 2013 Alasdair Mercer
Freely distributable under the MIT license.
For all details and documentation:
http://neocotic.com/iOrder

Private constants

                ¶

Extension ID being used by iOrder.

EXTENSION_ID      = i18n.get '@@extension_id'

                ¶

Domain of this extension's homepage.

HOMEPAGE_DOMAIN   = 'neocotic.com'

                ¶

Extension ID of the production version of iOrder.

REAL_EXTENSION_ID = 'kflemogpkbophbipihnbcmlplbihbdhb'

                ¶

Private variables

                ¶

Indicate whether or not iOrder has just been installed.

isNewInstall      = no

                ¶

Indicate whether or not iOrder is currently running the production build.

isProductionBuild = EXTENSION_ID is REAL_EXTENSION_ID

                ¶

Number of status updates since the user last cleared it.

updates           = 0

                ¶

Private functions

                ¶

Inject and execute install.coffee within each of the tabs provided (where valid).

executeScriptsInExistingTabs = (tabs) ->
  log.trace()
  log.info 'Retrieved the following tabs...', tabs
  for tab in tabs when tab.url.indexOf(HOMEPAGE_DOMAIN) isnt -1
    chrome.tabs.executeScript tab.id, file: 'lib/install.js'

                ¶

Inject and execute install.coffee within all the tabs (where valid) of each Chrome window.

executeScriptsInExistingWindows = ->
  log.trace()
  chrome.windows.getAll null, (windows) ->
    log.info 'Retrieved the following windows...', windows
    for win in windows
      chrome.tabs.query windowId: win.id, executeScriptsInExistingTabs

                ¶

Return the number of status updates detected by this extension for an order since the specified
time.

getOrderStatusUpdates = (order, lastRead) ->
  log.trace()
  count = 0
  count++ for update in order.updates when update.timeStamp > lastRead
  count

                ¶

Return the recognized status that matches the specified text.

getStatus = (text) ->
  log.trace()
  ext.config.apple.status[getStatusIndex text]

                ¶

Return the index of the recognized status that matches the specified text.

getStatusIndex = (text) ->
  log.trace()
  text = text?.trim()
  return i for status, i in ext.config.apple.status when status.value.test text
  -1

                ¶

Return the total number of detected status updates for all existing orders since the last time
badges were cleared.

getStatusUpdates = ->
  log.trace()
  count    = 0
  lastRead = store.get 'lastRead'
  count += getOrderStatusUpdates order, lastRead for order in ext.orders
  count

                ¶

Return all windows managed by this extension that are displaying a page that begins with the
specified URL.

getWindows = (url) ->
  log.trace()
  chrome.extension.getViews(type: 'tab').filter (element) ->
    element.location.href.indexOf(url) is 0

                ¶

Determine whether or not an order already has the specified status.

isOrderStatusNew = (order, status) ->
  log.trace()
  return no for update in order.updates when update.status is status
  yes

                ¶

Ensure any badge notification is cleared.

markRead = (retainTimeStamp) ->
  log.trace()
  updates = 0
  store.set 'lastRead', $.now() unless retainTimeStamp
  do setBadge

                ¶

Update the UI so the clear button vanishes.

  do updatePopup

                ¶

Attempt to notify the user of any unread status updates.
If there are no status updates, remove any visible badge.

notify = ->
  log.trace()
  notifications = store.get 'notifications'
  oldUpdates    = updates
  updates       = getStatusUpdates()

                ¶

Update/clear badge depending on setting and updates available.

  setBadge if notifications.badges then updates or ''

                ¶

Show the notification when new updates are found.

  if updates > oldUpdates
    ext.notification.description = i18n.get 'notification'
    ext.notification.title       = i18n.get 'name'
    do showNotification
  else
    ext.reset()

                ¶

Listener for internal messages.
This function will handle the message based on its type and the data provided.

onMessage = (message, sender, sendResponse) ->
  log.trace()
  order = {}
  url   = ''

                ¶

Attempt to return the order whose details match the specified criteria.

  getOrder = (data) ->
    ext.queryOrder (order) -> order.key is data.key

                ¶

Check what needs to be done... and then do it.

  switch message.type
    when 'clear' then do markRead
    when 'options'

                ¶

Try using existing tabs for the options page before creating one.

      url = utils.url 'pages/options.html'
      selectOrCreateTab url, (isNew) ->
        return if isNew
        win.options.refresh() for win in getWindows url
    when 'info', 'version' then sendResponse? id: EXTENSION_ID, version: ext.version
    when 'refresh' then ext.updateOrders()
    when 'track'
      order = getOrder message.data
      chrome.tabs.create url: order.trackingUrl if order and order.trackingUrl
    when 'viewAll' then chrome.tabs.create url: ext.config.apple.url.list
    when 'view'
      order = getOrder message.data
      chrome.tabs.create url: ext.getOrderUrl order if order
  log.debug "Finished handling #{message.type} message"

                ¶

Attempt to select a tab in the current window displaying a page whose location begins with the
specified URL.
If no existing tab exists a new one is simply created.

selectOrCreateTab = (url, callback) ->
  log.trace()
  chrome.windows.getCurrent (win) ->
    log.debug 'Retrieved the following window...', win
    chrome.tabs.query windowId: win.id, (tabs) ->
      log.debug 'Retrieved the following tabs...', tabs

                ¶

Try to find an existing tab.

      for tab in tabs
        if tab.url.indexOf(url) is 0
          existingTab = tab
          break
      if existingTab

                ¶

Found one! Now to select it.

        chrome.tabs.update existingTab.id, selected: yes
        callback? no
      else

                ¶

Ach well, let's just create a new one.

        chrome.tabs.create url: url
        callback? yes

                ¶

Set the badge text to the specified string.
If no string is specified the badge is cleared.

setBadge = (str = '') ->
  log.trace()
  chrome.browserAction.setBadgeText text: String str

                ¶

Display a desktop notification informing the user on new order updates.
Also, ensure that ext is reset and that notifications are only displayed if the user has
enabled the corresponding option (which is enabled by default).

showNotification = ->
  log.trace()
  if store.get 'notifications.enabled'
    webkitNotifications.createHTMLNotification(utils.url 'pages/notification.html').show()
  else
    ext.reset()

                ¶

Send an AJAX request to the specified order's page on the Apple US store and parses the response
to update the order's properties.
If an error occurs during the update process assign a short description to order.error.

updateOrder = (order, callback) ->
  log.trace()
  $.get(ext.getOrderUrl order)
  .done (data) ->

                ¶

Probably won't happen; more of a sanity check.

    return order.error = 'update_invalid_page_error' unless data

                ¶

Extract the relevant elements wrapped in jQuery goodness.

    heading     = $(data).find '.order .ship-group .sb-heading'
    status      = heading.find 'h4 span:first-child'
    trackingUrl = heading.find """
      .group-actions tr:first-child td a[href^='#{ext.config.apple.url.track}']
    """

                ¶

Dig deeper and try and get the actual values.

    status      = getStatusIndex if status.length then status.text() else ''
    trackingUrl = if trackingUrl.length then trackingUrl.attr 'href' else ''
    if status >= 0

                ¶

OK, it was valid; but is it new???

      if isOrderStatusNew order, status

                ¶

Right! It was valid and new! Just add it already.

        order.updates.push
          status:    status
          timeStamp: $.now()
    else

                ¶

Bad user data or extension could need updated.

      return order.error = 'update_invalid_status_error'

                ¶

Only update the Track link if it was found.

    order.trackingUrl = trackingUrl if trackingUrl

                ¶

Clear any pre-existing errors.

    order.error = ''
  .fail ->

                ¶

Something went wrong.

    order.error = 'update_page_not_found_error'
  .always ->

                ¶

Done! Now let's tell the boss.

    callback?.apply updateManager, [order]

                ¶

Build the HTML to populate the popup with to optimize popup loading times and updates any popup
currently being displayed.

updatePopup = ->
  log.trace()
  do buildPopup
  chrome.extension.getViews(type: 'popup')[0]?.popup.init()

                ¶

Configuration functions

                ¶

Transform specific sections of the data loaded from configuration.json so that they're more
useable and localized.

buildConfig = ->
  log.trace()
  do buildFrequencies
  do buildStatus

                ¶

Transform the configuration frequencies into useable localized options.

buildFrequencies = ->
  log.trace()
  for mins, i in ext.config.frequencies
    hours = mins / 60
    ext.config.frequencies[i] = if mins is -1
      text:  i18n.get 'freq_disabled'
      value: mins
    else
      text:  (
        if hours < 1
          i18n.get 'freq_minutes', [mins]
        else if hours is 1
          i18n.get 'freq_hour'
        else
          i18n.get 'freq_hours', [hours]
      )
      value: mins * 60 * 1000

                ¶

Transform the configuration status into useable localized options.

buildStatus = ->
  log.trace()
  for status, i in ext.config.apple.status
    ext.config.apple.status[i] =
      text:  i18n.get "status_#{i}_text"
      value: /// ^ #{status} $ ///i

                ¶

HTML building functions

                ¶

Create a tr element to represent order.
The element should then be inserted in to the tbody element in the popup page but is created
here to optimize display times of the popup window.

buildOrder = (order) ->
  log.trace()
  log.debug "Creating popup table for #{order.label} (#{order.number})"
  row = $ '<tr/>'
  row.addClass 'error' if order.error
  column = $ '<td/>'
  if order.error
    column.append $ '<i/>',
      class: 'icon-exclamation-sign'
      title: i18n.get order.error
  column.append $ '<strong/>', text: order.label
  column.append '<br/>'
  column.append $ '<a/>',
    'data-order-action': 'view'
    'data-order-key':    order.key
    text:                order.number
    title:               i18n.get 'pop_order_title'
  row.append column
  column = $ '<td/>'
  column.append $ '<span/>', text: ext.getStatusText order
  row.append column
  column = $ '<td/>'

                ¶

Found the track link so I'll share it with the user. I'm good like that.

  if order.trackingUrl
    column.append $ '<a/>',
      'data-order-action': 'track'
      'data-order-key':    order.key
      text:                i18n.get 'pop_track_text'
      title:               i18n.get 'pop_track_title'
  else
    column.append ' '
  row.append column

                ¶

Build the HTML to populate the popup with to optimize popup loading times.

buildPopup = ->
  log.trace()
  rows = $()

                ¶

Generate the HTML for each order.

  rows = rows.add buildOrder order for order in ext.orders

                ¶

Add a generic message to state the obvious... that the list is empty.

  if rows.length is 0
    rows = rows.add $('<tr/>').append $ '<td/>',
      class:   'empty'
      colspan: 3
      html:    i18n.get 'empty'
  ext.ordersHtml = $('<div/>').append(rows).html()

                ¶

Build the HTML to indicate in a user-friendly manner the time since/until that specified.

buildTimeAgo = (time) ->
  log.trace()
  time   ?= $.now()
  time    = new Date time if 'date' isnt $.type time
  timeAgo = $('<abbr/>', title: time.toISOString()).timeago()
  $('<div/>').append(timeAgo).html()

                ¶

Initialization functions

                ¶

Handle the conversion/removal of older version of settings that may have been stored previously
by ext.init.

init_update = ->
  log.trace()

                ¶

Update the update progress indicator itself.

  if store.exists 'update_progress'
    store.modify 'updates', (updates) ->
      progress = store.remove 'update_progress'
      for own namespace, versions of progress
        updates[namespace] = if versions?.length then versions.pop() else ''

                ¶

Create updater for the settings namespace.

  updater      = new store.Updater 'settings'
  isNewInstall = updater.isNew

                ¶

Define the processes for all required updates to the settings namespace.

  updater.update '1.1.0', ->
    log.info 'Updating general settings for 1.1.0'
    freq      = ext.config.frequencies[1].value
    frequency = store.get 'frequency'
    store.set 'frequency', freq if frequency > -1 and frequency < freq
  updater.update '1.2.0', ->
    log.info 'Updating general settings for 1.2.0'
    notifications = store.get 'notifications'
    store.set 'notifications',
      badges:   store.get('badges')               ? on
      duration: store.get('notificationDuration') ? 3000
      enabled:  if $.type(notifications) is 'boolean' then notifications else yes
    store.remove 'badges', 'notificationDuration'

                ¶

Initialize order and its properties.

initOrder = (order) ->
  log.trace()
  order.error       ?= ''
  order.code        ?= ''
  order.email       ?= ''
  order.label       ?= ''
  order.number      ?= ''
  order.trackingUrl ?= ''
  order.updates     ?= []
  for update in order.updates
    update.status    ?= -1
    update.timeStamp ?= $.now()
  order

                ¶

Initialize the persisted managed orders.

initOrders = ->
  log.trace()
  do initOrders_update

                ¶

Initialize all orders to ensure their properties are valid.

  store.modify 'orders', (orders) ->
    initOrder order for order in orders
  ext.updateOrders()

                ¶

Handle the conversion/removal of older version of settings that may have been stored previously
by initOrders.

initOrders_update = ->
  log.trace()

                ¶

Create updater for the orders namespace.

  updater = new store.Updater 'orders'

                ¶

Define the processes for all required updates to the orders namespace.

  updater.update '1.2.0', ->
    log.info 'Updating order settings for 1.2.0'
    store.modify 'orders', (orders) ->
      for order in orders
        if order.error is 'update_status_not_found_error'
          order.error = 'update_invalid_status_error'
        order.key    ?= utils.keyGen()
        update.status = getStatusIndex update.status for update in order.updates

                ¶

Initialize the timeago jQuery plugin.

initTimeAgo = ->
  log.trace()
  messageOrNull = (messageKey) -> i18n.get(messageKey) or null
  numbers = messageOrNull 'ta_numbers'
  numbers = if numbers? then numbers.trim().split /\s+/ else []

                ¶

Apply localized strings to timeago.

  $.timeago.settings.strings =
    day:           messageOrNull 'ta_day'
    days:          messageOrNull 'ta_days'
    hour:          messageOrNull 'ta_hour'
    hours:         messageOrNull 'ta_hours'
    minute:        messageOrNull 'ta_minute'
    minutes:       messageOrNull 'ta_minutes'
    month:         messageOrNull 'ta_month'
    months:        messageOrNull 'ta_months'
    numbers:       numbers
    prefixAgo:     messageOrNull 'ta_prefix_ago'
    prefixFromNow: messageOrNull 'ta_prefix_from_now'
    seconds:       messageOrNull 'ta_seconds'
    suffixAgo:     messageOrNull 'ta_suffix_ago'
    suffixFromNow: messageOrNull 'ta_suffix_from_now'
    wordSeparator: i18n.get 'ta_word_separator'
    year:          messageOrNull 'ta_year'
    years:         messageOrNull 'ta_years'

                ¶

Update Manager setup

                ¶

Central manager for updating the orders.
This manager can handle concurrent start, stop and restart requests while also supporting repeat
(looping) functionality.

updateManager =

                ¶

Unique interval identifier used to managed repeating updates.

  id: undefined

                ¶

Message stack used by the current update process.
Any start/stop/restart requests made while the manager is updating is added to this stack and
actioned upon completion of the process. Afterwards, the stack is cleared for the next process.

  messages: []

                ¶

Indicate whether or not the update manager is currently running through an update process.

  updating: no

                ¶

Restart the update manager, which may run once or start a repeating cycle based on the current
update frequency.
If this is called during an active update process the manager will restart upon completion.

  restart: ->
    log.trace()
    log.info 'Restarting update manager'
    frequency = store.get 'frequency'

                ¶

I'm busy; I'll do it later.

    return @messages.push 'restart' if @updating

                ¶

Clear the current cycle, where applicable.

    if @id
      clearInterval @id

                ¶

Ensure that it is disabled, where applicable.

      @id = undefined if frequency is -1

                ¶

Start a new cycle if required.

    @id = setInterval @run, frequency if frequency isnt -1

                ¶

Run the initial process.

    do @run

                ¶

Core of the update manager which actually performs the update process.
This process updates all orders and ensures the results are reflected in the popup.

  run: ->
    log.trace()
    log.info 'Running update manager'
    @progress = 0
    @updating = yes

                ¶

Update the UI to show that I'm busy.

    do notify
    do updatePopup

                ¶

Called when the AJAX request has been parsed and read for each order.
This should be called regardless of errors being encountered.

    updated = (order) ->
      log.trace()
      log.debug 'Updating order...', order
      @progress++

                ¶

Check if all orders have been updated; supports no orders.

      if @progress >= ext.orders.length
        @updating = no

                ¶

Persist orders and update time stamp.

        store.set 'orders', ext.orders
        store.set 'lastUpdated', $.now()

                ¶

Update the UI again to reflect the changes.

        do notify
        do updatePopup

                ¶

Now read the message stack.

        this[message]?() for message in @messages
        @messages = []

                ¶

Finish this now since no orders exist.

    updated.apply this unless ext.orders.length

                ¶

Update each order by parsing its page on the Apple US store.

    updateOrder order, updated for order in ext.orders

                ¶

Start the update manager, which may run once or start a repeating cycle based on the current
update frequency.

  start: ->
    log.trace()
    log.info 'Starting update manager'
    frequency = store.get 'frequency'

                ¶

Clear the current cycle, where applicable.

    if frequency is -1
      if @id
        clearInterval @id
        @id = undefined
    else

                ¶

I start twice for no one... see RESTART for that.

      return if @id

                ¶

Start a new cycle.

      @id = setInterval @run, frequency

                ¶

Run the initial process.

    do @run

                ¶

Stop the update manager.
If this is called during an active update process the manager will stop upon completion.

  stop: ->
    log.trace()
    log.info 'Stopping update manager'

                ¶

I'm busy; I'll do it later.

    return @messages.push 'stop' if @updating

                ¶

Clear the current cycle, where possible.

    if @id
      clearInterval @id
      @id = undefined

                ¶

Background page setup

                ¶

ext = window.ext = new class Extension extends utils.Class

                ¶

Public variables

                ¶

Configuration data loaded at runtime.

  config: {}

                ¶

Information specifying what should be displaying in the notification.
This should be reset after every update.

  notification:
    description:      ''
    descriptionStyle: ''
    html:             ''
    icon:             utils.url '../images/icon_48.png'
    iconStyle:        ''
    title:            ''
    titleStyle:       ''

                ¶

List of orders currently being maintained.
This should always be an exact reflection of the orders persisted in localStorage.

  orders: []

                ¶

Pre-prepared HTML for the popup to be populated using.
This should be updated whenever orders are changed/updated in any way as this is generated to
improve performance and load times of the popup frame.

  ordersHtml: ''

                ¶

Current version of iOrder.

  version: ''

                ¶

Public functions

                ¶

Initialize the background page.
This will involve initializing the settings, adding the message listeners and starting the
update manager.

  init: ->
    log.trace()
    log.info 'Initializing extension controller'

                ¶

Add support for analytics if the user hasn't opted out.

    analytics.add() if store.get 'analytics'
    $.getJSON(utils.url 'manifest.json')
    .then (data) =>

                ¶

It's nice knowing what version is running.

      @version = data.version
    .then $.getJSON(utils.url 'configuration.json')
    .done (data) =>

                ¶

Load and store the configuration data.

      @config = data
      do buildConfig

                ¶

Begin initialization.

      store.init
        frequency:     @config.frequencies[1].value
        lastRead:      $.now()
        lastUpdated:   $.now()
        notifications: {}
        orders:        []
      do init_update
      store.modify 'notifications', (notifications) ->
        notifications.badges   ?= on
        notifications.duration ?= 3000
        notifications.enabled  ?= yes
      utils.onMessage 'extension', no, onMessage
      do initTimeAgo
      do initOrders
      analytics.track 'Installs', 'New', @version, Number isProductionBuild if isNewInstall

                ¶

Execute content scripts now that we know the version.

      do executeScriptsInExistingWindows

                ¶

Attempt to retrieve the details for the persisted update frequency.

  getFrequency: ->
    log.trace()
    frequency = store.get 'frequency'
    return freq for freq in @config.frequencies when freq.value is frequency

                ¶

Return the URL of the page on the Apple store for the specified order.

  getOrderUrl: (order) ->
    log.trace()
    encode = encodeURIComponent
    "#{@config.apple.url.detail}#{encode order.number}/#{encode order.email or order.code}"

                ¶

Attempt to derive the status text to be displayed for the order.
The status text will either be that of the latest update or a single whitespace character if no
status updates have been detected yet for that order.

  getStatusText: (order) ->
    log.trace()
    index = if order.updates?.length then order.updates[-1..][0].status else -1
    @config.apple.status[index]?.text

                ¶

Retrieve the HTML for a user-friendly timestamp representing the time since/until that
specified.

  getTimeAgoHtml: (time) -> buildTimeAgo time

                ¶

Indicate whether any errors were encountered when orders were last updated.

  hasErrors: ->
    log.trace()
    return yes for order in @orders when order.error
    no

                ¶

Indicate whether any order updates were detected.

  hasUpdates: ->
    log.trace()
    updates > 0

                ¶

Indicate whether the update manager is currently processing order updates.

  isUpdating: ->
    log.trace()
    updateManager.updating

                ¶

Retrieve the first order that passes the specified filter.

  queryOrder: (filter, singular = yes) ->
    log.trace()
    utils.query @orders, singular, filter

                ¶

Retrieve all orders that pass the specified filter.

  queryOrders: (filter) -> @queryOrder filter, no

                ¶

Reset the notification information associated with the current update process.
This should be called once updating has completed, regardless of it's outcome.

  reset: ->
    log.trace()
    @notification =
      description:      ''
      descriptionStyle: ''
      html:             ''
      icon:             utils.url '../images/icon_48.png'
      iconStyle:        ''
      title:            ''
      titleStyle:       ''

                ¶

Update the local list of orders to reflect those persisted.
It is very important that this is called whenever orders may have been changed in order to
prepare the popup HTML and optimize performance, while also ensuring orders are correctly
managed during by the next update.

  updateOrders: ->
    log.trace()
    @orders = store.get 'orders'
    @orders.sort (a, b) -> a.index - b.index
    do updatePopup
    updateManager.restart()

                ¶

Initialize ext when the DOM is ready.

utils.ready -> ext.init()


text:
<?php

namespace Oro\Bundle\WorkflowBundle\Tests\Unit\Model\Condition;

use Symfony\Component\PropertyAccess\PropertyPath;

use Oro\Bundle\WorkflowBundle\Model\ContextAccessor;
use Oro\Bundle\WorkflowBundle\Model\Condition;
use Oro\Bundle\EntityBundle\ORM\DoctrineHelper;

class EqualToTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var DoctrineHelper|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $doctrineHelper;

    /**
     * @var Condition\EqualTo
     */
    protected $condition;

    protected function setUp()
    {
        $this->doctrineHelper = $this->getMockDoctrineHelper();
        $this->condition = new Condition\EqualTo(new ContextAccessor(), $this->doctrineHelper);
    }

    /**
     * @dataProvider isAllowedDataProvider
     *
     * @param array $options
     * @param $context
     * @param array $expectedCalls
     * @param $expectedResult
     */
    public function testIsAllowed(array $options, $context, array $expectedCalls, $expectedResult)
    {
        foreach ($expectedCalls as $key => $calls) {
            $this->addMockExpectedCalls($key, $calls);
        }

        $this->condition->initialize($options);
        $this->assertEquals($expectedResult, $this->condition->isAllowed($context));
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject
     */
    protected function getMockDoctrineHelper()
    {
        if (!$this->doctrineHelper) {
            $this->doctrineHelper = $this->getMockBuilder('Oro\Bundle\EntityBundle\ORM\DoctrineHelper')
                ->disableOriginalConstructor()
                ->getMock();
        }
        return $this->doctrineHelper;
    }

    /**
     * @return array
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function isAllowedDataProvider()
    {
        $options = array('left' => new PropertyPath('[foo]'), 'right' => new PropertyPath('[bar]'));

        return array(
            'scalars_equal' => array(
                'options' => $options,
                'context' => array('foo' => 'value', 'bar' => 'value'),
                'expectedCalls' => array('doctrineHelper' => array()),
                'expectedResult' => true
            ),
            'scalars_not_equal' => array(
                'options' => $options,
                'context' => array('foo' => 'fooValue', 'bar' => 'barValue'),
                'expectedCalls' => array('doctrineHelper' => array()),
                'expectedResult' => false
            ),
            'objects_equal' => array(
                'options' => $options,
                'context' => array(
                    'foo' => $left = $this->createMockObject(),
                    'bar' => $right = $this->createMockObject(),
                ),
                'expectedCalls' => array(
                    'doctrineHelper' => array(
                        array('getEntityClass', array($left), '\stdClass'),
                        array('getEntityClass', array($right), '\stdClass'),
                    ),
                ),
                'expectedResult' => true
            ),
            'objects_not_equal' => array(
                'options' => $options,
                'context' => array(
                    'foo' => $left = $this->createMockObject(array('foo' => 'bar')),
                    'bar' => $right = $this->createMockObject(array('foo' => 'baz')),
                ),
                'expectedCalls' => array(
                    'doctrineHelper' => array(
                        array('getEntityClass', array($left), '\stdClass'),
                        array('getEntityClass', array($right), '\stdClass'),
                        array('isManageableEntity', array($left), false),
                    ),
                ),
                'expectedResult' => false
            ),
            'object_and_entity_not_equal' => array(
                'options' => $options,
                'context' => array(
                    'foo' => $left = $this->createMockObject(array('foo' => 'bar')),
                    'bar' => $right = $this->createMockObject(),
                ),
                'expectedCalls' => array(
                    'doctrineHelper' => array(
                        array('getEntityClass', array($left), '\stdClass'),
                        array('getEntityClass', array($right), '\stdClass'),
                        array('isManageableEntity', array($left), true),
                        array('isManageableEntity', array($right), false),
                    ),
                ),
                'expectedResult' => false
            ),
            'entities_equal' => array(
                'options' => $options,
                'context' => array(
                    'foo' => $left = $this->createMockObject(),
                    'bar' => $right = $this->createMockObject(),
                ),
                'expectedCalls' => array(
                    'doctrineHelper' => array(
                        array('getEntityClass', array($left), '\stdClass'),
                        array('getEntityClass', array($right), '\stdClass'),
                        array('isManageableEntity', array($left), true),
                        array('isManageableEntity', array($right), true),
                        array('getEntityIdentifier', array($left), array('id' => 1)),
                        array('getEntityIdentifier', array($right), array('id' => 1)),
                    ),
                ),
                'expectedResult' => true
            ),
            'entities_not_equal_identifiers' => array(
                'options' => $options,
                'context' => array(
                    'foo' => $left = $this->createMockObject(), 'bar' => $right = $this->createMockObject(),
                ),
                'expectedCalls' => array(
                    'doctrineHelper' => array(
                        array('getEntityClass', array($left), '\stdClass'),
                        array('getEntityClass', array($right), '\stdClass'),
                        array('isManageableEntity', array($left), true),
                        array('isManageableEntity', array($right), true),
                        array('getEntityIdentifier', array($left), array('id' => 1)),
                        array('getEntityIdentifier', array($right), array('id' => 2)),
                    ),
                ),
                'expectedResult' => false
            ),

        );
    }

    /**
     * @param \PHPUnit_Framework_MockObject_MockObject|string $mock
     * @param array $expectedCalls
     */
    private function addMockExpectedCalls($mock, array $expectedCalls)
    {
        if (is_string($mock)) {
            $mockGetter = 'getMock' . ucfirst($mock);
            $mock = $this->$mockGetter($mock);
        }
        $index = 0;
        if ($expectedCalls) {
            foreach ($expectedCalls as $expectedCall) {
                list($method, $arguments, $result) = $expectedCall;

                if (is_callable($result)) {
                    $result = call_user_func($result);
                }

                $methodExpectation = $mock->expects($this->at($index++))->method($method);
                $methodExpectation = call_user_func_array(array($methodExpectation, 'with'), $arguments);
                $methodExpectation->will($this->returnValue($result));
            }
        } else {
            $mock->expects($this->never())->method($this->anything());
        }
    }

    /**
     * @param array $data
     * @param string $class
     * @return \PHPUnit_Framework_MockObject_MockObject
     */
    protected function createMockObject(array $data = array(), $class = 'stdClass')
    {
        $result = $this->getMock($class);
        foreach ($data as $property => $value) {
            $result->$property = $value;
        }
        return $result;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
AbstractKetaiInputService
</TITLE>

<META NAME="date" CONTENT="2012-05-23">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

ketai.data.inputService

Class AbstractKetaiInputService

java.lang.Object
  ketai.data.inputService.AbstractKetaiInputService

All Implemented Interfaces:
IKetaiInputService

Direct Known Subclasses:
CameraService, LocationService, SensorService

public abstract class AbstractKetaiInputService
extends java.lang.Object
implements IKetaiInputService

Field Summary

Fields inherited from interface ketai.data.inputService.IKetaiInputService

STATE_STARTED, STATE_STARTED_WITH_ERRORS, STATE_STOPPED

Constructor Summary

AbstractKetaiInputService()

Method Summary

 void
broadcastData(java.lang.Object data)

 void
registerAnalyzer(IKetaiAnalyzer _analyzer)

 void
removeAnalyzer(IKetaiAnalyzer _analyzer)

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Methods inherited from interface ketai.data.inputService.IKetaiInputService

getServiceDescription, getStatus, list, startService, stopService

Constructor Detail

AbstractKetaiInputService

public AbstractKetaiInputService()

Method Detail

registerAnalyzer

public void registerAnalyzer(IKetaiAnalyzer _analyzer)

Specified by:
registerAnalyzer in interface IKetaiInputService

removeAnalyzer

public void removeAnalyzer(IKetaiAnalyzer _analyzer)

Specified by:
removeAnalyzer in interface IKetaiInputService

broadcastData

public void broadcastData(java.lang.Object data)

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
import threading
import select
import re
import hashlib
import base64
import lowlevel

class Client(object):
    def __init__(self, sock, address, host):
        self.socket = sock
        self.socket.setblocking(0)
        self.server = host
        self.address = address
        self.connected = True
        self.exit_request = False
        self.handshake_start = False
        self.handshake_completed = False
        self.buffer = bytearray()

        #
        self.thread = ClientThread(self)
        self.thread.start()

    def handshake(self, command):
        if not self.handshake_start:
            check = re.match('GET', command)
            if check:
                self.handshake_start = True
        else:
            check = re.match(r'Sec-WebSocket-Key: (.*?)$', command, re.M | re.I)
            if check:
                wskey = str(check.group(1)).strip()
                wskey += str('258EAFA5-E914-47DA-95CA-C5AB0DC85B11')

                response_code = base64.b64encode(hashlib.sha1(wskey).digest())

                response = 'HTTP/1.1 101 Switching Protocols\r\n'
                response += 'Upgrade: websocket\r\n'
                response += 'Connection: Upgrade\r\n'
                response += 'Sec-WebSocket-Accept: '+response_code+'\r\n'
                response += '\r\n'

                self.send_raw(response)
                self.handshake_start = False
                self.handshake_completed = True

    def on_receive(self, data):
        for byte in data:
            self.buffer.append(byte)
        self.parse_buffer()

    def cut_to_frame_begining(self):
        allowed_frame_opcodes = [0x01, 0x02, 0x08, 0x09, 0x0A, 0x0B]
        # 0x01 is a text frame
        # 0x02 is a binary frame
        # 0x03 - 0x07 are reserved
        # 0x08 indicates a connection close
        # 0x09 indicates a ping
        # 0x0A indicates a pong
        # 0x0B - 0x0F are reserverd
        allowed_frame_opcodes = [0x01, 0x02]  # we support only text and binary frames for now
        while len(self.buffer) > 0 and not self.buffer[0] & (~0x80) in allowed_frame_opcodes:
            self.buffer.pop(0)

    def parse_buffer(self):
        if not self.handshake_completed:
            command = ''
            for byte in self.buffer:
                if chr(byte) == '\n':
                    self.handshake(command)
                    for k in command:
                        self.buffer.pop(0)
                    self.buffer.pop(0)

                    self.parse_buffer()
                    return
                command += chr(byte)
        else:
            self.cut_to_frame_begining()
            if len(self.buffer) > 0:
                self.parse_frame()

    def parse_frame(self):
        length = self.get_frame_length(self.buffer)

        if not length:  # buffer too short
            return

        if length <= len(self.buffer):
            data = self.unmask(self.buffer)
            if not data:
                return

            for i in range(0, length):
                self.buffer.pop(0)

            self.data_from_websocket(data)
            self.parse_buffer()
        else:  # buffer too short - wait until next data come
            return

    def get_frame_length(self, payload):
        try:
            length = payload[1] & 0x7F

            if length == 126:  # length field is next two bytes
                lenbytes = []
                for i in range(0, 2):
                    lenbytes.append(payload[2 + i])
                length = lowlevel.multibyteval(lenbytes)
                length += 2  # 2 bytes of length value
            elif length == 127:  # length field is next 8 bytes
                lenbytes = []
                for i in range(0, 8):
                    lenbytes.append(payload[2 + i])
                length = lowlevel.multibyteval(lenbytes)
                length += 8  # 8 bytes of length value
            elif length > 125:
                return None  # unknown length

        except IndexError:
            return None

        length += 1  # first field
        length += 1  # basic payload field len
        length += 4  # mask len

        return length

    def get_payload_length(self, payload):
        try:
            length = payload[1] & 0x7F

            if length <= 125:
                return length
            if length == 126:  # length field is next two bytes
                lenbytes = []
                for i in range(0, 2):
                    lenbytes.append(payload[2 + i])
                length = lowlevel.multibyteval(lenbytes)
            elif length == 127:  # length field is next 8 bytes
                lenbytes = []
                for i in range(0, 8):
                    lenbytes.append(payload[2 + i])
                length = lowlevel.multibyteval(lenbytes)
            else:
                return None  # unknown length

        except IndexError:
            return None

        return length

    def unmask(self, payload):
        try:
            length = payload[1] & 0x7F
        except IndexError:
            return None

        if length <= 125:
            maskstart_index = 2
        elif length == 126:  # length field is next two bytes
            length = self.get_payload_length(payload)
            maskstart_index = 4
        elif length == 127:  # length field is next 8 bytes
            length = self.get_payload_length(payload)
            maskstart_index = 10
        else:
            return None  # unknown length

        if not length:
            return None

        try:  # if frame is not complete, return None
            maskkey = payload[maskstart_index:(maskstart_index + 5)]
            data = payload[(maskstart_index + 4):]
            data = data[:length]
        except IndexError:
            return None

        text = ''
        for i, c in enumerate(data):
            text += chr(c ^ maskkey[i % 4])

        return text

    def encode_data(self, data):
        byte1 = 0x80 | (0x01 & 0x0F)
        length = len(data)

        output_buffer = bytearray()
        output_buffer.append(byte1)

        if length <= 125:
            output_buffer.append(length)
        elif length <= 0xFFFF:
            output_buffer.append(126)
            lenbytes = lowlevel.multibytetoarray(length)
            for i in range(0, 2):
                try:
                    output_buffer.append(lenbytes[i])
                except IndexError:
                    output_buffer.append(0)
        else:
            output_buffer.append(127)
            lenbytes = lowlevel.multibytetoarray(length)
            for i in range(0, 8):
                try:
                    output_buffer.append(lenbytes[i])
                except IndexError:
                    output_buffer.append(0)
            return None

        for byte in data:
            output_buffer.append(byte)

        return output_buffer

    def data_from_websocket(self, data):
        print 'ws: ', data
        self.send('thank you')

    def send(self, data):
        output_buffer = self.encode_data(data)
        if not output_buffer:
            return
        try:
            self.socket.sendall(output_buffer)
        except:
            return

    def send_raw(self, data):
        try:
            self.socket.sendall(data)
        except:
            return

    def disconnect(self):
        self.exit_request = True

class ClientThread(threading.Thread):
    def __init__(self, parent):
        super(ClientThread, self).__init__()
        self.parent = parent

    def run(self):
        while not self.parent.exit_request:
            ready_to_read, ready_to_write, in_error = select.select(
                [self.parent.socket], [], [], 2
            )
            if self.parent.socket not in ready_to_read:
                continue
            data = self.parent.socket.recv(1024)
            if not data:
                break
            self.parent.on_receive(data)

        self.parent.send('Bye!')
        self.parent.socket.close()
        self.parent.connected = False


text:
"""
因为heroku无法进行本地存储和读取,所有选择用数据库存储记录数据
→_→其实数据库也有只能保存1W行数据的限制
"""

import os
import urlparse
from sqlalchemy import Column, DateTime, Integer, create_engine,Boolean,String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from datetime import datetime

Base = declarative_base()

class TimeSign(Base):
    __tablename__ = 'time_sign'
    id = Column(Integer, primary_key=True)
    ts = Column(DateTime, default=datetime.utcnow())

    @staticmethod
    def gettime():
        return s.query(TimeSign).first().ts

    @staticmethod
    def settime(time=datetime.utcnow()):
        s.query(TimeSign).update({"ts": time})
        s.commit()

    @staticmethod
    def fight():
        #datetime.datetime.now()>datetime.datetime.utcnow() + datetime.timedelta(hours=1)→True
        #统一使用UTC
        if datetime.utcnow() > TimeSign.gettime() and 0 <= datetime.utcnow().hour <= 9:
            return True
        return False

class ReChargeLog(Base):
    __tablename__ = 'ReChargeLog'
    id = Column(Integer, primary_key=True)
    msg = Column(String)

    @staticmethod
    def savemsg(message):
        d = ReChargeLog(msg=message)
        s.add(d)
        s.commit()

#方便本地测试
if "DATABASE_URL" in list(os.environ):
    urlparse.uses_netloc.append("postgres")
    url = urlparse.urlparse(os.environ["DATABASE_URL"])
    engine = create_engine('postgresql+psycopg2://{user}:{pwd}@{host}:{port}/{database}'.format(database=url.path[1:],
                                                                                user=url.username,
                                                                                pwd=url.password,
                                                                                host=url.hostname,
                                                                                port=url.port))
else:
    engine = create_engine('postgresql+psycopg2://{user}:{pwd}@{host}:{port}/{database}'.format(database="test",
                                                                                user="test_postgres",
                                                                                pwd="123456",
                                                                                host="localhost",
                                                                                port=5432))
session = sessionmaker()
session.configure(bind=engine)
Base.metadata.create_all(engine)
s = session()
#设置初始时间
if not s.query(TimeSign).first():
    inittime = TimeSign()
    s.add(inittime)
    s.commit()


text:
package com.db4o.config;

/**
 * Configuration interface for db4o in embedded use.
 * @since 7.5
 */
public interface EmbeddedConfiguration extends FileConfigurationProvider, CommonConfigurationProvider, CacheConfigurationProvider, IdSystemConfigurationProvider {

	/**
     * adds ConfigurationItems to be applied when
     * a networking {@link EmbeddedObjectContainer} is opened.
     * @param configItem the {@link EmbeddedConfigurationItem}
     * @since 7.12
     */
	void addConfigurationItem(EmbeddedConfigurationItem configItem);

}


text:
title: "Personalizar el reproductor de vídeo"
description: "Cada plataforma muestra el vídeo de una forma distinta. Las soluciones para móviles deben tener en cuenta la orientación del dispositivo. Usa el API de Fullscreen para controlar el modo de pantalla completa del contenido de vídeo."
updated_on: 2014-04-29
key-takeaways:
  add-a-video:
    - Usa el elemento de vídeo que se cargará y que descodificará y reproducirá el vídeo en tu sitio.
    - Produce vídeos en varios formatos para llegar a varias plataformas móviles.
    - Dales un tamaño correcto a los vídeos y asegúrate de que no sobrepasen los elementos que los contienen.
    - La accesibilidad es importante; añade el elemento de pista como elemento secundario del elemento de vídeo.
notes:
  media-fragments:
    - El API de Media Fragments es compatible con la mayoría de las plataformas, pero no con iOS.
    - Asegúrate de que las solicitudes de intervalo de bytes sean compatibles con tu servidor. Las solicitudes de intervalo se habilitan de manera predeterminada en la mayoría de los servidores, pero algunos servicios de alojamiento pueden inhabilitarlas.
  dont-overflow:
    - No fuerces el tamaño de los elementos cuando este resulte en una relación de aspecto distinta a la del vídeo original. Los elementos achatados o estirados no quedan bien.
  accessibility-matters:
    - El elemento de pista es compatible con Chrome para Android, con iOS Safari y con todos los navegadores actuales de ordenador, excepto con Firefox (consulta caniuse.com/track). También hay varios Polyfill disponibles. Recomendamos Playr o Captionator.
  construct-video-streams:
    - MSE es compatible con Chrome y Opera en Android, y con Internet Explorer 11 y Chrome en ordenador. También está previsto que sea compatible con la Firefox.
  optimize:
    - Imágenes
    - Optimizar la eficacia del contenido
---

  Cada plataforma muestra el vídeo de una forma distinta. Las soluciones para móviles deben tener en cuenta la orientación del dispositivo. Usa el API de Fullscreen para controlar el modo de pantalla completa del contenido de vídeo.

{% include shared/toc.liquid %}

Cada plataforma muestra el vídeo de una forma distinta. Las soluciones para móviles deben tener en cuenta la orientación del dispositivo. Usa el API de Fullscreen para controlar el modo de pantalla completa del contenido de vídeo.

## Funcionamiento de la orientación de dispositivo en varios dispositivos

La orientación de dispositivo no representa ningún problema en monitores de ordenador y en portátiles, pero es muy importante a la hora de tener en cuenta el diseño de la página web para móviles y tablets.

Safari en iPhone cambia correctamente la orientación de pantalla de modo retrato a modo apaisado:

La orientación de dispositivo puede dar problemas en iPad y en Chrome para Android.
Por ejemplo, un vídeo sin personalizar reproduciéndose en un iPad en modo apaisado tiene el siguiente aspecto:

Al establecer el ancho del vídeo con `width: 100%` o con `max-width: 100%` en CSS, se resuelven muchos problemas de diseño a la hora de cambiar la orientación del dispositivo. Además, puedes tener en cuenta otras alternativas a la pantalla completa.

## Visualización junto al contenido o en pantalla completa

Cada plataforma muestra el vídeo de una forma distinta. Safari en iPhone muestra un elemento de vídeo junto al contenido en una página web, pero reproduce el vídeo en pantalla completa:

En Android, los usuarios pueden elegir el modo de pantalla completa haciendo clic en el icono de pantalla completa, aunque el modo predeterminado es reproducir el vídeo junto al contenido:

Safari para iPad reproduce los vídeos junto al contenido:

## Control del modo de pantalla completa del contenido

En las plataformas que no obligan a reproducir el vídeo en pantalla completa, el API de Fullscreen es [ampliamente compatible](//caniuse.com/fullscreen). Usa esta API para controlar la visualización en pantalla completa del contenido o de la página.

Para ver un elemento en pantalla completa, como un video::
{% highlight javascript %}
elem.requestFullScreen();
{% endhighlight %}

Para ver todo un documento en pantalla completa:
{% highlight javascript %}
document.body.requestFullScreen();
{% endhighlight %}

También puedes comprobar cambios de estado de pantalla completa:
{% highlight javascript %}
video.addEventListener("fullscreenchange", handler);
{% endhighlight %}

O bien comprobar si el elemento se encuentra en modo de pantalla completa actualmente:
{% highlight javascript %}
console.log("In full screen mode: ", video.displayingFullscreen);
{% endhighlight %}

Además, puedes usar la pseudoclase `fullscreen` en CSS para cambiar la forma en que se muestran los elementos en pantalla completa.

En los dispositivos que son compatibles con el API de Fullscreen, recomendamos usar imágenes en miniatura como marcadores de posición para vídeo:

<video autoplay loop class="center">
  <source src="video/fullscreen.webm" type="video/webm">
  <source src="video/fullscreen.mp4" type="video/mp4">

Este navegador no es compatible con el elemento de vídeo.

</video>

Para ver cómo funciona, echa un vistazo a la {% link_sample _code/fullscreen.html %}demostración{% endlink_sample %}.

**NOTE:** `requestFullScreen()` is currently vendor prefixed and may require
extra code for full cross browser compatibility.


text:
package com.dianping.cat.report;

import static com.dianping.cat.Constants.HOUR;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.codehaus.plexus.logging.LogEnabled;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable;
import org.unidal.lookup.ContainerHolder;
import org.unidal.lookup.annotation.Inject;

import com.dianping.cat.Cat;
import com.dianping.cat.configuration.NetworkInterfaceManager;
import com.dianping.cat.core.dal.HourlyReport;
import com.dianping.cat.core.dal.HourlyReportContent;
import com.dianping.cat.core.dal.HourlyReportContentDao;
import com.dianping.cat.core.dal.HourlyReportDao;
import com.dianping.cat.message.Message;
import com.dianping.cat.message.Transaction;

/**
 * Hourly report manager by domain of one report type(such as Transaction, Event, Problem, Heartbeat etc.) produced in
 * one machine for a couple of hours.
 */
public class DefaultReportManager<T> extends ContainerHolder implements ReportManager<T>, Initializable, LogEnabled {
	@Inject
	private ReportDelegate<T> m_reportDelegate;

	@Inject
	private ReportBucketManager m_bucketManager;

	@Inject
	private HourlyReportDao m_reportDao;

	@Inject
	private HourlyReportContentDao m_reportContentDao;

	@Inject
	private DomainValidator m_validator;

	private String m_name;

	private Map<Long, Map<String, T>> m_reports = new ConcurrentHashMap<Long, Map<String, T>>();

	private Logger m_logger;

	public void cleanup(long time) {
		List<Long> startTimes = new ArrayList<Long>(m_reports.keySet());

		for (long startTime : startTimes) {
			if (startTime <= time) {
				m_reports.remove(startTime);
			}
		}
	}

	public void destory() {
		super.release(this);
	}

	@Override
	public void enableLogging(Logger logger) {
		m_logger = logger;
	}

	@Override
	public Set<String> getDomains(long startTime) {
		Map<String, T> reports = m_reports.get(startTime);

		if (reports == null) {
			return new HashSet<String>();
		} else {
			Set<String> domains = reports.keySet();
			Set<String> result = new HashSet<String>();

			for (String domain : domains) {
				if (m_validator.validate(domain)) {
					result.add(domain);
				}
			}
			return result;
		}
	}

	@Override
	public T getHourlyReport(long startTime, String domain, boolean createIfNotExist) {
		Map<String, T> reports = m_reports.get(startTime);

		if (reports == null && createIfNotExist) {
			synchronized (m_reports) {
				reports = m_reports.get(startTime);

				if (reports == null) {
					reports = new ConcurrentHashMap<String, T>();
					m_reports.put(startTime, reports);
				}
			}
		}

		if (reports == null) {
			reports = new LinkedHashMap<String, T>();
		}

		T report = reports.get(domain);

		if (report == null && createIfNotExist) {
			synchronized (reports) {
				report = m_reportDelegate.makeReport(domain, startTime, HOUR);
				reports.put(domain, report);
			}
		}

		if (report == null) {
			report = m_reportDelegate.makeReport(domain, startTime, HOUR);
		}

		return report;
	}

	@Override
	public Map<String, T> getHourlyReports(long startTime) {
		Map<String, T> reports = m_reports.get(startTime);

		if (reports == null) {
			return Collections.emptyMap();
		} else {
			return reports;
		}
	}

	@Override
	public void initialize() {
	}

	@Override
	public Map<String, T> loadHourlyReports(long startTime, StoragePolicy policy, int index) {
		Transaction t = Cat.newTransaction("Restore", m_name);
		Map<String, T> reports = m_reports.get(startTime);
		Cat.logEvent("Restore", m_name + ":" + index);
		ReportBucket bucket = null;

		if (reports == null) {
			reports = new ConcurrentHashMap<String, T>();
			m_reports.put(startTime, reports);
		}

		try {
			bucket = m_bucketManager.getReportBucket(startTime, m_name, index);

			for (String id : bucket.getIds()) {
				String xml = bucket.findById(id);
				T report = m_reportDelegate.parseXml(xml);

				reports.put(id, report);
			}

			m_reportDelegate.afterLoad(reports);
			t.setStatus(Message.SUCCESS);
		} catch (Throwable e) {
			t.setStatus(e);
			Cat.logError(e);
			m_logger.error(String.format("Error when loading %s reports of %s!", m_name, new Date(startTime)), e);
		} finally {
			t.complete();

			if (bucket != null) {
				m_bucketManager.closeBucket(bucket);
			}
		}
		return reports;
	}

	public void setBucketManager(ReportBucketManager bucketManager) {
		m_bucketManager = bucketManager;
	}

	public void setName(String name) {
		m_name = name;
	}

	public void setReportContentDao(HourlyReportContentDao reportContentDao) {
		m_reportContentDao = reportContentDao;
	}

	public void setReportDao(HourlyReportDao reportDao) {
		m_reportDao = reportDao;
	}

	public void setReportDelegate(ReportDelegate<T> reportDelegate) {
		m_reportDelegate = reportDelegate;
	}

	public void setValidator(DomainValidator validator) {
		m_validator = validator;
	}

	private void storeDatabase(long startTime, Map<String, T> reports) {
		Date period = new Date(startTime);
		String ip = NetworkInterfaceManager.INSTANCE.getLocalHostAddress();

		for (T report : reports.values()) {
			try {
				String domain = m_reportDelegate.getDomain(report);
				HourlyReport r = m_reportDao.createLocal();

				r.setName(m_name);
				r.setDomain(domain);
				r.setPeriod(period);
				r.setIp(ip);
				r.setType(1);

				m_reportDao.insert(r);

				int id = r.getId();
				byte[] binaryContent = m_reportDelegate.buildBinary(report);
				HourlyReportContent content = m_reportContentDao.createLocal();

				content.setReportId(id);
				content.setContent(binaryContent);
				m_reportContentDao.insert(content);
				m_reportDelegate.createHourlyTask(report);
			} catch (Throwable e) {
				Cat.getProducer().logError(e);
			}
		}
	}

	private void storeFile(Map<String, T> reports, ReportBucket bucket) {
		for (T report : reports.values()) {
			try {
				String domain = m_reportDelegate.getDomain(report);
				String xml = m_reportDelegate.buildXml(report);

				bucket.storeById(domain, xml);
			} catch (Exception e) {
				Cat.logError(e);
			}
		}
	}

	@Override
	public void storeHourlyReports(long startTime, StoragePolicy policy, int index) {
		Transaction t = Cat.newTransaction("Checkpoint", m_name);
		Map<String, T> reports = m_reports.get(startTime);
		ReportBucket bucket = null;

		try {
			t.addData("reports", reports == null ? 0 : reports.size());

			if (reports != null) {
				Set<String> errorDomains = new HashSet<String>();

				for (String domain : reports.keySet()) {
					if (!m_validator.validate(domain)) {
						errorDomains.add(domain);
					}
				}
				for (String domain : errorDomains) {
					reports.remove(domain);
				}
				if (!errorDomains.isEmpty()) {
					m_logger.info("error domain:" + errorDomains);
				}

				m_reportDelegate.beforeSave(reports);

				if (policy.forFile()) {
					bucket = m_bucketManager.getReportBucket(startTime, m_name, index);

					try {
						storeFile(reports, bucket);
					} finally {
						m_bucketManager.closeBucket(bucket);
					}
				}

				if (policy.forDatabase()) {
					storeDatabase(startTime, reports);
				}
			}
			t.setStatus(Message.SUCCESS);
		} catch (Throwable e) {
			Cat.logError(e);
			t.setStatus(e);
			m_logger.error(String.format("Error when storing %s reports of %s!", m_name, new Date(startTime)), e);
		} finally {
			cleanup(startTime);
			t.complete();

			if (bucket != null) {
				m_bucketManager.closeBucket(bucket);
			}
		}
	}

	public static enum StoragePolicy {
		FILE,

		FILE_AND_DB;

		public boolean forDatabase() {
			return this == FILE_AND_DB;
		}

		public boolean forFile() {
			return this == FILE_AND_DB || this == FILE;
		}
	}

}


text:
using ChartControls;
using Common;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace ChartControlsDemo
{
    class StockVolumnList
    {
        public List<StockItem> Prices;
        public List<VolumnItem> Volumns;
    }

    class DataLoader
    {
        public const string sFileName = "s.json";
        public const string stFileName = "st.json";

        private List<CompleteShare> shares;
        private bool calChangeByStart;
        public DataLoader(string fileName, bool calChangeByStart = false)
        {
            this.calChangeByStart = calChangeByStart;
            Load(fileName);

        }

        public List<ChartItem> GetChartItems(string id)
        {
            List<ChartItem> result = null;

            var share = shares.FirstOrDefault(s => s.StockId == id);
            if (share != null)
            {
                result = FromSimpleStock(share);
            }

            return result;
        }

        public StockVolumnList GetStockItems(string id)
        {
            StockVolumnList result = null;

            var share = shares.FirstOrDefault(s => s.StockId == id);
            if (share != null)
            {
                result = FromCompleteStock(share);
            }

            return result;
        }

        private void Load(string fileName)
        {
            shares = new List<CompleteShare>();

            var location = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            location = Path.Combine(location, fileName);

            var content = File.ReadAllText(location, Encoding.UTF8);

            var jObjects = JArray.Parse(content);

            foreach (var jObject in jObjects)
            {
                CompleteShare share = jObject.ToObject<CompleteShare>();
                if(share != null)
                    shares.Add(share);
            }
        }

        private List<ChartItem> FromSimpleStock(SimpleShare s)
        {
            List<ChartItem> ctList = null;
            if (s.Dates != null)
            {
                ctList = new List<ChartItem>(s.Dates.Count);

                double preClose = calChangeByStart ? s.Closes[0] : 0;
                for (int i = 0; i < s.Dates.Count; i++)
                {
                    ctList.Add(new ChartItem()
                    {
                        Date = s.Dates[i],
                        Value = s.Closes[i],
                        ValueChange = i != 0 ? (s.Closes[i] - preClose) / preClose : 0
                    });

                    if(!calChangeByStart)
                        preClose = s.Closes[i];
                }
            }

            return ctList;
        }

        private StockVolumnList FromCompleteStock(CompleteShare s)
        {
            StockVolumnList svList = new StockVolumnList();

            if (s.Dates != null)
            {
                svList.Prices = new List<StockItem>(s.Dates.Count);
                svList.Volumns = new List<VolumnItem>(s.Dates.Count);

                double preClose = calChangeByStart ? s.Closes[0] : 0;
                for (int i = 0; i < s.Dates.Count; i++)
                {
                    var sItem = new StockItem()
                    {
                        Date = s.Dates[i],
                        Value = s.Closes[i],
                        ValueChange = i != 0 ? (s.Closes[i] - preClose) / preClose : 0,
                        High = s.Highs[i],
                        Low = s.Lows[i],
                        Open = s.Opens[i]
                    };

                    svList.Prices.Add(sItem);

                    svList.Volumns.Add(new VolumnItem()
                    {
                        Date = s.Dates[i],
                        Value = s.Volumns[i],
                        Turnover = s.Turnovers[i],
                        IsRaise = s.Closes[i] > s.Opens[i] || (s.Closes[i] == s.Opens[i] && sItem.CloseChange > 0)
                    });
                    if (!calChangeByStart)
                        preClose = s.Closes[i];
                }
            }

            return svList;
        }
    }
}


text:
"""Makes helper libraries available in the cifar10 package."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function


text:
1. Build the jar:

        mvn clean package

1. Download the DBPedia types file (en-nt) from http://wiki.dbpedia.org/Downloads39.
1. Download the DBPedia mapping based properties file (en-nt) from http://wiki.dbpedia.org/Downloads39.
1. Copy the MR input file to HDFS:

        hadoop fs -mkdir -p /lumify
        hadoop fs -put dbpedia-types /lumify
        hadoop fs -put dbpedia-mapping-properties /lumify

1. Submit the MR job:

        hadoop jar lumify-dbpedia-*-jar-with-dependencies.jar /lumify/dbpedia-types
        hadoop jar lumify-dbpedia-*-jar-with-dependencies.jar /lumify/dbpedia-mapping-properties

1. Wait for the MR job to complete

1. [Re-index the data](https://github.com/lumifyio/lumify/tree/master/tools/reindex-mr)

## Running inside an IDE

1. Run format

1. Import the wikipedia.owl

1. Import the dbpedia.owl downloaded from DBpedia's web site.

1. Import the ontology/dbpedia.owl

1. Run `io.lumify.dbpedia.mapreduce.ImportMR dbpedia-types`


text:
'use strict';

module.exports = function(settings) {
  var twtr = require('../helpers/getTwtrQueue');

  twtr('track', 'Download', settings);
  turbine.logger.log('Queue command: twtr("track", "Download", ' + JSON.stringify(settings) + ').');
};


text:
package com.mongodb;

import com.mongodb.util.management.MBeanServerFactory;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import static java.lang.String.format;

/**
 * A connection pool listener that manages a set of JMX MBeans, one for each connection pool.
 */
class JMXConnectionPoolListener implements ConnectionPoolListener {
    private final ConcurrentMap<ClusterIdServerAddressPair, ConnectionPoolStatistics> map =
    new ConcurrentHashMap<ClusterIdServerAddressPair, ConnectionPoolStatistics>();
    private final String clusterDescription;

    public JMXConnectionPoolListener(final String clusterDescription) {
        this.clusterDescription = clusterDescription;
    }

    public String getMBeanObjectName(final String clusterId, final ServerAddress serverAddress) {
        // we could do a url encode, but since : is the only invalid character in an object name, then
        // we'll simply do it.
        String adjustedClusterId = clusterId.replace(":", "%3A");
        String adjustedHost = serverAddress.getHost().replace(":", "%3A");

        String objectName = format("org.mongodb.driver:type=ConnectionPool,clusterId=%s,host=%s,port=%s", adjustedClusterId, adjustedHost,
                               serverAddress.getPort());
        if (clusterDescription != null) {
            String adjustedClusterDescription = clusterDescription.replace(":", "%3A");
            objectName = objectName + format(",description=%s", adjustedClusterDescription);
        }

        return objectName;
    }

    public ConnectionPoolStatisticsMBean getMBean(final String clusterId, final ServerAddress serverAddress) {
        return getStatistics(clusterId, serverAddress);
    }

    @Override
    public void connectionPoolOpened(final ConnectionPoolOpenedEvent event) {
        ConnectionPoolStatistics statistics = new ConnectionPoolStatistics(event);
        map.put(new ClusterIdServerAddressPair(event.getClusterId(), event.getServerAddress()), statistics);
        MBeanServerFactory.getMBeanServer().registerMBean(statistics, getMBeanObjectName(event.getClusterId(), event.getServerAddress()));
    }

    @Override
    public void connectionPoolClosed(final ConnectionPoolEvent event) {
        map.remove(new ClusterIdServerAddressPair(event.getClusterId(), event.getServerAddress()));
        MBeanServerFactory.getMBeanServer().unregisterMBean(getMBeanObjectName(event.getClusterId(), event.getServerAddress()));
    }

    @Override
    public void connectionCheckedOut(final ConnectionEvent event) {
        getStatistics(event).connectionCheckedOut(event);
    }

    @Override
    public void connectionCheckedIn(final ConnectionEvent event) {
        getStatistics(event).connectionCheckedIn(event);
    }

    @Override
    public void waitQueueEntered(final ConnectionPoolWaitQueueEvent event) {
        getStatistics(event).waitQueueEntered(event);
    }

    @Override
    public void waitQueueExited(final ConnectionPoolWaitQueueEvent event) {
        getStatistics(event).waitQueueExited(event);
    }

    @Override
    public void connectionAdded(final ConnectionEvent event) {
        getStatistics(event).connectionAdded(event);
    }

    @Override
    public void connectionRemoved(final ConnectionEvent event) {
        getStatistics(event).connectionRemoved(event);
    }

    private ConnectionPoolStatistics getStatistics(final ConnectionEvent event) {
        return getStatistics(event.getClusterId(), event.getServerAddress());
    }

    private ConnectionPoolListener getStatistics(final ConnectionPoolEvent event) {
        return getStatistics(event.getClusterId(), event.getServerAddress());
    }

    private ConnectionPoolStatistics getStatistics(final String clusterId, final ServerAddress serverAddress) {
        return map.get(new ClusterIdServerAddressPair(clusterId, serverAddress));
    }

    private static final class ClusterIdServerAddressPair {
        private final String clusterId;
        private final ServerAddress serverAddress;

        private ClusterIdServerAddressPair(final String clusterId, final ServerAddress serverAddress) {
            this.clusterId = clusterId;
            this.serverAddress = serverAddress;
        }

        @Override
        public boolean equals(final Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }

            ClusterIdServerAddressPair that = (ClusterIdServerAddressPair) o;

            if (!clusterId.equals(that.clusterId)) {
                return false;
            }

            if (!serverAddress.equals(that.serverAddress)) {
                return false;
            }

            return true;
        }

        @Override
        public int hashCode() {
            int result = clusterId.hashCode();
            result = 31 * result + serverAddress.hashCode();
            return result;
        }
    }
}