text:
<!DOCTYPE html>

    <meta charset='utf-8'>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta http-equiv="Content-Language" content="en">

    <title>Detectizr/detectizr.js at master · barisaydinoglu/Detectizr</title>
    <link rel="search" type="application/opensearchdescription+xml" href="/opensearch.xml" title="GitHub">
    <link rel="fluid-icon" href="https://github.com/fluidicon.png" title="GitHub">
    <link rel="apple-touch-icon" sizes="57x57" href="/apple-touch-icon-114.png">
    <link rel="apple-touch-icon" sizes="114x114" href="/apple-touch-icon-114.png">
    <link rel="apple-touch-icon" sizes="72x72" href="/apple-touch-icon-144.png">
    <link rel="apple-touch-icon" sizes="144x144" href="/apple-touch-icon-144.png">
    <meta property="fb:app_id" content="1401488693436528">

      <meta content="@github" name="twitter:site" /><meta content="summary" name="twitter:card" /><meta content="barisaydinoglu/Detectizr" name="twitter:title" /><meta content="Detectizr - A Modernizr extension to detect device, device model, screen size, operating system, and browser details" name="twitter:description" /><meta content="https://avatars2.githubusercontent.com/u/900545?v=2&s=400" name="twitter:image:src" />
<meta content="GitHub" property="og:site_name" /><meta content="object" property="og:type" /><meta content="https://avatars2.githubusercontent.com/u/900545?v=2&s=400" property="og:image" /><meta content="barisaydinoglu/Detectizr" property="og:title" /><meta content="https://github.com/barisaydinoglu/Detectizr" property="og:url" /><meta content="Detectizr - A Modernizr extension to detect device, device model, screen size, operating system, and browser details" property="og:description" />

    <link rel="assets" href="https://assets-cdn.github.com/">
    <link rel="conduit-xhr" href="https://ghconduit.com:25035">
    <link rel="xhr-socket" href="/_sockets">

    <meta name="msapplication-TileImage" content="/windows-tile.png">
    <meta name="msapplication-TileColor" content="#ffffff">
    <meta name="selected-link" value="repo_source" data-pjax-transient>
      <meta name="google-analytics" content="UA-3769691-2">

    <meta content="collector.githubapp.com" name="octolytics-host" /><meta content="collector-cdn.github.com" name="octolytics-script-host" /><meta content="github" name="octolytics-app-id" /><meta content="C3611E97:6A4A:193EB8C6:54084D58" name="octolytics-dimension-request_id" /><meta content="803983" name="octolytics-actor-id" /><meta content="mxa055" name="octolytics-actor-login" /><meta content="a42c0130ee8cef1af93552875d3aa29275323d6ff062d7b1a5b9a00fbed6c3ee" name="octolytics-actor-hash" />

    <link rel="icon" type="image/x-icon" href="https://assets-cdn.github.com/favicon.ico">

    <meta content="authenticity_token" name="csrf-param" />
<meta content="fmpCrk7RxwXDMeSeCD/iKeLYPQADXDb81GNQFwNIdToNmhSUf+AgrWtfZ+ofW3f4bY31qQcxyqqlrfrSzqxB4A==" name="csrf-token" />

    <link href="https://assets-cdn.github.com/assets/github-c0c2293be58dbb87efbe15f0252a75aa7f738724.css" media="all" rel="stylesheet" type="text/css" />
    <link href="https://assets-cdn.github.com/assets/github2-2c7d4f87e135381585a949e74aa65d44cca0232f.css" media="all" rel="stylesheet" type="text/css" />

    <meta http-equiv="x-pjax-version" content="62537849d5f6d9949c1a651bcb33b773">

  <meta name="description" content="Detectizr - A Modernizr extension to detect device, device model, screen size, operating system, and browser details">
  <meta name="go-import" content="github.com/barisaydinoglu/Detectizr git https://github.com/barisaydinoglu/Detectizr.git">

  <meta content="900545" name="octolytics-dimension-user_id" /><meta content="barisaydinoglu" name="octolytics-dimension-user_login" /><meta content="4248810" name="octolytics-dimension-repository_id" /><meta content="barisaydinoglu/Detectizr" name="octolytics-dimension-repository_nwo" /><meta content="true" name="octolytics-dimension-repository_public" /><meta content="false" name="octolytics-dimension-repository_is_fork" /><meta content="4248810" name="octolytics-dimension-repository_network_root_id" /><meta content="barisaydinoglu/Detectizr" name="octolytics-dimension-repository_network_root_nwo" />
  <link href="https://github.com/barisaydinoglu/Detectizr/commits/master.atom" rel="alternate" title="Recent Commits to Detectizr:master" type="application/atom+xml">

    Skip to content

          <form accept-charset="UTF-8" action="/barisaydinoglu/Detectizr/search" class="js-site-search-form" data-global-search-url="/search" data-repo-search-url="/barisaydinoglu/Detectizr/search" method="get">
<input name="utf8" type="hidden" value="✓" />

  <input type="text"
    class="js-site-search-field is-clearable"
    data-hotkey="s"
    name="q"
    placeholder="Search"
    data-global-scope-placeholder="Search GitHub"
    data-repo-scope-placeholder="Search"
    tabindex="1"
    autocapitalize="off">

This repository

</form>

          Explore

            Gist

            Blog

          Help

        mxa055

     New repository

     New organization

      This repository

         New issue

    <form accept-charset="UTF-8" action="/logout" class="logout-form" method="post">
<input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="p89CNahovSzhj2lQI2vE9jOnV+gbYManCOB8EGSeZ50XdgXJCD1lOPRHDEYrf/SYlSvmfh5l32RQ8ge0z3hl5g==" />

      <button class="header-nav-link sign-out-button tooltipped tooltipped-s" aria-label="Sign out" data-ga-click="Header, sign out, icon:logout">

      </button>
</form>

      <form accept-charset="UTF-8" action="/notifications/subscribe" class="js-social-container" data-autosubmit="true" data-remote="true" method="post">
<input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="qRZFTn8Jfd1KgDATgHl+V5LcrQ0ClmYTSaB91nEdZjnP3gELaTgkYzs5pm+jxLN9D5eWPdzPMl+WacDgQSplzA==" />
  <input id="repository_id" name="repository_id" type="hidden" value="4248810" />

        20

          Watch

            Notifications

                <input checked="checked" id="do_included" name="do" type="radio" value="included" />

Not watching

                Be notified when participating or @mentioned.

                  Watch

                <input id="do_subscribed" name="do" type="radio" value="subscribed" />

Watching

                Be notified of all conversations.

                  Unwatch

                <input id="do_ignore" name="do" type="radio" value="ignore" />

Ignoring

                Never be notified.

                  Stop ignoring

</form>

    <form accept-charset="UTF-8" action="/barisaydinoglu/Detectizr/unstar" class="js-toggler-form starred js-unstar-button" data-remote="true" method="post">
<input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="VLFcmBdlkvVIsby37PpCGfb078zyS8hu5nEo0dIHeqsrm1uM4Y99OeLxh310s9TzDQU8FS8nM1LCNVYbFx5Y3g==" />

      <button
        class="minibutton with-count js-toggler-target star-button"
        aria-label="Unstar this repository" title="Unstar barisaydinoglu/Detectizr">

        Unstar
      </button>

          137

</form>
    <form accept-charset="UTF-8" action="/barisaydinoglu/Detectizr/star" class="js-toggler-form unstarred js-star-button" data-remote="true" method="post">
<input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="wtzY7kb6wbGdgv/+EYiui0zT/E+d07lHxEoMHdayF5Gm6VrDd4xrUo3+WH4yPancZBlq7GDl4K3opM6b4hEQvQ==" />

      <button
        class="minibutton with-count js-toggler-target star-button"
        aria-label="Star this repository" title="Star barisaydinoglu/Detectizr">

        Star
      </button>

          137

</form>

            Fork

          33

          barisaydinoglu/Detectizr

           Code

             Issues

             Pull Requests

             Wiki

           Pulse

           Graphs

HTTPS clone URL

    <input type="text" class="input-mini input-monospace js-url-field"
           value="https://github.com/barisaydinoglu/Detectizr.git" readonly="readonly">

      <button aria-label="Copy to clipboard" class="js-zeroclipboard minibutton zeroclipboard-button" data-clipboard-text="https://github.com/barisaydinoglu/Detectizr.git" data-copied-hint="Copied!" type="button"></button>

SSH clone URL

    <input type="text" class="input-mini input-monospace js-url-field"
           value="git@github.com:barisaydinoglu/Detectizr.git" readonly="readonly">

      <button aria-label="Copy to clipboard" class="js-zeroclipboard minibutton zeroclipboard-button" data-clipboard-text="git@github.com:barisaydinoglu/Detectizr.git" data-copied-hint="Copied!" type="button"></button>

Subversion checkout URL

    <input type="text" class="input-mini input-monospace js-url-field"
           value="https://github.com/barisaydinoglu/Detectizr" readonly="readonly">

      <button aria-label="Copy to clipboard" class="js-zeroclipboard minibutton zeroclipboard-button" data-clipboard-text="https://github.com/barisaydinoglu/Detectizr" data-copied-hint="Copied!" type="button"></button>

You can clone with
      HTTPS,
      SSH,
      or Subversion.

    Clone in Desktop

                  Download ZIP

Permalink

    branch:
    master

        Switch branches/tags

          <input type="text" aria-label="Filter branches/tags" id="context-commitish-filter-field" class="js-filterable-field js-navigation-enable" placeholder="Filter branches/tags">

              Branches

              Tags

              gh-pages

              master

Nothing to show

              v2.0.0

              v1.5.0

              v1.4.5

Nothing to show

    <button class="js-zeroclipboard minibutton zeroclipboard-button"
          data-clipboard-text="dist/detectizr.js"
          aria-label="Copy to clipboard"
          data-copied-hint="Copied!">

    </button>

    Detectizr / dist / detectizr.js

        barisaydinoglu
        <time datetime="2014-03-21T19:21:34+02:00" is="relative-time">March 21, 2014</time>

            Update version to 2.0.0

          1
           contributor

