text:
package alma.acs.logging;

import java.io.PrintStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeSet;
import java.util.logging.Level;

import alma.acs.logging.level.AcsLogLevelDefinition;

/**
 * Defines ACS specific logging levels.
 * Also provides non-ACS level, which includes
 * set of standard logging and possibly other vendor levels,
 * to ACS level mapping. Maps Java-specific levels to ACS specific levels.

 * Although an OFF level is not mentioned in the Acs documentation, it is included
 * for the purpose of dealing with bad levels as well as of blocking logging.
 *
 * @author		Matej Sekoranja (matej.sekoranja@cosylab.com)
 * @version	@@VERSION@@
 */
public class AcsLogLevel extends Level implements Comparable<AcsLogLevel>
{
	/**
	 * The resource bundle name to be used in localizing ACS level name.
	 */
	private static final String ACS_BUNDLE_NAME = AcsLogLevel.class.getPackage().getName();

	/**
	 * List of all ACS levels, sorted automatically with lowest log level first.
	 */
	private static final TreeSet<AcsLogLevel> known = new TreeSet<AcsLogLevel>();

	/**
	 * Fast lookup table mapping.
	 */
	private static final Map<Level, AcsLogLevel> lookup = new HashMap<Level, AcsLogLevel>();

	/******************** Java API ACS Levels ********************/

// Currently we try to do without a level definition for ALL, see module loggingidl
//	/**
//	 * Messages indicating function-calling sequence.
//	 */
//	public static final AcsLogLevel ALL = new AcsLogLevel("ALL", Level.ALL.intValue(), ACS_LEVEL_ALL);

	/**
	 * Messages indicating function-calling sequence.
	 */
	public static final AcsLogLevel TRACE = new AcsLogLevel("TRACE", Level.FINEST.intValue(), AcsLogLevelDefinition.TRACE);

	/**
	 * A lower level than DEBUG, just to allow finer tuning. Generally same meaning. See COMP-3749.
	 */
	public static final AcsLogLevel DELOUSE = new AcsLogLevel("DELOUSE", Level.FINER.intValue(), AcsLogLevelDefinition.DELOUSE);

	/**
	 * Messages that contain information normally of use only when
	 * debugging a program.
	 * Java levels FINE and CONFIG map to this DEBUG level.
	 */
	public static final AcsLogLevel DEBUG = new AcsLogLevel("DEBUG", Level.CONFIG.intValue(), AcsLogLevelDefinition.DEBUG);

	/**
	 * Informational messages.
	 */
	public static final AcsLogLevel INFO = new AcsLogLevel("INFO", Level.INFO.intValue(), AcsLogLevelDefinition.INFO);

	/**
	 * Conditions that are not error conditions, but that may require
	 * special handling.
	 * TODO: use something like 850 instead of 801 to allow other levels between INFO and NOTICE
	 */
	public static final AcsLogLevel NOTICE = new AcsLogLevel("NOTICE", 801, AcsLogLevelDefinition.NOTICE);

	/**
	 * Warning messages.
	 */
	public static final AcsLogLevel WARNING = new AcsLogLevel("WARNING", Level.WARNING.intValue(), AcsLogLevelDefinition.WARNING);

	/**
	 * Error messages.
	 * TODO: use something like 930 instead of 901 to allow other levels between ERROR and WARNING
	 */
	public static final AcsLogLevel ERROR = new AcsLogLevel("ERROR", 901, AcsLogLevelDefinition.ERROR);

	/**
	 * Critical conditions, such as hard device errors.
	 * TODO: use something like 960 instead of 902 to allow other levels between CRITICAL and ERROR
	 */
	public static final AcsLogLevel CRITICAL = new AcsLogLevel("CRITICAL", 902, AcsLogLevelDefinition.CRITICAL);

	/**
	 * A condition that should be corrected immediately, such as a
	 * corrupted system database.
	 * TODO: use something like 980 instead of 903 to allow other levels between ERROR and ALERT
	 */
	public static final AcsLogLevel ALERT = new AcsLogLevel("ALERT", 903, AcsLogLevelDefinition.ALERT);

	/**
	 * A panic condition. This is normally broadcast to all users.
	 */
	public static final AcsLogLevel EMERGENCY = new AcsLogLevel("EMERGENCY", Level.SEVERE.intValue(), AcsLogLevelDefinition.EMERGENCY);

	/**
	 * Level not to be used for actual logging, but to set log levels for filtering.
	 * Overwrites/hides {@link Level.OFF}.
	 */
	public static final AcsLogLevel OFF = new AcsLogLevel(Level.OFF.getName(), Level.OFF.intValue(), AcsLogLevelDefinition.OFF);

	/**
	 * The ACS error system defined level (small integer) which this JDK-style level maps to
	 */
	private final AcsLogLevelDefinition acsCoreLevel;

	/**
	 * XML Entry name.
	 */
	private String entryName = null;

	/**
	 * Create a named Level with a given integer value.
	 *
	 * @param name  the name of the Level, for example "INFO".
	 * @param value an integer value for the level.
	 */
	public AcsLogLevel(String name, int value, AcsLogLevelDefinition acsCoreLevel)
	{
		super(name, value, ACS_BUNDLE_NAME);

		// create entry name, so that is computed only once
		entryName = name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase();

		this.acsCoreLevel = acsCoreLevel;

		// add to tree of known lists
		synchronized (known)
		{
			known.add(this);
		}

		// save for fast lookups
		synchronized (lookup) {
			lookup.put(this, this);
		}
	}

	/**
	 * Converts an ACS core log level (small integer as defined in ACS IDL)
	 * to the largest matching AcsLogLevel.
	 */
	public static AcsLogLevel fromAcsCoreLevel(AcsLogLevelDefinition acsCoreLevel) {
		AcsLogLevel ret = null;
		for (AcsLogLevel acsLogLevel : known) {
			ret = acsLogLevel;
			if (!(ret.getAcsLevel().compareTo(acsCoreLevel) < 0)) {
				break;
			}
		}
		return ret;
	}

	/**
	 * Converts an ACS core log level (small integer as defined in ACS IDL)
	 * to the lowest matching AcsLogLevel or JDK Level.
	 *

	 * Note the difference to {@link #fromAcsCoreLevel(AcsLogLevelDefinition)}:
	 *

	 *
If more than one JDK-style log level gets mapped to the given core level,
	 *       then the lowest of these levels gets returned.
	 *       This method is therefore suitable to compute JDK log levels for filtering
	 *       when logs with all matching JDK levels should be allowed.

	 *
Currently this method is implemented with hard-wired levels, which means that
	 *       user-defined subclasses of AcsLogLevel are not considered.
	 *       (As of ACS 8.x, there is no known usage of custom log levels.
	 *       Supporting them for this method would require to keep a list similar to {@link #known}
	 *       that includes all JDK Level and AcsLogLevel objects.)
	 *

	 */
	public static Level getLowestMatchingJdkLevel(AcsLogLevelDefinition acsCoreLevel) {
		switch (acsCoreLevel) {
		case TRACE:
			// numerically the same as Level.FINEST
			return AcsLogLevel.TRACE;
		case DELOUSE:
			// numerically the same as Level.FINER
			return AcsLogLevel.DELOUSE;
		case DEBUG:
			// Both JDK levels FINE and CONFIG map to AcsLogLevel.DEBUG.
			// AcsLogLevel.DEBUG is numerically the same as CONFIG, which is higher than FINE (reasons related to logic in getNativeLevel()).
			return Level.FINE;
		case INFO:
			// numerically the same as Level.INFO
			return AcsLogLevel.INFO;
		case NOTICE:
			return AcsLogLevel.NOTICE;
		case WARNING:
			// numerically the same as Level.WARNING
			return AcsLogLevel.WARNING;
		case ERROR:
			return AcsLogLevel.ERROR;
		case CRITICAL:
			return AcsLogLevel.CRITICAL;
		case ALERT:
			return AcsLogLevel.ALERT;
		case EMERGENCY:
			// numerically the same as Level.SEVERE
			return AcsLogLevel.EMERGENCY;
		case OFF:
			// numerically the same as Level.OFF
			return AcsLogLevel.OFF;
		default:
			throw new IllegalArgumentException("Unexpected enum literal AcsLogLevelDefinition." + acsCoreLevel.name);
		}
	}

	/**
	 * Returns the corresponding ACS core level, which is a small positive integer
	 * defined as "priority" in the ACS logging and archiving architecture document
	 * and coded in IDL (see {@link alma.AcsLogging.alma.LogLevels.WARNING_NAME} and similar constants).
	 *

	 * This level is different from the JDK-style level, which can be any integer.
	 * @return		ACS core level
	 */
	public AcsLogLevelDefinition getAcsLevel()
	{
		return acsCoreLevel;
	}

	/**
	 * Returns the ACS XML level entryName.
	 * @return		ACS XML level entryName
	 */
	public String getEntryName()
	{
		return entryName;
	}

	/**
	 * Compares the level with the specified level for order.
	 *
	 * @see java.lang.Comparable#compareTo(Object)
	 */
	public int compareTo(AcsLogLevel l)
	{
		if (intValue() < l.intValue())
			return -1;
		else if (intValue() == l.intValue())
			return 0;
		else
			return 1;
	}

	/**
	 * Maps any (JDK or ACS) level to an ACS native level.
	 *

	 * Note that for some strange historical reason, the ACS log level is called "native" here,
	 * to confuse those who think that JDK levels would be native...
	 *
	 * @param level	any level
	 * @return 		native level, can be null if no native level is found or if level==Level.OFF
	 */
	public static AcsLogLevel getNativeLevel(Level level)
	{
		// try fast lookup
		AcsLogLevel luLevel = null;
		synchronized (lookup) {
			luLevel = lookup.get(level);
		}
		if (luLevel != null) {
			return luLevel;
		}

		// check if there is any native level of OFF
		if (known.size() == 0 || level.intValue() == Level.OFF.intValue())
			return null;
//		if (level.intValue() == Level.ALL.intValue())
//			return AcsLogLevel.ALL;

		// search through iterator and find the most appropriate. Relies on "known" being a sorted set with low levels first.
		synchronized (known) {
			Iterator<AcsLogLevel> iter = known.iterator();
			AcsLogLevel acsLevel = iter.next();
			while (level.intValue() > acsLevel.intValue() && iter.hasNext()) {
				acsLevel = iter.next();
			}
			// save for lookup
			synchronized (lookup) {
				lookup.put(level, acsLevel);
			}

			return acsLevel;
		}
	}

	/**
	 * This method should only be used to generate documentation about the various level mappings in use.
	 * @param ps The PrintStream to print to, e.g. System.out
	 */
	static void printMappings(PrintStream ps) {
		final String delim = "\t";
		synchronized (known) {
			for (AcsLogLevel level : known) {
				String acsLevelName = level.getEntryName();
				int levelValue = level.intValue();
				int coreLevelValue = level.getAcsLevel().value;
				ps.println(acsLevelName + delim + levelValue + delim + coreLevelValue);
			}
		}
	}
}


text:
@script RequireComponent (Camera)

function Start () {
	var al : AudioListener = null;
	al = Camera.main.gameObject.GetComponent.<AudioListener> ();

	if (al)
		al.volume = 1.0f;

	var sm : ShaderDatabase = GetComponent.<ShaderDatabase> ();
	sm.WhiteIn ();

	GetComponent.<Camera>().backgroundColor = Color.white;
}

redpajama_set_name: RedPajamaGithub


