text:
package org.commcare.util.screen;

import org.commcare.modern.util.Pair;
import org.commcare.suite.model.Action;
import org.commcare.suite.model.Detail;
import org.commcare.suite.model.DetailField;
import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.core.model.trace.AccumulatingReporter;
import org.javarosa.core.model.trace.EvaluationTraceReporter;
import org.javarosa.core.model.trace.ReducingTraceReporter;
import org.javarosa.core.model.utils.InstrumentationUtils;
import org.javarosa.core.util.DataUtil;
import org.javarosa.xpath.XPathException;

import java.io.PrintStream;
import java.util.Vector;

/**
 * The entity list subscreen handles actually displaying the list of dynamic entities to the
 * user to be displayed and chosen during a <datum> selection
 *
 * Created by ctsims on 8/20/2015.
 */
public class EntityListSubscreen extends Subscreen<EntityScreen> {

    private static final int SCREEN_WIDTH = 100;

    private final TreeReference[] mChoices;
    private final String[] rows;
    private final String mHeader;

    private final Vector<Action> actions;

    private final Detail shortDetail;
    private final EvaluationContext rootContext;

    private boolean handleCaseIndex;

    public EntityListSubscreen(Detail shortDetail, Vector<TreeReference> references, EvaluationContext context, boolean handleCaseIndex) throws CommCareSessionException {
        mHeader = createHeader(shortDetail, context);
        this.shortDetail = shortDetail;
        this.rootContext = context;
        this.mChoices = new TreeReference[references.size()];
        this.handleCaseIndex = handleCaseIndex;
        references.copyInto(mChoices);
        actions = shortDetail.getCustomActions(context);
        rows = getRows(mChoices, context, shortDetail);
    }

    public static String[] getRows(TreeReference[] references,
                                   EvaluationContext evaluationContext,
                                   Detail detail) {
        String[] rows = new String[references.length];
        int i = 0;
        for (TreeReference entity : references) {
            rows[i] = createRow(entity, evaluationContext, detail);
            ++i;
        }
        return rows;
    }

    private static String createRow(TreeReference entity, EvaluationContext evaluationContext, Detail detail) {
        return createRow(entity, false, evaluationContext, detail);
    }

    private static String createRow(TreeReference entity,
                                    boolean collectDebug,
                                    EvaluationContext evaluationContext,
                                    Detail detail) {
        EvaluationContext context = new EvaluationContext(evaluationContext, entity);
        EvaluationTraceReporter reporter = new AccumulatingReporter();

        if (collectDebug) {
            context.setDebugModeOn(reporter);
        }
        detail.populateEvaluationContextVariables(context);

        if (collectDebug) {
            InstrumentationUtils.printAndClearTraces(reporter, "Variable Traces");
        }

        DetailField[] fields = detail.getFields();

        StringBuilder row = new StringBuilder();
        XPathException detailFieldException = null;
        int i = 0;
        for (DetailField field : fields) {
            Object o;
            try {
                o = field.getTemplate().evaluate(context);
            } catch (XPathException e) {
                o = "error (see output)";
                if (detailFieldException == null) {
                    detailFieldException = e;
                }
            }
            String s;
            if (!(o instanceof String)) {
                s = "";
            } else {
                s = (String)o;
            }
            row.append(ScreenUtils.pad(s, getWidthHint(fields, field)));
        }

        if (detailFieldException != null) {
            detailFieldException.printStackTrace();
        }

        if (collectDebug) {
            InstrumentationUtils.printAndClearTraces(reporter, "Template Traces:");
        }
        return row.toString();
    }

    public static Pair<String[], int[]> getHeaders(Detail shortDetail, EvaluationContext context, int sortIndex) {
        DetailField[] fields = shortDetail.getFields();
        String[] headers = new String[fields.length];
        int[] widthHints = new int[fields.length];

        boolean reverse = sortIndex < 0;
        sortIndex = Math.abs(sortIndex) - 1;
        int[] sorts = shortDetail.getOrderedFieldIndicesForSorting();

        StringBuilder row = new StringBuilder();
        int i = 0;
        for (DetailField field : fields) {
            String s = field.getHeader().evaluate(context);

            int widthHint = getWidthHint(fields, field);
            ScreenUtils.addPaddedStringToBuilder(row, s, widthHint);

            if (DataUtil.intArrayContains(sorts, i)) {
                if (i == sortIndex) {
                    if (reverse) {
                        s = s + " Λ ";
                    } else {
                        s = s + " V ";
                    }
                }
            }

            headers[i] = s;
            widthHints[i] = widthHint;

            i++;
            if (i != fields.length) {
                row.append(" | ");
            }
        }
        return new Pair<>(headers, widthHints);
    }

    //So annoying how identical this is...
    private static String createHeader(Detail shortDetail, EvaluationContext context) {
        DetailField[] fields = shortDetail.getFields();

        StringBuilder row = new StringBuilder();
        int i = 0;
        for (DetailField field : fields) {
            String s = field.getHeader().evaluate(context);

            int widthHint = getWidthHint(fields, field);
            ScreenUtils.addPaddedStringToBuilder(row, s, widthHint);
            i++;
            if (i != fields.length) {
                row.append(" | ");
            }
        }
        return row.toString();
    }

    @Override
    public void prompt(PrintStream out) {
        int maxLength = String.valueOf(mChoices.length).length();
        out.println(ScreenUtils.pad("", maxLength + 1) + mHeader);
        out.println("==============================================================================================");

        for (int i = 0; i < mChoices.length; ++i) {
            String d = rows[i];
            out.println(ScreenUtils.pad(String.valueOf(i), maxLength) + ") " + d);
        }

        if (actions != null) {
            int actionCount = 0;
            for (Action action : actions) {
                out.println();
                out.println("action " + actionCount + ") " + action.getDisplay().evaluate().getName());
                actionCount += 1;
            }
        }
    }

    @Override
    public String[] getOptions() {
        return rows;
    }

    @Override
    public boolean handleInputAndUpdateHost(String input, EntityScreen host, boolean allowAutoLaunch) throws CommCareSessionException {
        if (input.startsWith("action ") && actions != null) {
            int chosenActionIndex;
            try {
                chosenActionIndex = Integer.valueOf(input.substring("action ".length()).trim());
            } catch (NumberFormatException e) {
                return false;
            }
            if (actions.size() > chosenActionIndex) {
                host.setPendingAction(actions.elementAt(chosenActionIndex));
                return true;
            }
        } else if (host.getAutoLaunchAction() != null && allowAutoLaunch) {
            host.setPendingAction(host.getAutoLaunchAction());
            return true;
        }

        if (input.startsWith("debug ")) {
            String debugArg = input.substring("debug ".length());
            try {
                int chosenDebugIndex = Integer.valueOf(debugArg.trim());
                createRow(this.mChoices[chosenDebugIndex], rootContext, shortDetail);
            } catch (NumberFormatException e) {
                if ("list".equals(debugArg)) {
                    host.printNodesetExpansionTrace(new AccumulatingReporter());
                }
            }
            return false;
        }

        if (input.startsWith("profile list")) {
            host.printNodesetExpansionTrace(new ReducingTraceReporter(false));
        }

        if (handleCaseIndex) {
            try {
                int index = Integer.parseInt(input);
                host.setHighlightedEntity(mChoices[index]);
                // Set entity screen to show detail and redraw
                host.setCurrentScreenToDetail();
                return true;
            } catch (NumberFormatException e) {
                // This will result in things just executing again, which is fine.
                return false;
            }
        } else {
            host.setHighlightedEntity(input);
            // Set entity screen to show detail and redraw
            host.setCurrentScreenToDetail();
            return true;
        }
    }

    public Detail getShortDetail() {
        return shortDetail;
    }

    private static int getWidthHint(DetailField[] fields, DetailField field) {
        int widthHint = SCREEN_WIDTH / fields.length;
        try {
            widthHint = Integer.parseInt(field.getHeaderWidthHint());
        } catch (Exception e) {
            //Really don't care if it didn't work
        }
        return widthHint;
    }
}


text:
angular.module('services', [])

.value('criteres', [
	{libelle: 'Prix croissant', 	property: 'price', reverse : false}
		,{libelle: 'Prix decroissant', 	property: 'price', reverse : true}
		,{libelle: 'Titre', 			property: 'title', reverse : false}

	])

.value('currentSearchCriteria', {})

.factory('catalog', function($http, URL, KEY){

	// Pour n'exécuter les services qu'une seule fois
	var catalogPromise = $http.get(URL+KEY).then(function(response){
		return response.data;
	});

	return {

		getList: function(){
			return catalogPromise;
		}
		,getBook: function(id){
			return catalogPromise.then(function(books){
				for(var i = 0; i < books.length; i++){
					var book = books[i];
					if(book._id.$oid === id ){
						return book;
					}
				}
			});
		}
	}
})

.factory('panier', function(TVA){
	return {

		panier: {}

		,getPanier: function(){
			return this.panier;
		}

		,populePanier : function(article){
			var row = this.panier[article['ISBN-13']];
			if(row){
				row.qtt++;
				return;
			}
			else {
				var newItem = {
					id: article['ISBN-13']
					,qtt: 1
					,price: article.price
					,title: article.title
				};
				this.panier[article['ISBN-13']] = newItem;
			}
			return this.panier;
		}
		,remove: function(item){
			delete this.panier[item.id];
			return this.panier;
		}
		,prixArticleHT : function(article){
			return article.price * article.qtt;
			}

		,prixArticleTTC : function(article){
				return article.price * article.qtt * TVA;
			}

		,prixTotalHT : function(){
			var total = 0;
			angular.forEach(this.panier, function(article){
				total += prixArticleHT(article)
			});
			return total;
			}

		,prixTotalTTC : function(){
			var total = 0;
			angular.forEach(this.panier, function(article){
				total += prixArticleTTC(article)
			});
			return total;
		}
		,qttTotal: function(){
			var sum = 0;
			for(var i=0; i<this.panier.length; i++){
				sum += this.panier[i].qtt;
			}
			return sum;
		}
	};
})