Users who have contributed to this file

            barisaydinoglu

          503 lines (482 sloc)

        16.805 kb

          Raw
            Blame
          History

        window.Detectizr = (function(window, navigator, document, undefined) {

        	var Detectizr = {},

        		Modernizr = window.Modernizr,

        		deviceTypes = [ "tv", "tablet", "mobile", "desktop" ],

        		options = {

        			// option for enabling HTML classes of all features (not only the true features) to be added

        			addAllFeaturesAsClass: false,

        			// option for enabling detection of device

        			detectDevice: true,

        			// option for enabling detection of device model

        			detectDeviceModel: true,

        			// option for enabling detection of screen size

        			detectScreen: true,

        			// option for enabling detection of operating system type and version

        			detectOS: true,

        			// option for enabling detection of browser type and version

        			detectBrowser: true,

        			// option for enabling detection of common browser plugins

        			detectPlugins: true

        		},

        		plugins2detect = [ {

        			name: "adobereader",

        			substrs: [ "Adobe", "Acrobat" ],

        			// AcroPDF.PDF is used by version 7 and later

        			// PDF.PdfCtrl is used by version 6 and earlier

        			progIds: [ "AcroPDF.PDF", "PDF.PDFCtrl.5" ]

        		}, {

        			name: "flash",

        			substrs: [ "Shockwave Flash" ],

        			progIds: [ "ShockwaveFlash.ShockwaveFlash.1" ]

        		}, {

        			name: "wmplayer",

        			substrs: [ "Windows Media" ],

        			progIds: [ "wmplayer.ocx" ]

        		}, {

        			name: "silverlight",

        			substrs: [ "Silverlight" ],

        			progIds: [ "AgControl.AgControl" ]

        		}, {

        			name: "quicktime",

        			substrs: [ "QuickTime" ],

        			progIds: [ "QuickTime.QuickTime" ]

        		} ],

        		rclass = /[\t\r\n]/g,

        		docElement = document.documentElement,

        		resizeTimeoutId,

        		oldOrientation;

        	function extend(obj, extObj) {

        		var a, b, i;

        		if (arguments.length > 2) {

        			for (a = 1, b = arguments.length; a < b; a += 1) {

        				extend(obj, arguments[a]);

        			}

        		} else {

        			for (i in extObj) {

        				if (extObj.hasOwnProperty(i)) {

        					obj[i] = extObj[i];

        				}

        			}

        		}

        		return obj;

        	}

        	// simplified and localized indexOf method as one parameter fixed as useragent

        	function is(key) {

        		return Detectizr.browser.userAgent.indexOf(key) > -1;

        	}

        	// simplified and localized regex test method as one parameter fixed as useragent

        	function test(regex) {

        		return regex.test(Detectizr.browser.userAgent);

        	}

        	// simplified and localized regex exec method as one parameter fixed as useragent

        	function exec(regex) {

        		return regex.exec(Detectizr.browser.userAgent);

        	}

        	// localized string trim method

        	function trim(value) {

        		return value.replace(/^\s+|\s+$/g, "");

        	}

        	// convert string to camelcase

        	function toCamel(string) {

        		if (string === null || string === undefined) {

        			return "";

        		}

        		return String(string).replace(/((\s|\-|\.)+[a-z0-9])/g, function($1) {

        			return $1.toUpperCase().replace(/(\s|\-|\.)/g, "");

        		});

        	}

        	// removeClass function inspired from jQuery.removeClass

        	function removeClass(element, value) {

        		var class2remove = value || "",

        			cur = element.nodeType === 1 && (element.className ? (" " + element.className + " ").replace(rclass, " ") : "");

        		if (cur) {

        			while (cur.indexOf(" " + class2remove + " ") >= 0) {

        				cur = cur.replace(" " + class2remove + " ", " ");

        			}

        			element.className = value ? trim(cur) : "";

        		}

        	}

        	// add version test to Modernizr

        	function addVersionTest(version, major, minor) {

        		if ( !!version) {

        			version = toCamel(version);

        			if ( !!major) {

        				major = toCamel(major);

        				addConditionalTest(version + major, true);

        				if ( !!minor) {

        					addConditionalTest(version + major + "_" + minor, true);

        				}

        			}

        		}

        	}

        	function checkOrientation() {

        		//timeout wrapper points with doResizeCode as callback

        		window.clearTimeout(resizeTimeoutId);

        		resizeTimeoutId = window.setTimeout(function() {

        			oldOrientation = Detectizr.device.orientation;

        			//wrapper for height/width check

        			if (window.innerHeight > window.innerWidth) {

        				Detectizr.device.orientation = "portrait";

        			} else {

        				Detectizr.device.orientation = "landscape";

        			}

        			addConditionalTest(Detectizr.device.orientation, true);

        			if (oldOrientation !== Detectizr.device.orientation) {

        				addConditionalTest(oldOrientation, false);

        			}

        		}, 10);

        	}

        	// add test to Modernizr based on a condition

        	function addConditionalTest(feature, test) {

        		if ( !!feature && !!Modernizr) {

        			if (options.addAllFeaturesAsClass) {

        				Modernizr.addTest(feature, test);

        			} else {

        				test = typeof test === "function" ? test() : test;

        				if (test) {

        					Modernizr.addTest(feature, true);

        				} else {

        					delete Modernizr[feature];

        					removeClass(docElement, feature);

        				}

        			}

        		}

        	}

        	// set version based on versionFull

        	function setVersion(versionType, versionFull) {

        		versionType.version = versionFull;

        		var versionArray = versionFull.split(".");

        		if (versionArray.length > 0) {

        			versionArray = versionArray.reverse();

        			versionType.major = versionArray.pop();

        			if (versionArray.length > 0) {

        				versionType.minor = versionArray.pop();

        				if (versionArray.length > 0) {

        					versionArray = versionArray.reverse();

        					versionType.patch = versionArray.join(".");

        				} else {

        					versionType.patch = "0";

        				}

        			} else {

        				versionType.minor = "0";

        			}

        		} else {

        			versionType.major = "0";

        		}

        	}

        	function detect(opt) {

        		// Create Global "extend" method, so Detectizr does not need jQuery.extend

        		var that = this,

        			i, j, k, device, os, browser, plugin2detect, pluginFound;

        		options = extend({}, options, opt || {});

        		/** Device detection **/

        		if (options.detectDevice) {

        			Detectizr.device = {

        				type: "",

        				model: "",

        				orientation: ""

        			};

        			device = Detectizr.device;

        			if (test(/googletv|smarttv|internet.tv|netcast|nettv|appletv|boxee|kylo|roku|dlnadoc|ce\-html/)) {

        				// Check if user agent is a smart tv

        				device.type = deviceTypes[0];

        				device.model = "smartTv";

        			} else if (test(/xbox|playstation.3|wii/)) {

        				// Check if user agent is a game console

        				device.type = deviceTypes[0];

        				device.model = "gameConsole";

        			} else if (test(/ip(a|ro)d/)) {

        				// Check if user agent is a iPad

        				device.type = deviceTypes[1];

        				device.model = "ipad";

        			} else if ((test(/tablet/) && !test(/rx-34/)) || test(/folio/)) {

        				// Check if user agent is a Tablet

        				device.type = deviceTypes[1];

        				device.model = String(exec(/playbook/) || "");

        			} else if (test(/linux/) && test(/android/) && !test(/fennec|mobi|htc.magic|htcX06ht|nexus.one|sc-02b|fone.945/)) {

        				// Check if user agent is an Android Tablet

        				device.type = deviceTypes[1];

        				device.model = "android";

        			} else if (test(/kindle/) || (test(/mac.os/) && test(/silk/))) {

        				// Check if user agent is a Kindle or Kindle Fire

        				device.type = deviceTypes[1];

        				device.model = "kindle";

        			} else if (test(/gt-p10|sc-01c|shw-m180s|sgh-t849|sch-i800|shw-m180l|sph-p100|sgh-i987|zt180|htc(.flyer|\_flyer)|sprint.atp51|viewpad7|pandigital(sprnova|nova)|ideos.s7|dell.streak.7|advent.vega|a101it|a70bht|mid7015|next2|nook/) || (test(/mb511/) && test(/rutem/))) {

        				// Check if user agent is a pre Android 3.0 Tablet

        				device.type = deviceTypes[1];

        				device.model = "android";

        			} else if (test(/bb10/)) {

        				// Check if user agent is a BB10 device

        				device.type = deviceTypes[1];

        				device.model = "blackberry";

        			} else {

        				// Check if user agent is one of common mobile types

        				device.model = exec(/iphone|ipod|android|blackberry|opera mini|opera mobi|skyfire|maemo|windows phone|palm|iemobile|symbian|symbianos|fennec|j2me/);

        				if (device.model !== null) {

        					device.type = deviceTypes[2];

        					device.model = String(device.model);

        				} else {

        					device.model = "";

        					if (test(/bolt|fennec|iris|maemo|minimo|mobi|mowser|netfront|novarra|prism|rx-34|skyfire|tear|xv6875|xv6975|google.wireless.transcoder/)) {

        						// Check if user agent is unique Mobile User Agent

        						device.type = deviceTypes[2];

        					} else if (test(/opera/) && test(/windows.nt.5/) && test(/htc|xda|mini|vario|samsung\-gt\-i8000|samsung\-sgh\-i9/)) {

        						// Check if user agent is an odd Opera User Agent - http://goo.gl/nK90K

        						device.type = deviceTypes[2];

        					} else if ((test(/windows.(nt|xp|me|9)/) && !test(/phone/)) || test(/win(9|.9|nt)/) || test(/\(windows 8\)/)) {

        						// Check if user agent is Windows Desktop, "(Windows 8)" Chrome extra exception

        						device.type = deviceTypes[3];

        					} else if (test(/macintosh|powerpc/) && !test(/silk/)) {

        						// Check if agent is Mac Desktop

        						device.type = deviceTypes[3];

        						device.model = "mac";

        					} else if (test(/linux/) && test(/x11/)) {

        						// Check if user agent is a Linux Desktop

        						device.type = deviceTypes[3];

        					} else if (test(/solaris|sunos|bsd/)) {

        						// Check if user agent is a Solaris, SunOS, BSD Desktop

        						device.type = deviceTypes[3];

        					} else if (test(/bot|crawler|spider|yahoo|ia_archiver|covario-ids|findlinks|dataparksearch|larbin|mediapartners-google|ng-search|snappy|teoma|jeeves|tineye/) && !test(/mobile/)) {

        						// Check if user agent is a Desktop BOT/Crawler/Spider

        						device.type = deviceTypes[3];

        						device.model = "crawler";

        					} else {

        						// Otherwise assume it is a Mobile Device

        						device.type = deviceTypes[2];

        					}

        				}

        			}

        			for (i = 0, j = deviceTypes.length; i < j; i += 1) {

        				addConditionalTest(deviceTypes[i], (device.type === deviceTypes[i]));

        			}

        			if (options.detectDeviceModel) {

        				addConditionalTest(toCamel(device.model), true);

        			}

        		}

        		/** Screen detection **/

        		if (options.detectScreen) {

        			if ( !!Modernizr && !!Modernizr.mq) {

        				addConditionalTest("smallScreen", Modernizr.mq("only screen and (max-width: 480px)"));

        				addConditionalTest("verySmallScreen", Modernizr.mq("only screen and (max-width: 320px)"));

        				addConditionalTest("veryVerySmallScreen", Modernizr.mq("only screen and (max-width: 240px)"));

        			}

        			if (device.type === deviceTypes[1] || device.type === deviceTypes[2]) {

        				window.onresize = function(event) {

        					checkOrientation(event);

        				};

        				checkOrientation();

        			} else {

        				device.orientation = "landscape";

        				addConditionalTest(device.orientation, true);

        			}

        		}

        		/** OS detection **/

        		if (options.detectOS) {

        			Detectizr.os = {};

        			os = Detectizr.os;

        			if (device.model !== "") {

        				if (device.model === "ipad" || device.model === "iphone" || device.model === "ipod") {

        					os.name = "ios";

        					setVersion(os, (test(/os\s([\d_]+)/) ? RegExp.$1 : "").replace(/_/g, "."));

        				} else if (device.model === "android") {

        					os.name = "android";

        					setVersion(os, (test(/android\s([\d\.]+)/) ? RegExp.$1 : ""));

        				} else if (device.model === "blackberry") {

        					os.name = "blackberry";

        					setVersion(os, (test(/version\/([^\s]+)/) ? RegExp.$1 : ""));

        				} else if (device.model === "playbook") {

        					os.name = "blackberry";

        					setVersion(os, (test(/os ([^\s]+)/) ? RegExp.$1.replace(";", "") : ""));

        				}

        			}

        			if (!os.name) {

        				if (is("win") || is("16bit")) {

        					os.name = "windows";

        					if (is("windows nt 6.3")) {

        						setVersion(os, "8.1");

        					} else if (is("windows nt 6.2") || test(/\(windows 8\)/)) { //windows 8 chrome mac fix

        						setVersion(os, "8");

        					} else if (is("windows nt 6.1")) {

        						setVersion(os, "7");

        					} else if (is("windows nt 6.0")) {

        						setVersion(os, "vista");

        					} else if (is("windows nt 5.2") || is("windows nt 5.1") || is("windows xp")) {

        						setVersion(os, "xp");

        					} else if (is("windows nt 5.0") || is("windows 2000")) {

        						setVersion(os, "2k");

        					} else if (is("winnt") || is("windows nt")) {

        						setVersion(os, "nt");

        					} else if (is("win98") || is("windows 98")) {

        						setVersion(os, "98");

        					} else if (is("win95") || is("windows 95")) {

        						setVersion(os, "95");

        					}

        				} else if (is("mac") || is("darwin")) {

        					os.name = "mac os";

        					if (is("68k") || is("68000")) {

        						setVersion(os, "68k");

        					} else if (is("ppc") || is("powerpc")) {

        						setVersion(os, "ppc");

        					} else if (is("os x")) {

        						setVersion(os, (test(/os\sx\s([\d_]+)/) ? RegExp.$1 : "os x").replace(/_/g, "."));

        					}

        				} else if (is("webtv")) {

        					os.name = "webtv";

        				} else if (is("x11") || is("inux")) {

        					os.name = "linux";

        				} else if (is("sunos")) {

        					os.name = "sun";

        				} else if (is("irix")) {

        					os.name = "irix";

        				} else if (is("freebsd")) {

        					os.name = "freebsd";

        				} else if (is("bsd")) {

        					os.name = "bsd";

        				}

        			}

        			if ( !!os.name) {

        				addConditionalTest(os.name, true);

        				if ( !!os.major) {

        					addVersionTest(os.name, os.major);

        					if ( !!os.minor) {

        						addVersionTest(os.name, os.major, os.minor);

        					}

        				}

        			}

        			if (test(/\sx64|\sx86|\swin64|\swow64|\samd64/)) {

        				os.addressRegisterSize = "64bit";

        			} else {

        				os.addressRegisterSize = "32bit";

        			}

        			addConditionalTest(os.addressRegisterSize, true);

        		}

        		/** Browser detection **/

        		if (options.detectBrowser) {

        			browser = Detectizr.browser;

        			if (!test(/opera|webtv/) && (test(/msie\s([\d\w\.]+)/) || is("trident"))) {

        				browser.engine = "trident";

        				browser.name = "ie";

        				if (!window.addEventListener && document.documentMode && document.documentMode === 7) {

        					setVersion(browser, "8.compat");

        				} else if (test(/trident.*rv[ :](\d+)\./)) {

        					setVersion(browser, RegExp.$1);

        				} else {

        					setVersion(browser, (test(/trident\/4\.0/) ? "8" : RegExp.$1));

        				}

        			} else if (is("firefox")) {

        				browser.engine = "gecko";

        				browser.name = "firefox";

        				setVersion(browser, (test(/firefox\/([\d\w\.]+)/) ? RegExp.$1 : ""));

        			} else if (is("gecko/")) {

        				browser.engine = "gecko";

        			} else if (is("opera")) {

        				browser.name = "opera";

        				browser.engine = "presto";

        				setVersion(browser, (test(/version\/([\d\.]+)/) ? RegExp.$1 : (test(/opera(\s|\/)([\d\.]+)/) ? RegExp.$2 : "")));

        			} else if (is("konqueror")) {

        				browser.name = "konqueror";

        			} else if (is("chrome")) {

        				browser.engine = "webkit";

        				browser.name = "chrome";

        				setVersion(browser, (test(/chrome\/([\d\.]+)/) ? RegExp.$1 : ""));

        			} else if (is("iron")) {

        				browser.engine = "webkit";

        				browser.name = "iron";

        			} else if (is("crios")) {

        				browser.name = "chrome";

        				browser.engine = "webkit";

        				setVersion(browser, (test(/crios\/([\d\.]+)/) ? RegExp.$1 : ""));

        			} else if (is("applewebkit/")) {

        				browser.name = "safari";

        				browser.engine = "webkit";

        				setVersion(browser, (test(/version\/([\d\.]+)/) ? RegExp.$1 : ""));

        			} else if (is("mozilla/")) {

        				browser.engine = "gecko";

        			}

        			if ( !!browser.name) {

        				addConditionalTest(browser.name, true);

        				if ( !!browser.major) {

        					addVersionTest(browser.name, browser.major);

        					if ( !!browser.minor) {

        						addVersionTest(browser.name, browser.major, browser.minor);

        					}

        				}

        			}

        			addConditionalTest(browser.engine, true);

        			// Browser Language

        			browser.language = navigator.userLanguage || navigator.language;

        			addConditionalTest(browser.language, true);

        		}

        		/** Plugin detection **/

        		if (options.detectPlugins) {

        			browser.plugins = [];

        			that.detectPlugin = function(substrs) {

        				var plugins = navigator.plugins,

        					plugin, haystack, pluginFoundText;

        				for (j = plugins.length - 1; j >= 0; j--) {

        					plugin = plugins[j];

        					haystack = plugin.name + plugin.description;

        					pluginFoundText = 0;

        					for (k = substrs.length; k >= 0; k--) {

        						if (haystack.indexOf(substrs[k]) !== -1) {

        							pluginFoundText += 1;

        						}

        					}

        					if (pluginFoundText === substrs.length) {

        						return true;

        					}

        				}

        				return false;

        			};

        			that.detectObject = function(progIds) {

        				for (j = progIds.length - 1; j >= 0; j--) {

        					try {

        						new ActiveXObject(progIds[j]);

        					} catch (e) {

        						// Ignore

        					}

        				}

        				return false;

        			};

        			for (i = plugins2detect.length - 1; i >= 0; i--) {

        				plugin2detect = plugins2detect[i];

        				pluginFound = false;

        				if (window.ActiveXObject) {

        					pluginFound = that.detectObject(plugin2detect.progIds);

        				} else if (navigator.plugins) {

        					pluginFound = that.detectPlugin(plugin2detect.substrs);

        				}

        				if (pluginFound) {

        					browser.plugins.push(plugin2detect.name);

        					addConditionalTest(plugin2detect.name, true);

        				}

        			}

        			if (navigator.javaEnabled()) {

        				browser.plugins.push("java");

        				addConditionalTest("java", true);

        			}

        		}

        	}

        	Detectizr.detect = function(settings) {

        		return detect(settings);

        	};

        	Detectizr.init = function() {

        		if (Detectizr !== undefined) {

        			Detectizr.browser = {

        				userAgent: (navigator.userAgent || navigator.vendor || window.opera).toLowerCase()

        			};

        			Detectizr.detect();

        		}

        	};

        	Detectizr.init();

        	return Detectizr;

        }(this, this.navigator, this.document));