text:
// Provides functionality for activity detection
sap.ui.define(['jquery.sap.global'],
	function(jQuery) {
	"use strict";

	if (typeof window.jQuery.sap.act === "object" || typeof window.jQuery.sap.act === "function" ) {
		return jQuery;
	}

	/**
	 * @public
	 * @name jQuery.sap.act
	 * @namespace
	 * @static
	 */

	var _act = {},
		_active = true,
		_deactivatetimer = null,
		_I_MAX_IDLE_TIME = 10000, //max. idle time in ms
		_deactivateSupported = !!window.addEventListener, //Just skip IE8
		_aActivateListeners = [],
		_activityDetected = false,
		_domChangeObserver = null;

	function _onDeactivate(){
		_deactivatetimer = null;

		if (_activityDetected) {
			_onActivate();
			return;
		}

		_active = false;
		//_triggerEvent(_aDeactivateListeners); //Maybe provide later
		_domChangeObserver.observe(document.documentElement, {childList: true, attributes: true, subtree: true, characterData: true});
	}

	function _onActivate(){
		// Never activate when document is not visible to the user
		if (document.hidden === true) {
			// In case of IE<10 document.visible is undefined, else it is either true or false
			return;
		}

		if (!_active) {
			_active = true;
			_triggerEvent(_aActivateListeners);
			_domChangeObserver.disconnect();
		}
		if (_deactivatetimer) {
			_activityDetected = true;
		} else {
			_deactivatetimer = setTimeout(_onDeactivate, _I_MAX_IDLE_TIME);
			_activityDetected = false;
		}
	}

	function _triggerEvent(aListeners){
		if (aListeners.length == 0) {
			return;
		}
		var aEventListeners = aListeners.slice();
		setTimeout(function(){
			var oInfo;
			for (var i = 0, iL = aEventListeners.length; i < iL; i++) {
				oInfo = aEventListeners[i];
				oInfo.fFunction.call(oInfo.oListener || window);
			}
		}, 0);
	}

	/**
	 * Registers the given handler to the activity event, which is fired when an activity was detected after a certain period of inactivity.
	 *
	 * The Event is not fired for Internet Explorer 8.
	 *
	 * @param {Function} fnFunction The function to call, when an activity event occurs.
	 * @param {Object} [oListener] The 'this' context of the handler function.
	 * @protected
	 *
	 * @function
	 * @name jQuery.sap.act#attachActivate
	 */
	_act.attachActivate = function(fnFunction, oListener){
		_aActivateListeners.push({oListener: oListener, fFunction:fnFunction});
	};

	/**
	 * Deregisters a previously registered handler from the activity event.
	 *
	 * @param {Function} fnFunction The function to call, when an activity event occurs.
	 * @param {Object} [oListener] The 'this' context of the handler function.
	 * @protected
	 *
	 * @function
	 * @name jQuery.sap.act#detachActivate
	 */
	_act.detachActivate = function(fnFunction, oListener){
		for (var i = 0, iL = _aActivateListeners.length; i < iL; i++) {
			if (_aActivateListeners[i].fFunction === fnFunction && _aActivateListeners[i].oListener === oListener) {
				_aActivateListeners.splice(i,1);
				break;
			}
		}
	};

	/**
	 * Checks whether recently an activity was detected.
	 *
	 * Not supported for Internet Explorer 8.
	 *
	 * @return true if recently an activity was detected, false otherwise
	 * @protected
	 *
	 * @function
	 * @name jQuery.sap.act#isActive
	 */
	_act.isActive = !_deactivateSupported ? function(){ return true; } : function(){ return _active; };

	/**
	 * Reports an activity.
	 *
	 * @public
	 *
	 * @function
	 * @name jQuery.sap.act#refresh
	 */
	_act.refresh = !_deactivateSupported ? function(){} : _onActivate;

	// Setup and registering handlers

	if (_deactivateSupported) {
		var aEvents = ["resize", "orientationchange", "mousemove", "mousedown", "mouseup", //"mouseout", "mouseover",
					   "paste", "cut", "keydown", "keyup", "DOMMouseScroll", "mousewheel"];

		if (!!('ontouchstart' in window)) { //touch events supported
			aEvents.push("touchstart", "touchmove", "touchend", "touchcancel");
		}

		for (var i = 0; i < aEvents.length; i++) {
			window.addEventListener(aEvents[i], _act.refresh, true);
		}

		if (window.MutationObserver) {
			_domChangeObserver = new window.MutationObserver(_act.refresh);
			} else if (window.WebKitMutationObserver) {
				_domChangeObserver = new window.WebKitMutationObserver(_act.refresh);
			} else {
				_domChangeObserver = {
					observe : function(){
						document.documentElement.addEventListener("DOMSubtreeModified", _act.refresh);
					},
					disconnect : function(){
						document.documentElement.removeEventListener("DOMSubtreeModified", _act.refresh);
					}
				};
			}

		if (typeof (document.hidden) === "boolean") {
			document.addEventListener("visibilitychange", function() {
				// Only trigger refresh if document has changed to visible
				if (document.hidden !== true) {
					_act.refresh();
				}
			}, false);
		}

		_onActivate();
	}

	jQuery.sap.act = _act;

	return jQuery;

});


text:
import container from '../metal/container';
import Resolver from '../metal/resolver';
import Application from './application';
import Loader from '@denali-js/loader';

/**
 * Addons are the fundamental unit of organization for Denali apps. The
 * Application class is just a specialized Addon, and each Addon can contain
 * any amount of functionality - each one is essentially a mini Denali app.
 *
 * @package runtime
 * @since 0.1.0
 */
export default class Addon {

  /**
   * The current environment for the app, i.e. 'development'
   *
   * @since 0.1.0
   */
  environment: string;

  /**
   * The loader scope for this addon
   */
  loader: Loader;

  /**
   * The resolver for this addon's loader scope
   */
  get resolver(): Resolver {
    return this.loader.resolver;
  }

  constructor(loader: Loader, options: { environment: string }) {
    this.loader = loader;
    this.environment = options.environment;
    container.register(`addon:${ this.name }`, this);
  }

  /**
   * The name of the addon. Override this to use a different name than the
   * package name for your addon.
   *
   * @since 0.1.0
   */
  get name(): string {
    return `${ this.loader.pkgName }@${ this.loader.version }`;
  }

  /**
   * A hook to perform any shutdown actions necessary to gracefully exit the
   * application, i.e. close database/socket connections.
   *
   * @since 0.1.0
   */
  async shutdown(application: Application): Promise<void> {
    // defaults to noop
  }

}


text:
static foo: isize = 5;

fn main() {
    // assigning to various global constants
    foo = 6; //[ast]~ ERROR cannot assign to immutable static item
             //[mir]~^ ERROR cannot assign to immutable static item `foo`
}


text:
export function labelArrayToString(label: Float32Array, allLabels: string[]) {
  const [ind, _] = argmax(label);
  return allLabels[ind];
}

export function argmax(array: Float32Array) {
  let max = -Infinity;
  let argmax = -1;
  for (let i = 0; i < array.length; i++) {
    if (array[i] > max) {
      max = array[i];
      argmax = i;
    }
  }
  return [argmax, max];
}

export function getParameterByName(name: string, url?: string) {
  if (!url) url = window.location.href;
  name = name.replace(/[\[\]]/g, "\\$&");
  var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
    results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, " "));
}


text:
#ifndef __PANEL_COMPONENT_H__
#define __PANEL_COMPONENT_H__

#include "components/MeshComponent.h"

#include "Panel.h"

namespace Ogre {
  class Entity;
}

namespace components {

  /**
   * This component is responsible for taking a single Panel
   * and making sure it appears on screen for this actor
   */
  class PanelComponent : public MeshComponent
  {
    public:
      PanelComponent(Panel* panel)
        : MeshComponent(panel->meshName, panel->materialName),
          _panel(panel)
      {
        position = panel->position;
        rotation = panel->rotation;
      }

      Panel* _panel;
  };

}

#endif // __PANEL_COMPONENT_H__


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">

		<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
		<title>SnakeYAML 1.11 Reference Package org.yaml.snakeyaml.issues.issue74</title>
		<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="style" />

        	org.yaml.snakeyaml.issues.issue74

Classes

            	ArrayBean

            	ArrayBeanTest

            	ArrayMember


text:
title: Awards
bg: col3
color: white
fa-icon: trophy
---

	 (2016) The Hong Kong PhD Fellowship.
	Hong Kong PhD Fellowship Scheme (HKPFS) of the Research Grants Council (RGC) of Hong Kong. Hong Kong

	 (2016) Chow Yei Ching School of Graduate Studies Entrance Scholarship.  School of Graduate Studies - CityU. Hong Kong

	 (2013) Organization of American States (OAS-GCUB) Scholarship.
	MSc studies in Brazil. Research on Bioinformatics for Biotechnology. Washington, DC. USA.

	 (2013) Laureate Award by The Faculty of Engineering Council.
	Award for Excellence of the BSc. Graduation Project in Bioinformatics for Agriculture Biotechnology. Cali, COL.


text:
A simple RPC example implemented using gRPC

## Instalation