.constant('TVA', 20);

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ChangeListManager">
    <list default="true" id="d1f29b7e-b3f1-48be-b01f-400e854ed7a7" name="Default" comment="">
      <change type="NEW" beforePath="" afterPath="$PROJECT_DIR$/.idea/dictionaries/simon.xml" />
      <change type="NEW" beforePath="" afterPath="$PROJECT_DIR$/.idea/vcs.xml" />
      <change type="MODIFICATION" beforePath="$PROJECT_DIR$/detector/anomaly_detector.py" afterPath="$PROJECT_DIR$/detector/anomaly_detector.py" />
      <change type="MODIFICATION" beforePath="$PROJECT_DIR$/detector/src/detector.py" afterPath="$PROJECT_DIR$/detector/src/detector.py" />
      <change type="MODIFICATION" beforePath="$PROJECT_DIR$/detector/src/online_trainer.py" afterPath="$PROJECT_DIR$/detector/src/online_trainer.py" />
      <change type="MODIFICATION" beforePath="$PROJECT_DIR$/detector/src/parser.py" afterPath="$PROJECT_DIR$/detector/src/parser.py" />
      <change type="MODIFICATION" beforePath="$PROJECT_DIR$/detector/src/window.py" afterPath="$PROJECT_DIR$/detector/src/window.py" />
      <change type="MODIFICATION" beforePath="$PROJECT_DIR$/main.py" afterPath="$PROJECT_DIR$/main.py" />
    </list>
    <option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
    <option name="TRACKING_ENABLED" value="true" />
    <option name="SHOW_DIALOG" value="false" />
    <option name="HIGHLIGHT_CONFLICTS" value="true" />
    <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
    <option name="LAST_RESOLUTION" value="IGNORE" />
  </component>
  <component name="CreatePatchCommitExecutor">
    <option name="PATCH_PATH" value="" />
  </component>
  <component name="ExecutionTargetManager" SELECTED_TARGET="default_target" />
  <component name="FavoritesManager">
    <favorites_list name="mff-ai-anomaly-detector" />
  </component>
  <component name="FileEditorManager">
    <leaf>
      <file leaf-file-name="main.py" pinned="false" current-in-tab="true">
        <entry file="file://$PROJECT_DIR$/main.py">
          <provider selected="true" editor-type-id="text-editor">
            <state relative-caret-position="198">
              <caret line="11" column="33" lean-forward="true" selection-start-line="11" selection-start-column="33" selection-end-line="11" selection-end-column="33" />
              <folding>
                <element signature="e#24#33#0" expanded="true" />
              </folding>
            </state>
          </provider>
        </entry>
      </file>
      <file leaf-file-name="detector.py" pinned="false" current-in-tab="false">
        <entry file="file://$PROJECT_DIR$/detector/src/detector.py">
          <provider selected="true" editor-type-id="text-editor">
            <state relative-caret-position="67">
              <caret line="21" column="0" lean-forward="false" selection-start-line="21" selection-start-column="0" selection-end-line="21" selection-end-column="0" />
              <folding />
            </state>
          </provider>
        </entry>
      </file>
      <file leaf-file-name="anomaly_detector.py" pinned="false" current-in-tab="false">
        <entry file="file://$PROJECT_DIR$/detector/anomaly_detector.py">
          <provider selected="true" editor-type-id="text-editor">
            <state relative-caret-position="463">
              <caret line="33" column="0" lean-forward="false" selection-start-line="33" selection-start-column="0" selection-end-line="33" selection-end-column="0" />
              <folding>
                <element signature="e#94#131#0" expanded="true" />
              </folding>
            </state>
          </provider>
        </entry>
      </file>
      <file leaf-file-name="window.py" pinned="false" current-in-tab="false">
        <entry file="file://$PROJECT_DIR$/detector/src/window.py">
          <provider selected="true" editor-type-id="text-editor">
            <state relative-caret-position="337">
              <caret line="21" column="0" lean-forward="false" selection-start-line="21" selection-start-column="0" selection-end-line="21" selection-end-column="0" />
              <folding>
                <element signature="e#50#84#0" expanded="true" />
              </folding>
            </state>
          </provider>
        </entry>
      </file>
      <file leaf-file-name="online_trainer.py" pinned="false" current-in-tab="false">
        <entry file="file://$PROJECT_DIR$/detector/src/online_trainer.py">
          <provider selected="true" editor-type-id="text-editor">
            <state relative-caret-position="178">
              <caret line="24" column="45" lean-forward="false" selection-start-line="24" selection-start-column="34" selection-end-line="24" selection-end-column="45" />
              <folding />
            </state>
          </provider>
        </entry>
      </file>
    </leaf>
  </component>
  <component name="Git.Settings">
    <option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
  </component>
  <component name="IdeDocumentHistory">
    <option name="CHANGED_PATHS">
      <list>
        <option value="$PROJECT_DIR$/detector/anomaly_detector.py" />
        <option value="$PROJECT_DIR$/main.py" />
        <option value="$PROJECT_DIR$/detector/src/detector.py" />
        <option value="$PROJECT_DIR$/detector/src/window.py" />
        <option value="$PROJECT_DIR$/detector/src/online_trainer.py" />
      </list>
    </option>
  </component>
  <component name="ProjectFrameBounds">
    <option name="x" value="43" />
    <option name="y" value="27" />
    <option name="width" value="1877" />
    <option name="height" value="1053" />
  </component>
  <component name="ProjectView">
    <navigator currentView="ProjectPane" proportions="" version="1">
      <flattenPackages />
      <showMembers />
      <showModules />
      <showLibraryContents />
      <hideEmptyPackages />
      <abbreviatePackageNames />
      <autoscrollToSource />
      <autoscrollFromSource />
      <sortByType />
      <manualOrder />
      <foldersAlwaysOnTop value="true" />
    </navigator>
    <panes>
      <pane id="Scratches" />
      <pane id="ProjectPane">
        <subPane>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" value="mff-ai-anomaly-detector" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="mff-ai-anomaly-detector" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
          </PATH>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" value="mff-ai-anomaly-detector" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="mff-ai-anomaly-detector" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="mock-data" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
          </PATH>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" value="mff-ai-anomaly-detector" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="mff-ai-anomaly-detector" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="detector" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
          </PATH>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" value="mff-ai-anomaly-detector" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="mff-ai-anomaly-detector" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="detector" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="src" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
            </PATH_ELEMENT>
          </PATH>
        </subPane>
      </pane>
      <pane id="Scope" />
    </panes>
  </component>
  <component name="PropertiesComponent">
    <property name="settings.editor.selected.configurable" value="preferences.lookFeel" />
  </component>
  <component name="RunManager" selected="Python.main">
    <configuration default="false" name="main" type="PythonConfigurationType" factoryName="Python" temporary="true">
      <option name="INTERPRETER_OPTIONS" value="" />
      <option name="PARENT_ENVS" value="true" />
      <envs>
        <env name="PYTHONUNBUFFERED" value="1" />
      </envs>
      <option name="SDK_HOME" value="" />
      <option name="WORKING_DIRECTORY" value="$PROJECT_DIR$" />
      <option name="IS_MODULE_SDK" value="true" />
      <option name="ADD_CONTENT_ROOTS" value="true" />
      <option name="ADD_SOURCE_ROOTS" value="true" />
      <module name="mff-ai-anomaly-detector" />
      <option name="SCRIPT_NAME" value="$PROJECT_DIR$/main.py" />
      <option name="PARAMETERS" value="" />
      <option name="SHOW_COMMAND_LINE" value="false" />
      <method />
    </configuration>
    <configuration default="true" type="PythonConfigurationType" factoryName="Python">
      <option name="INTERPRETER_OPTIONS" value="" />
      <option name="PARENT_ENVS" value="true" />
      <envs>
        <env name="PYTHONUNBUFFERED" value="1" />
      </envs>
      <option name="SDK_HOME" value="" />
      <option name="WORKING_DIRECTORY" value="" />
      <option name="IS_MODULE_SDK" value="false" />
      <option name="ADD_CONTENT_ROOTS" value="true" />
      <option name="ADD_SOURCE_ROOTS" value="true" />
      <module name="mff-ai-anomaly-detector" />
      <option name="SCRIPT_NAME" value="" />
      <option name="PARAMETERS" value="" />
      <option name="SHOW_COMMAND_LINE" value="false" />
      <method />
    </configuration>
    <configuration default="true" type="Tox" factoryName="Tox">
      <option name="INTERPRETER_OPTIONS" value="" />
      <option name="PARENT_ENVS" value="true" />
      <envs />
      <option name="SDK_HOME" value="" />
      <option name="WORKING_DIRECTORY" value="" />
      <option name="IS_MODULE_SDK" value="false" />
      <option name="ADD_CONTENT_ROOTS" value="true" />
      <option name="ADD_SOURCE_ROOTS" value="true" />
      <module name="mff-ai-anomaly-detector" />
      <method />
    </configuration>
    <configuration default="true" type="tests" factoryName="Attests">
      <option name="INTERPRETER_OPTIONS" value="" />
      <option name="PARENT_ENVS" value="true" />
      <envs />
      <option name="SDK_HOME" value="" />
      <option name="WORKING_DIRECTORY" value="" />
      <option name="IS_MODULE_SDK" value="false" />
      <option name="ADD_CONTENT_ROOTS" value="true" />
      <option name="ADD_SOURCE_ROOTS" value="true" />
      <module name="mff-ai-anomaly-detector" />
      <option name="SCRIPT_NAME" value="" />
      <option name="CLASS_NAME" value="" />
      <option name="METHOD_NAME" value="" />
      <option name="FOLDER_NAME" value="" />
      <option name="TEST_TYPE" value="TEST_SCRIPT" />
      <option name="PATTERN" value="" />
      <option name="USE_PATTERN" value="false" />
      <method />
    </configuration>
    <configuration default="true" type="tests" factoryName="Doctests">
      <option name="INTERPRETER_OPTIONS" value="" />
      <option name="PARENT_ENVS" value="true" />
      <envs />
      <option name="SDK_HOME" value="" />
      <option name="WORKING_DIRECTORY" value="" />
      <option name="IS_MODULE_SDK" value="false" />
      <option name="ADD_CONTENT_ROOTS" value="true" />
      <option name="ADD_SOURCE_ROOTS" value="true" />
      <module name="mff-ai-anomaly-detector" />
      <option name="SCRIPT_NAME" value="" />
      <option name="CLASS_NAME" value="" />
      <option name="METHOD_NAME" value="" />
      <option name="FOLDER_NAME" value="" />
      <option name="TEST_TYPE" value="TEST_SCRIPT" />
      <option name="PATTERN" value="" />
      <option name="USE_PATTERN" value="false" />
      <method />
    </configuration>
    <configuration default="true" type="tests" factoryName="Nosetests">
      <option name="INTERPRETER_OPTIONS" value="" />
      <option name="PARENT_ENVS" value="true" />
      <envs />
      <option name="SDK_HOME" value="" />
      <option name="WORKING_DIRECTORY" value="" />
      <option name="IS_MODULE_SDK" value="false" />
      <option name="ADD_CONTENT_ROOTS" value="true" />
      <option name="ADD_SOURCE_ROOTS" value="true" />
      <module name="mff-ai-anomaly-detector" />
      <option name="SCRIPT_NAME" value="" />
      <option name="CLASS_NAME" value="" />
      <option name="METHOD_NAME" value="" />
      <option name="FOLDER_NAME" value="" />
      <option name="TEST_TYPE" value="TEST_SCRIPT" />
      <option name="PATTERN" value="" />
      <option name="USE_PATTERN" value="false" />
      <option name="PARAMS" value="" />
      <option name="USE_PARAM" value="false" />
      <method />
    </configuration>
    <configuration default="true" type="tests" factoryName="Unittests">
      <option name="INTERPRETER_OPTIONS" value="" />
      <option name="PARENT_ENVS" value="true" />
      <envs />
      <option name="SDK_HOME" value="" />
      <option name="WORKING_DIRECTORY" value="" />
      <option name="IS_MODULE_SDK" value="false" />
      <option name="ADD_CONTENT_ROOTS" value="true" />
      <option name="ADD_SOURCE_ROOTS" value="true" />
      <module name="mff-ai-anomaly-detector" />
      <option name="SCRIPT_NAME" value="" />
      <option name="CLASS_NAME" value="" />
      <option name="METHOD_NAME" value="" />
      <option name="FOLDER_NAME" value="" />
      <option name="TEST_TYPE" value="TEST_SCRIPT" />
      <option name="PATTERN" value="" />
      <option name="USE_PATTERN" value="false" />
      <option name="PUREUNITTEST" value="true" />
      <option name="PARAMS" value="" />
      <option name="USE_PARAM" value="false" />
      <method />
    </configuration>
    <configuration default="true" type="tests" factoryName="py.test">
      <option name="INTERPRETER_OPTIONS" value="" />
      <option name="PARENT_ENVS" value="true" />
      <envs />
      <option name="SDK_HOME" value="" />
      <option name="WORKING_DIRECTORY" value="" />
      <option name="IS_MODULE_SDK" value="false" />
      <option name="ADD_CONTENT_ROOTS" value="true" />
      <option name="ADD_SOURCE_ROOTS" value="true" />
      <module name="mff-ai-anomaly-detector" />
      <option name="SCRIPT_NAME" value="" />
      <option name="CLASS_NAME" value="" />
      <option name="METHOD_NAME" value="" />
      <option name="FOLDER_NAME" value="" />
      <option name="TEST_TYPE" value="TEST_SCRIPT" />
      <option name="PATTERN" value="" />
      <option name="USE_PATTERN" value="false" />
      <option name="testToRun" value="" />
      <option name="keywords" value="" />
      <option name="params" value="" />
      <option name="USE_PARAM" value="false" />
      <option name="USE_KEYWORD" value="false" />
      <method />
    </configuration>
    <list size="1">
      <item index="0" class="java.lang.String" itemvalue="Python.main" />
    </list>
    <recent_temporary>
      <list size="1">
        <item index="0" class="java.lang.String" itemvalue="Python.main" />
      </list>
    </recent_temporary>
  </component>
  <component name="ShelveChangesManager" show_recycled="false">
    <option name="remove_strategy" value="false" />
  </component>
  <component name="TaskManager">
    <task active="true" id="Default" summary="Default task">
      <changelist id="d1f29b7e-b3f1-48be-b01f-400e854ed7a7" name="Default" comment="" />
      <created>1494320556101</created>
      <option name="number" value="Default" />
      <option name="presentableId" value="Default" />
      <updated>1494320556101</updated>
    </task>
    <servers />
  </component>
  <component name="TodoView">
    <todo-panel id="selected-file">
      <is-autoscroll-to-source value="true" />
    </todo-panel>
    <todo-panel id="all">
      <are-packages-shown value="true" />
      <is-autoscroll-to-source value="true" />
    </todo-panel>
  </component>
  <component name="ToolWindowManager">
    <frame x="43" y="27" width="1877" height="1053" extended-state="6" />
    <editor active="true" />
    <layout>
      <window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" show_stripe_button="true" weight="0.18646777" sideWeight="0.5" order="0" side_tool="false" content_ui="combo" />
      <window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="6" side_tool="false" content_ui="tabs" />
      <window_info id="Event Log" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="true" content_ui="tabs" />
      <window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
      <window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
      <window_info id="Python Console" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
      <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.32944915" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" />
      <window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
      <window_info id="Terminal" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
      <window_info id="Favorites" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="true" content_ui="tabs" />
      <window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.3993644" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
      <window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" />
      <window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="2" side_tool="false" content_ui="combo" />
      <window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
      <window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
      <window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="5" side_tool="false" content_ui="tabs" />
      <window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
    </layout>
  </component>
  <component name="VcsContentAnnotationSettings">
    <option name="myLimit" value="2678400000" />
  </component>
  <component name="XDebuggerManager">
    <breakpoint-manager>
      <breakpoints>
        <line-breakpoint enabled="true" suspend="THREAD" type="python-line">
          <url>file://$PROJECT_DIR$/detector/src/online_trainer.py</url>
          <line>20</line>
          <option name="timeStamp" value="2" />
        </line-breakpoint>
        <line-breakpoint enabled="true" suspend="THREAD" type="python-line">
          <url>file://$PROJECT_DIR$/detector/src/window.py</url>
          <line>21</line>
          <option name="timeStamp" value="4" />
        </line-breakpoint>
        <line-breakpoint enabled="true" suspend="THREAD" type="python-line">
          <url>file://$PROJECT_DIR$/detector/src/online_trainer.py</url>
          <line>24</line>
          <option name="timeStamp" value="5" />
        </line-breakpoint>
      </breakpoints>
      <default-breakpoints>
        <breakpoint type="python-exception">
          <properties notifyOnTerminate="true" exception="BaseException">
            <option name="notifyOnTerminate" value="true" />
          </properties>
        </breakpoint>
      </default-breakpoints>
      <option name="time" value="6" />
    </breakpoint-manager>
    <watches-manager />
  </component>
  <component name="editorHistoryManager">
    <entry file="file://$PROJECT_DIR$/detector/anomaly_detector.py">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="463">
          <caret line="33" column="0" lean-forward="false" selection-start-line="33" selection-start-column="0" selection-end-line="33" selection-end-column="0" />
          <folding>
            <element signature="e#94#131#0" expanded="true" />
          </folding>
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/detector/src/detector.py">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="67">
          <caret line="21" column="0" lean-forward="false" selection-start-line="21" selection-start-column="0" selection-end-line="21" selection-end-column="0" />
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/detector/src/window.py">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="337">
          <caret line="21" column="0" lean-forward="false" selection-start-line="21" selection-start-column="0" selection-end-line="21" selection-end-column="0" />
          <folding>
            <element signature="e#50#84#0" expanded="true" />
          </folding>
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/detector/src/online_trainer.py">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="178">
          <caret line="24" column="45" lean-forward="false" selection-start-line="24" selection-start-column="34" selection-end-line="24" selection-end-column="45" />
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/main.py">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="198">
          <caret line="11" column="33" lean-forward="true" selection-start-line="11" selection-start-column="33" selection-end-line="11" selection-end-column="33" />
          <folding>
            <element signature="e#24#33#0" expanded="true" />
          </folding>
        </state>
      </provider>
    </entry>
  </component>