Jump to Line

  <form accept-charset="UTF-8" class="js-jump-to-line-form">
    <input class="linejump-input js-jump-to-line-field" type="text" placeholder="Jump to line…" autofocus>
    <button type="submit" class="button">Go</button>
  </form>

Status

API

Training

Shop

Blog

About

© 2014 GitHub, Inc.

Terms

Privacy

Security

Contact

      <textarea name="fullscreen-contents" id="fullscreen-contents" class="fullscreen-contents js-fullscreen-contents js-suggester-field" placeholder=""></textarea>

      Something went wrong with that request. Please try again.


text:
package org.apache.hadoop.yarn.util.resource;

import java.util.Arrays;
import java.util.Collection;

import com.google.common.collect.ImmutableSet;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.api.records.ResourceInformation;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import static org.junit.Assert.assertEquals;

@RunWith(Parameterized.class)
public class TestResourceCalculator {
  private static final String EXTRA_RESOURCE_NAME = "test";

  private final ResourceCalculator resourceCalculator;

  @Parameterized.Parameters(name = "{0}")
  public static Collection<Object[]> getParameters() {
    return Arrays.asList(new Object[][] {
        { "DefaultResourceCalculator", new DefaultResourceCalculator() },
        { "DominantResourceCalculator", new DominantResourceCalculator() } });
  }

  @Before
  public void setupNoExtraResource() {
    // This has to run before each test because we don't know when
    // setupExtraResource() might be called
    ResourceUtils.resetResourceTypes(new Configuration());
  }

  private static void setupExtraResource() {
    Configuration conf = new Configuration();

    conf.set(YarnConfiguration.RESOURCE_TYPES, EXTRA_RESOURCE_NAME);
    ResourceUtils.resetResourceTypes(conf);
  }

  public TestResourceCalculator(String name, ResourceCalculator rs) {
    this.resourceCalculator = rs;
  }

  @Test(timeout = 10000)
  public void testFitsIn() {

    if (resourceCalculator instanceof DefaultResourceCalculator) {
      Assert.assertTrue(resourceCalculator.fitsIn(
          Resource.newInstance(1, 2), Resource.newInstance(2, 1)));
      Assert.assertTrue(resourceCalculator.fitsIn(
          Resource.newInstance(1, 2), Resource.newInstance(2, 2)));
      Assert.assertTrue(resourceCalculator.fitsIn(
          Resource.newInstance(1, 2), Resource.newInstance(1, 2)));
      Assert.assertTrue(resourceCalculator.fitsIn(
          Resource.newInstance(1, 2), Resource.newInstance(1, 1)));
      Assert.assertFalse(resourceCalculator.fitsIn(
          Resource.newInstance(2, 1), Resource.newInstance(1, 2)));
    } else if (resourceCalculator instanceof DominantResourceCalculator) {
      Assert.assertFalse(resourceCalculator.fitsIn(
          Resource.newInstance(1, 2), Resource.newInstance(2, 1)));
      Assert.assertTrue(resourceCalculator.fitsIn(
          Resource.newInstance(1, 2), Resource.newInstance(2, 2)));
      Assert.assertTrue(resourceCalculator.fitsIn(
          Resource.newInstance(1, 2), Resource.newInstance(1, 2)));
      Assert.assertFalse(resourceCalculator.fitsIn(
          Resource.newInstance(1, 2), Resource.newInstance(1, 1)));
      Assert.assertFalse(resourceCalculator.fitsIn(
          Resource.newInstance(2, 1), Resource.newInstance(1, 2)));
    }
  }

