text:
noJavaHome=false
if [ -z "$JAVA_HOME" ] ; then
    noJavaHome=true
fi
if [ ! -e "$JAVA_HOME/bin/java" ] ; then
    noJavaHome=true
fi
if $noJavaHome ; then
    echo
    echo "Error: JAVA_HOME environment variable is not set."
    echo
    exit 1
fi
#==============================================================================
#set JAVA_OPTS
JAVA_OPTS="-server -Xms2G -Xmx2G -XX:MaxPermSize=64M  -XX:+AggressiveOpts -XX:MaxDirectMemorySize=2G"
#JAVA_OPTS="-server -Xms4G -Xmx4G -XX:MaxPermSize=64M  -XX:+AggressiveOpts -XX:MaxDirectMemorySize=6G"
#performance Options
#JAVA_OPTS="$JAVA_OPTS -Xss256k"
#JAVA_OPTS="$JAVA_OPTS -XX:+AggressiveOpts"
#JAVA_OPTS="$JAVA_OPTS -XX:+UseBiasedLocking"
#JAVA_OPTS="$JAVA_OPTS -XX:+UseFastAccessorMethods"
#JAVA_OPTS="$JAVA_OPTS -XX:+DisableExplicitGC"
#JAVA_OPTS="$JAVA_OPTS -XX:+UseParNewGC"
#JAVA_OPTS="$JAVA_OPTS -XX:+UseConcMarkSweepGC"
#JAVA_OPTS="$JAVA_OPTS -XX:+CMSParallelRemarkEnabled"
#JAVA_OPTS="$JAVA_OPTS -XX:+UseCMSCompactAtFullCollection"
#JAVA_OPTS="$JAVA_OPTS -XX:+UseCMSInitiatingOccupancyOnly"
#JAVA_OPTS="$JAVA_OPTS -XX:CMSInitiatingOccupancyFraction=75"
#JAVA_OPTS="$JAVA_OPTS -XX:CMSInitiatingOccupancyFraction=75"
#GC Log Options
#JAVA_OPTS="$JAVA_OPTS -XX:+PrintGCApplicationStoppedTime"
#JAVA_OPTS="$JAVA_OPTS -XX:+PrintGCTimeStamps"
#JAVA_OPTS="$JAVA_OPTS -XX:+PrintGCDetails"
#debug Options
#JAVA_OPTS="$JAVA_OPTS -Xdebug -Xrunjdwp:transport=dt_socket,address=8065,server=y,suspend=n"
#==============================================================================

#set HOME
CURR_DIR=`pwd`
cd `dirname "$0"`/..
MYCAT_HOME=`pwd`
cd $CURR_DIR
if [ -z "$MYCAT_HOME" ] ; then
    echo
    echo "Error: MYCAT_HOME environment variable is not defined correctly."
    echo
    exit 1
fi
#==============================================================================

#set CLASSPATH
MYCAT_CLASSPATH="$MYCAT_HOME/conf:$MYCAT_HOME/lib/classes"
for i in "$MYCAT_HOME"/lib/*.jar
do
    MYCAT_CLASSPATH="$MYCAT_CLASSPATH:$i"
done
#==============================================================================

#startup Server
RUN_CMD="\"$JAVA_HOME/bin/java\""
RUN_CMD="$RUN_CMD -DMYCAT_HOME=\"$MYCAT_HOME\""
RUN_CMD="$RUN_CMD -classpath \"$MYCAT_CLASSPATH\""
RUN_CMD="$RUN_CMD $JAVA_OPTS"
RUN_CMD="$RUN_CMD org.opencloudb.util.rehasher.RehashLauncher "
#to specify the following main args
#RUN_CMD="$RUN_CMD -jdbcDriver="
#RUN_CMD="$RUN_CMD -jdbcUrl="
#RUN_CMD="$RUN_CMD -host="
#RUN_CMD="$RUN_CMD -user="
#RUN_CMD="$RUN_CMD -database="
#RUN_CMD="$RUN_CMD -password="
#RUN_CMD="$RUN_CMD -tablesFile="
#RUN_CMD="$RUN_CMD -shardingField="
#RUN_CMD="$RUN_CMD -rehashHostsFile="
#RUN_CMD="$RUN_CMD -hashType="
#RUN_CMD="$RUN_CMD -seed="
#RUN_CMD="$RUN_CMD -virtualBucketTimes="
#RUN_CMD="$RUN_CMD -weightMapFile="
#RUN_CMD="$RUN_CMD -rehashNodeDir="

echo $RUN_CMD
eval $RUN_CMD
#==============================================================================


text:
	¿HAY FACTORES DE RIESGO DE ACCIDENTE CEREBROVASCULAR QUE NO ESTÁN CONSIDERADOS EN LA ESCALA CHADS2-VASC2 PERO QUE DEBEN TENERSE EN CUENTA EN EL MOMENTO DE LA TOMA DE DECISIONES?

	40

Alrededor de 20 a 25% de los eventos vasculares cerebrales agudos (accidente cerebrovascular
[ACV] o ictus) isquémicos son de origen cardioembólico; la fibrilación auricular no valvular es la
causa más frecuente. El riesgo de ACV en los pacientes con fibrilación auricular es 5 a 7 veces
mayor que en la población similar sin esta arritmia. El estudio de Framingham demostró que los
ictus provocados por una fibrilación auricular tienen mayor riesgo de recurrencia, incapacidad y
mortalidad que aquellos no asociados a ella.

La escala o puntaje de riesgo (score) más usada actualmente para estimar el riesgo de un ACV es
CHADS2-VASC2. Esta ha reemplazado a CHADS2 (Tabla 1) con la finalidad de mejorar la sensibilidad
en el subgrupo de riesgo bajo e intermedio, agregando tres variables: sexo femenino, edad entre
65 y 75 años, y enfermedad vascular periférica, considerando, además, la insuficiencia cardíaca
asintomática con fracción de eyección del ventrículo izquierdo, igual o menor de 40% (Tabla 2).

Tabla 1.Escala CHADS2

Tabla 2.Escala CHADS2-VASC2.

Si se tienen en cuenta ciertas limitaciones de los puntajes de riesgo, como un acotado valor predictivo,
una pobre discriminación en poblaciones de riesgo intermedio y reconociendo que el riesgo
es un continuo, algunas guías recomiendan incorporar el concepto de "factores de riesgo mayores"
y "factores de riesgo no mayores clínicamente relevantes" en el momento de la toma de decisiones.
Existen ciertos factores de riesgo para ACV no contemplados en la escala CHADS2-VASC2, como:

Genéticos: según el estudio de Framingham, el antecedente de ACV aumenta una vez y media
la posibilidad de un nuevo episodio.

Tamaño de la aurícula izquierda: algunos datos ecocardiográficos, como un significativo aumento
del tamaño de la aurícula mayor de 50 mm, pueden relacionarse en los pacientes con
fibrilación auricular con un mayor riesgo.

Enfermedad coronaria o infarto previo: se describe una elevada tasa de ACV luego de 5 años
de haberse producido el infarto de miocardio.

Tabaquismo: aumenta el fibrinógeno sanguíneo y la viscosidad de la sangre, y se asocia,
además, a disfunción endotelial.

Hiperhomocisteinemia: un metanálisis de 27 estudios relacionó el aumento de homocisteína
sanguínea con mayor probabilidad de ACV y enfermedad tromboembólica.

Insuficiencia renal severa: los pacientes con disfunción renal grave tienen un aumento del
riesgo de ACV y también de muerte cardiovascular y de sangrado. Estos pacientes suelen
ser excluidos de los estudios clínicos aleatorizados, por lo que se desconoce su verdadero
impacto en esta enfermedad. Además de asociarse con mayor prevalencia de fibrilación
auricular, se observó en estos pacientes una menor probabilidad de mantenimiento en ritmo
sinusal. Recientes análisis de los estudios ROCKET y ATRIA proponen un modelo de riesgo
para ACV que incluya la disfunción renal. Este factor de riesgo se desarrolla en extenso en
otra pregunta.

Los obesos tienen un riesgo 41 a 49% mayor de presentar fibrilación auricular que los no obesos.
A su vez, presentan mayor tasa de fibrilación auricular permanente. Esto podría deberse a la disfunción
diastólica que sufren muchos de estos pacientes.

En 1978, Ettinger y cols. describieron el "síndrome cardíaco" relacionado con las vacaciones. Pacientes
sanos que ingerían grandes cantidades de alcohol presentaban fibrilación auricular paroxística
en períodos vacacionales o fines de semana. La prevalencia de fibrilación auricular es dependiente
de la dosis y existe evidencia de que, sin importar el tipo de fibrilación auricular (paroxística,
persistente o permanente), hay un aumento del riesgo de ACV en esta población. El aumento de
incidencia de fibrilación auricular es 8% por cada 10 g de alcohol ingeridos por día.

La asociación con una patología oncológica es frecuente, ya sea porque ambas poblaciones son
coincidentes en el grupo etario o por las modificaciones proinflamatorias de muchas de las patologías
oncológicas.

Lamentablemente no existe información de ensayos clínicos específicos en esta asociación.
Las afecciones tiroideas son otros de los trastornos asociados con la fibrilación auricular. Bruere
siguió durante más de 3 años a 8.962 pacientes y no observó mayor frecuencia de ACV o fenómenos
embólicos entre los hipertiroideos e hipotiroideos y el grupo con tiroides normofuncionante. Los
hipotiroideos sí tuvieron más episodios de sangrado (HR 1,35; IC 95%: 1,02 a 1,79).

Otros, como la apnea del sueño, son muy estudiados con una relación evidente con la fibrilación
auricular. Igualmente los anticonceptivos orales son identificados con mayor frecuencia de eventos
embólicos.

Muchos de estos factores de riesgo no contemplados en los scores deben considerarse a la hora de
decidir la prescripción de un tratamiento anticoagulante en los pacientes con fibrilación auricular
no valvular.

        CONCLUSIONES

El ACV es la complicación cardioembólica más temida de la fibrilación auricular no valvular.

La escala CHADS2-VASC2 es el más usada para determinar el riesgo de ACV y decidir un
tratamiento anticoagulante.

Otros factores de riesgo para ACV no contemplados en los puntajes deberían considerarse en
el momento de la toma de decisiones.

	LECTURAS RECOMENDADAS

2014 AHA/ACC/HRS Guideline for the management of patients with atrial fibrillation: executive summary. JACC
2014.

Azoulay L, et al. Comparison on the CHADS2 and CHA2DS2VASc scores in the predicting stroke events in patients
with atrial fibrillation. Circulation 2010;122:A180044.

Bruere H. History of thyroid disorders in relation to clinical outcomes in atrial fibrillation. Am J Med 2015;128:30-7.

Camm AJ, et al. Guideline for the management of atrial fibrillation: the Task Force for the management of atrial
fibrillation of the European Society of Cardiology (ESC). Eur Heart J 2010;31:2369-429.

Lip GY, et al. Atrial fibrillation and stroke prevention. Lancet Neurol 2007;6: 981-93.

Lip GY, et al. Refining clinical risk stratification for predicting stroke the thromboembolism in atrial fibrillation using
a novel risk factor-based approach: the euro heart survey on atrial fibrillation. Chest 2010;137:262-72.

Marinigh R, et al. Severe renal impairment and stroke prevention in atrial fibrillation: implications for thromboprophylaxis
and bleeding risk. J Am Coll Cardiol 2011;57:1339-48.

Markus HF, et al. Update on genetics of stroke and cerebrovascular disease 2005. Stroke 2006;37:288-9.

Menezes AR, Lavie CJ, DiNicolantonio JJ, O´Keefe J, Morin DP, Khatib S, Milani RV. Atrial fibrillation in the
21st century: a current understanding of risk factors and primary prevention strategies. Mayo Clin Proc
2013;88(4):394-409.

Piccini JP, et al. Renal dysfunction as a predictor of stroke and systemic embolism in patients with nonvalvular atrial
fibrillation: validation of the R(2)CHADS(2) index in the ROCKET AF (Rivaroxaban Once-daily, oral, direct factor Xa
inhibition Compared with vitamin K antagonism for prevention of stroke and Embolism Trial in Atrial Fibrillation) and
ATRIA (AnTicoagulation and Risk factors In Atrial fibrillation) study cohorts. Circulation 2013;127:224-32.

Rauch U, et al. Thrombus formation on atherosclerotic plaques: pathogenesis and clinical consequences. Ann
Intern Med 2001;134:222-38.

Singer DE, Chang Y, Borowsky LH, Fang MC, Pomernacki NK, Udaltsova N, Reynolds K, Go AS. A new risk scheme
to predict ischemic stroke and other thromboembolism in atrial fibrillation: The atria study stroke risk score. J Am
Heart Assoc 2013;2:e000250

Soldevila JG y cols. Evaluación del riesgo tromboembólico y hemorrágico de los pacientes con fibrilación auricular.
Rev Esp Cardiol 2013;13:9-13.

The homocysteine studies collaboration. Homocysteine and risk of ischemic heart disease and stroke: a meta-
analysis. JAMA 2002;288:2015-22.

Wolf PA, et al. Atrial fibrillation as an independent risk factor for stroke: the Framingham study. Stroke
1991;22:283-8.

redpajama_set_name: RedPajamaGithub


text:
// Copyright (C) 2014 Stephan Bouchard - All Rights Reserved
// This code can only be used under the standard Unity Asset Store End User License Agreement
// A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms

using UnityEngine;
using UnityEditor;
using System.Collections;

namespace TMPro.EditorUtilities
{

    [CustomPropertyDrawer(typeof(GlyphInfo))]
    public class GlyphInfoDrawer : PropertyDrawer
    {

        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            SerializedProperty prop_id = property.FindPropertyRelative("id");
            SerializedProperty prop_x = property.FindPropertyRelative("x");
            SerializedProperty prop_y = property.FindPropertyRelative("y");
            SerializedProperty prop_width = property.FindPropertyRelative("width");
            SerializedProperty prop_height = property.FindPropertyRelative("height");
            SerializedProperty prop_xOffset = property.FindPropertyRelative("xOffset");
            SerializedProperty prop_yOffset = property.FindPropertyRelative("yOffset");
            SerializedProperty prop_xAdvance = property.FindPropertyRelative("xAdvance");

            // We get Rect since a valid position may not be provided by the caller.
            Rect rect = GUILayoutUtility.GetRect(position.width, 48);
            rect.y -= 15;

            GUI.enabled = false;
            EditorGUIUtility.LookLikeControls(40, 45);
            EditorGUI.IntField(new Rect(rect.x + 5f, rect.y, 80f, 18), new GUIContent("Ascii:"), prop_id.intValue);
            EditorGUI.LabelField(new Rect(rect.x + 100f, rect.y, 80, 18), "Char: [ " + (char)prop_id.intValue + " ]");

            EditorGUIUtility.labelWidth = 20f;
            EditorGUIUtility.fieldWidth = 10f;

            GUI.enabled = true;
            float width = (rect.width - 5f) / 4;
            EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 0, rect.y + 22, width - 5f, 18), prop_x, new GUIContent("X:"));
            EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 1, rect.y + 22, width - 5f, 18), prop_y, new GUIContent("Y:"));
            EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 2, rect.y + 22, width - 5f, 18), prop_width, new GUIContent("W:"));
            EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 3, rect.y + 22, width - 5f, 18), prop_height, new GUIContent("H:"));

            GUI.enabled = true;
            EditorGUI.LabelField(new Rect(rect.x + 5f + width * 0, rect.y + 44, width - 5f, 18), "Offset Values:");
            EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 1, rect.y + 44, width - 5f, 18), prop_xOffset, new GUIContent("X:"));
            EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 2, rect.y + 44, width - 5f, 18), prop_yOffset, new GUIContent("Y:"));
            GUI.enabled = true;
            EditorGUI.PropertyField(new Rect(rect.x + 5f + width * 3, rect.y + 44, width - 5f, 18), prop_xAdvance, new GUIContent("Advance:"));

        }

    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Col. fig. Engl. Fung. Mushr. 3: 160, pl. 377 (1803)

#### Original name
Sphaeria profusa Sowerby

### Remarks
null


text:
class Subject < ActiveRecord::Base
  has_and_belongs_to_many :lessons
  has_and_belongs_to_many :students
end


text:
namespace switches {

bool IsTouchDragDropEnabled() {
  return CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kEnableTouchDragDrop);
}

bool IsTouchEditingEnabled() {
  return CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kEnableTouchEditing);
}

bool IsNewDialogStyleEnabled() {
  CommandLine* command_line = CommandLine::ForCurrentProcess();
  if (command_line->HasSwitch(switches::kDisableNewDialogStyle))
    return false;
  if (command_line->HasSwitch(switches::kEnableNewDialogStyle))
    return true;
  return true;
}

}  // namespace switches


text:
package org.jboss.pnc.jenkinsbuilddriver;

import org.jboss.pnc.spi.builddriver.BuildDriverResult;
import org.jboss.pnc.spi.builddriver.BuildDriverStatus;
import org.jboss.pnc.spi.builddriver.CompletedBuild;
import org.jboss.pnc.spi.builddriver.exception.BuildDriverException;
import org.jboss.pnc.spi.environment.RunningEnvironment;

/**
 * Created by Matej Lazar on 2014-12-23.
 */