Setup [learnscalability/vm](https://github.com/learnscalability/vm)

Install project dependencies
```sh
$ cd ~/go/src/github.com/learnscalability/grpc-echo-service
$ glide install
```

## How to run

Make sure the protobuf generated `pb` package is up-to-date:
```sh
$ ./script/proto
```

Running the server
```sh
$ go run ./cmd/server/main.go -bind="0.0.0.0:3000"
```

Running the client, both send and subscribe
```sh
$ go run ./cmd/client/main.go -message="hello there" -method="subscribe" -server="0.0.0.0:3000"
```

Running the godoc tool
```sh
godoc -http=:8080
```
then navigate to `192.168.33.10:8080/pkg/github.com/learnscalability/grpc-echo-service` for godoc.org style docs.


text:
import json
import unittest
from unittest import mock
import responses
import yaml
from tempfile import TemporaryDirectory
from pathlib import Path

import pytest

from cumulusci.tasks.bulkdata import GenerateMapping
from cumulusci.core.exceptions import TaskOptionsError
from cumulusci.tasks.bulkdata.generate_mapping import FieldData
from cumulusci.utils import temporary_dir
from cumulusci.tasks.bulkdata.tests.utils import _make_task

class TestMappingGenerator(unittest.TestCase):
    def test_defaults_options(self):
        t = _make_task(GenerateMapping, {"options": {"path": "t"}})

        self.assertEqual([], t.options["ignore"])
        self.assertEqual("", t.options["namespace_prefix"])
        self.assertEqual("ask", t.options["break_cycles"])
        self.assertEqual([], t.options["include"])

    def test_postfixes_underscores_to_namespace(self):
        t = _make_task(
            GenerateMapping, {"options": {"namespace_prefix": "t", "path": "t"}}
        )

        self.assertEqual("t__", t.options["namespace_prefix"])

    def test_splits_ignore_string(self):
        t = _make_task(
            GenerateMapping, {"options": {"ignore": "Account, Contact", "path": "t"}}
        )

        self.assertEqual(["Account", "Contact"], t.options["ignore"])

    def test_accepts_ignore_list(self):
        t = _make_task(
            GenerateMapping,
            {"options": {"ignore": ["Account", "Contact"], "path": "t"}},
        )

        self.assertEqual(["Account", "Contact"], t.options["ignore"])

    def test_accepts_include_list(self):
        t = _make_task(
            GenerateMapping, {"options": {"include": ["Foo", "Bar"], "path": "t"}}
        )

        self.assertEqual(["Foo", "Bar"], t.options["include"])

    @responses.activate
    def test_checks_include_list(self):
        t = _make_task(
            GenerateMapping, {"options": {"include": ["Foo", "Bar"], "path": "t"}}
        )
        t.project_config.project__package__api_version = "45.0"

        self._prepare_describe_mock(t, {})
        t._init_task()

        with pytest.raises(TaskOptionsError):
            t._collect_objects()

    def test_is_any_custom_api_name(self):
        t = _make_task(GenerateMapping, {"options": {"path": "t"}})

        self.assertTrue(t._is_any_custom_api_name("Custom__c"))
        self.assertFalse(t._is_any_custom_api_name("Standard"))

    def test_is_our_custom_api_name(self):
        t = _make_task(GenerateMapping, {"options": {"path": "t"}})

        self.assertTrue(t._is_our_custom_api_name("Custom__c"))
        self.assertFalse(t._is_our_custom_api_name("Standard"))
        self.assertFalse(t._is_our_custom_api_name("t__Custom__c"))
        self.assertFalse(t._is_our_custom_api_name("f__Custom__c"))

        t.options["namespace_prefix"] = "t__"
        self.assertTrue(t._is_our_custom_api_name("Custom__c"))
        self.assertTrue(t._is_our_custom_api_name("t__Custom__c"))
        self.assertFalse(t._is_our_custom_api_name("f__Custom__c"))

    def test_is_core_field(self):
        t = _make_task(GenerateMapping, {"options": {"path": "t"}})

        self.assertTrue(t._is_core_field("Name"))
        self.assertFalse(t._is_core_field("Custom__c"))

    def test_is_object_mappable(self):
        t = _make_task(GenerateMapping, {"options": {"ignore": "Account", "path": "t"}})

        self.assertTrue(
            t._is_object_mappable({"name": "Contact", "customSetting": False})
        )
        self.assertFalse(
            t._is_object_mappable({"name": "Account", "customSetting": False})
        )
        self.assertFalse(
            t._is_object_mappable(
                {"name": "Contact__ChangeEvent", "customSetting": False}
            )
        )
        self.assertFalse(
            t._is_object_mappable({"name": "Custom__c", "customSetting": True})
        )

    def test_is_field_mappable(self):
        t = _make_task(
            GenerateMapping, {"options": {"ignore": "Account.ParentId", "path": "t"}}
        )

        t.mapping_objects = ["Account", "Contact"]

        self.assertTrue(
            t._is_field_mappable(
                "Account",
                {"name": "Name", "type": "string", "label": "Name", "createable": True},
            )
        )
        self.assertFalse(
            t._is_field_mappable(
                "Account",
                {"name": "Name", "type": "base64", "label": "Name", "createable": True},
            )
        )
        self.assertFalse(
            t._is_field_mappable(
                "Account",
                {
                    "name": "Name",
                    "type": "string",
                    "label": "Name (Deprecated)",
                    "createable": True,
                },
            )
        )
        self.assertFalse(
            t._is_field_mappable(
                "Account",
                {
                    "name": "ParentId",
                    "type": "reference",
                    "label": "Parent",
                    "createable": True,
                    "referenceTo": ["Account"],
                },
            )
        )
        self.assertFalse(
            t._is_field_mappable(
                "Account",
                {
                    "name": "Name",
                    "type": "string",
                    "label": "Name",
                    "createable": False,
                },
            )
        )
        self.assertFalse(
            t._is_field_mappable(
                "Contact",
                {
                    "name": "OwnerId",
                    "type": "reference",
                    "label": "Owner",
                    "createable": True,
                    "referenceTo": ["User", "Group"],
                },
            )
        )

    def test_has_our_custom_fields(self):
        t = _make_task(GenerateMapping, {"options": {"path": "t"}})

        self.assertTrue(t._has_our_custom_fields({"fields": [{"name": "Custom__c"}]}))
        self.assertTrue(
            t._has_our_custom_fields(
                {"fields": [{"name": "Custom__c"}, {"name": "Standard"}]}
            )
        )
        self.assertFalse(t._has_our_custom_fields({"fields": [{"name": "Standard"}]}))
        self.assertFalse(t._has_our_custom_fields({"fields": []}))

    def test_is_lookup_to_included_object(self):
        t = _make_task(GenerateMapping, {"options": {"path": "t"}})

        t.mapping_objects = ["Account"]

        self.assertTrue(
            t._is_lookup_to_included_object(
                {"type": "reference", "referenceTo": ["Account"]}
            )
        )
        self.assertFalse(
            t._is_lookup_to_included_object(
                {"type": "reference", "referenceTo": ["Contact"]}
            )
        )
        self.assertFalse(
            t._is_lookup_to_included_object(
                {"type": "reference", "referenceTo": ["Account", "Contact"]}
            )
        )

    def _prepare_describe_mock(self, task, describe_data):
        responses.add(
            method="GET",
            url=f"{task.org_config.instance_url}/services/data/v45.0/sobjects",
            body=json.dumps(
                {
                    "sobjects": [
                        {"name": s, "customSetting": False} for s in describe_data
                    ]
                }
            ),
            status=200,
        )
        for s in describe_data:
            body = {"name": s, "customSetting": False}
            body.update(describe_data[s])
            responses.add(
                method="GET",
                url=f"{task.org_config.instance_url}/services/data/v45.0/sobjects/{s}/describe",
                body=json.dumps(body),
                status=200,
            )

    def _mock_field(self, name, field_type="string", **kwargs):
        field_data = {
            "name": name,
            "type": field_type,
            "createable": True,
            "nillable": True,
            "label": name,
        }
        field_data.update(kwargs)
        return field_data

    @responses.activate
    def test_run_task(self):
        t = _make_task(GenerateMapping, {"options": {"path": "mapping.yaml"}})
        t.project_config.project__package__api_version = "45.0"
        describe_data = {
            "Parent": {
                "fields": [self._mock_field("Id"), self._mock_field("Custom__c")]
            },
            "Child__c": {
                "fields": [
                    self._mock_field("Id"),
                    self._mock_field(
                        "Account__c",
                        field_type="reference",
                        referenceTo=["Parent"],
                        relationshipOrder=None,
                    ),
                ]
            },
        }

        self._prepare_describe_mock(t, describe_data)
        with temporary_dir():
            t()

            with open("mapping.yaml", "r") as fh:
                content = yaml.safe_load(fh)

            self.assertEqual(["Insert Parent", "Insert Child__c"], list(content.keys()))
            self.assertEqual("Parent", t.mapping["Insert Parent"]["sf_object"])
            self.assertEqual(["Custom__c"], t.mapping["Insert Parent"]["fields"])

            self.assertEqual("Child__c", t.mapping["Insert Child__c"]["sf_object"])
            assert "fields" not in t.mapping["Insert Child__c"]
            self.assertEqual(
                ["Account__c"], list(t.mapping["Insert Child__c"]["lookups"].keys())
            )
            self.assertEqual(
                "Parent", t.mapping["Insert Child__c"]["lookups"]["Account__c"]["table"]
            )

    @responses.activate
    def test_collect_objects__simple_custom_objects(self):
        t = _make_task(GenerateMapping, {"options": {"path": "t"}})
        t.project_config.project__package__api_version = "45.0"

        describe_data = {
            "Account": {
                "fields": [self._mock_field("Name"), self._mock_field("Custom__c")]
            },
            "Contact": {"fields": [self._mock_field("Name")]},
            "Custom__c": {
                "fields": [self._mock_field("Name"), self._mock_field("Custom__c")]
            },
            "User": {"fields": [self._mock_field("Name")]},
        }

        self._prepare_describe_mock(t, describe_data)
        t._init_task()
        t._collect_objects()

        self.assertEqual(set(["Account", "Custom__c"]), set(t.mapping_objects))

    @responses.activate
    def test_collect_objects__force_include_objects(self):
        t = _make_task(
            GenerateMapping, {"options": {"path": "t", "include": ["Contact", "User"]}}
        )
        t.project_config.project__package__api_version = "45.0"

        describe_data = {
            "Account": {
                "fields": [self._mock_field("Name"), self._mock_field("Custom__c")]
            },
            "Contact": {"fields": [self._mock_field("Name")]},
            "Custom__c": {
                "fields": [self._mock_field("Name"), self._mock_field("Custom__c")]
            },
            "User": {"fields": [self._mock_field("Name")]},
        }

        self._prepare_describe_mock(t, describe_data)
        t._init_task()
        t._collect_objects()

        self.assertEqual(
            set(["Account", "Custom__c", "Contact", "User"]), set(t.mapping_objects)
        )

    @responses.activate
    def test_collect_objects__force_include_objects__already_included(self):
        t = _make_task(
            GenerateMapping,
            {"options": {"path": "t", "include": ["Contact", "Custom__c"]}},
        )
        t.project_config.project__package__api_version = "45.0"

        describe_data = {
            "Account": {
                "fields": [self._mock_field("Name"), self._mock_field("Custom__c")]
            },
            "Contact": {"fields": [self._mock_field("Name")]},
            "Custom__c": {
                "fields": [self._mock_field("Name"), self._mock_field("Custom__c")]
            },
            "User": {"fields": [self._mock_field("Name")]},
        }

        self._prepare_describe_mock(t, describe_data)
        t._init_task()
        t._collect_objects()
        assert len(t.mapping_objects) == 3

        self.assertEqual(
            set(["Account", "Custom__c", "Contact"]), set(t.mapping_objects)
        )

    @responses.activate
    def test_collect_objects__custom_lookup_fields(self):
        t = _make_task(GenerateMapping, {"options": {"path": "t"}})
        t.project_config.project__package__api_version = "45.0"

        describe_data = {
            "Account": {
                "fields": [self._mock_field("Name"), self._mock_field("Custom__c")]
            },
            "Contact": {"fields": [self._mock_field("Name")]},
            "Custom__c": {
                "fields": [
                    self._mock_field("Name"),
                    self._mock_field("Custom__c"),
                    self._mock_field(
                        "Lookup__c",
                        field_type="reference",
                        relationshipOrder=None,
                        referenceTo=["Contact"],
                    ),
                ]
            },
        }

        self._prepare_describe_mock(t, describe_data)
        t._init_task()
        t._collect_objects()

        self.assertEqual(
            set(["Account", "Custom__c", "Contact"]), set(t.mapping_objects)
        )

    @responses.activate
    def test_collect_objects__master_detail_fields(self):
        t = _make_task(GenerateMapping, {"options": {"path": "t"}})
        t.project_config.project__package__api_version = "45.0"

        describe_data = {
            "Account": {
                "fields": [self._mock_field("Name"), self._mock_field("Custom__c")]
            },
            "Opportunity": {"fields": [self._mock_field("Name")]},
            "OpportunityLineItem": {
                "fields": [
                    self._mock_field("Name"),
                    self._mock_field("Custom__c"),
                    self._mock_field(
                        "OpportunityId",
                        field_type="reference",
                        relationshipOrder=1,
                        referenceTo=["Opportunity"],
                    ),
                ]
            },
        }

        self._prepare_describe_mock(t, describe_data)
        t._init_task()
        t._collect_objects()

        self.assertEqual(
            set(["Account", "OpportunityLineItem", "Opportunity"]),
            set(t.mapping_objects),
        )

    @responses.activate
    def test_collect_objects__duplicate_references(self):
        t = _make_task(GenerateMapping, {"options": {"path": "t"}})
        t.project_config.project__package__api_version = "45.0"

        describe_data = {
            "Account": {
                "fields": [self._mock_field("Name"), self._mock_field("Custom__c")]
            },
            "Opportunity": {"fields": [self._mock_field("Name")]},
            "OpportunityLineItem": {
                "fields": [
                    self._mock_field("Name"),
                    self._mock_field("Custom__c"),
                    self._mock_field(
                        "OpportunityId",
                        field_type="reference",
                        relationshipOrder=1,
                        referenceTo=["Opportunity"],
                    ),
                    self._mock_field(
                        "CustomLookup__c",
                        field_type="reference",
                        relationshipOrder=None,
                        referenceTo=["Opportunity"],
                    ),
                ]
            },
        }

        self._prepare_describe_mock(t, describe_data)
        t._init_task()
        t._collect_objects()

        self.assertEqual(
            set(["Account", "OpportunityLineItem", "Opportunity"]),
            set(t.mapping_objects),
        )

    def test_build_schema(self):
        t = _make_task(GenerateMapping, {"options": {"path": "t"}})

        t.mapping_objects = ["Account", "Opportunity", "Child__c"]
        stage_name = self._mock_field("StageName")
        stage_name["nillable"] = False
        t.describes = {
            "Account": {
                "fields": [self._mock_field("Name"), self._mock_field("Industry")]
            },
            "Opportunity": {"fields": [self._mock_field("Name"), stage_name]},
            "Child__c": {
                "fields": [
                    self._mock_field("Name"),
                    self._mock_field("Test__c"),
                    self._mock_field("Attachment__c", field_type="base64"),
                ]
            },
        }

        t._build_schema()
        self.assertEqual(
            {
                "Account": {"Name": self._mock_field("Name")},
                "Opportunity": {
                    "Name": self._mock_field("Name"),
                    "StageName": stage_name,
                },
                "Child__c": {
                    "Name": self._mock_field("Name"),
                    "Test__c": self._mock_field("Test__c"),
                },
            },
            t.schema,
        )

    def test_build_schema__tracks_references(self):
        t = _make_task(GenerateMapping, {"options": {"path": "t"}})

        t.mapping_objects = ["Account", "Opportunity"]
        t.describes = {
            "Account": {"fields": [self._mock_field("Name")]},
            "Opportunity": {
                "fields": [
                    self._mock_field("Name"),
                    self._mock_field(
                        "AccountId",
                        field_type="reference",
                        referenceTo=["Account"],
                        relationshipOrder=1,
                    ),
                ]
            },
        }

        t._build_schema()

        self.assertEqual(
            {"Opportunity": {"Account": {"AccountId": FieldData({"nillable": True})}}},
            dict(t.refs),
        )

    def test_build_schema__includes_recordtypeid(self):
        t = _make_task(GenerateMapping, {"options": {"path": "t"}})

        t.mapping_objects = ["Account", "Opportunity"]
        t.describes = {
            "Account": {"fields": [self._mock_field("Name")]},
            "Opportunity": {
                "fields": [
                    self._mock_field("Name"),
                    self._mock_field(
                        "AccountId",
                        field_type="reference",
                        referenceTo=["Account"],
                        relationshipOrder=1,
                    ),
                    self._mock_field("RecordTypeId"),
                ],
                "recordTypeInfos": [{"Name": "Master"}, {"Name": "Donation"}],
            },
        }

        t._build_schema()
        self.assertIn("RecordTypeId", t.schema["Opportunity"])
        self.assertNotIn("RecordTypeId", t.schema["Account"])

    @mock.patch("click.prompt")
    def test_build_mapping(self, prompt):
        t = _make_task(GenerateMapping, {"options": {"path": "t"}})
        prompt.return_value = "Account"

        t.schema = {
            "Account": {
                "Name": self._mock_field("Name"),
                "Dependent__c": self._mock_field(
                    "Dependent__c", field_type="reference", referenceTo=["Child__c"]
                ),
            },
            "Child__c": {
                "Name": self._mock_field("Name"),
                "Account__c": self._mock_field(
                    "Account__c", field_type="reference", referenceTo=["Account"]
                ),
                "Self__c": self._mock_field(
                    "Self__c", field_type="reference", referenceTo=["Child__c"]
                ),
            },
        }
        t.refs = {
            "Child__c": {"Account": {"Account__c": FieldData({"nillable": True})}},
            "Account": {"Child__c": {"Dependent__c": FieldData({"nillable": True})}},
        }

        t._build_mapping()
        self.assertEqual(["Insert Account", "Insert Child__c"], list(t.mapping.keys()))
        self.assertEqual("Account", t.mapping["Insert Account"]["sf_object"])
        self.assertEqual(["Name"], t.mapping["Insert Account"]["fields"])
        self.assertEqual(
            ["Dependent__c"], list(t.mapping["Insert Account"]["lookups"].keys())
        )
        self.assertEqual(
            "Child__c", t.mapping["Insert Account"]["lookups"]["Dependent__c"]["table"]
        )

        self.assertEqual("Child__c", t.mapping["Insert Child__c"]["sf_object"])
        self.assertEqual(["Name"], t.mapping["Insert Child__c"]["fields"])
        self.assertEqual(
            ["Account__c", "Self__c"],
            list(t.mapping["Insert Child__c"]["lookups"].keys()),
        )
        self.assertEqual(
            "Account", t.mapping["Insert Child__c"]["lookups"]["Account__c"]["table"]
        )
        self.assertEqual(
            "Child__c", t.mapping["Insert Child__c"]["lookups"]["Self__c"]["table"]
        )

    @mock.patch("click.prompt")
    def test_build_mapping__strip_namespace(self, prompt):
        t = _make_task(GenerateMapping, {"options": {"path": "t"}})
        t.project_config.project__package__namespace = "ns"
        prompt.return_value = "ns__Parent__c"

        t.schema = {
            "ns__Parent__c": {
                "Name": self._mock_field("Name"),
                "ns__Dependent__c": self._mock_field(
                    "ns__Dependent__c",
                    field_type="reference",
                    referenceTo=["ns__Child__c"],
                ),
            },
            "ns__Child__c": {
                "Name": self._mock_field("Name"),
                "ns__Parent__c": self._mock_field(
                    "ns__Parent__c",
                    field_type="reference",
                    referenceTo=["ns__Parent__c"],
                ),
                "ns__Self__c": self._mock_field(
                    "ns__Self__c", field_type="reference", referenceTo=["ns__Child__c"]
                ),
            },
        }
        t.refs = {
            "ns__Child__c": {
                "ns__Parent__c": {"ns__Parent__c": FieldData({"nillable": False})}
            },
            "ns__Parent__c": {
                "ns__Child__c": {"ns__Dependent__c": FieldData({"nillable": True})}
            },
        }

        t._build_mapping()
        self.assertEqual(
            ["Insert Parent__c", "Insert Child__c"], list(t.mapping.keys())
        )
        self.assertEqual("Parent__c", t.mapping["Insert Parent__c"]["sf_object"])
        self.assertEqual(["Name"], t.mapping["Insert Parent__c"]["fields"])
        self.assertEqual(
            ["Dependent__c"], list(t.mapping["Insert Parent__c"]["lookups"].keys())
        )
        self.assertEqual(
            "Child__c",
            t.mapping["Insert Parent__c"]["lookups"]["Dependent__c"]["table"],
        )

        self.assertEqual("Child__c", t.mapping["Insert Child__c"]["sf_object"])
        self.assertEqual(["Name"], t.mapping["Insert Child__c"]["fields"])
        self.assertEqual(
            ["Parent__c", "Self__c"],
            list(t.mapping["Insert Child__c"]["lookups"].keys()),
        )
        self.assertEqual(
            "Parent__c", t.mapping["Insert Child__c"]["lookups"]["Parent__c"]["table"]
        )
        self.assertEqual(
            "Child__c", t.mapping["Insert Child__c"]["lookups"]["Self__c"]["table"]
        )

    @mock.patch("click.prompt")
    def test_build_mapping__no_strip_namespace_if_dup_component(self, prompt):
        t = _make_task(GenerateMapping, {"options": {"path": "t"}})
        t.project_config.project__package__namespace = "ns"
        prompt.return_value = "ns__Parent__c"

        t.schema = {
            "ns__Parent__c": {"Name": self._mock_field("Name")},
            "ns__Child__c": {
                "Name": self._mock_field("Name"),
                "Test__c": self._mock_field("Test__c"),
                "ns__Test__c": self._mock_field("ns__Test__c"),
                "ns__Parent__c": self._mock_field(
                    "ns__Parent__c",
                    field_type="reference",
                    referenceTo=["ns__Parent__c"],
                ),
                "Parent__c": self._mock_field(
                    "Parent__c", field_type="reference", referenceTo=["ns__Child__c"]
                ),
            },
            "Child__c": {"Name": self._mock_field("Name")},
        }
        t.refs = {"ns__Child__c": {"ns__Parent__c": {"ns__Parent__c": FieldData({})}}}

        t._build_mapping()

        self.assertEqual(
            set(["Insert Parent__c", "Insert ns__Child__c", "Insert Child__c"]),
            set(t.mapping.keys()),
        )

        self.assertEqual("ns__Child__c", t.mapping["Insert ns__Child__c"]["sf_object"])
        self.assertEqual(
            ["Name", "Test__c", "ns__Test__c"],
            t.mapping["Insert ns__Child__c"]["fields"],
        )
        self.assertEqual(
            set(["ns__Parent__c", "Parent__c"]),
            set(t.mapping["Insert ns__Child__c"]["lookups"].keys()),
        )
        self.assertEqual(
            "Parent__c",
            t.mapping["Insert ns__Child__c"]["lookups"]["ns__Parent__c"]["table"],
        )
        self.assertEqual(
            "ns__Child__c",
            t.mapping["Insert ns__Child__c"]["lookups"]["Parent__c"]["table"],
        )

        self.assertEqual("Child__c", t.mapping["Insert Child__c"]["sf_object"])
        self.assertEqual(["Name"], t.mapping["Insert Child__c"]["fields"])

    def test_build_mapping__warns_polymorphic_lookups(self):
        t = _make_task(GenerateMapping, {"options": {"path": "t"}})

        t.mapping_objects = ["Account", "Contact", "Custom__c"]
        t.schema = {
            "Account": {"Name": self._mock_field("Name")},
            "Contact": {"Name": self._mock_field("Name")},
            "Custom__c": {
                "Name": self._mock_field("Name"),
                "PolyLookup__c": self._mock_field(
                    "PolyLookup__c",
                    field_type="reference",
                    referenceTo=["Account", "Contact"],
                ),
            },
        }
        t.refs = {
            "Custom__c": {
                "Account": {"PolyLookup__c": FieldData({})},
                "Contact": {"PolyLookup__c": FieldData({})},
            }
        }
        t.logger = mock.Mock()

        t._build_mapping()
        t.logger.warning.assert_called_once_with(
            "Field Custom__c.PolyLookup__c is a polymorphic lookup, which is not supported"
        )

    def test_split_dependencies__no_cycles(self):
        t = _make_task(GenerateMapping, {"options": {"path": "t"}})

        stack = t._split_dependencies(
            ["Account", "Contact", "Opportunity", "Custom__c"],
            {
                "Contact": {"Account": {"AccountId": FieldData({})}},
                "Opportunity": {
                    "Account": {"AccountId": FieldData({})},
                    "Contact": {"Primary_Contact__c": FieldData({})},
                },
                "Custom__c": {
                    "Account": {"Account__c": FieldData({})},
                    "Contact": {"Contact__c": FieldData({})},
                    "Opportunity": {"Opp__c": FieldData({})},
                },
            },
        )

        self.assertEqual(["Account", "Contact", "Opportunity", "Custom__c"], stack)

    @mock.patch("click.prompt")
    def test_split_dependencies__interviews_for_cycles(self, prompt):
        t = _make_task(GenerateMapping, {"options": {"path": "t"}})

        prompt.return_value = "Account"

        self.assertEqual(
            ["Custom__c", "Account", "Contact", "Opportunity"],
            t._split_dependencies(
                ["Account", "Contact", "Opportunity", "Custom__c"],
                {
                    "Account": {
                        "Contact": {"Primary_Contact__c": FieldData({"nillable": True})}
                    },
                    "Contact": {
                        "Account": {"AccountId": FieldData({"nillable": True})}
                    },
                    "Opportunity": {
                        "Account": {"AccountId": FieldData({"nillable": True})},
                        "Contact": {
                            "Primary_Contact__c": FieldData({"nillable": True})
                        },
                    },
                },
            ),
        )

    @mock.patch("click.prompt")
    @mock.patch("random.choice")
    def test_split_dependencies__auto_pick_cycles_priortize_Account(
        self, choice, prompt
    ):
        t = _make_task(
            GenerateMapping, {"options": {"path": "t", "break_cycles": "auto"}}
        )

        prompt.side_effect = AssertionError("Shouldn't be called")
        choice.side_effect = AssertionError("Shouldn't be called")
        split_dependencies = t._split_dependencies(
            ["Account", "Contact", "Opportunity", "Custom__c"],
            {
                "Account": {
                    "Contact": {"Primary_Contact__c": FieldData({"nillable": False})}
                },
                "Contact": {"Account": {"AccountId": FieldData({"nillable": False})}},
                "Opportunity": {
                    "Account": {"AccountId": FieldData({"nillable": False})},
                    "Contact": {"Primary_Contact__c": FieldData({"nillable": False})},
                },
            },
        )

        self.assertEqual(
            ["Custom__c", "Account", "Contact", "Opportunity"], split_dependencies
        )
        assert not choice.mock_calls

    @mock.patch("click.prompt")
    def test_split_dependencies__auto_pick_cycles_randomly(self, prompt):
        t = _make_task(
            GenerateMapping, {"options": {"path": "t", "break_cycles": "auto"}}
        )

        prompt.side_effect = AssertionError("Shouldn't be called")
        split_dependencies = t._split_dependencies(
            ["Account", "Contact", "Opportunity", "Custom__c"],
            {
                "Account": {
                    "Custom__c": {
                        "Non_Nillable_Custom__c": FieldData({"nillable": False})
                    }
                },
                "Custom__c": {"Account": {"AccountId": FieldData({"nillable": False})}},
            },
        )

        self.assertEqual(
            ["Contact", "Opportunity", "Account", "Custom__c"], split_dependencies
        )

    @mock.patch("click.prompt")
    @mock.patch("random.choice")
    def test_split_dependencies__auto_pick_cycles_by_relationship_type(
        self, random_choice, prompt
    ):
        t = _make_task(
            GenerateMapping, {"options": {"path": "t", "break_cycles": "auto"}}
        )

        prompt.side_effect = AssertionError("Shouldn't be called")
        random_choice.side_effect = AssertionError("Shouldn't be called")

        split_dependencies = t._split_dependencies(
            ["AccountLike__c", "ContactLike__c", "OpportunityLike__c", "Custom__c"],
            {
                # Primary_Contact__c is not nillable, so ContactLike__c must be loaded before
                # AccountLike__c despite the cycle
                "AccountLike__c": {
                    "ContactLike__c": {
                        "Primary_Contact__c": FieldData({"nillable": False})
                    }
                },
                "ContactLike__c": {
                    "AccountLike__c": {"AccountId": FieldData({"nillable": True})}
                },
                "OpportunityLike__c": {
                    "AccountLike__c": {"AccountId": FieldData({"nillable": True})},
                    "ContactLike__c": {
                        "Primary_Contact__c": FieldData({"nillable": True})
                    },
                },
            },
        )

        self.assertEqual(
            ["Custom__c", "ContactLike__c", "AccountLike__c", "OpportunityLike__c"],
            split_dependencies,
        )
        random_choice.assert_not_called()

    @mock.patch("click.prompt")
    def test_split_dependencies__auto_pick_cycles(self, prompt):
        t = _make_task(
            GenerateMapping, {"options": {"path": "t", "break_cycles": "auto"}}
        )

        prompt.return_value = AssertionError("Shouldn't be called")

        self.assertEqual(
            set(["Custom__c", "Account", "Contact", "Opportunity"]),
            set(
                t._split_dependencies(
                    ["Account", "Contact", "Opportunity", "Custom__c"],
                    {
                        "Account": {
                            "Contact": {
                                "Primary_Contact__c": FieldData({"nillable": True})
                            }
                        },
                        "Contact": {
                            "Account": {"AccountId": FieldData({"nillable": True})}
                        },
                        "Opportunity": {
                            "Account": {"AccountId": FieldData({"nillable": True})},
                            "Contact": {
                                "Primary_Contact__c": FieldData({"nillable": True})
                            },
                        },
                    },
                )
            ),
        )

    @mock.patch("click.prompt")
    def test_split_dependencies__ask_pick_cycles(self, prompt):
        t = _make_task(
            GenerateMapping, {"options": {"path": "t", "break_cycles": "ask"}}
        )
        prompt.return_value = "Custom__c"

        self.assertEqual(
            set(["Custom__c", "Account", "Contact", "Opportunity"]),
            set(
                t._split_dependencies(
                    ["Account", "Contact", "Opportunity", "Custom__c"],
                    {
                        "Account": {
                            "Custom__c": {"Custom__c": FieldData({"nillable": False})}
                        },
                        "Custom__c": {
                            "Account": {"Account__c": FieldData({"nillable": False})}
                        },
                    },
                )
            ),
        )

        prompt.assert_called_once()
        assert prompt.mock_calls

    def test_options_error(self):
        with pytest.raises(TaskOptionsError):
            _make_task(
                GenerateMapping, {"options": {"path": "t", "break_cycles": "foo"}}
            )

@pytest.mark.integration_test()
class TestIntegrationGenerateMapping:
    @pytest.mark.vcr()
    def test_simple_generate(self, create_task):
        "Generate a mapping against a provided org."
        with TemporaryDirectory() as t:
            tempfile = Path(t) / "tempfile.mapping.yml"

            task = create_task(GenerateMapping, {"path": tempfile})
            assert not Path(tempfile).exists()
            task()
            assert Path(tempfile).exists()

    @pytest.mark.vcr()
    def test_generate_with_cycles(self, create_task):
        "Generate a mapping that necessarily includes some reference cycles"
        with TemporaryDirectory() as t:
            tempfile = Path(t) / "tempfile.mapping.yml"

            task = create_task(
                GenerateMapping,
                {
                    "path": tempfile,
                    "include": [
                        "Account",
                        "Contact",
                        "Opportunity",
                        "OpportunityContactRole",
                    ],
                },
            )
            assert not Path(tempfile).exists()
            task()
            assert Path(tempfile).exists()

    @pytest.mark.vcr()
    def test_big_generate(self, create_task, sf):
        "Generate a large mapping that includes every reachable object"
        with TemporaryDirectory() as t:
            tempfile = Path(t) / "tempfile.mapping.yml"

            every_obj = [obj["name"] for obj in sf.describe()["sobjects"]]

            task = create_task(
                GenerateMapping, {"path": tempfile, "include": every_obj}
            )
            assert not Path(tempfile).exists()
            task()
            assert Path(tempfile).exists()


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.3.1"/>
<title>libxml++: xmlpp::SaxParser::Attribute Struct Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

libxml++
    2.37.1

Main Page

Related Pages

Namespaces

Classes

Class List

Class Index

Class Hierarchy

Class Members

xmlpp

SaxParser

Attribute

Public Member Functions |
Public Attributes |
List of all members

xmlpp::SaxParser::Attribute Struct Reference

Simple structure used in the start_element callback, in which the attributes are a list of name/value pairs.
 More...

#include <libxml++/parsers/saxparser.h>

Public Member Functions

 	Attribute (Glib::ustring const& n, Glib::ustring const& v)

Public Attributes

Glib::ustring 	name

Glib::ustring 	value

Detailed Description

Simple structure used in the start_element callback, in which the attributes are a list of name/value pairs.

Constructor & Destructor Documentation

          xmlpp::SaxParser::Attribute::Attribute
          (
          Glib::ustring const &
          n,

          Glib::ustring const &
          v

          )

inline

Member Data Documentation

          Glib::ustring xmlpp::SaxParser::Attribute::name

          Glib::ustring xmlpp::SaxParser::Attribute::value

<address class="footer">
Generated on Mon Sep 16 2013 11:27:49 for libxml++ by

 1.8.3.1
</address>


text:
package ru.bartwell.ultradebugger;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;

public class ServerService extends Service {
    private static final String EXTRA_PORT = "port";
    private HttpServer mHttpServer;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int port = intent == null ? HttpServer.DEFAULT_PORT : intent.getIntExtra(EXTRA_PORT, HttpServer.DEFAULT_PORT);
        mHttpServer = new HttpServer(port);
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        mHttpServer.stop();
        super.onDestroy();
    }

    public static void start(Context context, int port) {
        Intent intent = new Intent(context, ServerService.class);
        intent.putExtra(EXTRA_PORT, port);
        context.startService(intent);
    }

    public static void stop(Context context) {
        context.stopService(new Intent(context, ServerService.class));
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

angular.
  module('core.upgrade').
  factory('Upgrades', ['$resource',
    function($resource) {
      return $resource('store/upgrades/upgrades.json', {}, {
        query: {
          method: 'GET',
          isArray: true
        }
      });
    }
  ]);


text:
package org.zaproxy.clientapi.gen.deprecated;

import java.util.HashMap;
import java.util.Map;
import org.zaproxy.clientapi.core.ApiResponse;
import org.zaproxy.clientapi.core.ClientApi;
import org.zaproxy.clientapi.core.ClientApiException;

/** API implementation with deprecated methods, (re)moved from generated class. */
@SuppressWarnings("javadoc")
public class ScriptDeprecated {

    private final ClientApi api;

    public ScriptDeprecated(ClientApi api) {
        this.api = api;
    }

    /**
     * @deprecated (1.1.0) Use the method without the API key and use one of the {@code ClientApi}
     *     constructors that allow to set the API key (e.g. {@link ClientApi#ClientApi(String, int,
     *     String)}).
     */
    @Deprecated
    public ApiResponse enable(String apikey, String scriptname) throws ClientApiException {
        Map<String, String> map = new HashMap<>();
        if (apikey != null) {
            map.put("apikey", apikey);
        }
        map.put("scriptName", scriptname);
        return api.callApi("script", "action", "enable", map);
    }

    /**
     * @deprecated (1.1.0) Use the method without the API key and use one of the {@code ClientApi}
     *     constructors that allow to set the API key (e.g. {@link ClientApi#ClientApi(String, int,
     *     String)}).
     */
    @Deprecated
    public ApiResponse disable(String apikey, String scriptname) throws ClientApiException {
        Map<String, String> map = new HashMap<>();
        if (apikey != null) {
            map.put("apikey", apikey);
        }
        map.put("scriptName", scriptname);
        return api.callApi("script", "action", "disable", map);
    }

    /**
     * @deprecated (1.1.0) Use the method without the API key and use one of the {@code ClientApi}
     *     constructors that allow to set the API key (e.g. {@link ClientApi#ClientApi(String, int,
     *     String)}).
     */
    @Deprecated
    public ApiResponse load(
            String apikey,
            String scriptname,
            String scripttype,
            String scriptengine,
            String filename,
            String scriptdescription)
            throws ClientApiException {
        Map<String, String> map = new HashMap<>();
        if (apikey != null) {
            map.put("apikey", apikey);
        }
        map.put("scriptName", scriptname);
        map.put("scriptType", scripttype);
        map.put("scriptEngine", scriptengine);
        map.put("fileName", filename);
        if (scriptdescription != null) {
            map.put("scriptDescription", scriptdescription);
        }
        return api.callApi("script", "action", "load", map);
    }

    /**
     * @deprecated (1.1.0) Use the method without the API key and use one of the {@code ClientApi}
     *     constructors that allow to set the API key (e.g. {@link ClientApi#ClientApi(String, int,
     *     String)}).
     */
    @Deprecated
    public ApiResponse remove(String apikey, String scriptname) throws ClientApiException {
        Map<String, String> map = new HashMap<>();
        if (apikey != null) {
            map.put("apikey", apikey);
        }
        map.put("scriptName", scriptname);
        return api.callApi("script", "action", "remove", map);
    }

    /**
     * @deprecated (1.1.0) Use the method without the API key and use one of the {@code ClientApi}
     *     constructors that allow to set the API key (e.g. {@link ClientApi#ClientApi(String, int,
     *     String)}).
     */
    @Deprecated
    public ApiResponse runStandAloneScript(String apikey, String scriptname)
            throws ClientApiException {
        Map<String, String> map = new HashMap<>();
        if (apikey != null) {
            map.put("apikey", apikey);
        }
        map.put("scriptName", scriptname);
        return api.callApi("script", "action", "runStandAloneScript", map);
    }

    /**
     * Loads a script into ZAP from the given local file, with the given name, type and engine,
     * optionally with a description
     */
    public ApiResponse load(
            String scriptname,
            String scripttype,
            String scriptengine,
            String filename,
            String scriptdescription)
            throws ClientApiException {
        Map<String, String> map = new HashMap<>();
        map.put("scriptName", scriptname);
        map.put("scriptType", scripttype);
        map.put("scriptEngine", scriptengine);
        map.put("fileName", filename);
        if (scriptdescription != null) {
            map.put("scriptDescription", scriptdescription);
        }
        return api.callApi("script", "action", "load", map);
    }
}


text:
// mingw does not ship with winhttp. So, this class is not available for mingw compiler.
#ifndef __MINGW32__

#include "KInternet.h"
#include <string.h>
#include <stdio.h>

KInternet::KInternet(){}

KInternet::~KInternet(){}

void KInternet::ApplyProxySettings(const wchar_t* url, HINTERNET hInternet)
{
	WINHTTP_CURRENT_USER_IE_PROXY_CONFIG proxyConfig;
	WINHTTP_PROXY_INFO proxyInfoTemp, proxyInfo;
	WINHTTP_AUTOPROXY_OPTIONS OptPAC;

	::ZeroMemory(&proxyConfig, sizeof(WINHTTP_CURRENT_USER_IE_PROXY_CONFIG));
	::ZeroMemory(&proxyInfo, sizeof(WINHTTP_PROXY_INFO));

	if (::WinHttpGetIEProxyConfigForCurrentUser(&proxyConfig))
	{
		if (proxyConfig.lpszProxy) {
			proxyInfo.lpszProxy = proxyConfig.lpszProxy;
			proxyInfo.dwAccessType = WINHTTP_ACCESS_TYPE_NAMED_PROXY;
			proxyInfo.lpszProxyBypass = NULL;
		}

		if (proxyConfig.lpszAutoConfigUrl) {
			// Script proxy pac
			OptPAC.dwFlags = WINHTTP_AUTOPROXY_CONFIG_URL;
			OptPAC.lpszAutoConfigUrl = proxyConfig.lpszAutoConfigUrl;
			OptPAC.dwAutoDetectFlags = 0;
			OptPAC.fAutoLogonIfChallenged = TRUE;
			OptPAC.lpvReserved = 0;
			OptPAC.dwReserved = 0;

			if (::WinHttpGetProxyForUrl(hInternet, url, &OptPAC, &proxyInfoTemp))
				::memcpy(&proxyInfo, &proxyInfoTemp, sizeof(WINHTTP_PROXY_INFO));
		}

		if (proxyConfig.fAutoDetect) {
			// Autodetect proxy
			OptPAC.dwFlags = WINHTTP_AUTOPROXY_AUTO_DETECT;
			OptPAC.dwAutoDetectFlags = WINHTTP_AUTO_DETECT_TYPE_DHCP | WINHTTP_AUTO_DETECT_TYPE_DNS_A;
			OptPAC.fAutoLogonIfChallenged = TRUE;
			OptPAC.lpszAutoConfigUrl = NULL;
			OptPAC.lpvReserved = 0;
			OptPAC.dwReserved = 0;

			if (::WinHttpGetProxyForUrl(hInternet, url, &OptPAC, &proxyInfoTemp))
				::memcpy(&proxyInfo, &proxyInfoTemp, sizeof(WINHTTP_PROXY_INFO));
		}

		if (proxyInfo.lpszProxy)
			::WinHttpSetOption(hInternet, WINHTTP_OPTION_PROXY, &proxyInfo, sizeof(WINHTTP_PROXY_INFO));
	}
}

KString KInternet::UrlEncodeString(const KString &text)
{
	if (text.GetLength() == 0)
		return KString();

	KString new_str;
	char c;
	int ic;
	const char* chars = text;
	char bufHex[10];
	int len = text.GetLength();

	for (int i = 0; i < len; i++)
	{
		c = chars[i];
		ic = c;

		if (c == ' ')
		{
			new_str = new_str.AppendStaticText(L"+", 1, true);
		}
		else if (::isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~')
		{
			char tmp[] = { c, 0 };
			new_str = new_str.Append(KString(tmp));
		}
		else
		{
			::sprintf_s(bufHex, 10, "%X", c);

			if (ic < 16)
				new_str = new_str.AppendStaticText(L"%0", 2, true);
			else
				new_str = new_str.AppendStaticText(L"%", 1, true);

			new_str = new_str.Append(KString(bufHex));
		}
	}
	return new_str;
}

KString KInternet::UrlDecodeString(const KString &text)
{
	if (text.GetLength() == 0)
		return KString();

	KString ret;
	const char* str = text;

	char ch;
	int i, ii, len = text.GetLength();

	for (i = 0; i < len; i++)
	{
		if (str[i] != '%')
		{
			if (str[i] == '+')
			{
				ret = ret.AppendStaticText(L" ", 1, true);
			}
			else
			{
				char tmp[] = { str[i], 0 };
				ret = ret.Append(KString(tmp));
			}
		}
		else
		{
			KString sub(text.SubString(i + 1, i + 2));
			::sscanf_s(sub, "%x", &ii);
			ch = static_cast<char>(ii);

			char tmp[] = { ch, 0 };
			ret = ret.Append(KString(tmp));

			i = i + 2;
		}
	}
	return ret;
}

KString KInternet::PostText(const wchar_t* url,
	const wchar_t* objectName,
	const bool isHttps,
	const char* postData,
	const int postDataLength,
	const bool ignoreCertificateErros,
	const wchar_t* userAgent)
{
	HINTERNET hInternet = 0, hConnect = 0, hRequest = 0;
	BOOL resultOK = FALSE;
	KString receivedText;

	//hInternet = ::WinHttpOpen(userAgent, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
	hInternet = ::WinHttpOpen(userAgent, WINHTTP_ACCESS_TYPE_NO_PROXY, 0, WINHTTP_NO_PROXY_BYPASS, 0);

	if (hInternet)
		KInternet::ApplyProxySettings(url, hInternet);

	if (hInternet)
		hConnect = ::WinHttpConnect(hInternet, url, INTERNET_DEFAULT_PORT, 0);

	if (hConnect)
		hRequest = ::WinHttpOpenRequest(hConnect, L"POST", objectName, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, isHttps ? (WINHTTP_FLAG_REFRESH | WINHTTP_FLAG_SECURE) : WINHTTP_FLAG_REFRESH);

	if (hRequest)
	{
		if (ignoreCertificateErros)
		{
			DWORD dwFlags = SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE | SECURITY_FLAG_IGNORE_CERT_CN_INVALID | SECURITY_FLAG_IGNORE_CERT_DATE_INVALID;
			::WinHttpSetOption(hRequest, WINHTTP_OPTION_SECURITY_FLAGS, &dwFlags, sizeof(DWORD));
		}

		resultOK = ::WinHttpSendRequest(hRequest, L"Content-Type: application/x-www-form-urlencoded\r\n", -1, (LPVOID)postData, postDataLength, postDataLength, 0); // Send a request
	}

	if (resultOK)
		resultOK = ::WinHttpReceiveResponse(hRequest, NULL);

	if (resultOK)
	{
		DWORD dwSize = 0;
		DWORD dwDownloaded = 0;

		do
		{
			dwSize = 0;
			if (::WinHttpQueryDataAvailable(hRequest, &dwSize))
			{
				char* outBuffer = new char[dwSize + 1];
				::ZeroMemory(outBuffer, dwSize + 1);

				if (::WinHttpReadData(hRequest, (LPVOID)outBuffer, dwSize, &dwDownloaded))
				{
					receivedText = receivedText + KString(outBuffer);
				}

				delete[] outBuffer;
			}

		} while (dwSize > 0);
	}

	if (hRequest)
		::WinHttpCloseHandle(hRequest);

	if (hConnect)
		::WinHttpCloseHandle(hConnect);

	if (hInternet)
		::WinHttpCloseHandle(hInternet);

	return receivedText;
}

#endif


text:
CKEDITOR.plugins.setLang( 'quickquestion', 'en',
    {
        insertQuickQuestion: 'Add a quick question box',
        askQuestion: 'Ask you question here',
        showAnswer: 'Show answer',
        addAnswer: 'Insert your answer here'
    }
);


text:
import {Services} from '#service';
import {installDocService} from '#service/ampdoc-impl';

import {
  registerServiceBuilderForDoc,
  resetServiceForTesting,
} from '../../../../src/service-helpers';
import {handleAds} from '../monetization';

describes.realWin(
  'amp-apester-media-monetization',
  {
    amp: {
      extensions: ['amp-apester-media'],
    },
  },
  (env) => {
    let win, doc;
    let baseElement;
    let docInfo;
    const queryAmpAdBladeSelector = (myDoc) =>
      myDoc.querySelector('amp-ad[type=blade]');
    const queryAmpAdAniviewSelector = (myDoc) =>
      myDoc.querySelector('amp-iframe[id=amp-iframe]');
    const queryAmpAdDisplaySelector = (myDoc) =>
      myDoc.querySelector('amp-ad[type=doubleclick]');

    const testRtcConfig = {
      vendors: {
        'vendorA': {'SLOT_ID': '1'},
      },
    };

    beforeEach(() => {
      win = env.win;
      doc = win.document;

      baseElement = doc.createElement('amp-apester-media');
      baseElement.setAttribute('layout', 'fixed-height');

      const mutator = {
        requestChangeSize: () => env.sandbox.stub(),
      };
      env.sandbox.stub(Services, 'mutatorForDoc').returns(mutator);

      doc.body.appendChild(baseElement);
      docInfo = {
        canonicalUrl: 'https://www.example.com/path',
        sourceUrl: 'https://source.example.com/path',
      };
      installDocService(win, /* isSingleDoc */ true);
      resetServiceForTesting(win, 'documentInfo');
      return registerServiceBuilderForDoc(doc, 'documentInfo', function () {
        return {
          get: () => docInfo,
        };
      });
    });

    it('Should show a companion display ad', async () => {
      const media = createCampaignData({display: true});
      await handleAds(media, baseElement);
      const displayAd = queryAmpAdDisplaySelector(doc);
      expect(displayAd).to.exist;
      expect(baseElement.nextSibling).to.be.equal(displayAd);
    });
    it('Should show a companion bottom ad', async () => {
      const media = createCampaignData({display: false, bottomAd: true});
      await handleAds(media, baseElement);
      const bottomAd = queryAmpAdDisplaySelector(doc);
      expect(bottomAd).to.exist;
      expect(baseElement.lastChild).to.be.equal(bottomAd);
    });
    it('Should show an SR companion ad below', async () => {
      const media = createCampaignData({
        display: false,
        srAbove: false,
        srBelow: true,
      });
      await handleAds(media, baseElement);
      const srAdBelow = queryAmpAdBladeSelector(doc);
      expect(srAdBelow).to.exist;
      expect(baseElement.nextSibling).to.be.equal(srAdBelow);
    });
    it('Should show an SR companion ad above', async () => {
      const media = createCampaignData({
        display: false,
        srAbove: true,
        srBelow: false,
      });
      await handleAds(media, baseElement);
      const srAboveAd = queryAmpAdBladeSelector(doc);
      expect(srAboveAd).to.exist;
      expect(baseElement.previousSibling).to.be.equal(srAboveAd);
    });
    it('Should show an Aniview companion ad below', async () => {
      const media = createCampaignData({
        display: false,
        avAbove: false,
        avBelow: true,
      });
      await handleAds(media, baseElement);
      const avAdBelow = queryAmpAdAniviewSelector(doc);
      expect(avAdBelow).to.exist;
      expect(baseElement.nextSibling).to.be.equal(avAdBelow);
    });
    it('Should show an Aniview companion ad above', async () => {
      const media = createCampaignData({
        display: false,
        avAbove: true,
        avBelow: false,
      });
      await handleAds(media, baseElement);
      const avAboveAd = queryAmpAdAniviewSelector(doc);
      expect(avAboveAd).to.exist;
      expect(baseElement.previousSibling).to.be.equal(avAboveAd);
    });
    it('Should show an SR companion above with display companion', async () => {
      const media = createCampaignData({
        display: true,
        srAbove: true,
        srBelow: false,
      });
      await handleAds(media, baseElement);
      const displayAd = queryAmpAdDisplaySelector(doc);
      expect(displayAd).to.exist;
      expect(baseElement.nextSibling).to.be.equal(displayAd);
      const srAboveAd = queryAmpAdBladeSelector(doc);
      expect(srAboveAd).to.exist;
      expect(baseElement.previousSibling).to.be.equal(srAboveAd);
    });
    it('Should not show ads if disabled amp companion ads', async () => {
      const media = createCampaignData({
        display: true,
        bottomAd: true,
        srAbove: true,
        srBelow: false,
        disabledAmpCompanionAds: true,
      });
      await handleAds(media, baseElement);
      const displayAd = queryAmpAdDisplaySelector(doc);
      expect(displayAd).to.not.exist;
      const srAboveAd = queryAmpAdBladeSelector(doc);
      expect(srAboveAd).to.not.exist;
    });
    it('Should not show bottom ad if there no bottomAdOptions', async () => {
      const media = createCampaignData({
        bottomAd: true,
      });
      delete media.campaignData.bottomAdOptions;
      await handleAds(media, baseElement);
      const bottomAd = queryAmpAdDisplaySelector(doc);
      expect(bottomAd).to.not.exist;
    });
    it('Should have rtc-config attribute if set in bottom ad', async () => {
      const media = createCampaignData({
        bottomAd: true,
      });
      media.campaignData.bottomAdOptions.rtcConfig = testRtcConfig;
      await handleAds(media, baseElement);
      const bottomAd = queryAmpAdDisplaySelector(doc);
      expect(bottomAd.getAttribute('rtc-config')).to.exist;
      expect(bottomAd).to.exist;
    });
    it('Should have rtc-config attribute if set companion display ad', async () => {
      const media = createCampaignData({display: true});
      media.campaignData.companionOptions.rtcConfig = testRtcConfig;
      await handleAds(media, baseElement);
      const displayAd = queryAmpAdDisplaySelector(doc);
      expect(displayAd.getAttribute('rtc-config')).to.exist;
      expect(displayAd).to.exist;
    });
    it('Should show Aniview video for in-unit video', async () => {
      const media = createCampaignData({inUnitVideo: true});
      await handleAds(media, baseElement);
      const inUnitVidoe = queryAmpAdAniviewSelector(doc);
      expect(inUnitVidoe).to.exist;
    });
    it('Should not show Aniview video for in-unit video', async () => {
      const media = createCampaignData({inUnitVideo: false});
      await handleAds(media, baseElement);
      const inUnitVidoe = queryAmpAdAniviewSelector(doc);
      expect(inUnitVidoe).to.not.exist;
    });
  }
);

function createCampaignData({
  avAbove,
  avBelow,
  bottomAd,
  disabledAmpCompanionAds,
  display,
  inUnitVideo,
  srAbove,
  srBelow,
}) {
  const media = {};
  const campaignData = {
    'companionOptions': {
      'settings': {
        'slot': '/57806026/Dev_DT_300x250',
        'options': {
          'refreshOnClick': 'none',
          'lockTime': 5000,
        },
        'bannerAdProvider': 'gdt',
        'bannerSizes': [[300, 250]],
      },
      'enabled': false,
      'video': {
        'playerOptions': {
          'aniviewChannelId': '5fad4ac42cd6d91dcb6e50e9',
        },
        'videoTag': '5d14c0ded1fb9900016a3118',
        'enabled': false,
        'floating': {
          'enabled': false,
        },
        'companion': {
          'enabled': false,
        },
        'companion_below': {
          'enabled': false,
        },
        'provider': 'sr',
      },
    },
    'bottomAdOptions': {
      'idleAds': {
        'timeout': null,
      },
      'enabled': false,
      'videoPlayer': 'gpt',
      'tag': '/6355419/Travel/Europe/France/Paris',
      'playerProps': {
        'auctionCode': 'aR1s',
        'dfp': true,
      },
    },
    'companionCampaignOptions': {
      'companionCampaignId': '5d8b267a50bf9482f458d2ca',
    },
  };
  if (display) {
    campaignData.companionOptions.enabled = true;
  }
  if (bottomAd) {
    campaignData.bottomAdOptions.enabled = true;
  }
  if (srAbove) {
    campaignData.companionOptions.video.enabled = true;
    campaignData.companionOptions.video.provider = 'sr';
    campaignData.companionOptions.video.companion.enabled = true;
  }
  if (srBelow) {
    campaignData.companionOptions.video.enabled = true;
    campaignData.companionOptions.video.provider = 'sr';
    campaignData.companionOptions.video.companion_below.enabled = true;
  }
  if (avAbove) {
    campaignData.companionOptions.video.enabled = true;
    campaignData.companionOptions.video.provider = 'aniview';
    campaignData.companionOptions.video.companion.enabled = true;
  }
  if (avBelow) {
    campaignData.companionOptions.video.enabled = true;
    campaignData.companionOptions.video.provider = 'aniview';
    campaignData.companionOptions.video.companion_below.enabled = true;
  }
  if (disabledAmpCompanionAds) {
    campaignData.disabledAmpCompanionAds = true;
  }
  if (inUnitVideo) {
    campaignData.playerOptions = [
      {
        'requests': [
          {
            'type': 'idle',
            'options': {
              'timeout': 5,
              'skipTimer': 10,
            },
          },
        ],
        'player': {
          'type': 'va',
          'provider': {
            'type': 'aniview',
            'options': {
              'aniviewChannelId': '5fad4ac42cd6d91dcb6e50e9',
              'aniviewPlayerId': '5faf2a6e1b1ab26edc3f9173',
            },
          },
          'playerId': 'a5ccbc2f0aff9adba5c9c3f1d7eba69c',
        },
      },
    ];
  }
  media.campaignData = campaignData;
  return media;
}


text:
<?php $this->widget('ext.easyui.EasyuiGrid',array(
		'title'=>Yii::t('project','List NewsCate'),
		'url'=>Yii::app()->createUrl('newscate/loadData'),
		'model'=>'NewsCate',
		'idField'=>'cat_id',
		'htmlOptions'=>array(
			'method'=>'POST',
			'width'=>1250,
			'height'=>630,
		//	'idField'=>'good_id',
			'fitColumns'=>true,
			'nowrap'=>false,
			'rownumbers'=>true,
			'showFooter'=>true,
			'pagination'=>true,
			'rownumbers'=>false,
                        'singleSelect'=>false,
		),
		'toolbar_show'=>array(
			'add'=>array('href'=>Yii::app()->createUrl('newscate/create'),'text'=>'添加新闻分类'),
			'delete'=>array('href'=>Yii::app()->createUrl('newscate/delete'),'text'=>'删除新闻分类'),
			'edit'=>array('href'=>Yii::app()->createUrl('newscate/update')),
			'view'=>array('href'=>Yii::app()->createUrl('newscate/view')),
			'search'=>array('href'=>Yii::app()->createUrl('newscate/loadData'),'text'=>'搜索新闻分类','formTpl'=>'searchNewsCate'),
                        'multiple'=>array('href'=>Yii::app()->createUrl('newscate/updateBatch'),'text'=>'批量更改','formTpl'=>'multipleNewsCate'),
		),
		'columns'=>array(
                        array('field'=>'cat_id','title'=>Yii::t('project',NewsCate::model()->getAttributeLabel('cat_id')),'width'=>80,'checkbox'=>true),
                      //  array('field'=>'good_id','title'=>Yii::t('webshop',Goods::model()->getAttributeLabel('good_id')),'width'=>80),
			array('field'=>'cat_name','title'=>Yii::t('project',NewsCate::model()->getAttributeLabel('cat_name')),'width'=>100,'search'=>true),
                        array('field'=>'cat_alia','title'=>Yii::t('project',NewsCate::model()->getAttributeLabel('cat_alia')),'width'=>30,'search'=>true),
                        array('field'=>'sort_order','title'=>Yii::t('project',NewsCate::model()->getAttributeLabel('sort_order')),'width'=>100,'search'=>true),
		),
	));?>


text:
function runTriplePortExperiment(varargin)

global arduinoConnection arduinoPort
global arduinoMessageString

global p % parameter structure
global info % structure containing mouse name and folder to be saved in
%% Setup

% cleanup routine to be executed even if this function is terminated early
finishup = onCleanup(@triplePortCleanup);

% seed random number generator (to prevent repeating the same values on
% different experiments)
rng('shuffle');

%gets the mouse's name
mouseName = info.mouseName;
%creates the log file name
mouseLog = strcat(mouseName,'_log');
%sets up the logging for mouseLog
setupLogging(mouseLog);

%% log all paramters and inital values
fn = fieldnames(p);
for i=1:length(fn)
    fName = fn{i};
    logValue(fName,p.(fName));
end
rngState = rng;
logValue('RNG Seed', rngState.Seed);
logValue('RNG Type', rngState.Type);

%% set up Arduino
arduinoMessageString = '';
clearPorts();
arduinoPortNum = findArduinoPort();
if ~arduinoPortNum
    disp('Can''t find serial port with Arduino')
    return
end
arduinoConnection = 0;
arduinoPort = setupArduinoSerialPort(arduinoPortNum);
% wait for Arduino startup
fprintf('Waiting for Arduino startup')
while (arduinoConnection == 0)
    fprintf('.');
    pause(0.5);
end
fprintf('\n')

%% setup ports/arduino
global centerPort rightPort leftPort syncPort

centerPort = NosePort(5,13);
centerPort.setLEDPin(8);
centerPort.deactivate();
centerPort.noseInFunc = @centerPortPokeFunc;
logValue('center port ID', centerPort.portID);

rightPort = NosePort(7,4);
rightPort.setLEDPin(9);
rightPort.setRewardDuration(p.rewardDurationRight);
rightPort.setToSingleRewardMode();
rightPort.rewardFunc = @rewardFunc;
rightPort.noseOutFunc = @endTrial;
rightPort.noseInFunc = @noseIn;
logValue('right port ID', rightPort.portID);

leftPort = NosePort(6,3);
leftPort.setLEDPin(10);
leftPort.setRewardDuration(p.rewardDurationLeft);
leftPort.setToSingleRewardMode();
leftPort.rewardFunc = @rewardFunc;
leftPort.noseOutFunc = @endTrial;
leftPort.noseInFunc = @noseIn;
logValue('left port ID', leftPort.portID);

syncPort = NosePort(11,13);
syncPort.deactivate()
syncPort.noseInFunc = @syncIn;
logValue('Sync port ID', syncPort.portID);

global sync_counter
sync_counter = 0;

if p.centerPokeTrigger
    rightPort.deactivate();
    leftPort.deactivate();
else
    rightPort.activate();
    leftPort.activate();
end

%% run trials
global numBlocks
numBlocks = struct;
numBlocks.left = 0;
numBlocks.right = 0;
if p.rightRewardProb >= p.leftRewardProb
    numBlocks.right = 1;
else
    numBlocks.left = 1;
end

global currBlockReward blockRange currBlockSize
currBlockReward = 0;
blockRange = [p.blockRangeMin:p.blockRangeMax];
currBlockSize = randi([min(blockRange),max(blockRange)]);
display(currBlockSize)

global pokeHistory pokeCount
pokeCount = 0;
pokeHistory= struct;

global iti lastPokeTime
iti = p.minInterTrialInterval;
lastPokeTime = clock;

%create stats structure for online analysis and visualization
global stats
% initialize the first entry of stats to be zeros
stats = initializestats;
cumstats = cumsumstats(stats);
%create figure for onilne visualization
global h
h = initializestatsfig(cumstats);

%% run the program.....
%runs as long as info.running has not been set to false via the Stop
%Experiment button
while info.running
    pause(0.1)
        % actively probe whether or note enough time has elapsed to start a
    % new trial. If so, turn on the LED>
    if etime(clock,lastPokeTime) >= iti
        centerPort.ledOn();
    end
end
triplePortCleanup();
end

%% Subfunctions

%% Nose In Functions
function syncIn(portID)
% simply count the inscopix frames in a global variable.
global sync_counter
sync_counter = sync_counter + 1;
end

function noseIn(portID)
global sync_counter sync_frame
sync_frame = sync_counter;

disp('noseIn')
global p
global pokeHistory pokeCount lastPokeTime
global rightPort leftPort centerPort
global activateLeft activateRight
global stats
global iti
global h

pokeCount = pokeCount+1; %increment pokeCount
timeSinceLastPoke = etime(clock,lastPokeTime);

%Update pokeHistory
pokeHistory(pokeCount).timeStamp = now;
if portID == rightPort.portID
    pokeHistory(pokeCount).portPoked = 'rightPort';
elseif portID == leftPort.portID
    pokeHistory(pokeCount).portPoked = 'leftPort';
elseif portID == centerPort.portID
    pokeHistory(pokeCount).portPoked = 'centerPort';
end

%first need to deal with special case of first poke
if pokeCount == 1
    if portID == centerPort.portID
        pokeHistory(pokeCount).isTRIAL = 1;
    else
        pokeHistory(pokeCount).isTRIAL = 0;
    end
%if this is a left or right port, there is a possibility this is the
%decision poke of a trial. If so, there's a bunch of info we need.
elseif portID == rightPort.portID || portID == leftPort.portID
    %check to see if we are in a trial.
    if pokeHistory(pokeCount-1).isTRIAL == 1
        %if we are in a trial, check to see if we are within the
        %response time (p.centerPokeRewardWindow). If so, set
        %pokeHistory.isTrial to 2 (which denotes that this is a
        %decision poke), and set the pokeHistory.trialTime as the time
        %elapsed from the trial iniation (last poke) to now.
        if timeSinceLastPoke <= p.centerPokeRewardWindow
            pokeHistory(pokeCount).isTRIAL = 2;
            pokeHistory(pokeCount).trialTime = etime(clock,lastPokeTime);
            pokeHistory(pokeCount).leftPortStats.prob = p.leftRewardProb;
            pokeHistory(pokeCount).rightPortStats.prob = p.rightRewardProb;
            pokeHistory(pokeCount).leftPortStats.ACTIVATE = activateLeft;
            pokeHistory(pokeCount).rightPortStats.ACTIVATE = activateRight;
            %if a decision is made, turn off the LEDs.
            rightPort.ledOff();
            leftPort.ledOff();
        else %if reward window is passed, than this is not a trial poke
            pokeHistory(pokeCount).isTRIAL = 0;
        end
    else %if we're not in a trial then any left or right poke is an error poke.
        pokeHistory(pokeCount).isTRIAL = 0;
        %and we should turn off the lights until the center port is active
        %again
        centerPort.ledOff();
    end
    %finally have to deal with the center pokes
elseif portID == centerPort.portID
    if pokeHistory(pokeCount-1).isTRIAL == 0 || pokeHistory(pokeCount-1).isTRIAL == 2
        if timeSinceLastPoke >= iti
            pokeHistory(pokeCount).isTRIAL = 1;
        else
            pokeHistory(pokeCount).isTRIAL = 0;
        end
    elseif pokeHistory(pokeCount-1).isTRIAL == 1
        if timeSinceLastPoke < p.centerPokeRewardWindow
            pokeHistory(pokeCount).isTRIAL = 0;
            deactivateSidePorts(); % this type of poke is technically a
            %decision poke in the center, so we should deactivate the
            %ports. I added this line 4/21/16. Before this, two quick pokes
            %in the center followed by a poke on the side could lead to a
            %reward.
            %should also turn off the side LEDs
            rightPort.ledOff();
            leftPort.ledOff();
        elseif timeSinceLastPoke >= iti
            pokeHistory(pokeCount).isTRIAL = 1;
        else
            pokeHistory(pokeCount).isTRIAL = 0;
        end
    end
end
%in order to run update stats, we need a value for pokeHistory.REWARD
pokeHistory(pokeCount).REWARD = 0;

%update stats and refresh figures
stats = updatestats(stats,pokeHistory(pokeCount),pokeCount,sync_frame);
global handlesCopy
leftRewards = sum(stats.rewards.left);
rightRewards = sum(stats.rewards.right);
totalRewards = leftRewards + rightRewards;
leftTrials = sum(stats.trials.left)/2;
rightTrials = sum(stats.trials.right)/2;
totalTrials = leftTrials + rightTrials;
global numBlocks
leftBlocks = numBlocks.left;
rightBlocks = numBlocks.right;
totalBlocks = leftBlocks+rightBlocks;
data = [leftRewards, rightRewards, totalRewards; leftTrials, rightTrials, ...
    totalTrials;leftBlocks,rightBlocks,totalBlocks];
set(handlesCopy.statsTable,'data',data);
cumstats = cumsumstats(stats);
updatestatsfig(cumstats,h,pokeCount);

%update the lastPokeTime
lastPokeTime = clock;

end

function centerPortPokeFunc(portID)
disp('centerPortPokeFunc')
noseIn(portID);

global p pokeHistory pokeCount
global activateLeft activateRight
global centerPort rightPort leftPort

if p.centerPokeTrigger % if we're in centerPokeTrigger mode
    %see if we are currently in a trial
    %Note   isTRIAL == 1 means that centerPort has correctly initiated trial
           %isTRIAL == 0 means that the poke is 'incorrect' and not a trial
           %isTRIAL == 2 means that the poke is a decision poke
    if pokeHistory(pokeCount).isTRIAL == 1;
        centerPort.ledOff();
        leftPort.ledOn();
        rightPort.ledOn();
        executeFunctionWithDelay(@rightPort.ledOff,p.centerPokeRewardWindow);
        executeFunctionWithDelay(@leftPort.ledOff,p.centerPokeRewardWindow);
        %activate side ports with appropriate probs
        activateLeft = (rand <= p.leftRewardProb); % activate left port with prob = p.leftRewardProb
        activateRight = (rand <= p.rightRewardProb); % activate right port with prob = p.rightRewardProb
        activateSidePortsForDuration(activateLeft, activateRight, p.centerPokeRewardWindow);
    end
end
end

%% Activate / deactivate side port functions

function activateSidePortsForDuration(activateLeft, activateRight, rewardWindow)
disp(sprintf('activateSidePorts:  R:%g  L:%g', activateRight, activateLeft));
global rightPort leftPort deactivateTimer

% activate only the desired port(s)
if activateRight
    rightPort.activate();
end
if activateLeft
    leftPort.activate();
end
deactivateTimer = executeFunctionWithDelay(@deactivateSidePorts, rewardWindow);
end

function activateBothSidePorts()
disp('activateBothSidePorts')
global rightPort leftPort
rightPort.activate();
leftPort.activate();
end

function deactivateSidePorts()
disp('deactivateSidePorts')
global rightPort leftPort deactivateTimer
try
    stop(deactivateTimer)
end
rightPort.deactivate();
leftPort.deactivate();

end

%% Reward Function
function rewardFunc(portID)
disp('rewardFunc')
global p reactivateTimer
global pokeHistory pokeCount stats sync_frame
global h
global currBlockReward blockRange currBlockSize

currBlockReward = currBlockReward + 1;
display(currBlockReward)

% log rewarded port to poke history
pokeHistory(pokeCount).REWARD = 1;
%update stats and refresh figures
stats = updatestats(stats,pokeHistory(pokeCount),pokeCount,sync_frame);
cumstats = cumsumstats(stats);
updatestatsfig(cumstats,h,pokeCount);

if p.centerPokeTrigger % if we're in centerPokeTrigger mode
    deactivateSidePorts();
else
    % deactive; wait x seconds; reactive
    deactivateSidePorts();
    reactivateTimer = executeFunctionWithDelay(@activateBothSidePorts, p.minInterTrialInterval);
end

%reupdate reward probabilities if needed.
if currBlockReward >= currBlockSize
    p.leftRewardProb = 1 - p.leftRewardProb;
    p.rightRewardProb = 1 - p.rightRewardProb;
    currBlockReward = 0;
    currBlockSize = randi([min(blockRange),max(blockRange)]);
    display('Reward Probabilities Switched')
    display('Left Reward Prob:')
    p.leftRewardProb
    display('Right Reward Prob:')
    p.rightRewardProb
    display('Current Block Size:')
    global numBlocks
    if p.rightRewardProb >= p.leftRewardProb
        numBlocks.right = numBlocks.right + 1;
    else
        numBlocks.left = numBlocks.left + 1;
    end
    currBlockSize
end

end

%% End Trial Function
function endTrial()
global p
if p.centerPokeTrigger % if we're in centerPokeTrigger mode
    disp('endTrial')
    deactivateSidePorts();
end
end

%% cleanup function is run when program ends (either naturally or after ctl-c)
function triplePortCleanup()
disp('Cleaning up...')

%turn all LEDs off
global centerPort rightPort leftPort
centerPort.ledOff();
rightPort.ledOff();
leftPort.ledOff();

%close log file
global logFileID AllNosePorts
fclose(logFileID);

%deactivate any nose ports (just to make sure)
for n = AllNosePorts
    n{1}.deactivate();
end
AllNosePorts = {};
clearPorts(); %clear nose ports

% prompt user to select directory to save pokeHistory
global info
global p h
%if user chose to save the data
if info.save == 1
    global pokeHistory stats
    folderName = info.folderName;
    cd(folderName);
    currDay = datestr(date);
    %save pokeHistory and stats variables
    save(strcat('pokeHistory',currDay,'.mat'),'pokeHistory');
    save(strcat('stats',currDay,'.mat'),'stats');
    figHandles = findobj('Type','figure');
    % now that we have multiple figures (ie. the gui) we need to loop
    % through all the figure handles, find the one that is that stats fig,
    % and save it to the current directory.
    for i = 1:size(figHandles,1)
        if strcmpi('Stats Figure',figHandles(i).Name)
            savefig(figHandles(i),'stats.fig');
        end
    end
   %properly formats the parameters and saves them in the same format as
   %the log
    parameters = strcat(info.mouseName,'_parameters');
    baseName = [parameters, '_', int2str(yyyymmdd(datetime)), '_'];
    fileCounter = 1;
    fName = [baseName, int2str(fileCounter), '.mat'];
    while (exist(fName, 'file'))
        fileCounter = fileCounter + 1;
        fName = [baseName, int2str(fileCounter), '.mat'];
    end
    save(fName,'p');
end
close 'Stats Figure'
end


text:
'use strict';

// http://stackoverflow.com/questions/10343913/how-to-create-a-web-worker-from-a-string

var URL = window.URL || window.webkitURL;

module.exports = function (content, url) {
  try {
    try {
      var blob;

      try {
        // BlobBuilder = Deprecated, but widely implemented
        var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;

        blob = new BlobBuilder();

        blob.append(content);

        blob = blob.getBlob();
      } catch (e) {
        // The proposed API
        blob = new Blob([content]);
      }

      return new Worker(URL.createObjectURL(blob));
    } catch (e) {
      return new Worker('data:application/javascript,' + encodeURIComponent(content));
    }
  } catch (e) {
    if (!url) {
      throw Error('Inline worker is not supported');
    }

    return new Worker(url);
  }
};


text:
require "fast_uri/version"
require "fast_uri/fast_uri"

module FastURI
end