</project>


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

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

import com.amazonaws.AmazonWebServiceRequest;

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

    /**
     *

     * The globally unique identifier for the identity store.
     *

     */
    private String identityStoreId;
    /**
     *

     * An object that contains the identifier of a group member. Setting the UserID field to the specific
     * identifier for a user indicates that the user is a member of the group.
     *

     */
    private MemberId memberId;
    /**
     *

     * The maximum number of results to be returned per request. This parameter is used in the ListUsers
     * and ListGroups requests to specify how many results to return in one page. The length limit is 50
     * characters.
     *

     */
    private Integer maxResults;
    /**
     *

     * The pagination token used for the ListUsers, ListGroups, and
     * ListGroupMemberships API operations. This value is generated by the identity store service. It is
     * returned in the API response if the total results are more than the size of one page. This token is also returned
     * when it is used in the API request to search for the next page.
     *

     */
    private String nextToken;

    /**
     *

     * The globally unique identifier for the identity store.
     *

     *
     * @param identityStoreId
     *        The globally unique identifier for the identity store.
     */

    public void setIdentityStoreId(String identityStoreId) {
        this.identityStoreId = identityStoreId;
    }

    /**
     *

     * The globally unique identifier for the identity store.
     *

     *
     * @return The globally unique identifier for the identity store.
     */

    public String getIdentityStoreId() {
        return this.identityStoreId;
    }

    /**
     *

     * The globally unique identifier for the identity store.
     *

     *
     * @param identityStoreId
     *        The globally unique identifier for the identity store.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListGroupMembershipsForMemberRequest withIdentityStoreId(String identityStoreId) {
        setIdentityStoreId(identityStoreId);
        return this;
    }

    /**
     *

     * An object that contains the identifier of a group member. Setting the UserID field to the specific
     * identifier for a user indicates that the user is a member of the group.
     *

     *
     * @param memberId
     *        An object that contains the identifier of a group member. Setting the UserID field to the
     *        specific identifier for a user indicates that the user is a member of the group.
     */

    public void setMemberId(MemberId memberId) {
        this.memberId = memberId;
    }

    /**
     *

     * An object that contains the identifier of a group member. Setting the UserID field to the specific
     * identifier for a user indicates that the user is a member of the group.
     *

     *
     * @return An object that contains the identifier of a group member. Setting the UserID field to the
     *         specific identifier for a user indicates that the user is a member of the group.
     */

    public MemberId getMemberId() {
        return this.memberId;
    }

    /**
     *

     * An object that contains the identifier of a group member. Setting the UserID field to the specific
     * identifier for a user indicates that the user is a member of the group.
     *

     *
     * @param memberId
     *        An object that contains the identifier of a group member. Setting the UserID field to the
     *        specific identifier for a user indicates that the user is a member of the group.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListGroupMembershipsForMemberRequest withMemberId(MemberId memberId) {
        setMemberId(memberId);
        return this;
    }

    /**
     *

     * The maximum number of results to be returned per request. This parameter is used in the ListUsers
     * and ListGroups requests to specify how many results to return in one page. The length limit is 50
     * characters.
     *

     *
     * @param maxResults
     *        The maximum number of results to be returned per request. This parameter is used in the
     *        ListUsers and ListGroups requests to specify how many results to return in one
     *        page. The length limit is 50 characters.
     */

    public void setMaxResults(Integer maxResults) {
        this.maxResults = maxResults;
    }

    /**
     *

     * The maximum number of results to be returned per request. This parameter is used in the ListUsers
     * and ListGroups requests to specify how many results to return in one page. The length limit is 50
     * characters.
     *

     *
     * @return The maximum number of results to be returned per request. This parameter is used in the
     *         ListUsers and ListGroups requests to specify how many results to return in one
     *         page. The length limit is 50 characters.
     */

    public Integer getMaxResults() {
        return this.maxResults;
    }

    /**
     *

     * The maximum number of results to be returned per request. This parameter is used in the ListUsers
     * and ListGroups requests to specify how many results to return in one page. The length limit is 50
     * characters.
     *

     *
     * @param maxResults
     *        The maximum number of results to be returned per request. This parameter is used in the
     *        ListUsers and ListGroups requests to specify how many results to return in one
     *        page. The length limit is 50 characters.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListGroupMembershipsForMemberRequest withMaxResults(Integer maxResults) {
        setMaxResults(maxResults);
        return this;
    }

    /**
     *

     * The pagination token used for the ListUsers, ListGroups, and
     * ListGroupMemberships API operations. This value is generated by the identity store service. It is
     * returned in the API response if the total results are more than the size of one page. This token is also returned
     * when it is used in the API request to search for the next page.
     *

     *
     * @param nextToken
     *        The pagination token used for the ListUsers, ListGroups, and
     *        ListGroupMemberships API operations. This value is generated by the identity store service.
     *        It is returned in the API response if the total results are more than the size of one page. This token is
     *        also returned when it is used in the API request to search for the next page.
     */

    public void setNextToken(String nextToken) {
        this.nextToken = nextToken;
    }

    /**
     *

     * The pagination token used for the ListUsers, ListGroups, and
     * ListGroupMemberships API operations. This value is generated by the identity store service. It is
     * returned in the API response if the total results are more than the size of one page. This token is also returned
     * when it is used in the API request to search for the next page.
     *

     *
     * @return The pagination token used for the ListUsers, ListGroups, and
     *         ListGroupMemberships API operations. This value is generated by the identity store service.
     *         It is returned in the API response if the total results are more than the size of one page. This token is
     *         also returned when it is used in the API request to search for the next page.
     */

    public String getNextToken() {
        return this.nextToken;
    }

    /**
     *

     * The pagination token used for the ListUsers, ListGroups, and
     * ListGroupMemberships API operations. This value is generated by the identity store service. It is
     * returned in the API response if the total results are more than the size of one page. This token is also returned
     * when it is used in the API request to search for the next page.
     *

     *
     * @param nextToken
     *        The pagination token used for the ListUsers, ListGroups, and
     *        ListGroupMemberships API operations. This value is generated by the identity store service.
     *        It is returned in the API response if the total results are more than the size of one page. This token is
     *        also returned when it is used in the API request to search for the next page.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ListGroupMembershipsForMemberRequest withNextToken(String nextToken) {
        setNextToken(nextToken);
        return this;
    }

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

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

        if (obj instanceof ListGroupMembershipsForMemberRequest == false)
            return false;
        ListGroupMembershipsForMemberRequest other = (ListGroupMembershipsForMemberRequest) obj;
        if (other.getIdentityStoreId() == null ^ this.getIdentityStoreId() == null)
            return false;
        if (other.getIdentityStoreId() != null && other.getIdentityStoreId().equals(this.getIdentityStoreId()) == false)
            return false;
        if (other.getMemberId() == null ^ this.getMemberId() == null)
            return false;
        if (other.getMemberId() != null && other.getMemberId().equals(this.getMemberId()) == false)
            return false;
        if (other.getMaxResults() == null ^ this.getMaxResults() == null)
            return false;
        if (other.getMaxResults() != null && other.getMaxResults().equals(this.getMaxResults()) == false)
            return false;
        if (other.getNextToken() == null ^ this.getNextToken() == null)
            return false;
        if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
            return false;
        return true;
    }

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

        hashCode = prime * hashCode + ((getIdentityStoreId() == null) ? 0 : getIdentityStoreId().hashCode());
        hashCode = prime * hashCode + ((getMemberId() == null) ? 0 : getMemberId().hashCode());
        hashCode = prime * hashCode + ((getMaxResults() == null) ? 0 : getMaxResults().hashCode());
        hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
        return hashCode;
    }

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

}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Fl. agri belgr. 130. 1865

#### Original name
null

### Remarks
null


text:
using NUnit.Framework;
using QuantConnect.Indicators;

package com.quantconnect.lean.Tests.Indicators
{
    [TestFixture]
    public class DoubleExponentialMovingAverageTests
    {
        [Test]
        public void ComparesAgainstExternalData() {
            dema = new DoubleExponentialMovingAverage( "DEMA", 5);

            RunTestIndicator(dema);
        }

        [Test]
        public void ComparesAgainstExternalDataAfterReset() {
            dema = new DoubleExponentialMovingAverage( "DEMA", 5);

            RunTestIndicator(dema);
            dema.Reset();
            RunTestIndicator(dema);
        }

        [Test]
        public void ResetsProperly() {
            dema = new DoubleExponentialMovingAverage( "DEMA", 5);

            TestHelper.TestIndicatorReset(dema, "spy_dema.txt");
        }

        private static void RunTestIndicator(DoubleExponentialMovingAverage dema) {
            TestHelper.TestIndicator(dema, "spy_dema.txt", "DEMA_5", (ind, expected) -> Assert.AreEqual(expected, (double)ind.Current.Value, 1e-2));
        }
    }
}


text:
package apple.usernotificationsui.enums;

import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.NUInt;

@Generated
public final class UNNotificationContentExtensionResponseOption {
    @Generated @NUInt public static final long DoNotDismiss = 0x0000000000000000L;
    @Generated @NUInt public static final long Dismiss = 0x0000000000000001L;
    @Generated @NUInt public static final long DismissAndForwardAction = 0x0000000000000002L;

    @Generated
    private UNNotificationContentExtensionResponseOption() {
    }
}


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

package org.chromium.chrome.browser.firstrun;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;

import android.app.Activity;
import android.app.Instrumentation;
import android.app.Instrumentation.ActivityMonitor;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.SystemClock;
import android.support.test.InstrumentationRegistry;
import android.view.View;
import android.widget.CheckBox;

import androidx.annotation.IntDef;
import androidx.test.filters.SmallTest;

import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;

import org.chromium.base.Callback;
import org.chromium.base.CommandLine;
import org.chromium.base.metrics.RecordHistogram;
import org.chromium.base.test.util.CallbackHelper;
import org.chromium.base.test.util.Criteria;
import org.chromium.base.test.util.CriteriaHelper;
import org.chromium.base.test.util.DisabledTest;
import org.chromium.base.test.util.Feature;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.customtabs.CustomTabsIntentTestUtils;
import org.chromium.chrome.browser.enterprise.util.EnterpriseInfo;
import org.chromium.chrome.browser.enterprise.util.FakeEnterpriseInfo;
import org.chromium.chrome.browser.flags.ChromeSwitches;
import org.chromium.chrome.browser.init.BrowserParts;
import org.chromium.chrome.browser.init.ChromeBrowserInitializer;
import org.chromium.chrome.browser.policy.PolicyServiceFactory;
import org.chromium.chrome.browser.preferences.ChromePreferenceKeys;
import org.chromium.chrome.browser.preferences.SharedPreferencesManager;
import org.chromium.chrome.browser.privacy.settings.PrivacyPreferencesManagerImpl;
import org.chromium.chrome.browser.signin.services.FREMobileIdentityConsistencyFieldTrial;
import org.chromium.chrome.test.ChromeJUnit4ClassRunner;
import org.chromium.chrome.test.util.ChromeRenderTestRule;
import org.chromium.chrome.test.util.browser.signin.AccountManagerTestRule;
import org.chromium.components.externalauth.ExternalAuthUtils;
import org.chromium.components.policy.PolicyService;
import org.chromium.content_public.browser.test.util.TestThreadUtils;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeoutException;

/**
 * Test for first run activity and {@link TosAndUmaFirstRunFragmentWithEnterpriseSupport}.
 * For the outside signals that used in this test so that the verification is focusing on the
 * workflow and UI transition.
 */