  private Resource newResource(long memory, int cpu) {
    Resource res = Resource.newInstance(memory, cpu);

    return res;
  }

  private Resource newResource(long memory, int cpu, int extraResource) {
    Resource res = newResource(memory, cpu);

    res.setResourceValue(EXTRA_RESOURCE_NAME, extraResource);

    return res;
  }

  /**
   * Test that the compare() method returns the expected result (0, -1, or 1).
   * If the expected result is not 0, this method will also test the resources
   * in the opposite order and check for the negative of the expected result.
   *
   * @param cluster the cluster resource
   * @param res1 the LHS resource
   * @param res2 the RHS resource
   * @param expected the expected result
   */
  private void assertComparison(Resource cluster, Resource res1, Resource res2,
      int expected) {
    int actual = resourceCalculator.compare(cluster, res1, res2);

    assertEquals(String.format("Resource comparison did not give the expected "
        + "result for %s v/s %s", res1.toString(), res2.toString()),
        expected, actual);

    if (expected != 0) {
      // Try again with args in the opposite order and the negative of the
      // expected result.
      actual = resourceCalculator.compare(cluster, res2, res1);
      assertEquals(String.format("Resource comparison did not give the "
          + "expected result for %s v/s %s", res2.toString(), res1.toString()),
          expected * -1, actual);
    }
  }

  @Test
  public void testCompareWithOnlyMandatory() {
    // This test is necessary because there are optimizations that are only
    // triggered when only the mandatory resources are configured.

    // Keep cluster resources even so that the numbers are easy to understand
    Resource cluster = newResource(4, 4);

    assertComparison(cluster, newResource(1, 1), newResource(1, 1), 0);
    assertComparison(cluster, newResource(0, 0), newResource(0, 0), 0);
    assertComparison(cluster, newResource(2, 2), newResource(1, 1), 1);
    assertComparison(cluster, newResource(2, 2), newResource(0, 0), 1);

    if (resourceCalculator instanceof DefaultResourceCalculator) {
      testCompareDefaultWithOnlyMandatory(cluster);
    } else if (resourceCalculator instanceof DominantResourceCalculator) {
      testCompareDominantWithOnlyMandatory(cluster);
    }
  }

  private void testCompareDefaultWithOnlyMandatory(Resource cluster) {
    assertComparison(cluster, newResource(1, 1), newResource(1, 1), 0);
    assertComparison(cluster, newResource(1, 2), newResource(1, 1), 0);
    assertComparison(cluster, newResource(1, 1), newResource(1, 0), 0);
    assertComparison(cluster, newResource(2, 1), newResource(1, 1), 1);
    assertComparison(cluster, newResource(2, 1), newResource(1, 2), 1);
    assertComparison(cluster, newResource(2, 1), newResource(1, 0), 1);
  }

  private void testCompareDominantWithOnlyMandatory(Resource cluster) {
    assertComparison(cluster, newResource(2, 1), newResource(2, 1), 0);
    assertComparison(cluster, newResource(2, 1), newResource(1, 2), 0);
    assertComparison(cluster, newResource(2, 1), newResource(1, 1), 1);
    assertComparison(cluster, newResource(2, 2), newResource(2, 1), 1);
    assertComparison(cluster, newResource(2, 2), newResource(1, 2), 1);
    assertComparison(cluster, newResource(3, 1), newResource(3, 0), 1);
  }

  @Test
  public void testCompare() {
    // Test with 3 resources
    setupExtraResource();

    // Keep cluster resources even so that the numbers are easy to understand
    Resource cluster = newResource(4L, 4, 4);

    assertComparison(cluster, newResource(1, 1, 1), newResource(1, 1, 1), 0);
    assertComparison(cluster, newResource(0, 0, 0), newResource(0, 0, 0), 0);
    assertComparison(cluster, newResource(2, 2, 2), newResource(1, 1, 1), 1);
    assertComparison(cluster, newResource(2, 2, 2), newResource(0, 0, 0), 1);

    if (resourceCalculator instanceof DefaultResourceCalculator) {
      testCompareDefault(cluster);
    } else if (resourceCalculator instanceof DominantResourceCalculator) {
      testCompareDominant(cluster);
      testCompareDominantZeroValueResource();
    }
  }

  private void testCompareDefault(Resource cluster) {
    assertComparison(cluster, newResource(1, 1, 2), newResource(1, 1, 1), 0);
    assertComparison(cluster, newResource(1, 2, 1), newResource(1, 1, 1), 0);
    assertComparison(cluster, newResource(1, 2, 2), newResource(1, 1, 1), 0);
    assertComparison(cluster, newResource(1, 2, 2), newResource(1, 0, 0), 0);
    assertComparison(cluster, newResource(2, 1, 1), newResource(1, 1, 1), 1);
    assertComparison(cluster, newResource(2, 1, 1), newResource(1, 2, 1), 1);
    assertComparison(cluster, newResource(2, 1, 1), newResource(1, 1, 2), 1);
    assertComparison(cluster, newResource(2, 1, 1), newResource(1, 2, 2), 1);
    assertComparison(cluster, newResource(2, 1, 1), newResource(1, 0, 0), 1);
  }

  /**
   * Verify compare when one or all the resource are zero.
   */
  private void testCompareDominantZeroValueResource(){
    Resource cluster = newResource(4L, 4, 0);
    assertComparison(cluster, newResource(2, 1, 1), newResource(1, 1, 2), 1);
    assertComparison(cluster, newResource(2, 2, 1), newResource(1, 2, 2), 1);
    assertComparison(cluster, newResource(2, 2, 1), newResource(2, 2, 2), 0);
    assertComparison(cluster, newResource(0, 2, 1), newResource(0, 2, 2), 0);
    assertComparison(cluster, newResource(0, 1, 2), newResource(1, 1, 2), -1);
    assertComparison(cluster, newResource(1, 1, 2), newResource(2, 1, 2), -1);

    // cluster resource zero
    cluster = newResource(0, 0, 0);
    assertComparison(cluster, newResource(2, 1, 1), newResource(1, 1, 1), 1);
    assertComparison(cluster, newResource(2, 2, 2), newResource(1, 1, 1), 1);
    assertComparison(cluster, newResource(2, 1, 1), newResource(1, 2, 1), 0);
    assertComparison(cluster, newResource(1, 1, 1), newResource(1, 1, 1), 0);
    assertComparison(cluster, newResource(1, 1, 1), newResource(1, 1, 2), -1);
    assertComparison(cluster, newResource(1, 1, 1), newResource(1, 2, 1), -1);
  }

  private void testCompareDominant(Resource cluster) {
    assertComparison(cluster, newResource(2, 1, 1), newResource(2, 1, 1), 0);
    assertComparison(cluster, newResource(2, 1, 1), newResource(1, 2, 1), 0);
    assertComparison(cluster, newResource(2, 1, 1), newResource(1, 1, 2), 0);
    assertComparison(cluster, newResource(2, 1, 0), newResource(0, 1, 2), 0);
    assertComparison(cluster, newResource(2, 2, 1), newResource(1, 2, 2), 0);
    assertComparison(cluster, newResource(2, 2, 1), newResource(2, 1, 2), 0);
    assertComparison(cluster, newResource(2, 2, 1), newResource(2, 2, 1), 0);
    assertComparison(cluster, newResource(2, 2, 0), newResource(2, 0, 2), 0);
    assertComparison(cluster, newResource(3, 2, 1), newResource(3, 2, 1), 0);
    assertComparison(cluster, newResource(3, 2, 1), newResource(3, 1, 2), 0);
    assertComparison(cluster, newResource(3, 2, 1), newResource(1, 2, 3), 0);
    assertComparison(cluster, newResource(3, 2, 1), newResource(1, 3, 2), 0);
    assertComparison(cluster, newResource(3, 2, 1), newResource(2, 1, 3), 0);
    assertComparison(cluster, newResource(3, 2, 1), newResource(2, 3, 1), 0);
    assertComparison(cluster, newResource(2, 1, 1), newResource(1, 1, 1), 1);
    assertComparison(cluster, newResource(2, 1, 1), newResource(1, 1, 0), 1);
    assertComparison(cluster, newResource(2, 2, 1), newResource(2, 1, 1), 1);
    assertComparison(cluster, newResource(2, 2, 1), newResource(1, 2, 1), 1);
    assertComparison(cluster, newResource(2, 2, 1), newResource(1, 1, 2), 1);
    assertComparison(cluster, newResource(2, 2, 1), newResource(0, 2, 2), 1);
    assertComparison(cluster, newResource(2, 2, 2), newResource(2, 1, 1), 1);
    assertComparison(cluster, newResource(2, 2, 2), newResource(1, 2, 1), 1);
    assertComparison(cluster, newResource(2, 2, 2), newResource(1, 1, 2), 1);
    assertComparison(cluster, newResource(2, 2, 2), newResource(2, 2, 1), 1);
    assertComparison(cluster, newResource(2, 2, 2), newResource(2, 1, 2), 1);
    assertComparison(cluster, newResource(2, 2, 2), newResource(1, 2, 2), 1);
    assertComparison(cluster, newResource(3, 2, 1), newResource(2, 2, 2), 1);
    assertComparison(cluster, newResource(3, 1, 1), newResource(2, 2, 2), 1);
    assertComparison(cluster, newResource(3, 1, 1), newResource(3, 1, 0), 1);
    assertComparison(cluster, newResource(3, 1, 1), newResource(3, 0, 0), 1);
  }

  @Test(timeout = 10000)
  public void testCompareWithEmptyCluster() {
    Resource clusterResource = Resource.newInstance(0, 0);

    // For lhs == rhs
    Resource lhs = Resource.newInstance(0, 0);
    Resource rhs = Resource.newInstance(0, 0);
    assertResourcesOperations(clusterResource, lhs, rhs, false, true, false,
        true, lhs, lhs);

    // lhs > rhs
    lhs = Resource.newInstance(1, 1);
    rhs = Resource.newInstance(0, 0);
    assertResourcesOperations(clusterResource, lhs, rhs, false, false, true,
        true, lhs, rhs);

    // For lhs < rhs
    lhs = Resource.newInstance(0, 0);
    rhs = Resource.newInstance(1, 1);
    assertResourcesOperations(clusterResource, lhs, rhs, true, true, false,
        false, rhs, lhs);

    if (!(resourceCalculator instanceof DominantResourceCalculator)) {
      return;
    }

    // verify for 2 dimensional resources i.e memory and cpu
    // dominant resource types
    lhs = Resource.newInstance(1, 0);
    rhs = Resource.newInstance(0, 1);
    assertResourcesOperations(clusterResource, lhs, rhs, false, true, false,
        true, lhs, lhs);

    lhs = Resource.newInstance(0, 1);
    rhs = Resource.newInstance(1, 0);
    assertResourcesOperations(clusterResource, lhs, rhs, false, true, false,
        true, lhs, lhs);

    lhs = Resource.newInstance(1, 1);
    rhs = Resource.newInstance(1, 0);
    assertResourcesOperations(clusterResource, lhs, rhs, false, false, true,
        true, lhs, rhs);

    lhs = Resource.newInstance(0, 1);
    rhs = Resource.newInstance(1, 1);
    assertResourcesOperations(clusterResource, lhs, rhs, true, true, false,
        false, rhs, lhs);

  }