class JenkinsCompletedBuild implements CompletedBuild {

    private JenkinsServerFactory jenkinsServerFactory;
    private BuildJob buildJob;
    private RunningEnvironment runningEnvironment;
    private BuildDriverStatus buildDriverStatus;

    JenkinsCompletedBuild(JenkinsServerFactory jenkinsServerFactory, BuildJob buildJob, RunningEnvironment runningEnvironment, BuildDriverStatus buildDriverStatus) {
        this.jenkinsServerFactory = jenkinsServerFactory;
        this.buildJob = buildJob;
        this.runningEnvironment = runningEnvironment;
        this.buildDriverStatus = buildDriverStatus;
    }

    @Override
    public BuildDriverResult getBuildResult() throws BuildDriverException {
        return new JenkinsBuildResult(jenkinsServerFactory, buildJob, runningEnvironment);
    }

    @Override
    public RunningEnvironment getRunningEnvironment() {
        return runningEnvironment;
    }
}


text:
package net.akhyar.android.imgpro;

import java.util.ArrayList;

import android.graphics.Bitmap;
import android.util.Log;

public abstract class Filter {
	protected ArrayList<Action> actions = new ArrayList<Action>();
	private Bitmap bitmap = null;
	private FilterListener filterListener = null;
	protected boolean isDefault = false;

	public abstract String getName();

	/**
	 * Will be fired after setBitmap()
	 *
	 * @param bitmap
	 */
	public abstract void onBitmapSet(Bitmap bitmap);

	public Filter() {
	}

	public Filter(Bitmap bitmap) {
		this.setBitmap(bitmap);
	}

	public Filter(Bitmap bitmap, boolean isDefault) {
		this(bitmap);
		this.isDefault = isDefault;
	}

	protected void clearActions() {
		actions.clear();
	}

	protected void addAction(Action action) {
		actions.add(action);
	}

	protected void removeAction(int index) {
		actions.remove(index);
	}

	protected void removeAction(Action action) {
		actions.remove(action);
	}

	public final Bitmap apply() {

		if (getBitmap().isRecycled()) {
			Log.e("Filter", "Source bitmap is prematurely recycled");
			return null;
		}

		Bitmap bmp = getBitmap().copy(Bitmap.Config.ARGB_8888, true);

		if (!isDefault) {
			for (Action action : actions) {
				action.adjustBitmap(bmp);
			}
		}

		return bmp;
	}

	public final void applyInBackground() {
		FilterTask task = new FilterTask();
		task.execute(this);
	}

	public final void applyInBackground(FilterListener l) {
		setFilterListener(l);
		applyInBackground();
	}

	public FilterListener getFilterListener() {
		return filterListener;
	}

	public void setFilterListener(FilterListener filterListener) {
		this.filterListener = filterListener;
	}

	public Bitmap getBitmap() {
		return bitmap;
	}

	public void setBitmap(Bitmap bitmap) {
		this.bitmap = bitmap;
		onBitmapSet(bitmap);
	}
}


text:
<?php

namespace Brasa\RecursoHumanoBundle\Repository;

use Doctrine\ORM\EntityRepository;

/**
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class RhuEstudioEstadoInvalidoRepository extends EntityRepository {

}


text:
'''
TP-WIPE thePlatform Web Information Parser & Extractor
'''
__title__      = 'tpwipe'
__author__     = "Adam Garcia and Farrin A. Reid"
__copyright__  = 'Copyright 2012, Farrin Reid & Adam Garcia'
__credits__    = ["Adam Garcia",
                  "Farrin A. Reid"]
__liscense__   = 'MIT'
__version__    = "0.1"
__maintainer__ = ["Adam Garcia",
                  "Farrin A. Reid"]
__email__      = ["adam.garcia@theplatform.com",
                  "farrin.reid@theplatform.com"]
__status__     = "Development"

#from .api import request,login,logout
#from .exceptions import *
from .sessions import session, Session


text:
package org.apache.directory.api.ldap.trigger;

/**
 * An enumeration that represents change inducing LDAP operations.
 *
 * @author Apache Directory Project
 */
public enum LdapOperation
{
    MODIFY("Modify"),

    ADD("Add"),

    DELETE("Delete"),

    MODIFYDN("ModifyDN"),

    MODIFYDN_RENAME("ModifyDN.Rename"),

    MODIFYDN_EXPORT("ModifyDN.Export"),

    MODIFYDN_IMPORT("ModifyDN.Import");

    private final String name;

    /**
     *
     * Creates a new instance of LdapOperation.
     *
     * @param name
     */
    LdapOperation( String name )
    {
        this.name = name;
    }

    /**
     * @return the name of this LDAP operation
     */
    public String getName()
    {
        return name;
    }

    public String toString()
    {
        return name;
    }
}


text:
/**
 *
 */
package org.commcare.restore;

import javax.microedition.lcdui.Command;

import org.commcare.core.properties.CommCareProperties;
import org.javarosa.core.services.PropertyManager;
import org.javarosa.core.services.locale.Localization;
import org.javarosa.user.api.CreateUserController;
import org.javarosa.user.api.LoginController;

import de.enough.polish.ui.Form;
import de.enough.polish.ui.StringItem;
import de.enough.polish.ui.TextField;

/**
 * @author ctsims
 *
 */
public class CommCareOTACredentialEntry extends Form {

	public static final Command DOWNLOAD = new Command(Localization.get("restore.fetch"), Command.OK, 1);
	public static final Command CANCEL = new Command(Localization.get("polish.command.cancel"), Command.BACK, 2);

	private StringItem fetch;

	private StringItem instructions;
	private StringItem updates;
	private TextField username;
	private TextField password;

	public CommCareOTACredentialEntry(String title) {
		super(title);

		instructions = new StringItem("",Localization.get("restore.login.instructions"));
		this.append(instructions);

		username = new TextField(Localization.get("form.login.username"), null, 50, TextField.ANY);

		String passFormat = PropertyManager._().getSingularProperty(CommCareProperties.PASSWORD_FORMAT);

		int flags = CreateUserController.PASSWORD_FORMAT_ALPHA_NUMERIC.equals(passFormat) ? TextField.PASSWORD : TextField.PASSWORD | TextField.NUMERIC;

		password = new TextField(Localization.get("form.login.password"), null, 100, flags);

		this.append(username);
		this.append(password);

		//#style button
		fetch = new StringItem("",Localization.get("restore.fetch"));
		fetch.setDefaultCommand(DOWNLOAD);
		this.append(fetch);
		this.addCommand(CANCEL);

		updates = new StringItem("","");
		this.append(updates);
		setInteractive(true);
	}

	public String getUsername() {
		return username.getString();
	}

	public String getPassword() {
		return password.getString();
	}

	public void sendMessage(String message) {
		this.updates.setText(message);
	}

	public void setInteractive(boolean isInteractive) {
		if(isInteractive) {
			this.addCommand(CANCEL);
			fetch.setVisible(true);
		} else {
			this.removeCommand(CANCEL);
			fetch.setVisible(false);
		}
	}

	public void setUsername(String sampleUsername) {
		username.setText(sampleUsername);
	}
}


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<title>soma.js • TodoMVC</title>
	<link rel="stylesheet" href="../../../assets/base.css">