@RunWith(ChromeJUnit4ClassRunner.class)
public class TosAndUmaFirstRunFragmentWithEnterpriseSupportTest {
    @IntDef({FragmentState.LOADING, FragmentState.NO_POLICY, FragmentState.HAS_POLICY,
            FragmentState.WAITING_UNTIL_NEXT_PAGE})
    @Retention(RetentionPolicy.SOURCE)
    @interface FragmentState {
        int LOADING = 0;
        int NO_POLICY = 1;
        int HAS_POLICY = 2;
        int WAITING_UNTIL_NEXT_PAGE = 3;
    }

    @IntDef({SpeedComparedToInflation.NOT_RECORDED, SpeedComparedToInflation.FASTER,
            SpeedComparedToInflation.SLOWER})
    @Retention(RetentionPolicy.SOURCE)
    @interface SpeedComparedToInflation {
        int NOT_RECORDED = 0;
        int FASTER = 1;
        int SLOWER = 2;
    }

    private static final int RENDER_TEST_REVISION = 2;
    private static final String RENDER_TEST_REVISION_DESCRIPTION =
            "Change the button padding and font family.";

    @Rule
    public ChromeRenderTestRule mRenderTestRule =
            ChromeRenderTestRule.Builder.withPublicCorpus()
                    .setRevision(RENDER_TEST_REVISION)
                    .setDescription(RENDER_TEST_REVISION_DESCRIPTION)
                    .setBugComponent(ChromeRenderTestRule.Component.UI_BROWSER_FIRST_RUN)
                    .build();
    @Rule
    public final AccountManagerTestRule mAccountManagerTestRule = new AccountManagerTestRule();

    @Mock
    public FirstRunAppRestrictionInfo mMockAppRestrictionInfo;
    @Mock
    public PolicyService mPolicyService;
    @Mock
    public FirstRunUtils.Natives mFirstRunUtils;
    @Mock
    private PrivacyPreferencesManagerImpl mPrivacyPreferencesManagerMock;
    @Mock
    private ExternalAuthUtils mExternalAuthUtilsMock;

    @Spy
    public ChromeBrowserInitializer mInitializer;
    @Captor
    public ArgumentCaptor<BrowserParts> mBrowserParts;

    public FakeEnterpriseInfo mFakeEnterpriseInfo = new FakeEnterpriseInfo();
    private FirstRunActivity mActivity;
    private final List<PolicyService.Observer> mPolicyServiceObservers = new ArrayList<>();
    private final List<Callback<Boolean>> mAppRestrictionsCallbacks = new ArrayList<>();
    private final List<Callback<Long>> mAppRestrictionsDurationCallbacks = new ArrayList<>();
    private final CallbackHelper mAcceptTosCallbackHelper = new CallbackHelper();
    private CallbackHelper mOnNativeInitializedHelper = new CallbackHelper();
    private CallbackHelper mOnPolicyServiceInitializedHelper = new CallbackHelper();
    private CallbackHelper mOnHideLoadingUICompleteHelper = new CallbackHelper();
    private int mExitCount;