  private void assertResourcesOperations(Resource clusterResource,
      Resource lhs, Resource rhs, boolean lessThan, boolean lessThanOrEqual,
      boolean greaterThan, boolean greaterThanOrEqual, Resource max,
      Resource min) {

    assertEquals("Less Than operation is wrongly calculated.", lessThan,
        Resources.lessThan(resourceCalculator, clusterResource, lhs, rhs));

    assertEquals(
        "Less Than Or Equal To operation is wrongly calculated.",
        lessThanOrEqual, Resources.lessThanOrEqual(resourceCalculator,
            clusterResource, lhs, rhs));

    assertEquals("Greater Than operation is wrongly calculated.",
        greaterThan,
        Resources.greaterThan(resourceCalculator, clusterResource, lhs, rhs));

    assertEquals(
        "Greater Than Or Equal To operation is wrongly calculated.",
        greaterThanOrEqual, Resources.greaterThanOrEqual(resourceCalculator,
            clusterResource, lhs, rhs));

    assertEquals("Max(value) Operation wrongly calculated.", max,
        Resources.max(resourceCalculator, clusterResource, lhs, rhs));

    assertEquals("Min(value) operation is wrongly calculated.", min,
        Resources.min(resourceCalculator, clusterResource, lhs, rhs));
  }

  /**
   * Test resource normalization.
   */
  @Test(timeout = 10000)
  public void testNormalize() {
    // requested resources value cannot be an arbitrary number.
    Resource ask = Resource.newInstance(1111, 2);
    Resource min = Resource.newInstance(1024, 1);
    Resource max = Resource.newInstance(8 * 1024, 8);
    Resource increment = Resource.newInstance(1024, 4);
    if (resourceCalculator instanceof DefaultResourceCalculator) {
      Resource result = Resources.normalize(resourceCalculator,
          ask, min, max, increment);

      assertEquals(2 * 1024, result.getMemorySize());
    } else if (resourceCalculator instanceof DominantResourceCalculator) {
      Resource result = Resources.normalize(resourceCalculator,
          ask, min, max, increment);

      assertEquals(2 * 1024, result.getMemorySize());
      assertEquals(4, result.getVirtualCores());
    }

    // if resources asked are less than minimum resource, then normalize it to
    // minimum resource.
    ask = Resource.newInstance(512, 0);
    min = Resource.newInstance(2 * 1024, 2);
    max = Resource.newInstance(8 * 1024, 8);
    increment = Resource.newInstance(1024, 1);
    if (resourceCalculator instanceof DefaultResourceCalculator) {
      Resource result = Resources.normalize(resourceCalculator,
          ask, min, max, increment);

      assertEquals(2 * 1024, result.getMemorySize());
    } else if (resourceCalculator instanceof DominantResourceCalculator) {
      Resource result = Resources.normalize(resourceCalculator,
          ask, min, max, increment);

      assertEquals(2 * 1024, result.getMemorySize());
      assertEquals(2, result.getVirtualCores());
    }

    // if resources asked are larger than maximum resource, then normalize it to
    // maximum resources.
    ask = Resource.newInstance(9 * 1024, 9);
    min = Resource.newInstance(2 * 1024, 2);
    max = Resource.newInstance(8 * 1024, 8);
    increment = Resource.newInstance(1024, 1);
    if (resourceCalculator instanceof DefaultResourceCalculator) {
      Resource result = Resources.normalize(resourceCalculator,
          ask, min, max, increment);

      assertEquals(8 * 1024, result.getMemorySize());
    } else if (resourceCalculator instanceof DominantResourceCalculator) {
      Resource result = Resources.normalize(resourceCalculator,
          ask, min, max, increment);

      assertEquals(8 * 1024, result.getMemorySize());
      assertEquals(8, result.getVirtualCores());
    }

    // if increment is 0, use minimum resource as the increment resource.
    ask = Resource.newInstance(1111, 2);
    min = Resource.newInstance(2 * 1024, 2);
    max = Resource.newInstance(8 * 1024, 8);
    increment = Resource.newInstance(0, 0);
    if (resourceCalculator instanceof DefaultResourceCalculator) {
      Resource result = Resources.normalize(resourceCalculator,
          ask, min, max, increment);

      assertEquals(2 * 1024, result.getMemorySize());
    } else if (resourceCalculator instanceof DominantResourceCalculator) {
      Resource result = Resources.normalize(resourceCalculator,
          ask, min, max, increment);

      assertEquals(2 * 1024, result.getMemorySize());
      assertEquals(2, result.getVirtualCores());
    }
  }

  @Test
  public void testDivisionByZeroRatioDenominatorIsZero() {
    float ratio = resourceCalculator.ratio(newResource(1, 1), newResource(0,
        0));
    assertEquals(Float.POSITIVE_INFINITY, ratio, 0.00001);
  }

  @Test
  public void testDivisionByZeroRatioNumeratorAndDenominatorIsZero() {
    float ratio = resourceCalculator.ratio(newResource(0, 0), newResource(0,
        0));
    assertEquals(0.0, ratio, 0.00001);
  }

  @Test
  public void testFitsInDiagnosticsCollector() {
    if (resourceCalculator instanceof DefaultResourceCalculator) {
      // required-resource = (0, 0)
      assertEquals(ImmutableSet.of(),
          resourceCalculator.getInsufficientResourceNames(newResource(0, 0),
              newResource(0, 0)));
      assertEquals(ImmutableSet.of(),
          resourceCalculator.getInsufficientResourceNames(newResource(0, 0),
              newResource(0, 1)));
      assertEquals(ImmutableSet.of(),
          resourceCalculator.getInsufficientResourceNames(newResource(0, 0),
              newResource(1, 0)));
      assertEquals(ImmutableSet.of(),
          resourceCalculator.getInsufficientResourceNames(newResource(0, 0),
              newResource(1, 1)));

      // required-resource = (0, 1)
      assertEquals(ImmutableSet.of(),
          resourceCalculator.getInsufficientResourceNames(newResource(0, 1),
              newResource(0, 0)));
      assertEquals(ImmutableSet.of(),
          resourceCalculator.getInsufficientResourceNames(newResource(0, 1),
              newResource(0, 1)));
      assertEquals(ImmutableSet.of(),
          resourceCalculator.getInsufficientResourceNames(newResource(0, 1),
              newResource(1, 0)));
      assertEquals(ImmutableSet.of(),
          resourceCalculator.getInsufficientResourceNames(newResource(0, 1),
              newResource(1, 1)));

      // required-resource = (1, 0)
      assertEquals(ImmutableSet.of(ResourceInformation.MEMORY_URI),
          resourceCalculator.getInsufficientResourceNames(newResource(1, 0),
              newResource(0, 0)));
      assertEquals(ImmutableSet.of(ResourceInformation.MEMORY_URI),
          resourceCalculator.getInsufficientResourceNames(newResource(1, 0),
              newResource(0, 1)));
      assertEquals(ImmutableSet.of(),
          resourceCalculator.getInsufficientResourceNames(newResource(1, 0),
              newResource(1, 0)));
      assertEquals(ImmutableSet.of(),
          resourceCalculator.getInsufficientResourceNames(newResource(1, 0),
              newResource(1, 1)));

      // required-resource = (1, 1)
      assertEquals(ImmutableSet.of(ResourceInformation.MEMORY_URI),
          resourceCalculator.getInsufficientResourceNames(newResource(1, 1),
              newResource(0, 0)));
      assertEquals(ImmutableSet.of(ResourceInformation.MEMORY_URI),
          resourceCalculator.getInsufficientResourceNames(newResource(1, 1),
              newResource(0, 1)));
      assertEquals(ImmutableSet.of(),
          resourceCalculator.getInsufficientResourceNames(newResource(1, 1),
              newResource(1, 0)));
      assertEquals(ImmutableSet.of(),
          resourceCalculator.getInsufficientResourceNames(newResource(1, 1),
              newResource(1, 1)));
    } else if (resourceCalculator instanceof DominantResourceCalculator) {
      // required-resource = (0, 0)
      assertEquals(ImmutableSet.of(),
          resourceCalculator.getInsufficientResourceNames(newResource(0, 0),
              newResource(0, 0)));
      assertEquals(ImmutableSet.of(),
          resourceCalculator.getInsufficientResourceNames(newResource(0, 0),
              newResource(0, 1)));
      assertEquals(ImmutableSet.of(),
          resourceCalculator.getInsufficientResourceNames(newResource(0, 0),
              newResource(1, 0)));
      assertEquals(ImmutableSet.of(),
          resourceCalculator.getInsufficientResourceNames(newResource(0, 0),
              newResource(1, 1)));

      // required-resource = (0, 1)
      assertEquals(ImmutableSet.of(ResourceInformation.VCORES_URI),
          resourceCalculator.getInsufficientResourceNames(newResource(0, 1),
              newResource(0, 0)));
      assertEquals(ImmutableSet.of(),
          resourceCalculator.getInsufficientResourceNames(newResource(0, 1),
              newResource(0, 1)));
      assertEquals(ImmutableSet.of(ResourceInformation.VCORES_URI),
          resourceCalculator.getInsufficientResourceNames(newResource(0, 1),
              newResource(1, 0)));
      assertEquals(ImmutableSet.of(),
          resourceCalculator.getInsufficientResourceNames(newResource(0, 1),
              newResource(1, 1)));

      // required-resource = (1, 0)
      assertEquals(ImmutableSet.of(ResourceInformation.MEMORY_URI),
          resourceCalculator.getInsufficientResourceNames(newResource(1, 0),
              newResource(0, 0)));
      assertEquals(ImmutableSet.of(ResourceInformation.MEMORY_URI),
          resourceCalculator.getInsufficientResourceNames(newResource(1, 0),
              newResource(0, 1)));
      assertEquals(ImmutableSet.of(),
          resourceCalculator.getInsufficientResourceNames(newResource(1, 0),
              newResource(1, 0)));
      assertEquals(ImmutableSet.of(),
          resourceCalculator.getInsufficientResourceNames(newResource(1, 0),
              newResource(1, 1)));

      // required-resource = (1, 1)
      assertEquals(ImmutableSet.of(ResourceInformation.MEMORY_URI,
          ResourceInformation.VCORES_URI), resourceCalculator
          .getInsufficientResourceNames(newResource(1, 1), newResource(0, 0)));
      assertEquals(ImmutableSet.of(ResourceInformation.MEMORY_URI),
          resourceCalculator.getInsufficientResourceNames(newResource(1, 1),
              newResource(0, 1)));
      assertEquals(ImmutableSet.of(ResourceInformation.VCORES_URI),
          resourceCalculator.getInsufficientResourceNames(newResource(1, 1),
              newResource(1, 0)));
      assertEquals(ImmutableSet.of(),
          resourceCalculator.getInsufficientResourceNames(newResource(1, 1),
              newResource(1, 1)));
    }
  }