todos

			<input id="new-todo" placeholder="What needs to be done?" autofocus>

			<input id="toggle-all" type="checkbox">
			Mark all as complete

Double-click to edit a todo

Created by Romuald Quantin

With soma.js

Part of TodoMVC


text:
<!DOCTYPE html>

    <title>Preset store</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.purple-blue.min.css"/>
    <link rel="stylesheet" href="/file/berict/css/style.css" type="text/css">
    <link rel="stylesheet" href='https://fonts.googleapis.com/css?family=Roboto' type='text/css'>
    <link rel="stylesheet" href='https://fonts.googleapis.com/css?family=Roboto+Mono' type='text/css'>
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
    <link rel="stylesheet" href="/file/berict/css/font-awesome.min.css">

    <meta name="description" content="Quality software.">
    <meta name="author" content="Studio Berict">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0">
    <meta name="theme-color" content="#9575CD">
    <meta name="google-site-verification" content="2UUz8GiOgKqRZK5wiOw5VU700bSVCbzUtadaEo0B6dM"/>
    <link rel="icon"
          type="image/png"
          href="/file/berict/img/favicon.png">

Tapad Help

Welcome to the Tapad Help Center

Get started with Tapad

                            How to use Tapad

                            Change color, theme, and startup settings


text:
package com.stanfy.enroscar.net.test.cache;

import java.io.IOException;
import java.net.ResponseCache;

import org.junit.Before;

import com.stanfy.enroscar.beans.BeansManager;
import com.stanfy.enroscar.beans.BeansManager.Editor;
import com.stanfy.enroscar.io.BuffersPool;
import com.stanfy.enroscar.net.test.AbstractMockServerTest;

/**
 * Abstract one cache test.
 * @author Roman Mazur (Stanfy - http://stanfy.com)
 */
public abstract class AbstractOneCacheTest extends AbstractMockServerTest {

  /** Cache name. */
  protected static final String CACHE_NAME = "testCache";

  /** Cache instance. */
  SimpleFileCache cache;

  @Override
  protected void configureBeansManager(final Editor editor) {
    super.configureBeansManager(editor);
    editor
      .put(BuffersPool.class)
      .put(CACHE_NAME, new SimpleFileCache("test-base-cache"));
  }

  @Before
  public void setupCache() throws IOException {
    cache = BeansManager.get(null).getContainer().getBean("testCache", SimpleFileCache.class);
    ResponseCache.setDefault(cache);
  }

}


text:
<?php

namespace Magento\Payment\Model\Checks;

use Magento\Payment\Model\MethodInterface;
use Magento\Quote\Model\Quote;
use Magento\Payment\Model\Checks\CanUseForCountry\CountryProvider;

class CanUseForCountry implements SpecificationInterface
{
    /**
     * @var CountryProvider
     */
    protected $countryProvider;

    /**
     * @param CountryProvider $countryProvider
     */
    public function __construct(CountryProvider $countryProvider)
    {
        $this->countryProvider = $countryProvider;
    }

    /**
     * Check whether payment method is applicable to quote
     * @param MethodInterface $paymentMethod
     * @param Quote $quote
     * @return bool
     */
    public function isApplicable(MethodInterface $paymentMethod, Quote $quote)
    {
        return $paymentMethod->canUseForCountry($this->countryProvider->getCountry($quote));
    }
}


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

<title>LogRepository</title>
<meta name="date" content="2018-05-02">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

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

elastest.loganalyzer.es.client.repository

Interface LogRepository

All Superinterfaces:

org.springframework.data.repository.CrudRepository<Log,java.lang.String>, org.springframework.data.elasticsearch.repository.ElasticsearchCrudRepository<Log,java.lang.String>, org.springframework.data.repository.PagingAndSortingRepository<Log,java.lang.String>, org.springframework.data.repository.Repository<Log,java.lang.String>

@Repository
public interface LogRepository
extends org.springframework.data.elasticsearch.repository.ElasticsearchCrudRepository<Log,java.lang.String>

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

java.util.List<Log>
findByLoggerContainingIgnoreCaseAndProjectAndTestAndMethodOrderByIdAsc(java.lang.String logger,
                                                                      java.lang.String project,
                                                                      java.lang.String test,
                                                                      java.lang.String method)

java.util.List<Log>
findByLoggerContainingIgnoreCaseAndProjectAndTestOrderByIdAsc(java.lang.String logger,
                                                             java.lang.String project,
                                                             java.lang.String test)

java.util.List<Log>
findByProject(java.lang.String project)

java.util.List<Log>
findByProjectAndTestAndLevelOrderByIdAsc(java.lang.String project,
                                        java.lang.String test,
                                        java.lang.String level)

java.util.List<Log>
findByProjectAndTestAndMessageContainingIgnoreCaseOrderByIdAsc(java.lang.String project,
                                                              java.lang.String test,
                                                              java.lang.String message)

java.util.List<Log>
findByTestAndProjectAndThreadOrderByIdAsc(java.lang.String test,
                                         java.lang.String project,
                                         java.lang.String thread)

java.util.List<Log>
findByTestAndProjectOrderByIdAsc(java.lang.String test,
                                java.lang.String project)

java.util.List<Log>
findByTestOrderByIdAsc(java.lang.String test)

Methods inherited from interface org.springframework.data.repository.PagingAndSortingRepository

findAll, findAll

Methods inherited from interface org.springframework.data.repository.CrudRepository

count, delete, delete, delete, deleteAll, exists, findAll, findAll, findOne, save, save

Method Detail

findByLoggerContainingIgnoreCaseAndProjectAndTestAndMethodOrderByIdAsc

java.util.List<Log> findByLoggerContainingIgnoreCaseAndProjectAndTestAndMethodOrderByIdAsc(java.lang.String logger,
                                                                                java.lang.String project,
                                                                                java.lang.String test,
                                                                                java.lang.String method)

findByLoggerContainingIgnoreCaseAndProjectAndTestOrderByIdAsc

java.util.List<Log> findByLoggerContainingIgnoreCaseAndProjectAndTestOrderByIdAsc(java.lang.String logger,
                                                                                java.lang.String project,
                                                                                java.lang.String test)

findByProject

java.util.List<Log> findByProject(java.lang.String project)

findByProjectAndTestAndLevelOrderByIdAsc

java.util.List<Log> findByProjectAndTestAndLevelOrderByIdAsc(java.lang.String project,
                                                             java.lang.String test,
                                                             java.lang.String level)

findByProjectAndTestAndMessageContainingIgnoreCaseOrderByIdAsc

java.util.List<Log> findByProjectAndTestAndMessageContainingIgnoreCaseOrderByIdAsc(java.lang.String project,
                                                                                java.lang.String test,
                                                                                java.lang.String message)

findByTestAndProjectAndThreadOrderByIdAsc

java.util.List<Log> findByTestAndProjectAndThreadOrderByIdAsc(java.lang.String test,
                                                              java.lang.String project,
                                                              java.lang.String thread)

findByTestAndProjectOrderByIdAsc

java.util.List<Log> findByTestAndProjectOrderByIdAsc(java.lang.String test,
                                                     java.lang.String project)

findByTestOrderByIdAsc

java.util.List<Log> findByTestOrderByIdAsc(java.lang.String test)

Skip navigation links

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:
package ru.vyarus.dropwizard.guice.debug;

import com.google.inject.Binding;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.apache.commons.lang3.time.StopWatch;
import org.eclipse.jetty.util.component.LifeCycle;
import org.glassfish.jersey.server.monitoring.ApplicationEvent;
import org.glassfish.jersey.server.monitoring.ApplicationEventListener;
import org.glassfish.jersey.server.monitoring.RequestEvent;
import org.glassfish.jersey.server.monitoring.RequestEventListener;
import ru.vyarus.dropwizard.guice.debug.util.RenderUtils;
import ru.vyarus.dropwizard.guice.module.installer.util.BindingUtils;
import ru.vyarus.dropwizard.guice.module.lifecycle.UniqueGuiceyLifecycleListener;
import ru.vyarus.dropwizard.guice.module.lifecycle.event.configuration.BundlesFromLookupResolvedEvent;
import ru.vyarus.dropwizard.guice.module.lifecycle.event.configuration.BundlesInitializedEvent;
import ru.vyarus.dropwizard.guice.module.lifecycle.event.configuration.ClasspathExtensionsResolvedEvent;
import ru.vyarus.dropwizard.guice.module.lifecycle.event.configuration.CommandsResolvedEvent;
import ru.vyarus.dropwizard.guice.module.lifecycle.event.configuration.ConfigurationHooksProcessedEvent;
import ru.vyarus.dropwizard.guice.module.lifecycle.event.configuration.DropwizardBundlesInitializedEvent;
import ru.vyarus.dropwizard.guice.module.lifecycle.event.configuration.InstallersResolvedEvent;
import ru.vyarus.dropwizard.guice.module.lifecycle.event.configuration.ManualExtensionsValidatedEvent;
import ru.vyarus.dropwizard.guice.module.lifecycle.event.jersey.JerseyConfigurationEvent;
import ru.vyarus.dropwizard.guice.module.lifecycle.event.jersey.JerseyExtensionsInstalledEvent;
import ru.vyarus.dropwizard.guice.module.lifecycle.event.run.ApplicationRunEvent;
import ru.vyarus.dropwizard.guice.module.lifecycle.event.run.BundlesStartedEvent;
import ru.vyarus.dropwizard.guice.module.lifecycle.event.run.ExtensionsInstalledEvent;
import ru.vyarus.dropwizard.guice.module.lifecycle.event.run.ExtensionsResolvedEvent;
import ru.vyarus.dropwizard.guice.module.lifecycle.event.run.InjectorCreationEvent;
import ru.vyarus.dropwizard.guice.module.lifecycle.event.run.ModulesAnalyzedEvent;