    private View mTosText;
    private View mAcceptButton;
    private View mLowerSpinner;
    private View mCenterSpinner;
    private View mPrivacyDisclaimer;
    private CheckBox mUmaCheckBox;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);

        Assert.assertFalse(
                CommandLine.getInstance().hasSwitch(ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE));

        Mockito.doNothing()
                .when(mInitializer)
                .handlePostNativeStartup(anyBoolean(), any(BrowserParts.class));
        ChromeBrowserInitializer.setForTesting(mInitializer);

        when(mExternalAuthUtilsMock.canUseGooglePlayServices(any())).thenReturn(true);
        ExternalAuthUtils.setInstanceForTesting(mExternalAuthUtilsMock);
        FirstRunAppRestrictionInfo.setInitializedInstanceForTest(mMockAppRestrictionInfo);
        ToSAndUMAFirstRunFragment.setShowUmaCheckBoxForTesting(true);
        PolicyServiceFactory.setPolicyServiceForTest(mPolicyService);
        FirstRunUtils.setDisableDelayOnExitFreForTest(true);
        FirstRunUtilsJni.TEST_HOOKS.setInstanceForTesting(mFirstRunUtils);

        EnterpriseInfo.setInstanceForTest(mFakeEnterpriseInfo);

        FREMobileIdentityConsistencyFieldTrial.setFirstRunTrialGroupForTesting(
                FREMobileIdentityConsistencyFieldTrial.DISABLED_GROUP);

        setAppRestrictionsMockNotInitialized();
        setPolicyServiceMockNotInitialized();

        // TODO(https://crbug.com/1113229): Rework this to not depend on {@link FirstRunActivity}
        // implementation details.
        mExitCount = 0;
        FirstRunActivity.setObserverForTest(new FirstRunActivity.FirstRunActivityObserver() {
            @Override
            public void onCreatePostNativeAndPoliciesPageSequence(FirstRunActivity caller) {}

            @Override
            public void onAcceptTermsOfService(FirstRunActivity caller) {
                mAcceptTosCallbackHelper.notifyCalled();
            }

            @Override
            public void onJumpToPage(FirstRunActivity caller, int position) {}

            @Override
            public void onUpdateCachedEngineName(FirstRunActivity caller) {}

            @Override
            public void onAbortFirstRunExperience(FirstRunActivity caller) {}

            @Override
            public void onExitFirstRun(FirstRunActivity caller) {
                mExitCount++;
            }
        });
        ToSAndUMAFirstRunFragment.setObserverForTesting(new ToSAndUMAFirstRunFragment.Observer() {
            @Override
            public void onNativeInitialized() {
                mOnNativeInitializedHelper.notifyCalled();
            }

            @Override
            public void onPolicyServiceInitialized() {
                mOnPolicyServiceInitializedHelper.notifyCalled();
            }

            @Override
            public void onHideLoadingUIComplete() {
                mOnHideLoadingUICompleteHelper.notifyCalled();
            }
        });
    }

    @After
    public void tearDown() {
        FirstRunAppRestrictionInfo.setInitializedInstanceForTest(null);
        ToSAndUMAFirstRunFragment.setShowUmaCheckBoxForTesting(false);
        TosAndUmaFirstRunFragmentWithEnterpriseSupport.setOverrideOnExitFreRunnableForTest(null);
        PolicyServiceFactory.setPolicyServiceForTest(null);
        FirstRunUtils.setDisableDelayOnExitFreForTest(false);
        FirstRunUtilsJni.TEST_HOOKS.setInstanceForTesting(mFirstRunUtils);
        EnterpriseInfo.setInstanceForTest(null);
        SharedPreferencesManager.getInstance().writeBoolean(
                ChromePreferenceKeys.PRIVACY_METRICS_REPORTING_PERMITTED_BY_USER, false);
        if (mActivity != null) mActivity.finish();
    }

    @Test
    @SmallTest
    public void testNoRestriction() throws Exception {
        launchFirstRunThroughCustomTab();
        assertUIState(FragmentState.LOADING);

        setAppRestrictionsMockInitialized(false);
        assertUIState(FragmentState.NO_POLICY);

        assertHistograms(true, SpeedComparedToInflation.SLOWER,
                SpeedComparedToInflation.NOT_RECORDED, SpeedComparedToInflation.NOT_RECORDED);
        assertPolicyServiceInitDelayAfterNative(true, false);

        // Try to accept ToS.
        setMetricsReportDisabled();
        TestThreadUtils.runOnUiThreadBlocking((Runnable) mAcceptButton::performClick);
        Assert.assertTrue("Crash report should be enabled.",
                PrivacyPreferencesManagerImpl.getInstance()
                        .isUsageAndCrashReportingPermittedByUser());
    }

    @Test
    @SmallTest
    public void testNoRestriction_AcceptBeforeNative() throws Exception {
        launchFirstRunThroughCustomTabPreNative();
        assertUIState(FragmentState.LOADING);

        setAppRestrictionsMockInitialized(false);
        assertUIState(FragmentState.NO_POLICY);

        // Try to accept ToS.
        setMetricsReportDisabled();
        TestThreadUtils.runOnUiThreadBlocking((Runnable) mAcceptButton::performClick);
        assertUIState(FragmentState.WAITING_UNTIL_NEXT_PAGE);
        Assert.assertFalse("Crash report should not be enabled before native initialized.",
                PrivacyPreferencesManagerImpl.getInstance()
                        .isUsageAndCrashReportingPermittedByUser());

        // ToS should be accepted when native is initialized.
        startNativeInitializationAndWait();
        assertHistograms(true, SpeedComparedToInflation.SLOWER,
                SpeedComparedToInflation.NOT_RECORDED, SpeedComparedToInflation.NOT_RECORDED);
        assertPolicyServiceInitDelayAfterNative(false, false);
        String histogram = "MobileFre.TosFragment.SpinnerVisibleDuration";
        Assert.assertEquals(String.format("Histogram <%s> should be recorded.", histogram), 1,
                RecordHistogram.getHistogramTotalCountForTesting(histogram));
        Assert.assertTrue("Crash report should be enabled.",
                PrivacyPreferencesManagerImpl.getInstance()
                        .isUsageAndCrashReportingPermittedByUser());
    }

    @Test
    @SmallTest
    public void testNoRestriction_BeforeInflation() throws Exception {
        setAppRestrictionsMockInitialized(false);
        launchFirstRunThroughCustomTab();
        assertUIState(FragmentState.NO_POLICY);

        assertHistograms(false, SpeedComparedToInflation.FASTER,
                SpeedComparedToInflation.NOT_RECORDED, SpeedComparedToInflation.NOT_RECORDED);
        assertPolicyServiceInitDelayAfterNative(false, false);
    }

    @Test
    @SmallTest
    // TODO(https://crbug.com/1120859): Test the policy check when native initializes before
    // inflation. This will be possible when FragmentScenario is available.
    public void testDialogEnabled() throws Exception {
        setAppRestrictionsMockInitialized(true);
        launchFirstRunThroughCustomTab();
        assertUIState(FragmentState.LOADING);

        setPolicyServiceMockInitializedWithDialogEnabled(true);
        assertUIState(FragmentState.NO_POLICY);

        assertHistograms(true, SpeedComparedToInflation.FASTER,
                SpeedComparedToInflation.NOT_RECORDED, SpeedComparedToInflation.SLOWER);
        assertPolicyServiceInitDelayAfterNative(true, true);

        // Try to accept ToS.
        TestThreadUtils.runOnUiThreadBlocking((Runnable) mAcceptButton::performClick);
        Assert.assertTrue("Crash report should be enabled.",
                PrivacyPreferencesManagerImpl.getInstance()
                        .isUsageAndCrashReportingPermittedByUser());
    }

    @Test
    @SmallTest
    public void testDialogEnabled_BeforeAppRestrictions() throws Exception {
        launchFirstRunThroughCustomTab();
        assertUIState(FragmentState.LOADING);

        // When policy is loaded on fully managed device, we don't need app restriction.
        setPolicyServiceMockInitializedWithDialogEnabled(true);
        assertUIState(FragmentState.NO_POLICY);

        assertHistograms(true, SpeedComparedToInflation.NOT_RECORDED,
                SpeedComparedToInflation.NOT_RECORDED, SpeedComparedToInflation.SLOWER);
        assertPolicyServiceInitDelayAfterNative(true, true);
    }

    @Test
    @SmallTest
    public void testNotOwnedDevice() throws Exception {
        setAppRestrictionsMockInitialized(true);
        launchFirstRunThroughCustomTab();
        assertUIState(FragmentState.LOADING);

        setEnterpriseInfoInitializedWithDeviceOwner(false);
        assertUIState(FragmentState.NO_POLICY);

        assertHistograms(true, SpeedComparedToInflation.FASTER, SpeedComparedToInflation.SLOWER,
                SpeedComparedToInflation.NOT_RECORDED);
        assertPolicyServiceInitDelayAfterNative(false, false);
    }

    @Test
    @SmallTest
    public void testNotOwnedDevice_AcceptBeforePolicy() throws Exception {
        setAppRestrictionsMockInitialized(true);
        launchFirstRunThroughCustomTab();
        assertUIState(FragmentState.LOADING);

        setEnterpriseInfoInitializedWithDeviceOwner(false);
        assertUIState(FragmentState.NO_POLICY);

        // Try to accept Tos.
        setMetricsReportDisabled();
        TestThreadUtils.runOnUiThreadBlocking((Runnable) mAcceptButton::performClick);
        assertUIState(FragmentState.WAITING_UNTIL_NEXT_PAGE);

        setPolicyServiceMockInitializedWithDialogEnabled(false);
        CriteriaHelper.pollUiThread(()
                                            -> PrivacyPreferencesManagerImpl.getInstance()
                                                       .isUsageAndCrashReportingPermittedByUser());
        String histogram = "MobileFre.TosFragment.SpinnerVisibleDuration";
        Assert.assertEquals(String.format("Histogram <%s> should be recorded.", histogram), 1,
                RecordHistogram.getHistogramTotalCountForTesting(histogram));

        assertHistograms(true, SpeedComparedToInflation.FASTER, SpeedComparedToInflation.SLOWER,
                SpeedComparedToInflation.SLOWER);
        assertPolicyServiceInitDelayAfterNative(true, true);
    }

    @Test
    @SmallTest
    public void testNotOwnedDevice_InitBeforeInflation() throws Exception {
        setAppRestrictionsMockInitialized(true);
        setEnterpriseInfoInitializedWithDeviceOwner(false);

        launchFirstRunThroughCustomTab();
        assertUIState(FragmentState.NO_POLICY);

        // Despite EnterpriseInfo being ready to report owned state before inflation, there is no
        // gap on the UI thread between the request and inflation. So the posted response to the
        // EnterpriseInfo request is always slower.
        assertHistograms(true, SpeedComparedToInflation.FASTER, SpeedComparedToInflation.SLOWER,
                SpeedComparedToInflation.NOT_RECORDED);
        assertPolicyServiceInitDelayAfterNative(false, false);
    }

    @Test
    @SmallTest
    public void testOwnedDevice_NoRestriction() throws Exception {
        setEnterpriseInfoInitializedWithDeviceOwner(true);
        launchFirstRunThroughCustomTab();
        assertUIState(FragmentState.LOADING);

        setAppRestrictionsMockInitialized(false);
        assertUIState(FragmentState.NO_POLICY);

        assertHistograms(true, SpeedComparedToInflation.SLOWER, SpeedComparedToInflation.SLOWER,
                SpeedComparedToInflation.NOT_RECORDED);
        assertPolicyServiceInitDelayAfterNative(true, false);
    }

    @Test
    @SmallTest
    public void testOwnedDevice_NoPolicy() throws Exception {
        setEnterpriseInfoInitializedWithDeviceOwner(true);
        launchFirstRunThroughCustomTab();
        assertUIState(FragmentState.LOADING);

        setAppRestrictionsMockInitialized(true);
        assertUIState(FragmentState.LOADING);

        setPolicyServiceMockInitializedWithDialogEnabled(true);
        assertUIState(FragmentState.NO_POLICY);

        assertHistograms(true, SpeedComparedToInflation.SLOWER, SpeedComparedToInflation.SLOWER,
                SpeedComparedToInflation.SLOWER);
        assertPolicyServiceInitDelayAfterNative(true, true);
    }

    @Test
    @SmallTest
    public void testSkip_DeviceOwnedThenDialogPolicy() throws Exception {
        setAppRestrictionsMockInitialized(true);
        launchFirstRunThroughCustomTab();
        assertUIState(FragmentState.LOADING);

        setEnterpriseInfoInitializedWithDeviceOwner(true);
        assertUIState(FragmentState.LOADING);

        setPolicyServiceMockInitializedWithDialogEnabled(false);
        assertUIState(FragmentState.HAS_POLICY);

        assertHistograms(true, SpeedComparedToInflation.FASTER, SpeedComparedToInflation.SLOWER,
                SpeedComparedToInflation.SLOWER);
        assertPolicyServiceInitDelayAfterNative(true, true);
        Assert.assertFalse("Crash report should not be enabled.",
                PrivacyPreferencesManagerImpl.getInstance()
                        .isUsageAndCrashReportingPermittedByUser());
    }

    @Test
    @SmallTest
    public void testSkip_DialogPolicyThenDeviceOwned() throws Exception {
        setAppRestrictionsMockInitialized(true);
        launchFirstRunThroughCustomTab();
        assertUIState(FragmentState.LOADING);

        setPolicyServiceMockInitializedWithDialogEnabled(false);
        assertUIState(FragmentState.LOADING);

        setEnterpriseInfoInitializedWithDeviceOwner(true);
        assertUIState(FragmentState.HAS_POLICY);

        assertHistograms(true, SpeedComparedToInflation.FASTER, SpeedComparedToInflation.SLOWER,
                SpeedComparedToInflation.SLOWER);
        assertPolicyServiceInitDelayAfterNative(true, true);
        Assert.assertFalse("Crash report should not be enabled.",
                PrivacyPreferencesManagerImpl.getInstance()
                        .isUsageAndCrashReportingPermittedByUser());
    }

    @Test
    @SmallTest
    public void testSkip_LateAppRestrictions() throws Exception {
        launchFirstRunThroughCustomTab();
        assertUIState(FragmentState.LOADING);

        setPolicyServiceMockInitializedWithDialogEnabled(false);
        assertUIState(FragmentState.LOADING);

        // Skip should happen without app restrictions being completed.
        setEnterpriseInfoInitializedWithDeviceOwner(true);
        assertUIState(FragmentState.HAS_POLICY);

        assertHistograms(true, SpeedComparedToInflation.NOT_RECORDED,
                SpeedComparedToInflation.SLOWER, SpeedComparedToInflation.SLOWER);
        assertPolicyServiceInitDelayAfterNative(true, true);

        // assertUIState will verify that exit was not called a second time.
        setAppRestrictionsMockInitialized(true);
        assertUIState(FragmentState.HAS_POLICY);

        assertHistograms(true, SpeedComparedToInflation.SLOWER, SpeedComparedToInflation.SLOWER,
                SpeedComparedToInflation.SLOWER);
        Assert.assertFalse("Crash report should not be enabled.",
                PrivacyPreferencesManagerImpl.getInstance()
                        .isUsageAndCrashReportingPermittedByUser());
    }

    @Test
    @SmallTest
    public void testNullOwnedState() throws Exception {
        setAppRestrictionsMockInitialized(true);
        setPolicyServiceMockInitializedWithDialogEnabled(false);
        launchFirstRunThroughCustomTab();
        assertUIState(FragmentState.LOADING);

        // Null means loading checking if the device is owned failed. This should be treated the
        // same as not being owned, and no skipping should occur.
        mFakeEnterpriseInfo.initialize(null);
        assertUIState(FragmentState.NO_POLICY);
    }

    @Test
    @SmallTest
    @DisabledTest(message = "Flaky test - see: https://crbug.com/1171147")
    public void testAcceptTosWithoutCrashUpload() throws Exception {
        setAppRestrictionsMockInitialized(true);
        setEnterpriseInfoInitializedWithDeviceOwner(true);
        setPolicyServiceMockInitializedWithDialogEnabled(true);

        launchFirstRunThroughCustomTab();
        assertUIState(FragmentState.NO_POLICY);

        // Accept ToS without check on UMA.
        TestThreadUtils.runOnUiThreadBlocking(() -> {
            mUmaCheckBox.setChecked(false);
            mAcceptButton.performClick();
        });

        mAcceptTosCallbackHelper.waitForCallback("Accept Tos is never called.", 0);
        Assert.assertFalse("Crash report should not be enabled.",
                PrivacyPreferencesManagerImpl.getInstance()
                        .isUsageAndCrashReportingPermittedByUser());
    }

    @Test
    @SmallTest
    @Feature({"RenderTest", "FirstRun"})
    public void testRender() throws Exception {
        launchFirstRunThroughCustomTab();
        assertUIState(FragmentState.LOADING);

        // Clear the focus on view to avoid unexpected highlight on background.
        // @TODO(https://crbug.com/c/1289293): Background sometimes are highlighted in render tests.
        View tosAndUmaFragment =
                mActivity.getSupportFragmentManager().getFragments().get(0).getView();
        Assert.assertNotNull(tosAndUmaFragment);
        TestThreadUtils.runOnUiThreadBlocking(tosAndUmaFragment::clearFocus);

        renderWithPortraitAndLandscape(tosAndUmaFragment, "fre_tosanduma_loading");

        setAppRestrictionsMockInitialized(false);
        assertUIState(FragmentState.NO_POLICY);
        renderWithPortraitAndLandscape(tosAndUmaFragment, "fre_tosanduma_nopolicy");
    }

    /** Tests TosAndUmaFirstRunFragment with uma dialog */
    @Test
    @SmallTest
    @Feature({"RenderTest", "FirstRun"})
    public void testRenderWithUmaDialog() throws Exception {
        FREMobileIdentityConsistencyFieldTrial.setFirstRunTrialGroupForTesting(
                FREMobileIdentityConsistencyFieldTrial.OLD_FRE_WITH_UMA_DIALOG_GROUP);
        launchFirstRunThroughCustomTab();
        setAppRestrictionsMockInitialized(false);
        // Clear the focus on view to avoid unexpected highlight on background.
        View tosAndUmaFragment =
                mActivity.getSupportFragmentManager().getFragments().get(0).getView();
        Assert.assertNotNull(tosAndUmaFragment);
        TestThreadUtils.runOnUiThreadBlocking(tosAndUmaFragment::clearFocus);

        Assert.assertEquals(
                "Uma checkbox should not be visible.", View.GONE, mUmaCheckBox.getVisibility());
        renderWithPortraitAndLandscape(tosAndUmaFragment, "fre_tosandumadialog_nopolicy");
    }

    /** Tests TosAndUmaFirstRunFragment with uma dialog */
    @Test
    @SmallTest
    @Feature({"RenderTest", "FirstRun"})
    public void testRenderWithUmaDialogForChildAccount() throws Exception {
        FREMobileIdentityConsistencyFieldTrial.setFirstRunTrialGroupForTesting(
                FREMobileIdentityConsistencyFieldTrial.OLD_FRE_WITH_UMA_DIALOG_GROUP);
        mAccountManagerTestRule.addAccount(
                AccountManagerTestRule.generateChildEmail("account@gmail.com"));
        launchFirstRunThroughCustomTab();
        setAppRestrictionsMockInitialized(false);
        // Clear the focus on view to avoid unexpected highlight on background.
        View tosAndUmaFragment =
                mActivity.getSupportFragmentManager().getFragments().get(0).getView();
        Assert.assertNotNull(tosAndUmaFragment);
        TestThreadUtils.runOnUiThreadBlocking(tosAndUmaFragment::clearFocus);

        Assert.assertEquals(
                "Uma checkbox should not be visible.", View.GONE, mUmaCheckBox.getVisibility());
        renderWithPortraitAndLandscape(
                tosAndUmaFragment, "fre_tosandumadialog_childaccount_nopolicy");
    }

    @Test
    @SmallTest
    @Feature({"RenderTest", "FirstRun"})
    public void testRenderWithPolicy() throws Exception {
        final CallbackHelper onExitFreCallback = new CallbackHelper();
        TosAndUmaFirstRunFragmentWithEnterpriseSupport.setOverrideOnExitFreRunnableForTest(
                onExitFreCallback::notifyCalled);

        setAppRestrictionsMockInitialized(true);
        setEnterpriseInfoInitializedWithDeviceOwner(true);
        launchFirstRunThroughCustomTab();
        assertUIState(FragmentState.LOADING);

        // Clear the focus on view to avoid unexpected highlight on background.
        View tosAndUmaFragment =
                mActivity.getSupportFragmentManager().getFragments().get(0).getView();
        Assert.assertNotNull(tosAndUmaFragment);
        TestThreadUtils.runOnUiThreadBlocking(tosAndUmaFragment::clearFocus);

        setPolicyServiceMockInitializedWithDialogEnabled(false);
        onExitFreCallback.waitForFirst("OnExitFreCallback is never invoked.");
        Assert.assertEquals("Privacy disclaimer is not visible", mPrivacyDisclaimer.getVisibility(),
                View.VISIBLE);

        renderWithPortraitAndLandscape(tosAndUmaFragment, "fre_tosanduma_withpolicy");
    }

    @Test
    @SmallTest
    @Feature({"RenderTest", "FirstRun"})
    public void testRenderWhenMetricsReportingAreDisabled() throws Exception {
        launchFirstRunThroughCustomTab();
        assertUIState(FragmentState.LOADING);

        // Clear the focus on view to avoid unexpected highlight on background.
        View tosAndUmaFragment =
                mActivity.getSupportFragmentManager().getFragments().get(0).getView();
        Assert.assertNotNull(tosAndUmaFragment);
        TestThreadUtils.runOnUiThreadBlocking(tosAndUmaFragment::clearFocus);

        // Initialize policies.
        Mockito.when(mPrivacyPreferencesManagerMock.isUsageAndCrashReportingPermittedByPolicy())
                .thenReturn(false);
        PrivacyPreferencesManagerImpl.setInstanceForTesting(mPrivacyPreferencesManagerMock);
        setPolicyServiceMockInitializedWithDialogEnabled(true);
        setAppRestrictionsMockInitialized(true);
        mOnPolicyServiceInitializedHelper.waitForCallback("policy service never initialized.", 0);
        mOnHideLoadingUICompleteHelper.waitForCallback("loading ui never hidden.", 0);

        renderWithPortraitAndLandscape(tosAndUmaFragment, "fre_metricsreportingdisabled");
    }

    @Test
    @SmallTest
    @Feature({"RenderTest", "FirstRun"})
    public void testRenderWhenMetricsReportingAreDisabledWithUmaDialog() throws Exception {
        FREMobileIdentityConsistencyFieldTrial.setFirstRunTrialGroupForTesting(
                FREMobileIdentityConsistencyFieldTrial.OLD_FRE_WITH_UMA_DIALOG_GROUP);

        launchFirstRunThroughCustomTab();
        assertUIState(FragmentState.LOADING);

        // Clear the focus on view to avoid unexpected highlight on background.
        View tosAndUmaFragment =
                mActivity.getSupportFragmentManager().getFragments().get(0).getView();
        Assert.assertNotNull(tosAndUmaFragment);
        TestThreadUtils.runOnUiThreadBlocking(tosAndUmaFragment::clearFocus);

        // Initialize policies.
        Mockito.when(mPrivacyPreferencesManagerMock.isUsageAndCrashReportingPermittedByPolicy())
                .thenReturn(false);
        PrivacyPreferencesManagerImpl.setInstanceForTesting(mPrivacyPreferencesManagerMock);
        setPolicyServiceMockInitializedWithDialogEnabled(true);
        setAppRestrictionsMockInitialized(true);
        mOnPolicyServiceInitializedHelper.waitForCallback("policy service never initialized.", 0);
        mOnHideLoadingUICompleteHelper.waitForCallback("loading ui never hidden.", 0);

        renderWithPortraitAndLandscape(tosAndUmaFragment, "fre_metricsreportingdisabled_umadialog");
    }

    @Test
    @SmallTest
    @Feature({"RenderTest", "FirstRun"})
    public void testRenderWhenMetricsReportingAreDisabledWithUmaDialogForChildAccount()
            throws Exception {
        FREMobileIdentityConsistencyFieldTrial.setFirstRunTrialGroupForTesting(
                FREMobileIdentityConsistencyFieldTrial.OLD_FRE_WITH_UMA_DIALOG_GROUP);
        mAccountManagerTestRule.addAccount(
                AccountManagerTestRule.generateChildEmail("account@gmail.com"));

        launchFirstRunThroughCustomTab();
        assertUIState(FragmentState.LOADING);

        // Clear the focus on view to avoid unexpected highlight on background.
        View tosAndUmaFragment =
                mActivity.getSupportFragmentManager().getFragments().get(0).getView();
        Assert.assertNotNull(tosAndUmaFragment);
        TestThreadUtils.runOnUiThreadBlocking(tosAndUmaFragment::clearFocus);

        // Initialize policies.
        Mockito.when(mPrivacyPreferencesManagerMock.isUsageAndCrashReportingPermittedByPolicy())
                .thenReturn(false);
        PrivacyPreferencesManagerImpl.setInstanceForTesting(mPrivacyPreferencesManagerMock);
        setPolicyServiceMockInitializedWithDialogEnabled(true);
        setAppRestrictionsMockInitialized(true);
        mOnPolicyServiceInitializedHelper.waitForCallback("policy service never initialized.", 0);
        mOnHideLoadingUICompleteHelper.waitForCallback("loading ui never hidden.", 0);

        renderWithPortraitAndLandscape(
                tosAndUmaFragment, "fre_metricsreportingdisabled_umadialog_childaccount");
    }

    private void launchFirstRunThroughCustomTab() throws TimeoutException {
        launchFirstRunThroughCustomTabPreNative();
        startNativeInitializationAndWait();
    }

    /**
     * Launch chrome through custom tab and trigger first run.
     */
    private void launchFirstRunThroughCustomTabPreNative() {
        final Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
        final Context context = instrumentation.getTargetContext();

        // Create an Intent that causes Chrome to run.
        Intent intent =
                CustomTabsIntentTestUtils.createMinimalCustomTabIntent(context, "https://test.com");

        // Start the FRE.
        final ActivityMonitor freMonitor =
                new ActivityMonitor(FirstRunActivity.class.getName(), null, false);
        instrumentation.addMonitor(freMonitor);
        // As we want to test on FirstRunActivity, which starts its lifecycle *before*
        // CustomTabActivity fully initialized, we'll launch the activity without the help of
        // CustomTabActivityTestRule (which waits until any tab is created).
        context.startActivity(intent);

        // Wait for the FRE to be ready to use.
        Activity activity =
                freMonitor.waitForActivityWithTimeout(CriteriaHelper.DEFAULT_MAX_TIME_TO_POLL);
        instrumentation.removeMonitor(freMonitor);

        mActivity = (FirstRunActivity) activity;
        CriteriaHelper.pollUiThread(
                () -> mActivity.getSupportFragmentManager().getFragments().size() > 0);

        mTosText = mActivity.findViewById(R.id.tos_and_privacy);
        mUmaCheckBox = mActivity.findViewById(R.id.send_report_checkbox);
        mAcceptButton = mActivity.findViewById(R.id.terms_accept);
        mLowerSpinner = mActivity.findViewById(R.id.progress_spinner);
        mCenterSpinner = mActivity.findViewById(R.id.progress_spinner_large);
        mPrivacyDisclaimer = mActivity.findViewById(R.id.privacy_disclaimer);
    }

    private void assertUIState(@FragmentState int fragmentState) {
        int tosVisibility = (fragmentState == FragmentState.NO_POLICY) ? View.VISIBLE : View.GONE;
        int spinnerVisibility = (fragmentState == FragmentState.LOADING) ? View.VISIBLE : View.GONE;
        int privacyVisibility =
                (fragmentState == FragmentState.HAS_POLICY) ? View.VISIBLE : View.GONE;
        int lowerSpinnerVisibility =
                (fragmentState == FragmentState.WAITING_UNTIL_NEXT_PAGE) ? View.VISIBLE : View.GONE;

        CriteriaHelper.pollUiThread(
                ()
                        -> Criteria.checkThat(
                                "Visibility of Loading spinner never reached test setting.",
                                mCenterSpinner.getVisibility(), Matchers.is(spinnerVisibility)));

        Assert.assertEquals("Visibility of ToS text is different than the test setting.",
                tosVisibility, mTosText.getVisibility());
        Assert.assertEquals("Visibility of Uma Check Box is different than the test setting.",
                tosVisibility, mUmaCheckBox.getVisibility());
        Assert.assertEquals("Visibility of accept button is different than the test setting.",
                tosVisibility, mAcceptButton.getVisibility());
        Assert.assertEquals("Visibility of lower spinner is different than the test setting.",
                lowerSpinnerVisibility, mLowerSpinner.getVisibility());
        Assert.assertEquals("Visibility of privacy disclaimer is different than the test setting.",
                privacyVisibility, mPrivacyDisclaimer.getVisibility());

        Assert.assertTrue("Uma Check Box should be checked.", mUmaCheckBox.isChecked());

        int expectedExitCount = fragmentState == FragmentState.HAS_POLICY ? 1 : 0;
        CriteriaHelper.pollUiThread(
                () -> Criteria.checkThat(mExitCount, Matchers.is(expectedExitCount)));
    }

    private void startNativeInitializationAndWait() throws TimeoutException {
        Mockito.verify(mInitializer, Mockito.timeout(3000L))
                .handlePostNativeStartup(eq(true), mBrowserParts.capture());
        Mockito.doCallRealMethod()
                .when(mInitializer)
                .handlePostNativeStartup(anyBoolean(), any(BrowserParts.class));

        TestThreadUtils.runOnUiThreadBlocking(
                ()
                        -> mInitializer.handlePostNativeStartup(
                                /*isAsync*/ false, mBrowserParts.getValue()));
        mOnNativeInitializedHelper.waitForCallback("native never initialized.", 0);
    }

    /**
     * Asserts the speed histograms related to FirstRunAppRestrictions and TosAndUmaFirstRunFragment
     * are recorded correctly. Noting that with the current test setup, it is possible that the
     * FragmentInflationSpeedCheck might be flaky.
     *
     * TODO(https://crbug.com/1120859): Move to a different setup once this test file moves to
     * robolectric.
     *
     * @param didLoading If Welcome screen ever attempts to wait and load for policies.
     * @param appRestrictionMetricsState {@link SpeedComparedToInflation} for checks regarding
     *         {@link FirstRunAppRestrictionInfo#getHasAppRestriction(Callback)}
     * @param deviceOwnershipMetricsState {@link SpeedComparedToInflation} for checks regarding
     *         {@link EnterpriseInfo#getDeviceEnterpriseInfo(Callback)}}
     * @param policyCheckMetricsState {@link SpeedComparedToInflation} for checks regarding {@link
     *         PolicyService#isInitializationComplete()}
     */
    private void assertHistograms(boolean didLoading,
            @SpeedComparedToInflation int appRestrictionMetricsState,
            @SpeedComparedToInflation int deviceOwnershipMetricsState,
            @SpeedComparedToInflation int policyCheckMetricsState) {
        assertSingleHistogram("MobileFre.CctTos.LoadingDuration", didLoading);

        // WARNING: These two checks might be flaky with current test setup.
        assertSingleHistogram("MobileFre.FragmentInflationSpeed.FasterThanAppRestriction",
                appRestrictionMetricsState == SpeedComparedToInflation.SLOWER);
        assertSingleHistogram("MobileFre.FragmentInflationSpeed.SlowerThanAppRestriction",
                appRestrictionMetricsState == SpeedComparedToInflation.FASTER);

        assertSingleHistogram("MobileFre.CctTos.IsDeviceOwnedCheckSpeed2.FasterThanInflation",
                deviceOwnershipMetricsState == SpeedComparedToInflation.FASTER);
        assertSingleHistogram("MobileFre.CctTos.IsDeviceOwnedCheckSpeed2.SlowerThanInflation",
                deviceOwnershipMetricsState == SpeedComparedToInflation.SLOWER);

        assertSingleHistogram("MobileFre.CctTos.EnterprisePolicyCheckSpeed2.FasterThanInflation",
                policyCheckMetricsState == SpeedComparedToInflation.FASTER);
        assertSingleHistogram("MobileFre.CctTos.EnterprisePolicyCheckSpeed2.SlowerThanInflation",
                policyCheckMetricsState == SpeedComparedToInflation.SLOWER);
    }

    /**
     * Assert MobileFre.PolicyServiceInitDelayAfterNative.* is recorded correctly. The histogram
     * should be recorded when {@link PolicyLoadListener} is ready after native initialization.
     * @param recorded Whether the histogram should be recorded.
     * @param isPolicyFound Used to determine which suffix would have been used.
     */
    private void assertPolicyServiceInitDelayAfterNative(boolean recorded, boolean isPolicyFound) {
        assertSingleHistogram("MobileFre.PolicyServiceInitDelayAfterNative.WithPolicy2",
                recorded && isPolicyFound);
        assertSingleHistogram("MobileFre.PolicyServiceInitDelayAfterNative.WithoutPolicy2",
                recorded && !isPolicyFound);
    }

    private void assertSingleHistogram(String histogram, boolean recorded) {
        Assert.assertEquals("Histogram <" + histogram + "> is not recorded correctly.",
                recorded ? 1 : 0, RecordHistogram.getHistogramTotalCountForTesting(histogram));
    }

    private void setAppRestrictionsMockNotInitialized() {
        Mockito.doAnswer(invocation -> {
                   Callback<Boolean> callback = invocation.getArgument(0);
                   mAppRestrictionsCallbacks.add(callback);
                   return null;
               })
                .when(mMockAppRestrictionInfo)
                .getHasAppRestriction(any());

        Mockito.doAnswer(invocation -> {
                   Callback<Long> callback = invocation.getArgument(0);
                   mAppRestrictionsDurationCallbacks.add(callback);
                   return null;
               })
                .when(mMockAppRestrictionInfo)
                .getCompletionElapsedRealtimeMs(any());
    }

    private void setAppRestrictionsMockInitialized(boolean hasAppRestrictions) {
        Mockito.doAnswer(invocation -> {
                   Callback<Boolean> callback = invocation.getArgument(0);
                   callback.onResult(hasAppRestrictions);
                   return null;
               })
                .when(mMockAppRestrictionInfo)
                .getHasAppRestriction(any());

        long resolvingTime = SystemClock.elapsedRealtime();
        Mockito.doAnswer(invocation -> {
                   Callback<Long> callback = invocation.getArgument(0);
                   callback.onResult(resolvingTime);
                   return null;
               })
                .when(mMockAppRestrictionInfo)
                .getCompletionElapsedRealtimeMs(any());

        TestThreadUtils.runOnUiThreadBlocking(() -> {
            for (Callback<Boolean> callback : mAppRestrictionsCallbacks) {
                callback.onResult(hasAppRestrictions);
            }

            for (Callback<Long> callback : mAppRestrictionsDurationCallbacks) {
                callback.onResult(resolvingTime);
            }
        });
    }

    private void setPolicyServiceMockNotInitialized() {
        Mockito.when(mPolicyService.isInitializationComplete()).thenReturn(false);
        Mockito.doAnswer(invocation -> {
                   PolicyService.Observer observer = invocation.getArgument(0);
                   mPolicyServiceObservers.add(observer);
                   return null;
               })
                .when(mPolicyService)
                .addObserver(any());
    }

    private void setPolicyServiceMockInitializedWithDialogEnabled(boolean cctTosDialogEnabled) {
        setMockCctTosDialogEnabled(cctTosDialogEnabled);

        Mockito.when(mPolicyService.isInitializationComplete()).thenReturn(true);
        TestThreadUtils.runOnUiThreadBlocking(() -> {
            for (PolicyService.Observer observer : mPolicyServiceObservers) {
                observer.onPolicyServiceInitialized();
            }
        });
        mPolicyServiceObservers.clear();
    }

    private void setMockCctTosDialogEnabled(boolean cctTosDialogEnabled) {
        Mockito.when(mFirstRunUtils.getCctTosDialogEnabled()).thenReturn(cctTosDialogEnabled);
    }

    private void setEnterpriseInfoInitializedWithDeviceOwner(boolean hasDeviceOwner) {
        mFakeEnterpriseInfo.initialize(new EnterpriseInfo.OwnedState(hasDeviceOwner, false));
    }

    private void setMetricsReportDisabled() {
        SharedPreferencesManager.getInstance().writeBoolean(
                ChromePreferenceKeys.PRIVACY_METRICS_REPORTING_PERMITTED_BY_USER, false);
        Assert.assertFalse("Crash report should be disabled by shared preference.",
                PrivacyPreferencesManagerImpl.getInstance()
                        .isUsageAndCrashReportingPermittedByUser());
    }

    private void renderWithPortraitAndLandscape(View tosAndUmaFragmentView, String testPrefix)
            throws Exception {
        mRenderTestRule.render(tosAndUmaFragmentView, testPrefix + "_portrait");

        setDeviceOrientation(tosAndUmaFragmentView, Configuration.ORIENTATION_LANDSCAPE);
        mRenderTestRule.render(tosAndUmaFragmentView, testPrefix + "_landscape");

        setDeviceOrientation(tosAndUmaFragmentView, Configuration.ORIENTATION_PORTRAIT);
        mRenderTestRule.render(tosAndUmaFragmentView, testPrefix + "_portrait");
    }

    private void setDeviceOrientation(View tosAndUmaFragmentView, int orientation) {
        // TODO(https://crbug.com/1133789): This function is copied mostly copied from
        // TabUiTestHelper#rotateDeviceToOrientation. Merge / move these two test functions if
        // applicable.
        if (mActivity.getResources().getConfiguration().orientation == orientation) return;
        assertTrue(orientation == Configuration.ORIENTATION_LANDSCAPE
                || orientation == Configuration.ORIENTATION_PORTRAIT);

        boolean isLandscape = orientation == Configuration.ORIENTATION_LANDSCAPE;
        mActivity.setRequestedOrientation(isLandscape ? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
                                                      : ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        CriteriaHelper.pollUiThread(() -> {
            Criteria.checkThat(
                    mActivity.getResources().getConfiguration().orientation, is(orientation));
            Criteria.checkThat(tosAndUmaFragmentView.getWidth() > tosAndUmaFragmentView.getHeight(),
                    is(isLandscape));
        });
    }
}