  @Test
  public void testRatioWithNoExtraResource() {
    //setup
    Resource resource1 = newResource(1, 1);
    Resource resource2 = newResource(2, 1);

    //act
    float ratio = resourceCalculator.ratio(resource1, resource2);

    //assert
    if (resourceCalculator instanceof DefaultResourceCalculator) {
      double ratioOfMemories = 0.5;
      assertEquals(ratioOfMemories, ratio, 0.00001);
    } else if (resourceCalculator instanceof DominantResourceCalculator) {
      double ratioOfCPUs = 1.0;
      assertEquals(ratioOfCPUs, ratio, 0.00001);
    }
  }

  @Test
  public void testRatioWithExtraResource() {
    //setup
    setupExtraResource();
    Resource resource1 = newResource(1, 1, 2);
    Resource resource2 = newResource(2, 1, 1);

    //act
    float ratio = resourceCalculator.ratio(resource1, resource2);

    //assert
    if (resourceCalculator instanceof DefaultResourceCalculator) {
      double ratioOfMemories = 0.5;
      assertEquals(ratioOfMemories, ratio, 0.00001);
    } else if (resourceCalculator instanceof DominantResourceCalculator) {
      double ratioOfExtraResources = 2.0;
      assertEquals(ratioOfExtraResources, ratio, 0.00001);
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

describe('Controller Tests', function() {

    beforeEach(mockApiAccountCall);
    beforeEach(mockI18nCalls);

    describe('SessionsController', function() {

        var $scope, $q; // actual implementations
        var MockSessions, MockPrincipal; // mocks
        var createController; // local utility function

        var sessions = [{
            formattedTokenDate: "15 October 2015",
            ipAddress: "0:0:0:0:0:0:0:1",
            series: "xxxxxx==",
            userAgent: "Mozilla/5.0"
        }];

        beforeEach(inject(function($injector) {
            $q = $injector.get('$q');
            $scope = $injector.get('$rootScope').$new();
            MockSessions = jasmine.createSpyObj('MockSessions', ['getAll', 'delete']);
            MockPrincipal = jasmine.createSpyObj('MockPrincipal', ['identity']);

            var locals = {
                '$scope': $scope,
                'Sessions': MockSessions,
                'Principal': MockPrincipal
            };
            createController = function() {
                return $injector.get('$controller')('SessionsController', locals);
            };
        }));

        it('should define its initial state', function() {
            MockPrincipal.identity.and.returnValue($q.resolve({
                id: 'fuzzer'
            }));
            MockSessions.getAll.and.returnValue(sessions);
            // given
            $scope.$apply(createController);
            // then
            expect(MockPrincipal.identity).toHaveBeenCalled();
            expect(MockSessions.getAll).toHaveBeenCalled();
            expect($scope.success).toBeNull();
            expect($scope.error).toBeNull();
            expect($scope.account).toEqual({
                id: 'fuzzer'
            });
            expect($scope.sessions).toEqual(sessions);
        });

        it('should call delete on Sessions to invalidate a session', function() {
            MockPrincipal.identity.and.returnValue($q.resolve({
                id: 'fuzzer'
            }));
            MockSessions.getAll.and.returnValue(sessions);
            // given
            createController();
            $scope.invalidate('xyz');
            $scope.$apply();
            // then
            expect(MockSessions.delete).toHaveBeenCalledWith({
                series: 'xyz'
            }, jasmine.any(Function), jasmine.any(Function));
        });

        it('should call delete on Sessions and notify of error', function() {
            MockPrincipal.identity.and.returnValue($q.resolve({
                id: 'fuzzer'
            }));
            MockSessions.getAll.and.returnValue(sessions);
            MockSessions.delete.and.callFake(function resourceDelete(arg, success, failure) {
                failure();
            });
            // given
            createController();
            $scope.invalidate('xyz');
            $scope.$apply();
            // then
            expect($scope.success).toBeNull();
            expect($scope.error).toBe('ERROR');
        });

        it('should call notify of success upon session invalidation', function() {
            MockPrincipal.identity.and.returnValue($q.resolve({
                id: 'fuzzer'
            }));
            MockSessions.getAll.and.returnValue(sessions);
            MockSessions.delete.and.callFake(function resourceDelete(arg, success, failure) {
                success();
            });
            // given
            createController();
            $scope.invalidate('xyz');
            $scope.$apply();
            // then
            expect($scope.error).toBeNull();
            expect($scope.success).toBe('OK');
        });
    });
});


text:
package org.springframework.osgi.web.extender.internal.scanner;

import java.util.Enumeration;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.Bundle;
import org.springframework.osgi.util.OsgiStringUtils;

/**
 * Scanner for Web application ARchives (WARs). This implementation considers as
 * <tt>WAR</tt>s bundles that match the following rules (in this order):
 *

 *
have a <tt>.war</tt> extension

 *
contain the <tt>/WEB-INF/</tt> folder

 *

 *
 * @author Costin Leau
 */
public class DefaultWarScanner implements WarScanner {

	/** war extension */
	private static final String WAR_EXT = ".war";
	private static final String SLASH = "/";
	private static final String WEB_INF = "WEB-INF";

	/** logger */
	private static final Log log = LogFactory.getLog(DefaultWarScanner.class);

	public boolean isWar(Bundle bundle) {
		boolean trace = log.isTraceEnabled();
		boolean isWar = false;

		if (trace)
			log.trace("Scanning bundle " + OsgiStringUtils.nullSafeSymbolicName(bundle));

		if (bundle == null)
			return false;

		// check bundle extension
		String location = bundle.getLocation();

		if (location != null) {
			// handle unpacked bundles
			if (location.endsWith(SLASH)) {
				// remove trailing slash
				location = location.substring(0, location.length() - 1);
			}
			if (trace)
				log.trace("Scanning for war bundle location " + location);
			isWar = location.endsWith(WAR_EXT);
			if (isWar) {
				if (trace)
					log.trace("Location [" + location + "] has " + WAR_EXT + " extension; considering the bundle a WAR");
				return true;
			}
			else {
				if (trace)
					log.trace("Location [" + location + "] doesn't indicate a WAR; scanning the presence of /"
							+ WEB_INF + "/");
			}
		}
		return isWebInfPresent(bundle);
	}

	/**
	 * Checks if <tt>/WEB-INF/</tt> is available in the bundle.
	 *
	 * @param bundle OSGi bundle
	 * @return true if the folder is contained, false otherwise.
	 */
	private boolean isWebInfPresent(Bundle bundle) {
		if (!hasEntry(bundle, SLASH, WEB_INF)) {
			// since folders might not be stored inside the jar, try using a different approach
			return hasEntry(bundle, WEB_INF, null);
		}
		return true;
	}

	private boolean hasEntry(Bundle bundle, String path, String pattern) {
		Enumeration enm = bundle.findEntries(path, pattern, false);
		return (enm != null && enm.hasMoreElements());
	}
}


text:
Express Middleware to filter out Mongoose model attributes.
You pass an array of fields you do not want returned as part of
json or jsonp requests.

###Install
To install the latest official version, use NPM:

    npm install mongoosemask --save

To run the tests and see what is supported run either of the following commands

    npm test
    grunt

###Usage

    app.use(mongoosemask(['_id', '_privatefield']));

The '_id' and the '_privatefield' will then be removed from your json objects before sending to the
client.

    maksedObj = {
        //ALL fields except _id and _private
    };

You can also call the mask explicitly

    var maskedModel = mongomask.mask(model, ['_id']);

Additionally there is also a expose method which you can use to expose items instead of excluding them.

Mask all values on a given object except for those that
are explicitly exposed through the values array. The value
can be a String which will directly be a one-to-one mapping
for example

        _id -> _id will expose the _id mongoose value

or an object that maps keys to values
for example
    {_id:'id'}
    Will expose _id as id on the object.
    [ '_id', {_id:'id} ]
    Will expose both id and _id,
     {'nested.value.here' : 'exposed.at.any.level'}
     Will create a sub object {exposed:{at:{any:level:'valuehere'}}}]

    var exposedModel = mongoosemask.expose(model, [{_id:'id'}, {'email':'username'}, 'name', {'nested.value' : 'user.profile' }]);
     exposedModel = {
     id:12345,
     username:'my@email.com',
     name:'nodejs',
     user:{
            profile:'public ...'
          }
     }

###Notes
If you are using 'express-partial-response' you must place this middleware
AFTER you place the express-partial-response middleware as this middlware only works
with mongoose objects which the express-partial-response middleware does not return

###CHANGELOG

###0.0.5
Quick fix for nested objects.

###0.0.4
Added dot'.' notation support to expose/mask methods. The method will try to walk the
chain until it finds the value to expose/mask.

mask( ['this.sub.value'], model );
expose(['this.sub.value', { 'this.sub.value.two' : 'new.position.in.exposed.model' }], model );

If the expose method can not find the value then it will set it as undefined.

One limitation is that the dot notation can not traverse a sub array so model.[ {value:value}, {value:value}]
will not be able to mask the model.value of the two sub models.

###0.0.3
Added the ability to pass a function as the mask callback for the express middleware.
if you have a complex item that needs masking  you can pass a
callback funtion that will be invoked before your object is serialized to json.

 The callback must have the following signature.
 function(obj, mask, done);

     express.use(mongooseMask(function(value, mask, done){
             var masked = mask(value, ['_id', '__v']);
             if(masked.data){
                 masked.data = mask(value.data, ['_id', '__v']);
             }
             done(null, masked);
         }));

###0.0.6
Fixed NPE when passing nested objects

###0.0.2
Added support for calling mask directly.
Added expose() method as an inverse of mask.

###0.0.1
Initial release


text:
(function() {
    "use strict";
    var Async = require('../lib/async');

    var root = exports || this;

    root.pollUntil = function(obj, condition, iterations, callback) {
        callback = callback || function() {};

        var i = 0;
        Async.whilst(
            function() { return !condition(obj) && (i++ < iterations); },
            function(done) {
                Async.sleep(500, function() {
                    obj.fetch(done);
                });
            },
            function(err) {
                callback(err, obj);
            }
        );
    };

    // Minimal Http implementation that is designed to pass the tests
    // done by Context.init(), but nothing more.
    root.DummyHttp = {
        // Required by Context.init()
        _setSplunkVersion: function(version) {
            // nothing
        }
    };
})();


text:
package android.os;

@com.francetelecom.rd.stubs.annotation.ClassDone(0)
public class ConditionVariable
{
  // Constructors

  public ConditionVariable(){
  }
  public ConditionVariable(boolean arg1){
  }
  // Methods

  public void close(){
  }
  public void open(){
  }
  public void block(){
  }
  public boolean block(long arg1){
    return false;
  }
}


text:
package org.gavrog.joss.algorithms;

import java.util.List;

import buoy.event.EventProcessor;

/**
 * Generates all permutation of a given (small) degree. A first sample
 * application for the abstract {@link BranchAndCut} class. Does not use deductions
 * or canonicity, so is much too simplistic for a real test.
 *
 * @author Olaf Delgado
 * @version $Id: Permutations.java,v 1.5 2006/09/26 22:45:19 odf Exp $
 */
public class Permutations extends BranchAndCut<String> {
	final int degree;
	final int map[];
	final int inv[];

	private class PMove implements Move {
		public int from;
		public int to;

		public PMove(final int from, final int to) {
			this.from = from;
			this.to = to;
		}

		public String toString() {
			return String.format("(%d => %d)", from, to);
		}
	}

	public Permutations(final int degree) {
		if (degree < 1 || degree > 9) {
			throw new IllegalArgumentException("degree must be between 1 and 9");
		}
		this.degree = degree;
		this.map = new int[degree+1];
		this.inv = new int[degree+1];
	}

	protected Move nextChoice(final Move previous) {
		int n = 1;
		if (previous != null) {
			n = ((PMove) previous).from;
			while (n <= this.degree && this.map[n] != 0) {
				++n;
			}
		}
		if (n > this.degree) {
			return null;
		} else {
			return new PMove(n, 0);
		}
	}

	protected Move nextDecision(final Move previous) {
		final int from = ((PMove) previous).from;
		int to = ((PMove) previous).to + 1;
		while (to <= this.degree && this.inv[to] != 0) {
			++to;
		}
		if (to > this.degree) {
			return null;
		} else {
			return new PMove(from, to);
		}
	}

	protected Status checkMove(final Move move) {
		final int from = ((PMove) move).from;
		final int to = ((PMove) move).to;
		if (map[from] == to) {
			return Status.VOID;
		} else if (map[from] != 0 || inv[to] != 0) {
			return Status.ILLEGAL;
		} else {
			return Status.OK;
		}
	}

	protected void performMove(final Move move) {
		final int from = ((PMove) move).from;
		final int to = ((PMove) move).to;
		this.map[from] = to;
		this.inv[to] = from;
	}

	protected void undoMove(final Move move) {
		final int from = ((PMove) move).from;
		final int to = ((PMove) move).to;
		map[from] = 0;
		inv[to] = 0;
	}

	protected List<Move> deductions(final Move move) {
		return null;
	}

	protected boolean isValid() {
		return true;
	}

	protected boolean isComplete() {
		for (int i = 1; i <= this.degree; ++i) {
			final int k = this.map[i];
			if (k == 0) {
				return false;
			}
		}
		return true;
	}

	protected String makeResult() {
		final StringBuffer tmp = new StringBuffer(10);
		for (int i = 1; i <= this.degree; ++i) {
			tmp.append(this.map[i]);
		}
		return tmp.toString();
	}

	public static void main(final String args[]) {
		final int n;
		if (args.length == 0) {
			n = 4;
		} else {
			n = Integer.parseInt(args[0]);
		}
		final Permutations gen = new Permutations(n);
		if (args.length > 1) {
			gen.setResumePoint(args[1]);
		}
		gen.addEventLink(CheckpointEvent.class, new EventProcessor() {
			@Override
			public void handleEvent(Object event) {
				System.out.println(event);
				System.out.flush();
			}
		});
		int count = 0;
		for (final String p: gen) {
			System.out.println(p);
			System.out.flush();
			++count;
		}
		System.out.println("# Generated " + count + " permutations.");
	}
}


text:
from .core import *
from .core.utils.init import initialize_main

initialize_main()
del initialize_main


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('restaurant', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='Menu',
            fields=[
                ('id', models.AutoField(auto_created=True, verbose_name='ID', serialize=False, primary_key=True)),
                ('name', models.CharField(max_length=30)),
                ('menu_type', models.CharField(max_length=30)),
                ('restaurant', models.ForeignKey(to='restaurant.Restaurant')),
            ],
        ),
    ]


text:
#ifndef SOLOUD_BUS_H
#define SOLOUD_BUS_H

#include "soloud.h"

namespace SoLoud
{
	class Bus;

	class BusInstance : public AudioSourceInstance
	{
		Bus *mParent;
		unsigned int mScratchSize;
		AlignedFloatBuffer mScratch;
	public:
		// Approximate volume for channels.
		float mVisualizationChannelVolume[MAX_CHANNELS];
		// Mono-mixed wave data for visualization and for visualization FFT input
		float mVisualizationWaveData[256];

		BusInstance(Bus *aParent);
		virtual unsigned int getAudio(float *aBuffer, unsigned int aSamplesToRead, unsigned int aBufferSize);
		virtual bool hasEnded();
		virtual ~BusInstance();
	};

	class Bus : public AudioSource
	{
	public:
		Bus();
		virtual BusInstance *createInstance();
		// Set filter. Set to NULL to clear the filter.
		virtual void setFilter(unsigned int aFilterId, Filter *aFilter);
		// Play sound through the bus
		handle play(AudioSource &aSound, float aVolume = 1.0f, float aPan = 0.0f, bool aPaused = 0);
		// Play sound through the bus, delayed in relation to other sounds called via this function.
		handle playClocked(time aSoundTime, AudioSource &aSound, float aVolume = 1.0f, float aPan = 0.0f);
		// Start playing a 3d audio source through the bus
		handle play3d(AudioSource &aSound, float aPosX, float aPosY, float aPosZ, float aVelX = 0.0f, float aVelY = 0.0f, float aVelZ = 0.0f, float aVolume = 1.0f, bool aPaused = 0);
		// Start playing a 3d audio source through the bus, delayed in relation to other sounds called via this function.
		handle play3dClocked(time aSoundTime, AudioSource &aSound, float aPosX, float aPosY, float aPosZ, float aVelX = 0.0f, float aVelY = 0.0f, float aVelZ = 0.0f, float aVolume = 1.0f);
		// Set number of channels for the bus (default 2)
		result setChannels(unsigned int aChannels);
		// Enable or disable visualization data gathering
		void setVisualizationEnable(bool aEnable);
		// Move a live sound to this bus
		void annexSound(handle aVoiceHandle);

		// Calculate and get 256 floats of FFT data for visualization. Visualization has to be enabled before use.
		float *calcFFT();

		// Get 256 floats of wave data for visualization. Visualization has to be enabled before use.
		float *getWave();

		// Get approximate volume for output channel for visualization. Visualization has to be enabled before use.
		float getApproximateVolume(unsigned int aChannel);

		// Get number of immediate child voices to this bus
		unsigned int getActiveVoiceCount();
	public:
		BusInstance *mInstance;
		unsigned int mChannelHandle;
		// FFT output data
		float mFFTData[256];
		// Snapshot of wave data for visualization
		float mWaveData[256];
		// Internal: find the bus' channel
		void findBusHandle();
	};
};

#endif


text:
* {
  box-sizing: border-box;
  -moz-box-sizing: border-box;
}
body {
  font-family: sans-serif;
}

#filterBox {
  background: #efefef;
  padding: 5px;
  border-bottom: 1px solid gray;
  overflow: hidden;
}

#filterBox * {
  white-space: nowrap;
  font-family: sans-serif;
  font-size: 12px;
}

#filterBox input {
  width: 100%;
}