import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Debug guicey lifecycle listener. Could be installed with bundle shortcut:
 * {@link ru.vyarus.dropwizard.guice.GuiceBundle.Builder#printLifecyclePhases()}.
 *

 * Use system out instead of logger because logger in not initialized in time of first events and for
 * more clarity.
 *

 * Split logs with current phase name and startup timer. This should clarify custom logic execution times.
 *

 * If multiple listeners registered, only first registered will be actually used (allow safe multiple registrations).
 *
 * @author Vyacheslav Rusakov
 * @since 17.04.2018
 */
@SuppressWarnings({"checkstyle:ClassFanOutComplexity", "PMD.TooManyMethods", "PMD.ExcessiveImports"})
public class LifecycleDiagnostic extends UniqueGuiceyLifecycleListener {

    private static final String BUNDLES = "bundles";
    private static final String DISABLED = "disabled";
    private static final String IGNORED_DUPLICATES = "ignored duplicate instances";
    private static final String NL = "\n";
    private static final String EXTENSIONS = "extensions";
    private static final String INSTALLED_EXTENSIONS = "installed extensions";

    private final boolean showDetails;

    // counting time from listener creation (~same as bundle registration and app initial configuration)
    private final StopWatch timer = StopWatch.createStarted();

    public LifecycleDiagnostic(final boolean showDetails) {
        this.showDetails = showDetails;
    }

    @Override
    protected void configurationHooksProcessed(final ConfigurationHooksProcessedEvent event) {
        log("%s hooks processed", event.getHooks().size());
        if (showDetails) {
            logDetails("hooks", event.getHooks());
        }
    }

    @Override
    protected void dropwizardBundlesInitialized(final DropwizardBundlesInitializedEvent event) {
        log("Initialized %s%s dropwizard bundles",
                event.getBundles().size(), fmtDisabled(event.getDisabled()));
        if (showDetails) {
            logDetails(BUNDLES, event.getBundles());
            logDetails(DISABLED, event.getDisabled());
            logDetails(IGNORED_DUPLICATES, event.getIgnored());
        }
    }

    @Override
    protected void lookupBundlesResolved(final BundlesFromLookupResolvedEvent event) {
        log("%s lookup bundles recognized", event.getBundles().size());
        if (showDetails) {
            logDetails(BUNDLES, event.getBundles());
        }
    }

    @Override
    protected void bundlesInitialized(final BundlesInitializedEvent event) {
        log("Initialized %s%s GuiceyBundles",
                event.getBundles().size(), fmtDisabled(event.getDisabled()));
        if (showDetails) {
            logDetails(BUNDLES, event.getBundles());
            logDetails(DISABLED, event.getDisabled());
            logDetails(IGNORED_DUPLICATES, event.getIgnored());
        }
    }

    @Override
    protected void commandsResolved(final CommandsResolvedEvent event) {
        if (!event.getCommands().isEmpty()) {
            log("%s commands installed", event.getCommands().size());
            if (showDetails) {
                logDetails("commands", event.getCommands());
            }
        }
    }

    @Override
    protected void installersResolved(final InstallersResolvedEvent event) {
        log("%s%s installers initialized", event.getInstallers().size(), fmtDisabled(event.getDisabled()));
        if (showDetails) {
            logDetails("installers", event.getInstallers());
            logDetails(DISABLED, event.getDisabled());
        }
    }

    @Override
    protected void manualExtensionsValidated(final ManualExtensionsValidatedEvent event) {
        log("%s manual extensions validated (of %s registered)",
                event.getValidated().size(), event.getExtensions().size());
        if (showDetails) {
            logDetails("validated", event.getValidated());
            final List<Class<?>> ignored = new ArrayList<>(event.getExtensions());
            ignored.removeAll(event.getValidated());
            logDetails("ignored", ignored);
        }
    }

    @Override
    protected void classpathExtensionsResolved(final ClasspathExtensionsResolvedEvent event) {
        log("%s classpath extensions detected", event.getExtensions().size());
        if (showDetails) {
            logDetails(EXTENSIONS, event.getExtensions());
        }
    }

    @Override
    protected void bundlesStarted(final BundlesStartedEvent event) {
        log("Started %s GuiceyBundles", event.getBundles().size());
        if (showDetails) {
            logDetails(BUNDLES, event.getBundles());
        }
    }

    @Override
    protected void modulesAnalyzed(final ModulesAnalyzedEvent event) {
        log("%s binding extensions detected", event.getExtensions().size());
        if (showDetails) {
            logDetails(EXTENSIONS, event.getExtensions());
            logDetails("removed transitive modules", event.getTransitiveModulesRemoved());

            if (!event.getBindingsRemoved().isEmpty()) {
                final List<String> bindings = new ArrayList<>();
                for (Binding binding : event.getBindingsRemoved()) {
                    final List<String> modules = BindingUtils.getModules(binding).stream()
                            .sorted(Collections.reverseOrder())
                            .map(it -> it.substring(it.lastIndexOf(".") + 1))
                            .collect(Collectors.toList());
                    bindings.add(String.join("/", modules) + " | " + RenderUtils
                            .renderClassLine(binding.getKey().getTypeLiteral().getRawType()));
                }
                logDetails("removed extension bindings", bindings);
            }
        }
    }

    @Override
    protected void extensionsResolved(final ExtensionsResolvedEvent event) {
        log("%s%s extensions found", event.getExtensions().size(), fmtDisabled(event.getDisabled()));
        if (showDetails) {
            logDetails(EXTENSIONS, event.getExtensions());
            logDetails(DISABLED, event.getDisabled());
        }
    }

    @Override
    protected void injectorCreation(final InjectorCreationEvent event) {
        log("Starting guice with %s/%s%s modules...",
                event.getModules().size(), event.getOverridingModules().size(), fmtDisabled(event.getDisabled()));
        if (showDetails) {
            logDetails("modules", event.getModules());
            logDetails("overriding", event.getOverridingModules());
            logDetails(DISABLED, event.getDisabled());
            logDetails(IGNORED_DUPLICATES, event.getIgnored());
        }
    }

    @Override
    protected void extensionsInstalled(final ExtensionsInstalledEvent event) {
        log("%s extensions installed", event.getExtensions().size());
        if (showDetails) {
            logDetails(INSTALLED_EXTENSIONS, event.getExtensions());
        }
    }

    @Override
    protected void applicationRun(final ApplicationRunEvent event) {
        log("Guice started, app running...");
        event.registerJettyListener(new JettyLifecycleListener());
        event.registerJerseyListener(new JerseyEventListener());
    }

    @Override
    protected void jerseyConfiguration(final JerseyConfigurationEvent event) {
        log("Configuring Jersey...");
    }

    @Override
    protected void jerseyExtensionsInstalled(final JerseyExtensionsInstalledEvent event) {
        log("%s Jersey extensions installed", event.getExtensions().size());
        if (showDetails) {
            logDetails(INSTALLED_EXTENSIONS, event.getExtensions());
        }
    }

    @SuppressWarnings("PMD.SystemPrintln")
    private void log(final String message, final Object... args) {
        final int gap = 70;
        final String time = timer.toString();
        final String msg = String.format(message, args);
        final String topLine = String.format("%" + (gap + 3) + "s", "")
                + String.join("", Collections.nCopies(msg.length(), "\u2500"));
        final String prefix = "__[ " + time + " ]" + String.join("",
                Collections.nCopies((gap - 6) - time.length(), "_"));
        System.out.println("\n\n" + topLine + NL + prefix + "/  " + msg + "  \\____\n");
    }

    private String fmtDisabled(final List items) {
        return items.isEmpty() ? "" : " (-" + items.size() + ")";
    }

    @SuppressWarnings("PMD.SystemPrintln")
    private void logDetails(final String message, final Collection<?> items) {
        if (items.isEmpty()) {
            return;
        }
        final StringBuilder builder = new StringBuilder()
                .append('\t').append(message).append(" = \n");
        for (Object item : items) {
            builder.append("\t\t").append(item instanceof String ? item
                    // it is the only way to show something meaningful for proxy
                    : (item instanceof Proxy ? item.toString()
                    : RenderUtils.renderClassLine(item instanceof Class ? (Class) item : item.getClass())))
                    .append(NL);
        }
        System.out.println(builder.toString());
    }

    /**
     * Jetty listener.
     */
    private class JettyLifecycleListener implements LifeCycle.Listener {
        @Override
        public void lifeCycleStarting(final LifeCycle event) {
            log("Jetty starting...");
        }

        @Override
        public void lifeCycleStarted(final LifeCycle event) {
            log("Jetty started");
        }

        @Override
        public void lifeCycleStopping(final LifeCycle event) {
            timer.reset();
            log("Stopping Jetty...");
        }

        @Override
        public void lifeCycleStopped(final LifeCycle event) {
            log("Jetty stopped");
        }
    }

    /**
     * Jersey listener.
     */
    private class JerseyEventListener implements ApplicationEventListener {
        @Override
        @SuppressWarnings({"checkstyle:MissingSwitchDefault", "PMD.SwitchStmtsShouldHaveDefault"})
        @SuppressFBWarnings("SF_SWITCH_NO_DEFAULT")
        public void onEvent(final ApplicationEvent event) {
            switch (event.getType()) {
                case INITIALIZATION_START:
                    log("Initializing jersey app...");
                    break;
                case INITIALIZATION_APP_FINISHED:
                    log("Jersey app initialized");
                    break;
                case INITIALIZATION_FINISHED:
                    log("Jersey initialized");
                    break;
                case DESTROY_FINISHED:
                    log("Jersey app destroyed");
                    break;
            }
        }

        @Override
        public RequestEventListener onRequest(final RequestEvent requestEvent) {
            return null;
        }
    }
}


text:
package org.testng.internal;

import org.testng.IClass;
import org.testng.IRetryAnalyzer;
import org.testng.ITestClass;
import org.testng.ITestNGMethod;
import org.testng.collections.Lists;
import org.testng.xml.XmlTest;

import java.lang.reflect.Method;
import java.util.Collections;
import java.util.List;
import java.util.Map;

public class ClonedMethod implements ITestNGMethod {
  private static final long serialVersionUID = 1L;

  private ITestNGMethod m_method;
  transient private Method m_javaMethod;
  private String m_id;
  private int m_currentInvocationCount;
  private long m_date;

  private List<Integer> m_invocationNumbers = Lists.newArrayList();
  private List<Integer> m_failedInvocationNumbers = Lists.newArrayList();

  public ClonedMethod(ITestNGMethod method, Method javaMethod) {
    m_method = method;
    m_javaMethod = javaMethod;
  }

  @Override
  public void addMethodDependedUpon(String methodName) {
    // nop
  }

  @Override
  public boolean canRunFromClass(IClass testClass) {
    return m_method.canRunFromClass(testClass);
  }

  @Override
  public String[] getAfterGroups() {
    return m_method.getAfterGroups();
  }

  @Override
  public String[] getBeforeGroups() {
    return m_method.getBeforeGroups();
  }

  @Override
  public int getCurrentInvocationCount() {
    return m_currentInvocationCount;
  }

  @Override
  public long getDate() {
    return m_method.getDate();
  }

  @Override
  public String getDescription() {
    return "";
  }

  @Override
  public boolean getEnabled() {
    return true;
  }

  @Override
  public String[] getGroups() {
    return m_method.getGroups();
  }

  @Override
  public String[] getGroupsDependedUpon() {
    return new String[0];
  }

  @Override
  public String getId() {
    return m_id;
  }

  @Override
  public long[] getInstanceHashCodes() {
    return m_method.getInstanceHashCodes();
  }

  @Override
  public Object[] getInstances() {
    return m_method.getInstances();
  }

  @Override
  public Object getInstance() {
    return m_method.getInstance();
  }

  @Override
  public int getInvocationCount() {
    return 1;
  }

  @Override
  public long getInvocationTimeOut() {
    return m_method.getInvocationTimeOut();
  }

  @Override
  public Method getMethod() {
    return m_javaMethod;
  }

  @Override
  public String getMethodName() {
    return m_javaMethod.getName();
  }

  @Override
  public String[] getMethodsDependedUpon() {
    return new String[0];
  }

  @Override
  public String getMissingGroup() {
    return null;
  }

  @Override
  public int getParameterInvocationCount() {
    return 1;
  }

  @Override
  public Class getRealClass() {
    return m_javaMethod.getClass();
  }

  @Override
  public IRetryAnalyzer getRetryAnalyzer() {
    return m_method.getRetryAnalyzer();
  }

  @Override
  public int getSuccessPercentage() {
    return 100;
  }

  @Override
  public ITestClass getTestClass() {
    return m_method.getTestClass();
  }

  @Override
  public int getThreadPoolSize() {
    return m_method.getThreadPoolSize();
  }

  @Override
  public long getTimeOut() {
    return m_method.getTimeOut();
  }

  @Override
  public void setTimeOut(long timeOut) {
    m_method.setTimeOut(timeOut);
  }

  @Override
  public boolean ignoreMissingDependencies() {
    return false;
  }

  @Override
  public void incrementCurrentInvocationCount() {
    m_currentInvocationCount++;
  }

  @Override
  public boolean isAfterClassConfiguration() {
    return false;
  }

  @Override
  public boolean isAfterGroupsConfiguration() {
    return false;
  }

  @Override
  public boolean isAfterMethodConfiguration() {
    return false;
  }

  @Override
  public boolean isAfterSuiteConfiguration() {
    return false;
  }

  @Override
  public boolean isAfterTestConfiguration() {
    return false;
  }

  @Override
  public boolean isAlwaysRun() {
    return false;
  }

  @Override
  public boolean isBeforeClassConfiguration() {
    return false;
  }

  @Override
  public boolean isBeforeGroupsConfiguration() {
    return false;
  }

  @Override
  public boolean isBeforeMethodConfiguration() {
    return false;
  }

  @Override
  public boolean isBeforeSuiteConfiguration() {
    return false;
  }

  @Override
  public boolean isBeforeTestConfiguration() {
    return false;
  }

  @Override
  public boolean isTest() {
    return true;
  }

  @Override
  public void setDate(long date) {
    m_date = date;
  }

  @Override
  public void setId(String id) {
    m_id = id;
  }

  @Override
  public void setIgnoreMissingDependencies(boolean ignore) {
  }

  @Override
  public void setInvocationCount(int count) {
  }

  @Override
  public void setMissingGroup(String group) {
  }

  @Override
  public void setParameterInvocationCount(int n) {
  }

  @Override
  public void setRetryAnalyzer(IRetryAnalyzer retryAnalyzer) {
  }

  @Override
  public void setSkipFailedInvocations(boolean skip) {
  }

  @Override
  public void setTestClass(ITestClass cls) {
  }

  @Override
  public void setThreadPoolSize(int threadPoolSize) {
  }

  @Override
  public boolean skipFailedInvocations() {
    return false;
  }

  @Override
  public int compareTo(Object o) {
    int result = -2;
    Class<?> thisClass = getRealClass();
    Class<?> otherClass = ((ITestNGMethod) o).getRealClass();
    if (thisClass.isAssignableFrom(otherClass)) {
      result = -1;
    } else if (otherClass.isAssignableFrom(thisClass)) {
      result = 1;
    } else if (equals(o)) {
      result = 0;
    }

    return result;
  }

  @Override
  public ClonedMethod clone() {
    return new ClonedMethod(m_method, m_javaMethod);
  }

  @Override
  public String toString() {
    Method m = getMethod();
    String cls = m.getDeclaringClass().getName();
    StringBuffer result = new StringBuffer(cls + "." + m.getName() + "(");
    int i = 0;
    for (Class<?> p : m.getParameterTypes()) {
      if (i++ > 0) {
        result.append(", ");
      }
      result.append(p.getName());
    }
    result.append(")");

    return result.toString();
  }

  @Override
  public List<Integer> getInvocationNumbers() {
    return m_invocationNumbers;
  }

  @Override
  public void setInvocationNumbers(List<Integer> count) {
    m_invocationNumbers = count;
  }

  @Override
  public List<Integer> getFailedInvocationNumbers() {
    return m_failedInvocationNumbers;
  }

  @Override
  public void addFailedInvocationNumber(int number) {
    m_failedInvocationNumbers.add(number);
  }

  @Override
  public int getPriority() {
    return m_method.getPriority();
  }

  @Override
  public void setPriority(int priority) {
    // ignored
  }

  @Override
  public XmlTest getXmlTest() {
    return m_method.getXmlTest();
  }

  @Override
  public ConstructorOrMethod getConstructorOrMethod() {
    return null;
  }

  @Override
  public Map<String, String> findMethodParameters(XmlTest test) {
    return Collections.emptyMap();
  }
}


text:
package android.view.inputmethod;

import android.graphics.Matrix;
import android.graphics.RectF;
import android.os.Parcel;
import android.test.InstrumentationTestCase;
import android.test.suitebuilder.annotation.SmallTest;
import android.text.TextUtils;
import android.view.inputmethod.CursorAnchorInfo.Builder;

import java.util.Objects;

import static android.view.inputmethod.CursorAnchorInfo.FLAG_HAS_INVISIBLE_REGION;
import static android.view.inputmethod.CursorAnchorInfo.FLAG_HAS_VISIBLE_REGION;
import static android.view.inputmethod.CursorAnchorInfo.FLAG_IS_RTL;

public class CursorAnchorInfoTest extends InstrumentationTestCase {
    private static final RectF[] MANY_BOUNDS = new RectF[] {
            new RectF(101.0f, 201.0f, 301.0f, 401.0f),
            new RectF(102.0f, 202.0f, 302.0f, 402.0f),
            new RectF(103.0f, 203.0f, 303.0f, 403.0f),
            new RectF(104.0f, 204.0f, 304.0f, 404.0f),
            new RectF(105.0f, 205.0f, 305.0f, 405.0f),
            new RectF(106.0f, 206.0f, 306.0f, 406.0f),
            new RectF(107.0f, 207.0f, 307.0f, 407.0f),
            new RectF(108.0f, 208.0f, 308.0f, 408.0f),
            new RectF(109.0f, 209.0f, 309.0f, 409.0f),
            new RectF(110.0f, 210.0f, 310.0f, 410.0f),
            new RectF(111.0f, 211.0f, 311.0f, 411.0f),
            new RectF(112.0f, 212.0f, 312.0f, 412.0f),
            new RectF(113.0f, 213.0f, 313.0f, 413.0f),
            new RectF(114.0f, 214.0f, 314.0f, 414.0f),
            new RectF(115.0f, 215.0f, 315.0f, 415.0f),
            new RectF(116.0f, 216.0f, 316.0f, 416.0f),
            new RectF(117.0f, 217.0f, 317.0f, 417.0f),
            new RectF(118.0f, 218.0f, 318.0f, 418.0f),
            new RectF(119.0f, 219.0f, 319.0f, 419.0f),
    };
    private static final int[] MANY_FLAGS_ARRAY = new int[] {
        FLAG_HAS_INVISIBLE_REGION,
        FLAG_HAS_INVISIBLE_REGION | FLAG_HAS_VISIBLE_REGION,
        FLAG_HAS_VISIBLE_REGION,
        FLAG_HAS_VISIBLE_REGION,
        FLAG_HAS_VISIBLE_REGION,
        FLAG_HAS_VISIBLE_REGION,
        FLAG_HAS_VISIBLE_REGION | FLAG_IS_RTL,
        FLAG_HAS_INVISIBLE_REGION | FLAG_HAS_VISIBLE_REGION | FLAG_IS_RTL,
        FLAG_HAS_INVISIBLE_REGION | FLAG_IS_RTL,
        FLAG_HAS_VISIBLE_REGION | FLAG_IS_RTL,
        FLAG_HAS_VISIBLE_REGION,
        FLAG_HAS_VISIBLE_REGION | FLAG_IS_RTL,
        FLAG_HAS_VISIBLE_REGION,
        FLAG_HAS_VISIBLE_REGION | FLAG_IS_RTL,
        FLAG_HAS_VISIBLE_REGION,
        FLAG_HAS_VISIBLE_REGION | FLAG_IS_RTL,
        FLAG_HAS_VISIBLE_REGION,
        FLAG_HAS_INVISIBLE_REGION,
        FLAG_HAS_INVISIBLE_REGION | FLAG_IS_RTL,
    };

    @SmallTest
    public void testBuilder() throws Exception {
        final int SELECTION_START = 30;
        final int SELECTION_END = 40;
        final int COMPOSING_TEXT_START = 32;
        final String COMPOSING_TEXT = "test";
        final int INSERTION_MARKER_FLAGS =
                FLAG_HAS_VISIBLE_REGION | FLAG_HAS_INVISIBLE_REGION | FLAG_IS_RTL;
        final float INSERTION_MARKER_HORIZONTAL = 10.5f;
        final float INSERTION_MARKER_TOP = 100.1f;
        final float INSERTION_MARKER_BASELINE = 110.4f;
        final float INSERTION_MARKER_BOTOM = 111.0f;

        Matrix TRANSFORM_MATRIX = new Matrix(Matrix.IDENTITY_MATRIX);
        TRANSFORM_MATRIX.setScale(10.0f, 20.0f);

        final Builder builder = new Builder();
        builder.setSelectionRange(SELECTION_START, SELECTION_END)
                .setComposingText(COMPOSING_TEXT_START, COMPOSING_TEXT)
                .setInsertionMarkerLocation(INSERTION_MARKER_HORIZONTAL, INSERTION_MARKER_TOP,
                        INSERTION_MARKER_BASELINE, INSERTION_MARKER_BOTOM, INSERTION_MARKER_FLAGS)
                .setMatrix(TRANSFORM_MATRIX);
        for (int i = 0; i < MANY_BOUNDS.length; i++) {
            final RectF bounds = MANY_BOUNDS[i];
            final int flags = MANY_FLAGS_ARRAY[i];
            builder.addCharacterBounds(i, bounds.left, bounds.top, bounds.right, bounds.bottom,
                    flags);
        }

        final CursorAnchorInfo info = builder.build();
        assertEquals(SELECTION_START, info.getSelectionStart());
        assertEquals(SELECTION_END, info.getSelectionEnd());
        assertEquals(COMPOSING_TEXT_START, info.getComposingTextStart());
        assertTrue(TextUtils.equals(COMPOSING_TEXT, info.getComposingText()));
        assertEquals(INSERTION_MARKER_FLAGS, info.getInsertionMarkerFlags());
        assertEquals(INSERTION_MARKER_HORIZONTAL, info.getInsertionMarkerHorizontal());
        assertEquals(INSERTION_MARKER_TOP, info.getInsertionMarkerTop());
        assertEquals(INSERTION_MARKER_BASELINE, info.getInsertionMarkerBaseline());
        assertEquals(INSERTION_MARKER_BOTOM, info.getInsertionMarkerBottom());
        assertEquals(TRANSFORM_MATRIX, info.getMatrix());
        for (int i = 0; i < MANY_BOUNDS.length; i++) {
            final RectF expectedBounds = MANY_BOUNDS[i];
            assertEquals(expectedBounds, info.getCharacterBounds(i));
        }
        assertNull(info.getCharacterBounds(-1));
        assertNull(info.getCharacterBounds(MANY_BOUNDS.length + 1));
        for (int i = 0; i < MANY_FLAGS_ARRAY.length; i++) {
            final int expectedFlags = MANY_FLAGS_ARRAY[i];
            assertEquals(expectedFlags, info.getCharacterBoundsFlags(i));
        }
        assertEquals(0, info.getCharacterBoundsFlags(-1));
        assertEquals(0, info.getCharacterBoundsFlags(MANY_BOUNDS.length + 1));

        // Make sure that the builder can reproduce the same object.
        final CursorAnchorInfo info2 = builder.build();
        assertEquals(SELECTION_START, info2.getSelectionStart());
        assertEquals(SELECTION_END, info2.getSelectionEnd());
        assertEquals(COMPOSING_TEXT_START, info2.getComposingTextStart());
        assertTrue(TextUtils.equals(COMPOSING_TEXT, info2.getComposingText()));
        assertEquals(INSERTION_MARKER_FLAGS, info2.getInsertionMarkerFlags());
        assertEquals(INSERTION_MARKER_HORIZONTAL, info2.getInsertionMarkerHorizontal());
        assertEquals(INSERTION_MARKER_TOP, info2.getInsertionMarkerTop());
        assertEquals(INSERTION_MARKER_BASELINE, info2.getInsertionMarkerBaseline());
        assertEquals(INSERTION_MARKER_BOTOM, info2.getInsertionMarkerBottom());
        assertEquals(TRANSFORM_MATRIX, info2.getMatrix());
        for (int i = 0; i < MANY_BOUNDS.length; i++) {
            final RectF expectedBounds = MANY_BOUNDS[i];
            assertEquals(expectedBounds, info2.getCharacterBounds(i));
        }
        assertNull(info2.getCharacterBounds(-1));
        assertNull(info2.getCharacterBounds(MANY_BOUNDS.length + 1));
        for (int i = 0; i < MANY_FLAGS_ARRAY.length; i++) {
            final int expectedFlags = MANY_FLAGS_ARRAY[i];
            assertEquals(expectedFlags, info2.getCharacterBoundsFlags(i));
        }
        assertEquals(0, info2.getCharacterBoundsFlags(-1));
        assertEquals(0, info2.getCharacterBoundsFlags(MANY_BOUNDS.length + 1));
        assertEquals(info, info2);
        assertEquals(info.hashCode(), info2.hashCode());

        // Make sure that object can be marshaled via {@link Parsel}.
        final CursorAnchorInfo info3 = cloneViaParcel(info2);
        assertEquals(SELECTION_START, info3.getSelectionStart());
        assertEquals(SELECTION_END, info3.getSelectionEnd());
        assertEquals(COMPOSING_TEXT_START, info3.getComposingTextStart());
        assertTrue(TextUtils.equals(COMPOSING_TEXT, info3.getComposingText()));
        assertEquals(INSERTION_MARKER_FLAGS, info3.getInsertionMarkerFlags());
        assertEquals(INSERTION_MARKER_HORIZONTAL, info3.getInsertionMarkerHorizontal());
        assertEquals(INSERTION_MARKER_TOP, info3.getInsertionMarkerTop());
        assertEquals(INSERTION_MARKER_BASELINE, info3.getInsertionMarkerBaseline());
        assertEquals(INSERTION_MARKER_BOTOM, info3.getInsertionMarkerBottom());
        assertEquals(TRANSFORM_MATRIX, info3.getMatrix());
        for (int i = 0; i < MANY_BOUNDS.length; i++) {
            final RectF expectedBounds = MANY_BOUNDS[i];
            assertEquals(expectedBounds, info3.getCharacterBounds(i));
        }
        assertNull(info3.getCharacterBounds(-1));
        assertNull(info3.getCharacterBounds(MANY_BOUNDS.length + 1));
        for (int i = 0; i < MANY_FLAGS_ARRAY.length; i++) {
            final int expectedFlags = MANY_FLAGS_ARRAY[i];
            assertEquals(expectedFlags, info3.getCharacterBoundsFlags(i));
        }
        assertEquals(0, info3.getCharacterBoundsFlags(-1));
        assertEquals(0, info3.getCharacterBoundsFlags(MANY_BOUNDS.length + 1));
        assertEquals(info.hashCode(), info3.hashCode());

        builder.reset();
        final CursorAnchorInfo uninitializedInfo = builder.build();
        assertEquals(-1, uninitializedInfo.getSelectionStart());
        assertEquals(-1, uninitializedInfo.getSelectionEnd());
        assertEquals(-1, uninitializedInfo.getComposingTextStart());
        assertNull(uninitializedInfo.getComposingText());
        assertEquals(0, uninitializedInfo.getInsertionMarkerFlags());
        assertEquals(Float.NaN, uninitializedInfo.getInsertionMarkerHorizontal());
        assertEquals(Float.NaN, uninitializedInfo.getInsertionMarkerTop());
        assertEquals(Float.NaN, uninitializedInfo.getInsertionMarkerBaseline());
        assertEquals(Float.NaN, uninitializedInfo.getInsertionMarkerBottom());
        assertEquals(Matrix.IDENTITY_MATRIX, uninitializedInfo.getMatrix());
    }

    private static void assertNotEquals(final CursorAnchorInfo reference,
            final CursorAnchorInfo actual) {
        assertFalse(Objects.equals(reference, actual));
    }

    @SmallTest
    public void testEquality() throws Exception {
        final Matrix MATRIX1 = new Matrix();
        MATRIX1.setTranslate(10.0f, 20.0f);
        final Matrix MATRIX2 = new Matrix();
        MATRIX2.setTranslate(110.0f, 120.0f);
        final Matrix NAN_MATRIX = new Matrix();
        NAN_MATRIX.setValues(new float[]{
                Float.NaN, Float.NaN, Float.NaN,
                Float.NaN, Float.NaN, Float.NaN,
                Float.NaN, Float.NaN, Float.NaN});
        final int SELECTION_START1 = 2;
        final int SELECTION_END1 = 7;
        final String COMPOSING_TEXT1 = "0123456789";
        final int COMPOSING_TEXT_START1 = 0;
        final int INSERTION_MARKER_FLAGS1 = FLAG_HAS_VISIBLE_REGION;
        final float INSERTION_MARKER_HORIZONTAL1 = 10.5f;
        final float INSERTION_MARKER_TOP1 = 100.1f;
        final float INSERTION_MARKER_BASELINE1 = 110.4f;
        final float INSERTION_MARKER_BOTOM1 = 111.0f;
        final int SELECTION_START2 = 4;
        final int SELECTION_END2 = 8;
        final String COMPOSING_TEXT2 = "9876543210";
        final int COMPOSING_TEXT_START2 = 3;
        final int INSERTION_MARKER_FLAGS2 =
                FLAG_HAS_VISIBLE_REGION | FLAG_HAS_INVISIBLE_REGION | FLAG_IS_RTL;
        final float INSERTION_MARKER_HORIZONTAL2 = 14.5f;
        final float INSERTION_MARKER_TOP2 = 200.1f;
        final float INSERTION_MARKER_BASELINE2 = 210.4f;
        final float INSERTION_MARKER_BOTOM2 = 211.0f;

        // Default instance should be equal.
        assertEquals(new Builder().build(), new Builder().build());

        assertEquals(
                new Builder().setSelectionRange(SELECTION_START1, SELECTION_END1).build(),
                new Builder().setSelectionRange(SELECTION_START1, SELECTION_END1).build());
        assertNotEquals(
                new Builder().setSelectionRange(SELECTION_START1, SELECTION_END1).build(),
                new Builder().setSelectionRange(SELECTION_START1, SELECTION_END2).build());
        assertNotEquals(
                new Builder().setSelectionRange(SELECTION_START1, SELECTION_END1).build(),
                new Builder().setSelectionRange(SELECTION_START2, SELECTION_END1).build());
        assertNotEquals(
                new Builder().setSelectionRange(SELECTION_START1, SELECTION_END1).build(),
                new Builder().setSelectionRange(SELECTION_START2, SELECTION_END2).build());
        assertEquals(
                new Builder().setComposingText(COMPOSING_TEXT_START1, COMPOSING_TEXT1).build(),
                new Builder().setComposingText(COMPOSING_TEXT_START1, COMPOSING_TEXT1).build());
        assertNotEquals(
                new Builder().setComposingText(COMPOSING_TEXT_START1, COMPOSING_TEXT1).build(),
                new Builder().setComposingText(COMPOSING_TEXT_START2, COMPOSING_TEXT1).build());
        assertNotEquals(
                new Builder().setComposingText(COMPOSING_TEXT_START1, COMPOSING_TEXT1).build(),
                new Builder().setComposingText(COMPOSING_TEXT_START1, COMPOSING_TEXT2).build());
        assertNotEquals(
                new Builder().setComposingText(COMPOSING_TEXT_START1, COMPOSING_TEXT1).build(),
                new Builder().setComposingText(COMPOSING_TEXT_START2, COMPOSING_TEXT2).build());

        // For insertion marker locations, {@link Float#NaN} is treated as if it was a number.
        assertEquals(
                new Builder().setMatrix(MATRIX1).setInsertionMarkerLocation(
                        Float.NaN, Float.NaN, Float.NaN, Float.NaN,
                        INSERTION_MARKER_FLAGS1).build(),
                new Builder().setMatrix(MATRIX1).setInsertionMarkerLocation(
                        Float.NaN, Float.NaN, Float.NaN, Float.NaN,
                        INSERTION_MARKER_FLAGS1).build());

        // Check Matrix.
        assertEquals(
                new Builder().setMatrix(MATRIX1).build(),
                new Builder().setMatrix(MATRIX1).build());
        assertNotEquals(
                new Builder().setMatrix(MATRIX1).build(),
                new Builder().setMatrix(MATRIX2).build());
        assertNotEquals(
                new Builder().setMatrix(MATRIX1).build(),
                new Builder().setMatrix(NAN_MATRIX).build());
        // Unlike insertion marker locations, {@link Float#NaN} in the matrix is treated as just a
        // NaN as usual (NaN == NaN -> false).
        assertNotEquals(
                new Builder().setMatrix(NAN_MATRIX).build(),
                new Builder().setMatrix(NAN_MATRIX).build());

        assertEquals(
                new Builder().setMatrix(MATRIX1).setInsertionMarkerLocation(
                        INSERTION_MARKER_HORIZONTAL1, INSERTION_MARKER_TOP1,
                        INSERTION_MARKER_BASELINE1, INSERTION_MARKER_BOTOM1,
                        INSERTION_MARKER_FLAGS1).build(),
                new Builder().setMatrix(MATRIX1).setInsertionMarkerLocation(
                        INSERTION_MARKER_HORIZONTAL1, INSERTION_MARKER_TOP1,
                        INSERTION_MARKER_BASELINE1, INSERTION_MARKER_BOTOM1,
                        INSERTION_MARKER_FLAGS1).build());
        assertNotEquals(
                new Builder().setMatrix(MATRIX1).setInsertionMarkerLocation(
                        Float.NaN, INSERTION_MARKER_TOP1,
                        INSERTION_MARKER_BASELINE1, INSERTION_MARKER_BOTOM1,
                        INSERTION_MARKER_FLAGS1).build(),
                new Builder().setMatrix(MATRIX1).setInsertionMarkerLocation(
                        INSERTION_MARKER_HORIZONTAL1, INSERTION_MARKER_TOP1,
                        INSERTION_MARKER_BASELINE1, INSERTION_MARKER_BOTOM1,
                        INSERTION_MARKER_FLAGS1).build());
        assertNotEquals(
                new Builder().setMatrix(MATRIX1).setInsertionMarkerLocation(
                        INSERTION_MARKER_HORIZONTAL1, INSERTION_MARKER_TOP1,
                        INSERTION_MARKER_BASELINE1, INSERTION_MARKER_BOTOM1,
                        INSERTION_MARKER_FLAGS1).build(),
                new Builder().setMatrix(MATRIX1).setInsertionMarkerLocation(
                        INSERTION_MARKER_HORIZONTAL2, INSERTION_MARKER_TOP1,
                        INSERTION_MARKER_BASELINE1, INSERTION_MARKER_BOTOM1,
                        INSERTION_MARKER_FLAGS1).build());
        assertNotEquals(
                new Builder().setMatrix(MATRIX1).setInsertionMarkerLocation(
                        INSERTION_MARKER_HORIZONTAL1, INSERTION_MARKER_TOP1,
                        INSERTION_MARKER_BASELINE1, INSERTION_MARKER_BOTOM1,
                        INSERTION_MARKER_FLAGS1).build(),
                new Builder().setMatrix(MATRIX1).setInsertionMarkerLocation(
                        INSERTION_MARKER_HORIZONTAL1, INSERTION_MARKER_TOP2,
                        INSERTION_MARKER_BASELINE1, INSERTION_MARKER_BOTOM1,
                        INSERTION_MARKER_FLAGS1).build());
        assertNotEquals(
                new Builder().setMatrix(MATRIX1).setInsertionMarkerLocation(
                        INSERTION_MARKER_HORIZONTAL1, INSERTION_MARKER_TOP1,
                        INSERTION_MARKER_BASELINE1, INSERTION_MARKER_BOTOM1,
                        INSERTION_MARKER_FLAGS1).build(),
                new Builder().setMatrix(MATRIX1).setInsertionMarkerLocation(
                        INSERTION_MARKER_HORIZONTAL1, INSERTION_MARKER_TOP1,
                        INSERTION_MARKER_BASELINE2, INSERTION_MARKER_BOTOM1,
                        INSERTION_MARKER_FLAGS1).build());
        assertNotEquals(
                new Builder().setMatrix(MATRIX1).setInsertionMarkerLocation(
                        INSERTION_MARKER_HORIZONTAL1, INSERTION_MARKER_TOP1,
                        INSERTION_MARKER_BASELINE1, INSERTION_MARKER_BOTOM1,
                        INSERTION_MARKER_FLAGS1).build(),
                new Builder().setMatrix(MATRIX1).setInsertionMarkerLocation(
                        INSERTION_MARKER_HORIZONTAL2, INSERTION_MARKER_TOP1,
                        INSERTION_MARKER_BASELINE1, INSERTION_MARKER_BOTOM1,
                        INSERTION_MARKER_FLAGS1).build());
        assertNotEquals(
                new Builder().setMatrix(MATRIX1).setInsertionMarkerLocation(
                        INSERTION_MARKER_HORIZONTAL1, INSERTION_MARKER_TOP1,
                        INSERTION_MARKER_BASELINE1, INSERTION_MARKER_BOTOM1,
                        INSERTION_MARKER_FLAGS1).build(),
                new Builder().setMatrix(MATRIX1).setInsertionMarkerLocation(
                        INSERTION_MARKER_HORIZONTAL1, INSERTION_MARKER_TOP1,
                        INSERTION_MARKER_BASELINE1, INSERTION_MARKER_BOTOM2,
                        INSERTION_MARKER_FLAGS1).build());
        assertNotEquals(
                new Builder().setMatrix(MATRIX1).setInsertionMarkerLocation(
                        INSERTION_MARKER_HORIZONTAL1, INSERTION_MARKER_TOP1,
                        INSERTION_MARKER_BASELINE1, INSERTION_MARKER_BOTOM1,
                        INSERTION_MARKER_FLAGS1).build(),
                new Builder().setMatrix(MATRIX1).setInsertionMarkerLocation(
                        INSERTION_MARKER_HORIZONTAL1, INSERTION_MARKER_TOP1,
                        INSERTION_MARKER_BASELINE1, INSERTION_MARKER_BOTOM1,
                        INSERTION_MARKER_FLAGS2).build());
    }

    @SmallTest
    public void testMatrixIsCopied() throws Exception {
        final Matrix MATRIX1 = new Matrix();
        MATRIX1.setTranslate(10.0f, 20.0f);
        final Matrix MATRIX2 = new Matrix();
        MATRIX2.setTranslate(110.0f, 120.0f);
        final Matrix MATRIX3 = new Matrix();
        MATRIX3.setTranslate(210.0f, 220.0f);
        final Matrix matrix = new Matrix();
        final Builder builder = new Builder();

        matrix.set(MATRIX1);
        builder.setMatrix(matrix);
        matrix.postRotate(90.0f);

        final CursorAnchorInfo firstInstance = builder.build();
        assertEquals(MATRIX1, firstInstance.getMatrix());
        matrix.set(MATRIX2);
        builder.setMatrix(matrix);
        final CursorAnchorInfo secondInstance = builder.build();
        assertEquals(MATRIX1, firstInstance.getMatrix());
        assertEquals(MATRIX2, secondInstance.getMatrix());

        matrix.set(MATRIX3);
        assertEquals(MATRIX1, firstInstance.getMatrix());
        assertEquals(MATRIX2, secondInstance.getMatrix());
    }

    @SmallTest
    public void testMatrixIsRequired() throws Exception {
        final int SELECTION_START = 30;
        final int SELECTION_END = 40;
        final int COMPOSING_TEXT_START = 32;
        final String COMPOSING_TEXT = "test";
        final int INSERTION_MARKER_FLAGS = FLAG_HAS_VISIBLE_REGION;
        final float INSERTION_MARKER_HORIZONTAL = 10.5f;
        final float INSERTION_MARKER_TOP = 100.1f;
        final float INSERTION_MARKER_BASELINE = 110.4f;
        final float INSERTION_MARKER_BOTOM = 111.0f;
        Matrix TRANSFORM_MATRIX = new Matrix(Matrix.IDENTITY_MATRIX);
        TRANSFORM_MATRIX.setScale(10.0f, 20.0f);

        final Builder builder = new Builder();
        // Check twice to make sure if Builder#reset() works as expected.
        for (int repeatCount = 0; repeatCount < 2; ++repeatCount) {
            builder.setSelectionRange(SELECTION_START, SELECTION_END)
                    .setComposingText(COMPOSING_TEXT_START, COMPOSING_TEXT);
            try {
                // Should succeed as coordinate transformation matrix is not required if no
                // positional information is specified.
                builder.build();
            } catch (IllegalArgumentException ex) {
                assertTrue(false);
            }

            builder.setInsertionMarkerLocation(INSERTION_MARKER_HORIZONTAL, INSERTION_MARKER_TOP,
                    INSERTION_MARKER_BASELINE, INSERTION_MARKER_BOTOM, INSERTION_MARKER_FLAGS);
            try {
                // Coordinate transformation matrix is required if no positional information is
                // specified.
                builder.build();
                assertTrue(false);
            } catch (IllegalArgumentException ex) {
            }

            builder.setMatrix(TRANSFORM_MATRIX);
            try {
                // Should succeed as coordinate transformation matrix is required.
                builder.build();
            } catch (IllegalArgumentException ex) {
                assertTrue(false);
            }

            builder.reset();
        }
    }

    @SmallTest
    public void testBuilderAddCharacterBounds() throws Exception {
        // A negative index should be rejected.
        try {
            new Builder().addCharacterBounds(-1, 0.0f, 0.0f, 0.0f, 0.0f, FLAG_HAS_VISIBLE_REGION);
            assertTrue(false);
        } catch (IllegalArgumentException ex) {
        }
    }

    private static CursorAnchorInfo cloneViaParcel(final CursorAnchorInfo src) {
        Parcel parcel = null;
        try {
            parcel = Parcel.obtain();
            src.writeToParcel(parcel, 0);
            parcel.setDataPosition(0);
            return new CursorAnchorInfo(parcel);
        } finally {
            if (parcel != null) {
                parcel.recycle();
            }
        }
    }
}


text:
package com.xthena.bpm.calendar;

import com.xthena.api.workcal.WorkCalendarConnector;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

public class AdvancedBusinessCalendarManagerFactoryBean implements
        InitializingBean, FactoryBean<AdvancedBusinessCalendarManager> {
    private AdvancedBusinessCalendarManager advancedBusinessCalendarManager;
    private WorkCalendarConnector workCalendarConnector;

    @Override
	public AdvancedBusinessCalendarManager getObject() {
        return advancedBusinessCalendarManager;
    }

    @Override
	public Class<AdvancedBusinessCalendarManager> getObjectType() {
        return AdvancedBusinessCalendarManager.class;
    }

    @Override
	public boolean isSingleton() {
        return true;
    }

    @Override
	public void afterPropertiesSet() throws Exception {
        this.advancedBusinessCalendarManager = new AdvancedBusinessCalendarManager();
        this.addBusinessCalendar(new DueDateBusinessCalendar());
        this.addBusinessCalendar(new DurationBusinessCalendar());
        this.addBusinessCalendar(new CycleBusinessCalendar());
    }

    public void addBusinessCalendar(AdvancedBusinessCalendar businessCalendar) {
        businessCalendar.setWorkCalendarConnector(workCalendarConnector);
        this.advancedBusinessCalendarManager
                .addBusinessCalendar(businessCalendar);
    }

    public void setWorkCalendarConnector(
            WorkCalendarConnector workCalendarConnector) {
        this.workCalendarConnector = workCalendarConnector;
    }
}


text:
require 'rbconfig'

module Cucover
  module LineNumbers
    # Different Ruby versions have slightly different line numbers with rcov
    def self.offset
      Config::CONFIG['MINOR'] == '9' ? 0 : 1
    end
  end
end


text:
export type StyleValueConditionFunction = () => boolean | null | undefined;

export type StyleValueObject = Record<string | number, boolean | StyleValueConditionFunction>;

export type StyleValue = null | undefined | string | StyleValueObject;

export type StyleObject = Partial<Record<keyof CSSStyleDeclaration, StyleValue>>;

declare function styleNames(styles: StyleObject): string;

export default styleNames;


text:
module SessionGuard
  extend ActiveSupport::Concern

  def check_if_session_timed_out
    unless visit
      redirect_to(edit_prisoner_details_path, notice: 'Your session timed out because no information was entered for more than 20 minutes.')
      return
    end
    verify_authenticity_token
  end
end

module SessionGuardOnUpdateOnly
  extend ActiveSupport::Concern
  include SessionGuard

  included do
    before_filter :check_if_session_timed_out, only: :update
  end
end

module SessionGuard
  included do
    before_filter :check_if_session_timed_out, only: [:update, :edit]
  end
end


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information

namespace DotNetNuke.Web.Mvp
{
    using System;

    using WebFormsMvp.Web;

    [Obsolete("Deprecated in DNN 9.2.0. Replace WebFormsMvp and DotNetNuke.Web.Mvp with MVC or SPA patterns instead. Scheduled removal in v11.0.0.")]
    public abstract class WebServiceViewBase : MvpWebService, IWebServiceViewBase
    {
    }
}


text:
"""
Sponge Knowledge Base
Hello World action
"""

class HelloWorldAction(Action):
    def onConfigure(self):
        self.withLabel("Hello world").withDescription("Returns a greeting text.")
        self.withArg(StringType("name").withLabel("Your name").withDescription("Type your name."))
        self.withResult(StringType().withLabel("Greeting").withDescription("The greeting text."))
    def onCall(self, name):
        return "Hello World! Hello {}!".format(name)

def onStartup():
    sponge.logger.info("{}", sponge.call("HelloWorldAction", ["Sponge user"]))


text:
The heart of this project is GITransition object, it adopts `UIViewControllerAnimatedTransitioning` and `UIGestureRecognizerDelegate` protocol, which allows you to have one view controller at the bottom, and on the same time keeping your main navigation separate. This was inspired by the iOS 8 emails implementation where you can have your new email open at the bottom while still viewing all your old emails above it.

#Demo
![Demo](https://raw.githubusercontent.com/Dalein/VCTransition/master/demo.gif)

#Example
```objectivec
    transitionManager = [[GITransition alloc] init];
    self.transitioningDelegate = transitionManager;

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    controller = [storyboard instantiateViewControllerWithIdentifier:@"vcAddNewGoal"];
    controller.transitioningDelegate = transitionManager;
    controller.modalPresentationStyle = UIModalPresentationCustom;
    controller.transitionManager = transitionManager;

- (IBAction)show:(id)sender {
    [self presentViewController:controller animated:YES completion:nil];
}
```

#Usage
Copy GITransition folder into your project.

# License
Permission is hereby granted, free of charge, to any person obtaining a copy of
 this software and associated documentation files (the "Software"), to deal in
 the Software without restriction, including without limitation the rights to
 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 of the Software, and to permit persons to whom the Software is furnished to do
 so, subject to the following conditions:

 If you happen to meet one of the copyright holders in a bar you are obligated
 to buy them one pint of beer.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.


text:
using Android.App;
using Android.Content.PM;
using Android.OS;
using Microsoft.Maui;
using Microsoft.Maui.ApplicationModel;

namespace Mapsui.Samples.Maui
{
    [Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize)]
    public class MainActivity : MauiAppCompatActivity
    {
        protected override void OnCreate(Bundle? savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Platform.Init(this, savedInstanceState);
        }

        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
        {
            Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}


text:
<!doctype html>

  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>{{ title }}</title>
  <meta name="description" content="{{ description }}" />

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">

Broken links on url {{ rooturl }}

Here is the results of the broken link checker.

          Title
          Url
          Error
          Located on page

      {% for item in list_of_links %}

          {{ item.title }}
          {{ item.url }}
          {{ item.error }}
          {{ item.origin }}

      {% endfor %}


text:
"""
The `OpenType specification <https://docs.microsoft.com/en-us/typography/opentype/spec/otff#data-types>`_
defines two fixed-point data types:

``Fixed``
	A 32-bit signed fixed-point number with a 16 bit twos-complement
	magnitude component and 16 fractional bits.
``F2DOT14``
	A 16-bit signed fixed-point number with a 2 bit twos-complement
	magnitude component and 14 fractional bits.

To support reading and writing data with these data types, this module provides
functions for converting between fixed-point, float and string representations.

.. data:: MAX_F2DOT14

	The maximum value that can still fit in an F2Dot14. (1.99993896484375)
"""

from .roundTools import otRound, nearestMultipleShortestRepr
import logging

log = logging.getLogger(__name__)

__all__ = [
	"MAX_F2DOT14",
	"fixedToFloat",
	"floatToFixed",
	"floatToFixedToFloat",
	"floatToFixedToStr",
	"fixedToStr",
	"strToFixed",
	"strToFixedToFloat",
	"ensureVersionIsLong",
	"versionToFixed",
]

MAX_F2DOT14 = 0x7FFF / (1 << 14)

def fixedToFloat(value, precisionBits):
	"""Converts a fixed-point number to a float given the number of
	precision bits.

	Args:
		value (int): Number in fixed-point format.
		precisionBits (int): Number of precision bits.

	Returns:
		Floating point value.

	Examples::

		>>> import math
		>>> f = fixedToFloat(-10139, precisionBits=14)
		>>> math.isclose(f, -0.61883544921875)
		True
	"""
	return value / (1 << precisionBits)

def floatToFixed(value, precisionBits):
	"""Converts a float to a fixed-point number given the number of
	precision bits.

	Args:
		value (float): Floating point value.
		precisionBits (int): Number of precision bits.

	Returns:
		int: Fixed-point representation.

	Examples::

		>>> floatToFixed(-0.61883544921875, precisionBits=14)
		-10139
		>>> floatToFixed(-0.61884, precisionBits=14)
		-10139
	"""
	return otRound(value * (1 << precisionBits))

def floatToFixedToFloat(value, precisionBits):
	"""Converts a float to a fixed-point number and back again.

	By converting the float to fixed, rounding it, and converting it back
	to float again, this returns a floating point values which is exactly
	representable in fixed-point format.

	Note: this **is** equivalent to ``fixedToFloat(floatToFixed(value))``.

	Args:
		value (float): The input floating point value.
		precisionBits (int): Number of precision bits.

	Returns:
		float: The transformed and rounded value.

	Examples::
		>>> import math
		>>> f1 = -0.61884
		>>> f2 = floatToFixedToFloat(-0.61884, precisionBits=14)
		>>> f1 != f2
		True
		>>> math.isclose(f2, -0.61883544921875)
		True
	"""
	scale = 1 << precisionBits
	return otRound(value * scale) / scale

def fixedToStr(value, precisionBits):
	"""Converts a fixed-point number to a string representing a decimal float.

	This chooses the float that has the shortest decimal representation (the least
	number of fractional decimal digits).

	For example, to convert a fixed-point number in a 2.14 format, use
	``precisionBits=14``::

		>>> fixedToStr(-10139, precisionBits=14)
		'-0.61884'

	This is pretty slow compared to the simple division used in ``fixedToFloat``.
	Use sporadically when you need to serialize or print the fixed-point number in
	a human-readable form.
	It uses nearestMultipleShortestRepr under the hood.

	Args:
		value (int): The fixed-point value to convert.
		precisionBits (int): Number of precision bits, *up to a maximum of 16*.

	Returns:
		str: A string representation of the value.
	"""
	scale = 1 << precisionBits
	return nearestMultipleShortestRepr(value/scale, factor=1.0/scale)

def strToFixed(string, precisionBits):
	"""Converts a string representing a decimal float to a fixed-point number.

	Args:
		string (str): A string representing a decimal float.
		precisionBits (int): Number of precision bits, *up to a maximum of 16*.

	Returns:
		int: Fixed-point representation.

	Examples::

		>>> ## to convert a float string to a 2.14 fixed-point number:
		>>> strToFixed('-0.61884', precisionBits=14)
		-10139
	"""
	value = float(string)
	return otRound(value * (1 << precisionBits))

def strToFixedToFloat(string, precisionBits):
	"""Convert a string to a decimal float with fixed-point rounding.

	This first converts string to a float, then turns it into a fixed-point
	number with ``precisionBits`` fractional binary digits, then back to a
	float again.

	This is simply a shorthand for fixedToFloat(floatToFixed(float(s))).

	Args:
		string (str): A string representing a decimal float.
		precisionBits (int): Number of precision bits.

	Returns:
		float: The transformed and rounded value.

	Examples::

		>>> import math
		>>> s = '-0.61884'
		>>> bits = 14
		>>> f = strToFixedToFloat(s, precisionBits=bits)
		>>> math.isclose(f, -0.61883544921875)
		True
		>>> f == fixedToFloat(floatToFixed(float(s), precisionBits=bits), precisionBits=bits)
		True
	"""
	value = float(string)
	scale = 1 << precisionBits
	return otRound(value * scale) / scale

def floatToFixedToStr(value, precisionBits):
	"""Convert float to string with fixed-point rounding.

	This uses the shortest decimal representation (ie. the least
	number of fractional decimal digits) to represent the equivalent
	fixed-point number with ``precisionBits`` fractional binary digits.
	It uses nearestMultipleShortestRepr under the hood.

	>>> floatToFixedToStr(-0.61883544921875, precisionBits=14)
	'-0.61884'

	Args:
		value (float): The float value to convert.
		precisionBits (int): Number of precision bits, *up to a maximum of 16*.

	Returns:
		str: A string representation of the value.

	"""
	scale = 1 << precisionBits
	return nearestMultipleShortestRepr(value, factor=1.0/scale)

def ensureVersionIsLong(value):
	"""Ensure a table version is an unsigned long.

	OpenType table version numbers are expressed as a single unsigned long
	comprising of an unsigned short major version and unsigned short minor
	version. This function detects if the value to be used as a version number
	looks too small (i.e. is less than ``0x10000``), and converts it to
	fixed-point using :func:`floatToFixed` if so.

	Args:
		value (Number): a candidate table version number.

	Returns:
		int: A table version number, possibly corrected to fixed-point.
	"""
	if value < 0x10000:
		newValue = floatToFixed(value, 16)
		log.warning(
			"Table version value is a float: %.4f; "
			"fix to use hex instead: 0x%08x", value, newValue)
		value = newValue
	return value

def versionToFixed(value):
	"""Ensure a table version number is fixed-point.

	Args:
		value (str): a candidate table version number.

	Returns:
		int: A table version number, possibly corrected to fixed-point.
	"""
	value = int(value, 0) if value.startswith("0") else float(value)
	value = ensureVersionIsLong(value)
	return value


text:
package com.intellij.vcs.log.graph.render;

import com.intellij.vcs.log.VcsRef;
import com.intellij.vcs.log.printmodel.GraphPrintCell;
import org.jetbrains.annotations.NotNull;

import java.util.Collection;

/**
 * @author erokhins
 */
public class GraphCommitCell extends CommitCell {

  private final GraphPrintCell row;

  public GraphCommitCell(@NotNull GraphPrintCell row, @NotNull String text,
                         @NotNull Collection<VcsRef> refsToThisCommit) {
    super(text, refsToThisCommit);
    this.row = row;
  }

  public GraphPrintCell getPrintCell() {
    return row;
  }
}


text:
using DescribeMe.Core.DesignByContract;
using DescribeMe.Core.DomainModels;

namespace DescribeMe.Core.Infrastructure
{
    public abstract class Event : IEvent
    {
        protected Event(
            DomainModel sender,
            bool isLongRunning = false)
        {
            Requires.IsNotNull(sender, "sender");

            Sender = sender;
            IsLongRunning = isLongRunning;
        }

        public DomainModel Sender { get; private set; }

        public bool IsLongRunning { get; private set; }
    }
}


text:
<?php

namespace Google\Service\BinaryAuthorization\Resource;

use Google\Service\BinaryAuthorization\Policy;

/**
 * The "projects" collection of methods.
 * Typical usage is:
 *  <code>
 *   $binaryauthorizationService = new Google\Service\BinaryAuthorization(...);
 *   $projects = $binaryauthorizationService->projects;
 *  </code>
 */
class Projects extends \Google\Service\Resource
{
  /**
   * A policy specifies the attestors that must attest to a container image,
   * before the project is allowed to deploy that image. There is at most one
   * policy per project. All image admission requests are permitted if a project
   * has no policy. Gets the policy for this project. Returns a default policy if
   * the project does not have one. (projects.getPolicy)
   *
   * @param string $name Required. The resource name of the policy to retrieve, in
   * the format `projects/policy`.
   * @param array $optParams Optional parameters.
   * @return Policy
   */
  public function getPolicy($name, $optParams = [])
  {
    $params = ['name' => $name];
    $params = array_merge($params, $optParams);
    return $this->call('getPolicy', [$params], Policy::class);
  }
  /**
   * Creates or updates a project's policy, and returns a copy of the new policy.
   * A policy is always updated as a whole, to avoid race conditions with
   * concurrent policy enforcement (or management!) requests. Returns NOT_FOUND if
   * the project does not exist, INVALID_ARGUMENT if the request is malformed.
   * (projects.updatePolicy)
   *
   * @param string $name Output only. The resource name, in the format
   * `projects/policy`. There is at most one policy per project.
   * @param Policy $postBody
   * @param array $optParams Optional parameters.
   * @return Policy
   */
  public function updatePolicy($name, Policy $postBody, $optParams = [])
  {
    $params = ['name' => $name, 'postBody' => $postBody];
    $params = array_merge($params, $optParams);
    return $this->call('updatePolicy', [$params], Policy::class);
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(Projects::class, 'Google_Service_BinaryAuthorization_Resource_Projects');


text:
from __future__ import unicode_literals

from django.core.cache import cache
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.test.client import Client
from django.test.utils import override_settings

import cached_auth

try:
    from django.contrib.auth import get_user_model
except ImportError:
    from django.contrib.auth.models import User
    get_user_model = lambda: User

try:
    # Python 3.4+ includes reload in importlib
    from importlib import reload
except ImportError:
    try:
        # Python 3.3 includes reload in imp
        from imp import reload
    except ImportError:
        # Python 2 includes reload as a builtin
        pass

class MiddlewareTest(TestCase):

    def setUp(self):
        user_model = get_user_model()
        self.user = user_model.objects.create_user(username='test', password='a')
        self.user.is_superuser = True
        self.user.is_staff = True
        self.user.save()
        cache.clear()

    def test_anonymous(self):
        # Anonymous user doesn't cause cache to be set
        client = Client()
        key = cached_auth.CACHE_KEY % self.user.id
        client.get(reverse('admin:index'))
        self.assertEqual(cache.get(key), None)

    def test_cached_middleware(self):
        client = Client()
        key = cached_auth.CACHE_KEY % self.user.id
        self.assertEqual(cache.get(key), None)

        # Visiting admin causes the cache to be populated
        client.login(username='test', password='a')
        client.get(reverse('admin:index'))
        self.assertEqual(cache.get(key), self.user)

        # Changing user model invalidates cache
        self.user.save()
        self.assertEqual(cache.get(key), None)

        # Deleting user invalidates cache
        client.get(reverse('admin:index'))
        self.assertEqual(cache.get(key), self.user)
        self.user.delete()
        self.assertEqual(cache.get(key), None)

    @override_settings(CACHED_AUTH_PREPROCESSOR='test_project.utils.auth_preprocessor')
    def test_cached_auth_preprocessor_function(self):
        reload(cached_auth)
        client = Client()
        key = cached_auth.CACHE_KEY % self.user.id
        self.assertEqual(cache.get(key), None)

        client.login(username='test', password='a')
        client.get(reverse('admin:index'))
        user = cache.get(key)
        self.assertEqual(user.username, 'test_auth')


text:
#ifndef DEVTOOLS_CDBG_DEBUGLETS_PYTHON_PYTHON_CALLBACK_H_
#define DEVTOOLS_CDBG_DEBUGLETS_PYTHON_PYTHON_CALLBACK_H_

#include <functional>

#include "common.h"
#include "python_util.h"

namespace devtools {
namespace cdbg {

// Wraps std::function in a zero arguments Python callable.
class PythonCallback {
 public:
  PythonCallback() {}

  // Creates a zero argument Python callable that will delegate to "callback"
  // when invoked. The callback returns will always return None.
  static ScopedPyObject Wrap(std::function<void()> callback);

  // Disables any futher invocations of "callback_". The "method" is the
  // return value of "Wrap".
  static void Disable(PyObject* method);

  static PyTypeObject python_type_;

 private:
  static PyObject* Run(PyObject* self);

 private:
  // Callback to invoke or nullptr if the callback was cancelled.
  std::function<void()> callback_;

  static PyMethodDef callback_method_def_;

  DISALLOW_COPY_AND_ASSIGN(PythonCallback);
};

}  // namespace cdbg
}  // namespace devtools

#endif  // DEVTOOLS_CDBG_DEBUGLETS_PYTHON_PYTHON_CALLBACK_H_


text:
/**
 * Alias for require('http') that uses real http or fake-http modules and dispatches events.
 */

const Channel = require('chnl');
const httpBrowserify = require('http-browserify');
const httpsBrowserify = require('https-browserify');
const fakeHttp = require('../utils/fake-http');

const LOOPBACK_HOST = 'autotester';

// intercept for event dispatching
const realHttpWrapped = intercept(httpBrowserify);
const realHttpsWrapped = intercept(httpsBrowserify);
const fakeHttpWrapped = intercept(fakeHttp);

exports.request = function (opts) {
  const http = opts.hostname === LOOPBACK_HOST
    ? fakeHttpWrapped
    : (opts.protocol === 'https:' ? realHttpsWrapped : realHttpWrapped);
  return http.request.apply(http, arguments);
};

exports.onRequest = new Channel();
exports.onRequestData = new Channel();
exports.onResponse = new Channel();

function intercept(http) {
  const origRequest = http.request;
  http.request = function (options) {
    const request = origRequest.apply(http, arguments);
    exports.onRequest.dispatchAsync({request, options});
    request.on('response', response => {
      const chunks = [];
      response.on('data', chunk => chunks.push(chunk));
      response.on('end', () => {
        exports.onResponse.dispatchAsync({request, options, response, data: chunks.join('')});
      });
    });

    const origWrite = request.write;
    request.write = function (data) {
      exports.onRequestData.dispatchAsync({request, data});
      return origWrite.apply(request, arguments);
    };

    return request;
  };
  return http;
}