text:
Confirm Delete View

Warning: This action is not reversible.

Deleting {{viewsDeleteViewDialogCtl.currentViewName}}
      from design document {{viewsDeleteViewDialogCtl.currentDdocName}}
      will force the index for this design document to be regenerated when next requested.
      Are you sure you want to delete this view?

    Cancel
    <button
       type="submit"
       ng-click="viewsDeleteViewDialogCtl.doDelete()">Delete View</button>


text:
`whtranscripts` helps you fetch and parse transcripts from the [American Presidency Project](http://www.presidency.ucsb.edu/)'s press-briefing and presidential-news-conference transcripts.

## Installation

`whtranscripts` is a Python library. To install it, run:

```sh
pip install whtranscripts
```

## Downloading Transcripts

To download the HTML of all news-conference transcripts:

```sh
mkdir ~/Downloads/conference-transcripts
python -m "whtranscripts.download" -t conference --dest ~/Downloads/conference-transcripts/
```

For press-briefings:

```sh
mkdir ~/Downloads/another-dir
python -m "whtranscripts.download" -t briefing --dest ~/Downloads/another-dir/
```

You can also limit downloads to a particular year-range, e.g., from 2001 *through* 2008:

```sh
python -m "whtranscripts.download" -t conference --dest ~/Downloads/conference-transcripts/ --start 2001 --end 2008
```

## Parsing Transcripts

You can load single transcripts from a file, URL, or the HTML itself. From a file:

```python
import whtranscripts
transcript = whtranscripts.Conference.from_path("test/pages/conferences/99975.html")
```

Alternatively, for a briefing:

```python
import whtranscripts
transcript = whtranscripts.Briefing.from_path("test/pages/briefings/47646.html")
```

From a URL:

```python
import whtranscripts
url = "http://www.presidency.ucsb.edu/ws/index.php?pid=99975"
transcript = whtranscripts.Conference.from_url(url)
```

Directly from American Presidency Project HTML:

```python
import whtranscripts
import requests
url = "http://www.presidency.ucsb.edu/ws/index.php?pid=99975"
html = requests.get(url).content
transcript = whtranscripts.Conference(html)
```

You can also load multiple at once, from a directory:

```python
import whtranscripts
transcripts = whtranscripts.Conference.from_dir("test/pages/conferences")
```

*Note: The files you want to parse from directory must end in `.html`*

## Analyzing Transcripts

Each `Conference` and `Briefing` has the following attributes:

- `doc_id`: The document ID assigned to it by the American Presidency Project.
- `date`: The date the conference or briefing took place.
- `president`: The U.S. president at the time of the briefing.
- `passages`: A list of `Passage` objects.

Each `Passage` object has the following attributes:

- `speaker`: The person who spoke the passage.
- `is_question`: `False` if the speaker was an government official/guest, `True` if they were someone from the audience.
- `text`: What was said.
- `transcript`: A pointer back to the parent transcript in which this passage can be found.
- `tokens`: All of the tokens in the passage (using NLTK's word_tokenize module). Requires NLTK to be installed.

Each `Passage` object also has the following methods:

- `get_word_count`: Returns the total word count of the passage, found by splitting on spaces.
- `count_occurrences`: Returns the total number of occurences of a string. Note: This method catches strings inside of words. So *go* will match twice on "I wish I could go somewhere a long time ago." (*go* and *ago*.) By default, this is *not* case sensitive. Pass `case_sensitive=True` to make the search case sensitive.
- `count_token_occurrences`: Similar to `count_occurrences`, but uses "tokens" generated by [NLTK](http://www.nltk.org/). Will raise an error if NLTK is not installed.

## Exporting Transcripts

You can export transcripts as CSVs, using the `TranscriptSet` class:

```python
import whtranscripts
urls = whtranscripts.download.get_urls("conference", 2013, 2013)
transcripts = map(whtranscripts.conference.Conference.from_url, urls)
t_set = whtranscripts.TranscriptSet(transcripts)
t_set.to_csv(sys.stdout)
```