#actionBox {
  background: #efefef;
  white-space: nowrap;
  border-top: 1px solid gray;
  overflow: hidden;
}

#eventsBox {
  overflow-x: hidden;
  overflow-y: auto
}

#detailsBox {
  overflow: auto;
}

#splitterBox {
  background: #bfbfbf;
  border-left: 1px inset black;
  border-right: 1px solid black;
  position:absolute;
  width: 8px;
  cursor: col-resize;
  user-select: none;
}

#eventsListTable {
  cursor: pointer;
}

#eventsListTable thead td {
  text-align: left;
  font-weight: bold;
  background: rgb(229, 236, 249);
}

#eventsListTable td {
  padding: 3px;
  border-left: 1px solid #afafaf;
  border-bottom: 1px solid #afafaf;
  text-overflow: ellipsis;
  font-size: 12px;
  white-space: nowrap;
}

#eventsListTableBody .mouseover {
  background: rgb(244,244,255);
}

#eventsListTableBody .selected,
#eventsListTableBody .mouseover .selected {
  background: #C3D9FF;
}

#eventsListTableBody .source_CONNECT_JOB {
  color: blue;
}

#eventsListTableBody .source_HOST_RESOLVER_IMPL_JOB,
#eventsListTableBody .source_HOST_RESOLVER_IMPL_REQUEST {
  color: #308080;
}

#eventsListTableBody .source_DISK_CACHE_ENTRY,
#eventsListTableBody .source_MEMORY_CACHE_ENTRY {
  color: gray;
}

#eventsListTableBody .source_SOCKET {
  color: purple;
}

#eventsListTableBody .source_INIT_PROXY_RESOLVER {
  color: green;
}

#eventsListTableBody .source_NONE {
  color: red;
}

.tabSwitcher {
  margin-top: 10px;
  margin-left: 10px;
}

.tabSwitcher th {
  background: rgb(229,236,249);
  cursor: pointer;
  background-clip: border-box;
  border-top-left-radius: 5px 5px;
  border-top-right-radius: 5px 5px;
  padding-left: 4px;
  padding-top: 4px;
  padding-right: 4px;
  font-size: 12px;
  margin-left: 30px;
}

.tabSwitcher th.selected, .tabSwitcherLine {
  background: rgb(195,217,255);
}

.tabSwitcherLine {
  height: 10px;
}

#detailsTabHandles {
  border: 1px solid white;
}

.logSourceEntry {
  margin: 5px;
}

.logSourceEntry * p {
  font-weight: bold;
  font-size: 12px;
}

.logSourceEntry * td {
  font-size: 10px;
}

#detailsLogBox,
#detailsTimelineBox,
#httpCacheTabContent,
#proxyTabContent,
#dataTabContent,
#dnsTabContent,
#socketsTabContent,
#spdyTabContent,
#serviceProvidersTabContent,
#testTabContent,
#hstsTabContent,
#httpThrottlingTabContent {
  overflow: auto;
  padding: 10px;
}

#proxyTabContent td,
#proxyTabContent th {
  font-size: 12px;
}

/*
 * Styles for TABLE that uses a thin collapsed border.
 */
table.styledTable {
  border-collapse:collapse;
}

table.styledTable,
.styledTable th,
.styledTable td {
  border: 1px solid #777;
  padding-right: 4px;
  padding-left: 4px;
}

.styledTable th {
  background: rgb(224,236,255);
}

.styledTable th.title {
  background: rgb(255,217,217);
}

/*
 * This is the box in the top right of the Data tab which shows how many
 * events have been captured so far.
 */
.capturingBox {
  border: 1px dashed black;
  display: inline-block;
  text-align: left;
  padding: 5px;
}

/**
 * Styling for an emphasized button.
 */
.bigButton {
  font-size: 100%;
  font-weight: bold;
}

/**
 * Styling for text indicating a potential problem or error state.
 */
.warningText {
  color: red;
}


text:
Neo4j
=====

.. toctree::
   :maxdepth: 3
   :titlesonly:

   Neo4j/Error

   Neo4j/RecordNotFound

   Neo4j/InvalidPropertyOptionsError

   Neo4j/InvalidParameterError

   Neo4j/UnknownTypeConverterError

   Neo4j/DangerousAttributeError

   Neo4j/UnknownAttributeError

   Neo4j/Config

   Neo4j/Shared

   Neo4j/Railtie

   Neo4j/ClassWrapper

   Neo4j/Paginated

   Neo4j/Migration

   Neo4j/ActiveRel

   Neo4j/Core

   Neo4j/Timestamps

   Neo4j/ActiveNode

   Neo4j/TypeConverters

   Neo4j/ClassArguments

   Neo4j/Schema

   Neo4j/Relationship

   Neo4j/Node

   Neo4j/Generators

Constants
---------

  * VERSION

Files
-----

  * `lib/neo4j/errors.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/errors.rb#L1>`_

  * `lib/neo4j/config.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/config.rb#L1>`_

  * `lib/neo4j/shared.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/shared.rb#L1>`_

  * `lib/neo4j/railtie.rb:6 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/railtie.rb#L6>`_

  * `lib/neo4j/version.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/version.rb#L1>`_

  * `lib/neo4j/wrapper.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/wrapper.rb#L1>`_

  * `lib/neo4j/paginated.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/paginated.rb#L1>`_

  * `lib/neo4j/migration.rb:3 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/migration.rb#L3>`_

  * `lib/neo4j/active_rel.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/active_rel.rb#L1>`_

  * `lib/neo4j/timestamps.rb:4 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/timestamps.rb#L4>`_

  * `lib/neo4j/active_node.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/active_node.rb#L1>`_

  * `lib/neo4j/shared/marshal.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/shared/marshal.rb#L1>`_

  * `lib/neo4j/type_converters.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/type_converters.rb#L1>`_

  * `lib/neo4j/class_arguments.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/class_arguments.rb#L1>`_

  * `lib/neo4j/active_rel/types.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/active_rel/types.rb#L1>`_

  * `lib/neo4j/shared/callbacks.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/shared/callbacks.rb#L1>`_

  * `lib/neo4j/schema/operation.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/schema/operation.rb#L1>`_

  * `lib/neo4j/active_node/query.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/active_node/query.rb#L1>`_

  * `lib/neo4j/shared/typecaster.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/shared/typecaster.rb#L1>`_

  * `lib/neo4j/timestamps/updated.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/timestamps/updated.rb#L1>`_

  * `lib/neo4j/timestamps/created.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/timestamps/created.rb#L1>`_

  * `lib/neo4j/active_node/labels.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/active_node/labels.rb#L1>`_

  * `lib/neo4j/shared/validations.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/shared/validations.rb#L1>`_

  * `lib/neo4j/active_rel/callbacks.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/active_rel/callbacks.rb#L1>`_

  * `lib/neo4j/active_node/dependent.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/active_node/dependent.rb#L1>`_

  * `lib/neo4j/active_node/callbacks.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/active_node/callbacks.rb#L1>`_

  * `lib/neo4j/active_rel/validations.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/active_rel/validations.rb#L1>`_

  * `lib/neo4j/active_node/validations.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/active_node/validations.rb#L1>`_

  * `lib/neo4j/active_node/orm_adapter.rb:3 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/active_node/orm_adapter.rb#L3>`_

  * `lib/neo4j/active_node/unpersisted.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/active_node/unpersisted.rb#L1>`_

  * `lib/neo4j/active_node/query_methods.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/active_node/query_methods.rb#L1>`_

  * `lib/rails/generators/neo4j_generator.rb:5 <https://github.com/neo4jrb/neo4j/blob/master/lib/rails/generators/neo4j_generator.rb#L5>`_

  * `lib/neo4j/active_node/has_n/association.rb:4 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/active_node/has_n/association.rb#L4>`_

  * `lib/neo4j/active_node/query/query_proxy.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/active_node/query/query_proxy.rb#L1>`_

  * `lib/neo4j/active_node/query/query_proxy_link.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/active_node/query/query_proxy_link.rb#L1>`_

  * `lib/neo4j/active_node/query/query_proxy_methods.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/active_node/query/query_proxy_methods.rb#L1>`_

  * `lib/neo4j/active_node/query/query_proxy_enumerable.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/active_node/query/query_proxy_enumerable.rb#L1>`_

  * `lib/neo4j/active_node/dependent/association_methods.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/active_node/dependent/association_methods.rb#L1>`_

  * `lib/neo4j/active_node/dependent/query_proxy_methods.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/active_node/dependent/query_proxy_methods.rb#L1>`_

  * `lib/neo4j/active_node/query/query_proxy_eager_loading.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/active_node/query/query_proxy_eager_loading.rb#L1>`_

  * `lib/neo4j/active_node/has_n/association_cypher_methods.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/active_node/has_n/association_cypher_methods.rb#L1>`_

  * `lib/neo4j/active_node/query/query_proxy_find_in_batches.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/active_node/query/query_proxy_find_in_batches.rb#L1>`_

  * `lib/neo4j/active_node/query/query_proxy_methods_of_mass_updating.rb:1 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/active_node/query/query_proxy_methods_of_mass_updating.rb#L1>`_

Methods
-------


text:
namespace SuperMap.Web.iServerJava6R
{
    /// <para>${iServerJava6R_QueryBySQLParameters_Tile}</para>
    public class QueryBySQLParameters :QueryParameters
    {
        /// ${iServerJava6R_QueryBySQLParameters_constructor_None_D}
        public QueryBySQLParameters()
        { }
    }
}


text:
package co.aurasphere.botmill.core.datastore.model;

/**
 * The Interface BotMillState.
 */
public interface BotMillState {

	/**
	 * Builds the session.
	 *
	 * @param identifier the identifier
	 * @return the session
	 */
	public Session buildSession(String identifier);

	/**
	 * Destroy session.
	 *
	 * @param identifier the identifier
	 */
	public void destroySession(String identifier);

	/**
	 * Sets the variable.
	 *
	 * @param identifier the identifier
	 * @param keyValuePair the key value pair
	 * @return the session
	 */
	public Session setVariable(String identifier, KeyValuePair keyValuePair);

	/**
	 * Gets the variable.
	 *
	 * @param identifier the identifier
	 * @param key the key
	 * @return the variable
	 */
	public KeyValuePair getVariable(String identifier, String key);

}


text:
from telemetry.page import page_test
from telemetry.timeline import model
from telemetry.timeline import tracing_config
from telemetry.value import scalar

class DrawProperties(page_test.PageTest):

  def __init__(self):
    super(DrawProperties, self).__init__()

  def CustomizeBrowserOptions(self, options):
    options.AppendExtraBrowserArgs([
        '--enable-prefer-compositing-to-lcd-text',
    ])

  def WillNavigateToPage(self, page, tab):
    config = tracing_config.TracingConfig()
    config.tracing_category_filter.AddDisabledByDefault(
        'disabled-by-default-cc.debug.cdp-perf')
    config.enable_chrome_trace = True
    tab.browser.platform.tracing_controller.StartTracing(config)

  def ComputeAverageOfDurations(self, timeline_model, name):
    events = timeline_model.GetAllEventsOfName(name)
    event_durations = [d.duration for d in events]
    assert event_durations, 'Failed to find durations'

    duration_sum = sum(event_durations)
    duration_count = len(event_durations)
    duration_avg = duration_sum / duration_count
    return duration_avg

  def ValidateAndMeasurePage(self, page, tab, results):
    timeline_data = tab.browser.platform.tracing_controller.StopTracing()
    timeline_model = model.TimelineModel(timeline_data)

    pt_avg = self.ComputeAverageOfDurations(
        timeline_model,
        'LayerTreeHostCommon::ComputeVisibleRectsWithPropertyTrees')

    results.AddValue(scalar.ScalarValue(
        results.current_page, 'PT_avg_cost', 'ms', pt_avg,
        description='Average time spent processing property trees'))

  def DidRunPage(self, platform):
    tracing_controller = platform.tracing_controller
    if tracing_controller.is_tracing_running:
      tracing_controller.StopTracing()


text:
 // Includes I did make myself
#include "Gamestate.hpp"

class Menu : public GameState {
public:
	Menu();
	~Menu();

	int events(sf::RenderWindow& window);
    int logic(sf::RenderWindow& window);
    int render(sf::RenderWindow& window);

private:
	sf::Font mainFont;
	sf::Text playText;
	sf::Text scoreText;
};

#endif


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="#FFFFFF">
    <RelativeLayout
   	  android:id="@+id/talk_current_userinfo"
	  android:layout_width="170dip"
	  android:layout_height="wrap_content">
     <ImageView
      android:id="@+id/talk_current_userinfo_image"
	  android:layout_width="wrap_content"
	  android:layout_height="wrap_content"
	  android:layout_alignParentLeft="true"
	  android:src="@drawable/person_haomeili"/>
	 <LinearLayout
	  android:id="@+id/talk_current_userinfo_name"
	  android:layout_toRightOf="@id/talk_current_userinfo_image"
	  android:orientation="vertical"
	  android:layout_width="wrap_content"
	  android:layout_height="wrap_content">
	     <TextView
	         android:id="@+id/talk_uname_text"
		     android:layout_width="wrap_content"
		  	 android:layout_height="wrap_content"
		  	 android:text="傻逼"
		  	 android:textColor="@color/black"/>
	     <TextView
	     	 android:id="@+id/talk_signature_text"
		     android:layout_width="wrap_content"
		  	 android:layout_height="wrap_content"
		  	 android:text="我在学习中。。。。"
		  	 android:textColor="@color/black"/>
	 </LinearLayout>
  </RelativeLayout>
</LinearLayout>


text:
package s_mach.concurrent.impl

import scala.concurrent.{ExecutionContext, Future}

trait DelegatingTaskRunner extends TaskRunner {
  def taskHooks : Seq[TaskHook]
  def taskStepHooks : Seq[TaskStepHook]

  override def hookStepFunction0[R](
    step: (TaskStepId) => Future[R]
  )(implicit ec:ExecutionContext): (TaskStepId) => Future[R] = {
    taskStepHooks.foldLeft(step)((step, taskStepHook) => taskStepHook.hookStepFunction0(step))
  }

  override def hookStepFunction1[A, R](
    step: (TaskStepId, A) => Future[R]
  )(implicit ec:ExecutionContext): (TaskStepId, A) => Future[R] = {
    taskStepHooks.foldLeft(step)((step, taskStepHook) => taskStepHook.hookStepFunction1(step))
  }

  override def hookStepFunction2[A, B, R](
    step: (TaskStepId, A, B) => Future[R]
  )(implicit ec:ExecutionContext): (TaskStepId, A, B) => Future[R] = {
    taskStepHooks.foldLeft(step)((step, taskStepHook) => taskStepHook.hookStepFunction2(step))
  }

  override def hookTask[R](
    task: () => Future[R]
  )(implicit ec:ExecutionContext): () => Future[R] = {
    taskHooks.foldLeft(task)((task, taskHook) => taskHook.hookTask(task))
  }
}