text:
"""Provide access to Python's configuration information.  The specific
configuration variables available depend heavily on the platform and
configuration.  The values may be retrieved using
get_config_var(name), and the list of variables is available via
get_config_vars().keys().  Additional convenience functions are also
available.

Written by:   Fred L. Drake, Jr.
Email:        <fdrake@acm.org>
"""

__revision__ = "$Id$"

import os
import re
import string
import sys

from distutils.errors import DistutilsPlatformError

# These are needed in a couple of spots, so just compute them once.
PREFIX = os.path.normpath(sys.prefix)
EXEC_PREFIX = os.path.normpath(sys.exec_prefix)

# Path to the base directory of the project. On Windows the binary may
# live in project/PCBuild9.  If we're dealing with an x64 Windows build,
# it'll live in project/PCbuild/amd64.
project_base = os.path.dirname(os.path.abspath(sys.executable))
if os.name == "nt" and "pcbuild" in project_base[-8:].lower():
    project_base = os.path.abspath(os.path.join(project_base, os.path.pardir))
# PC/VS7.1
if os.name == "nt" and "\\pc\\v" in project_base[-10:].lower():
    project_base = os.path.abspath(os.path.join(project_base, os.path.pardir,
                                                os.path.pardir))
# PC/AMD64
if os.name == "nt" and "\\pcbuild\\amd64" in project_base[-14:].lower():
    project_base = os.path.abspath(os.path.join(project_base, os.path.pardir,
                                                os.path.pardir))

# set for cross builds
if "_PYTHON_PROJECT_BASE" in os.environ:
    # this is the build directory, at least for posix
    project_base = os.path.normpath(os.environ["_PYTHON_PROJECT_BASE"])

# python_build: (Boolean) if true, we're either building Python or
# building an extension with an un-installed Python, so we use
# different (hard-wired) directories.
# Setup.local is available for Makefile builds including VPATH builds,
# Setup.dist is available on Windows
def _python_build():
    for fn in ("Setup.dist", "Setup.local"):
        if os.path.isfile(os.path.join(project_base, "Modules", fn)):
            return True
    return False
python_build = _python_build()

def get_python_version():
    """Return a string containing the major and minor Python version,
    leaving off the patchlevel.  Sample return values could be '1.5'
    or '2.2'.
    """
    return sys.version[:3]

def get_python_inc(plat_specific=0, prefix=None):
    """Return the directory containing installed Python header files.

    If 'plat_specific' is false (the default), this is the path to the
    non-platform-specific header files, i.e. Python.h and so on;
    otherwise, this is the path to platform-specific header files
    (namely pyconfig.h).

    If 'prefix' is supplied, use it instead of sys.prefix or
    sys.exec_prefix -- i.e., ignore 'plat_specific'.
    """
    if prefix is None:
        prefix = plat_specific and EXEC_PREFIX or PREFIX

    if os.name == "posix":
        if python_build:
            buildir = os.path.dirname(sys.executable)
            if plat_specific:
                # python.h is located in the buildir
                inc_dir = buildir
            else:
                # the source dir is relative to the buildir
                srcdir = os.path.abspath(os.path.join(buildir,
                                         get_config_var('srcdir')))
                # Include is located in the srcdir
                inc_dir = os.path.join(srcdir, "Include")
            return inc_dir
        return os.path.join(prefix, "include", "python" + get_python_version())
    elif os.name == "nt":
        return os.path.join(prefix, "include")
    elif os.name == "os2":
        return os.path.join(prefix, "Include")
    else:
        raise DistutilsPlatformError(
            "I don't know where Python installs its C header files "
            "on platform '%s'" % os.name)

def get_python_lib(plat_specific=0, standard_lib=0, prefix=None):
    """Return the directory containing the Python library (standard or
    site additions).

    If 'plat_specific' is true, return the directory containing
    platform-specific modules, i.e. any module from a non-pure-Python
    module distribution; otherwise, return the platform-shared library
    directory.  If 'standard_lib' is true, return the directory
    containing standard Python library modules; otherwise, return the
    directory for site-specific modules.

    If 'prefix' is supplied, use it instead of sys.prefix or
    sys.exec_prefix -- i.e., ignore 'plat_specific'.
    """
    if prefix is None:
        prefix = plat_specific and EXEC_PREFIX or PREFIX

    if os.name == "posix":
        libpython = os.path.join(prefix,
                                 "lib", "python" + get_python_version())
        if standard_lib:
            return libpython
        else:
            return os.path.join(libpython, "site-packages")

    elif os.name == "nt":
        if standard_lib:
            return os.path.join(prefix, "Lib")
        else:
            if get_python_version() < "2.2":
                return prefix
            else:
                return os.path.join(prefix, "Lib", "site-packages")

    elif os.name == "os2":
        if standard_lib:
            return os.path.join(prefix, "Lib")
        else:
            return os.path.join(prefix, "Lib", "site-packages")

    else:
        raise DistutilsPlatformError(
            "I don't know where Python installs its library "
            "on platform '%s'" % os.name)

def customize_compiler(compiler):
    """Do any platform-specific customization of a CCompiler instance.

    Mainly needed on Unix, so we can plug in the information that
    varies across Unices and is stored in Python's Makefile.
    """
    if compiler.compiler_type == "unix":
        if sys.platform == "darwin":
            # Perform first-time customization of compiler-related
            # config vars on OS X now that we know we need a compiler.
            # This is primarily to support Pythons from binary
            # installers.  The kind and paths to build tools on
            # the user system may vary significantly from the system
            # that Python itself was built on.  Also the user OS
            # version and build tools may not support the same set
            # of CPU architectures for universal builds.
            global _config_vars
            if not _config_vars.get('CUSTOMIZED_OSX_COMPILER', ''):
                import _osx_support
                _osx_support.customize_compiler(_config_vars)
                _config_vars['CUSTOMIZED_OSX_COMPILER'] = 'True'

        (cc, cxx, opt, cflags, ccshared, ldshared, so_ext, ar, ar_flags) = \
            get_config_vars('CC', 'CXX', 'OPT', 'CFLAGS',
                            'CCSHARED', 'LDSHARED', 'SO', 'AR',
                            'ARFLAGS')

        newcc = None
        if 'CC' in os.environ:
            cc = os.environ['CC']
        if 'CXX' in os.environ:
            cxx = os.environ['CXX']
        if 'LDSHARED' in os.environ:
            ldshared = os.environ['LDSHARED']
        if 'CPP' in os.environ:
            cpp = os.environ['CPP']
        else:
            cpp = cc + " -E"           # not always
        if 'LDFLAGS' in os.environ:
            ldshared = ldshared + ' ' + os.environ['LDFLAGS']
        if 'CFLAGS' in os.environ:
            cflags = opt + ' ' + os.environ['CFLAGS']
            ldshared = ldshared + ' ' + os.environ['CFLAGS']
        if 'CPPFLAGS' in os.environ:
            cpp = cpp + ' ' + os.environ['CPPFLAGS']
            cflags = cflags + ' ' + os.environ['CPPFLAGS']
            ldshared = ldshared + ' ' + os.environ['CPPFLAGS']
        if 'AR' in os.environ:
            ar = os.environ['AR']
        if 'ARFLAGS' in os.environ:
            archiver = ar + ' ' + os.environ['ARFLAGS']
        else:
            archiver = ar + ' ' + ar_flags

        cc_cmd = cc + ' ' + cflags
        compiler.set_executables(
            preprocessor=cpp,
            compiler=cc_cmd,
            compiler_so=cc_cmd + ' ' + ccshared,
            compiler_cxx=cxx,
            linker_so=ldshared,
            linker_exe=cc,
            archiver=archiver)

        compiler.shared_lib_extension = so_ext

def get_config_h_filename():
    """Return full pathname of installed pyconfig.h file."""
    if python_build:
        if os.name == "nt":
            inc_dir = os.path.join(project_base, "PC")
        else:
            inc_dir = project_base
    else:
        inc_dir = get_python_inc(plat_specific=1)
    if get_python_version() < '2.2':
        config_h = 'config.h'
    else:
        # The name of the config.h file changed in 2.2
        config_h = 'pyconfig.h'
    return os.path.join(inc_dir, config_h)

def get_makefile_filename():
    """Return full pathname of installed Makefile from the Python build."""
    if python_build:
        return os.path.join(project_base, "Makefile")
    lib_dir = get_python_lib(plat_specific=1, standard_lib=1)
    return os.path.join(lib_dir, "config", "Makefile")

def parse_config_h(fp, g=None):
    """Parse a config.h-style file.

    A dictionary containing name/value pairs is returned.  If an
    optional dictionary is passed in as the second argument, it is
    used instead of a new dictionary.
    """
    if g is None:
        g = {}
    define_rx = re.compile("#define ([A-Z][A-Za-z0-9_]+) (.*)\n")
    undef_rx = re.compile("/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\n")
    #
    while 1:
        line = fp.readline()
        if not line:
            break
        m = define_rx.match(line)
        if m:
            n, v = m.group(1, 2)
            try: v = int(v)
            except ValueError: pass
            g[n] = v
        else:
            m = undef_rx.match(line)
            if m:
                g[m.group(1)] = 0
    return g

# Regexes needed for parsing Makefile (and similar syntaxes,
# like old-style Setup files).
_variable_rx = re.compile("([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)")
_findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)")
_findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}")

def parse_makefile(fn, g=None):
    """Parse a Makefile-style file.

    A dictionary containing name/value pairs is returned.  If an
    optional dictionary is passed in as the second argument, it is
    used instead of a new dictionary.
    """
    from distutils.text_file import TextFile
    fp = TextFile(fn, strip_comments=1, skip_blanks=1, join_lines=1)

    if g is None:
        g = {}
    done = {}
    notdone = {}

    while 1:
        line = fp.readline()
        if line is None:  # eof
            break
        m = _variable_rx.match(line)
        if m:
            n, v = m.group(1, 2)
            v = v.strip()
            # `$$' is a literal `$' in make
            tmpv = v.replace('$$', '')

            if "$" in tmpv:
                notdone[n] = v
            else:
                try:
                    v = int(v)
                except ValueError:
                    # insert literal `$'
                    done[n] = v.replace('$$', '$')
                else:
                    done[n] = v

    # do variable interpolation here
    while notdone:
        for name in notdone.keys():
            value = notdone[name]
            m = _findvar1_rx.search(value) or _findvar2_rx.search(value)
            if m:
                n = m.group(1)
                found = True
                if n in done:
                    item = str(done[n])
                elif n in notdone:
                    # get it on a subsequent round
                    found = False
                elif n in os.environ:
                    # do it like make: fall back to environment
                    item = os.environ[n]
                else:
                    done[n] = item = ""
                if found:
                    after = value[m.end():]
                    value = value[:m.start()] + item + after
                    if "$" in after:
                        notdone[name] = value
                    else:
                        try: value = int(value)
                        except ValueError:
                            done[name] = value.strip()
                        else:
                            done[name] = value
                        del notdone[name]
            else:
                # bogus variable reference; just drop it since we can't deal
                del notdone[name]

    fp.close()

    # strip spurious spaces
    for k, v in done.items():
        if isinstance(v, str):
            done[k] = v.strip()

    # save the results in the global dictionary
    g.update(done)
    return g

def expand_makefile_vars(s, vars):
    """Expand Makefile-style variables -- "${foo}" or "$(foo)" -- in
    'string' according to 'vars' (a dictionary mapping variable names to
    values).  Variables not present in 'vars' are silently expanded to the
    empty string.  The variable values in 'vars' should not contain further
    variable expansions; if 'vars' is the output of 'parse_makefile()',
    you're fine.  Returns a variable-expanded version of 's'.
    """

    # This algorithm does multiple expansion, so if vars['foo'] contains
    # "${bar}", it will expand ${foo} to ${bar}, and then expand
    # ${bar}... and so forth.  This is fine as long as 'vars' comes from
    # 'parse_makefile()', which takes care of such expansions eagerly,
    # according to make's variable expansion semantics.

    while 1:
        m = _findvar1_rx.search(s) or _findvar2_rx.search(s)
        if m:
            (beg, end) = m.span()
            s = s[0:beg] + vars.get(m.group(1)) + s[end:]
        else:
            break
    return s

_config_vars = None

def _init_posix():
    """Initialize the module as appropriate for POSIX systems."""
    # _sysconfigdata is generated at build time, see the sysconfig module
    from _sysconfigdata import build_time_vars
    global _config_vars
    _config_vars = {}
    _config_vars.update(build_time_vars)

def _init_nt():
    """Initialize the module as appropriate for NT"""
    g = {}
    # set basic install directories
    g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1)
    g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1)

    # XXX hmmm.. a normal install puts include files here
    g['INCLUDEPY'] = get_python_inc(plat_specific=0)

    g['SO'] = '.pyd'
    g['EXE'] = ".exe"
    g['VERSION'] = get_python_version().replace(".", "")
    g['BINDIR'] = os.path.dirname(os.path.abspath(sys.executable))

    global _config_vars
    _config_vars = g

def _init_os2():
    """Initialize the module as appropriate for OS/2"""
    g = {}
    # set basic install directories
    g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1)
    g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1)

    # XXX hmmm.. a normal install puts include files here
    g['INCLUDEPY'] = get_python_inc(plat_specific=0)

    g['SO'] = '.pyd'
    g['EXE'] = ".exe"

    global _config_vars
    _config_vars = g

def get_config_vars(*args):
    """With no arguments, return a dictionary of all configuration
    variables relevant for the current platform.  Generally this includes
    everything needed to build extensions and install both pure modules and
    extensions.  On Unix, this means every variable defined in Python's
    installed Makefile; on Windows and Mac OS it's a much smaller set.

    With arguments, return a list of values that result from looking up
    each argument in the configuration variable dictionary.
    """
    global _config_vars
    if _config_vars is None:
        func = globals().get("_init_" + os.name)
        if func:
            func()
        else:
            _config_vars = {}

        # Normalized versions of prefix and exec_prefix are handy to have;
        # in fact, these are the standard versions used most places in the
        # Distutils.
        _config_vars['prefix'] = PREFIX
        _config_vars['exec_prefix'] = EXEC_PREFIX

        # OS X platforms require special customization to handle
        # multi-architecture, multi-os-version installers
        if sys.platform == 'darwin':
            import _osx_support
            _osx_support.customize_config_vars(_config_vars)

    if args:
        vals = []
        for name in args:
            vals.append(_config_vars.get(name))
        return vals
    else:
        return _config_vars

def get_config_var(name):
    """Return the value of a single variable using the dictionary
    returned by 'get_config_vars()'.  Equivalent to
    get_config_vars().get(name)
    """
    return get_config_vars().get(name)


text:
<!doctype html>

    <meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE" />
    <meta charset="utf-8" />
    <title>Gauge Test Results</title>
    <link rel="shortcut icon" type="image/x-icon" href="../../images/favicon.ico">
    <link rel="stylesheet" type="text/css" href="../../css/open-sans.css">
    <link rel="stylesheet" type="text/css" href="../../css/font-awesome.css">
    <link rel="stylesheet" type="text/css" href="../../css/normalize.css" />
    <link rel="stylesheet" type="text/css" href="../../css/style.css" />

Project: quorum-acceptance-test

        <svg id="pie-chart" data-results="1,3,0" data-total="4">
          <path class="status failed" />
          <path class="shadow failed" data-status="failed"><title>Failed: 1/4</title></path>
          <path class="status passed" />
          <path class="shadow passed" data-status="passed"><title>Passed: 3/4</title></path>
          <path class="status skipped" />
          <path class="shadow skipped" data-status="skipped"><title>Skipped: 0/4</title></path>
        </svg>

4Total specs

1Failed

3Passed

0Skipped

          Environment
          default

          Success Rate
          75%

          Total Time
          00:00:37

          Generated On
          Sep 25, 2018 at 2:00am

Specifications

        <input id="searchSpecifications" placeholder="Type specification or tag name" type="text" />

              Value-based Private Transactions
              00:00:00

              Multiple Private Smart Contracts
              00:00:19

              Single Private Smart Contract
              00:00:11

              Value-based Public Transactions
              00:00:05

Value-based Private Transactions

1Failed

1Passed

0Skipped

          File Path
          <input id="specFileName" value="/home/travis/build/trung/quorum-acceptance-test/src/specs/value_based_private_transactions.spec" readonly/>
          <button class="clipboard-btn" data-clipboard-target="#specFileName" title="Copy to Clipboard">

          </button>

        00:00:00

Quorum does not support value-based private transactions.

Unsuccessful signed private transaction submission

    00:00:00

      Tags:

         privacy

         nosupport

         sign

Signing the transaction before submitting it to the node

      Execution Time : 00:00:00

        Send some ETH from a default account in

      "Node3"

         to a default account in

      "Node4"

         in a signed private transaction.

      Execution Time : 00:00:00

        An error is returned.

java.lang.AssertionError: [An error must be returned]
Expecting actual not to be null

com.quorum.gauge.ValueBasedPrivateTransaction.verifyError(ValueBasedPrivateTransaction.java:42)

Unsuccessful private transaction submission

    00:00:00

      Tags:

         privacy

         nosupport

      Execution Time : 00:00:00

        Send some ETH from a default account in

      "Node1"

         to a default account in

      "Node2"

         in a private transaction.

      Execution Time : 00:00:00

        An error is returned.

Generated by Gauge HTML Report

redpajama_set_name: RedPajamaGithub


text:
using System;

namespace Mozu.Api.Contracts.CommerceRuntime.Fulfillment
{
		public class DigitalPackageItem
		{
			///
			///This specifies the fulfillment type of digital package item.
			///
			public string FulfillmentItemType { get; set; }

			///
			///Specifies the gift card code for the digital package item.
			///
			public string GiftCardCode { get; set; }

			///
			///The line id associated with the fulfillment.
			///
			public int? LineId { get; set; }

			///
			///Fully qualified name of the selected option's attribute. Bundledproducts result from a static bundle or are dynamically added as a result of the shopper selecting products as extras. When the bundled item is dynamic, it includes the attribute's fully qualified name of the extra that it came from. When `optionAttributeFQN `is null, the bundled item was statically defined. When not null, the item came from an extra selection.
			///
			public string OptionAttributeFQN { get; set; }

			///
			///The unique, user-defined  product code of a product, used throughout Mozu to reference and associate to a product.
			///
			public string ProductCode { get; set; }

			///
			///The specified quantity of objects and items. This property is used for numerous object types including products, options, components within a product bundle, cart and order items, returned items, shipping line items, items in a digital product. and items associated with types and reservations.
			///
			public int Quantity { get; set; }

		}

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Syst. mycol. (Lundae) 2(1): 189 (1822)

#### Original name
Cenangium turgidum Fr.

### Remarks
null


text:
angular
.module("content", ['KM_tools', 'ngRoute', 'socket.io', 'infinite-scroll', 'angularModalService'])
.config(['$routeProvider', function ($routeProvider) {
			$routeProvider
			.when('/search', {
				templateUrl : '_search.html',
				controller : '_search'
			})
			.when('/borrowed', {
				templateUrl : '_borrowed.html',
				controller : '_borrowed'
			})
			.when('/lent', {
				templateUrl : '_lent.html',
				controller : '_lent'
			})
			.when('/mylist', {
				templateUrl : '_mylist.html',
				controller : '_mylist'
			})
			.when('/new', {
				templateUrl : '_edit.html',
				controller : '_new'
			})
			.when('/edit/:itemId', {
				templateUrl : '_edit.html',
				controller : '_edit'
			})
			.when('/user/:userId', {
				templateUrl : '_user.html',
				controller : '_user'
			})
			.when('/editUser', {
				templateUrl : '_editUser.html',
				controller : '_editUser'
			})
			.when('/directDb', {
				templateUrl : '_directDb.html',
				controller : '_directDb'
			})
			.when('/messages', {
				templateUrl : '_messages.html',
				controller : '_messages'
			})
			.otherwise({
				templateUrl : '_messages.html',
				controller : '_messages'
			});
		}
	])
.config(['$socketProvider', 'configPara', function ($socketProvider, configPara) {
			$socketProvider.setConnectionUrl(configPara.ip);
		}
	])
.service('rootData', ['common', '$rootScope', function (common, $rootScope) {
			var listData = {
				search : [],
				borrowed : [],
				lent : [],
				mylist : [],
				messages: []
			},
			historyRec = {
				data : ['', '', '', '', '', '', '', '', '', ''],
				ptr : 0,
				showBackArrow : false
			};
			this.historyRec = historyRec;
			this.historyRec.set = function (url, level) {
				historyRec.showBackArrow = (level < 2) ? false : true;
				historyRec.ptr = level;
				historyRec.data[level] = url;
			};
			this.historyRec.push = function (url) {
				historyRec.showBackArrow = true;
				historyRec.data[++historyRec.ptr] = url;
			};
			this.historyRec.pop = function (url) {
				if (historyRec.ptr > 0) {
					--historyRec.ptr;
					if (historyRec.ptr === 0) {
						historyRec.showBackArrow = false;
					}
				}
			};
			this.listData = listData;
			var UpdateRootData = function (whatData) {
				if (whatData) {
					return common.xhr('getAllData', {whatData: whatData}).then(function (data) {
						Object.keys(data).forEach(function (key) {
							listData[key] = data[key];
						});
						return listData;
					});
				}
			};
			this.UpdateRootData = UpdateRootData;
		}
	])
.service('PushService', ['common', 'rootData', '$rootScope', '$injector', function (common, rootData, $rootScope, $injector) {
	if (window.cordova) {
		var push = PushNotification.init({
				android: {
						senderID: "605583753010"
				},
				ios: {
						alert: "true",
						badge: "true",
						sound: "true"
				},
				windows: {}
		});
		push.on('registration', function(data) {
			// data.registrationId
			function retryInterval(){
				common.xhr('GCMregistrationId', data).then(function(msg){
					if (msg) {
						setTimeout(retryInterval, 15000); // retry registration
					}
				}, function(){setTimeout(retryInterval, 3000)});
			}
			retryInterval();
		});
		push.on('notification', function(data) {
			common.xhr('ReportBrowserError', {message: data}).then(function (msg) {});
			common.xhr('ReportBrowserError', {message: data.additionalData.whatData}).then(function (msg) {});
			// rootData.UpdateRootData([{name: 'all'}]);
			rootData.UpdateRootData(data.additionalData.whatData);
		});
		push.on('error', function(e) {
			// e.message
			common.xhr('ReportBrowserError', e).then(function (msg) {});
		});
		rootData.UpdateRootData([{name: 'all'}]); // when app starts
		document.addEventListener("resume", function(){rootData.UpdateRootData([{name: 'all'}]);}, false);
	} else { // fall back to socket.io if in browser
		if ($injector.has('$socket')) {
			$socket = $injector.get('$socket');
			$socket.on('connect', function () {
				console.log('Socket connected.');
				rootData.UpdateRootData([{name: 'all'}]);
			});
			$socket.on('update', function (whatData) {
				rootData.UpdateRootData(whatData);
			});
		}
	}
}])
.controller("content_main", ['$scope', 'common', 'rootData', 'PushService', function ($scope, common, rootData, PushService) {
			$scope.showAlert = false;
			$scope.errorMsg = '';
			$scope.historyRec = rootData.historyRec;
			common.xhr('isLoggedIn', {}).then(function (msg) {
				if (msg) {
				} else {
					window.location.assign("signInUp.html");
				}
			});
			$scope.logoff = function () {
				common.xhr('logoff', {}).then(function (msg) {
					if (msg) {
						$scope.showAlert = true;
						$scope.errorMsg = msg;
					} else {
						window.location.assign("signInUp.html");
					}
				});
			};
			$scope.GoBack = function () {
				if (rootData.historyRec.ptr > 1) {
					rootData.historyRec.ptr = rootData.historyRec.ptr - 2;
					window.location.assign('#/' + rootData.historyRec.data[rootData.historyRec.ptr + 1]);
				}
			};
		}
	])
.controller("_search", ['$scope', 'common', 'rootData', 'ModalService', function ($scope, common, rootData, ModalService) {
			rootData.historyRec.set('search', 1);
			//console.log(rootData.historyRec.data, rootData.historyRec.ptr);
			$scope.listData = rootData.listData;
			$scope.showAlert = false;
			$scope.errorMsg = '';
			$scope.itemsInList = 5;
			$scope.LoadMore = function () {
				$scope.itemsInList = $scope.itemsInList + 5;
			};
			$scope.SearchItem = function () {
				common.xhr('SearchItem', {
					searchString : $scope.search
				}).then(function (items) {
					$scope.items = items;
				});
			};
			$scope.GrabItem = function (itemId) {
				common.xhr('GrabItem', {
					id : itemId
				}).then(function (msg) {
					if (msg) {
						$scope.showAlert = true;
						$scope.errorMsg = msg + 'error';
					} else {
						$scope.showAlert = true;
						$scope.errorMsg = 'One item got!';
					}
				});
			};
			$scope.showModal = function(user) {
				ModalService.showModal({
					templateUrl: '_showUserModal.html',
					controller: "_showUserModal",
					inputs: {
						showUserModalData: user
					}
				}).then(function(modal) {
					modal.element.modal();
					modal.close.then(function(result) {
							$scope.message = "You said " + result;
					});
				});
			};
		}
	])
.controller("_showUserModal", ['$scope', 'showUserModalData', 'close', function ($scope, showUserModalData, close) {
	$scope.user = showUserModalData;
	$scope.close = function(result) {
		close(result, 500); // close, but give 500ms for bootstrap to animate
	};
}])
.controller("_borrowed", ['$scope', 'common', 'rootData', function ($scope, common, rootData) {
			rootData.historyRec.set('borrowed', 1);
			$scope.listData = rootData.listData;
			$scope.showAlert = false;
			$scope.errorMsg = '';
			$scope.itemsInList = 5;
			$scope.LoadMore = function () {
				$scope.itemsInList = $scope.itemsInList + 5;
			};
		}
	])
.controller("_lent", ['$scope', 'common', 'rootData', function ($scope, common, rootData) {
			rootData.historyRec.set('lent', 1);
			$scope.listData = rootData.listData;
			$scope.showAlert = false;
			$scope.errorMsg = '';
			$scope.itemsInList = 5;
			$scope.LoadMore = function () {
				$scope.itemsInList = $scope.itemsInList + 5;
			};
			$scope.ReceiveItem = function (holderId, itemId) {
				console.log(itemId);
				common.xhr('ReceiveItem', {
					from : holderId,
					item : itemId
				}).then(function (msg) {
					if (msg) {
						$scope.showAlert = true;
						$scope.errorMsg = msg + 'error';
					} else {
						$scope.showAlert = true;
						$scope.errorMsg = 'One item got back!';
					}
				});
			};
		}
	])
.controller('_mylist', ['$scope', 'common', 'rootData', function ($scope, common, rootData) {
			rootData.historyRec.push('mylist');
			$scope.listData = rootData.listData;
			$scope.itemsInList = 5;
			$scope.LoadMore = function () {
				$scope.itemsInList = $scope.itemsInList + 5;
			};
		}
	])
.controller('_new', ['$scope', 'common', 'rootData', function ($scope, common, rootData) {
			rootData.historyRec.push('new');
			$scope.showQuantity = true;
			$scope.item = {
				MLS : 123,
				quantity : 2,
				street : '1 king st',
				city : 'London',
				province : 'FS',
				postcode : 'H0H0H0',
				description : 'good location'
			};
			$scope.ChangeItem = function () {
				common.xhr('NewItem', $scope.item).then(function (msg) {
					if (msg) {
						$scope.showAlert = true;
						$scope.errorMsg = msg + 'error';
					} else {
						$scope.showAlert = true;
						$scope.errorMsg = 'Item created!';
					}
				});
			};
		}
	])
.controller('_edit', ['$scope', 'common', 'rootData', '$routeParams', function ($scope, common, rootData, $routeParams) {
			rootData.historyRec.push('edit/' + $routeParams.itemId);
			$scope.showQuantity = false;
			common.xhr('GetItem', {
				id : $routeParams.itemId
			}).then(function (item) {
				$scope.item = item;
			});
			$scope.ChangeItem = function () {
				common.xhr('UpdateItem', $scope.item).then(function (msg) {
					if (msg) {
						$scope.showAlert = true;
						$scope.errorMsg = msg;
					} else {
						$scope.showAlert = true;
						$scope.errorMsg = 'Item updated!';
					}
				});
			};
			$scope.DeleteItem = function () {
				common.xhr('DeleteItem', $scope.item).then(function (msg) {
					if (msg) {
						$scope.showAlert = true;
						$scope.errorMsg = msg;
					} else {
						$scope.showAlert = true;
						$scope.errorMsg = 'Item deleted!';
					}
				});
			};
		}
	])
.controller('_user', ['$scope', 'common', 'rootData', '$routeParams', function ($scope, common, rootData, $routeParams) {
			rootData.historyRec.push('user/' + $routeParams.userId);
			common.xhr('GetUser', {
				id : Number($routeParams.userId)
			}).then(function (tempUser) {
				$scope.user = tempUser;
				if (Number($routeParams.userId) === 0) {
					$scope.isThisUser = true;
				} else {
					common.xhr('GetUser', {})
					.then(function (tempUser2) {
						$scope.isThisUser = (Number($routeParams.userId) === tempUser2.id);
					});
				}
			});
		}
	])
.controller('_editUser', ['$scope', 'common', 'rootData', '$routeParams', function ($scope, common, rootData, $routeParams) {
			rootData.historyRec.push('editUser/');
			common.xhr('GetUser', {}).then(function (user) {
				$scope.user = user;
			});
			$scope.UpdateUser = function () {
				common.xhr('UpdateUser', $scope.user).then(function (msg) {
					if (msg) {
						$scope.showAlert = true;
						$scope.errorMsg = msg;
					} else {
						$scope.showAlert = true;
						$scope.errorMsg = 'User updated!';
					}
				});
			};
		}
	])
.controller('_directDb', ['$scope', 'common', 'rootData', '$routeParams', function ($scope, common, rootData, $routeParams) {
			rootData.historyRec.push('directDb/');
			$scope.item = {content: '', command: ''};
			$scope.DirectDb = function () {
				$scope.item.content += '--- COMMAND --- \n';
				$scope.item.content += $scope.item.command;
				$scope.item.content += '\n--- RESPONSE --- \n';
				common.xhr('DirectDb', {command: $scope.item.command}).then(function (msg) {
					$scope.item.command = '';
					$scope.item.content += JSON.stringify(msg);
					$scope.item.content += '\n\n';
					setTimeout(function(){
						document.getElementById("textarea1").scrollTop = document.getElementById("textarea1").scrollHeight;
					}, 200);

				});
			};
		}
	])
.controller('_messages', ['$scope', 'common', 'rootData', function ($scope, common, rootData) {
			rootData.historyRec.push('messages');
			$scope.listData = rootData.listData;
			$scope.listLength = 5;
			$scope.LoadMore = function () {
				$scope.listLength = $scope.listLength + 5;
			};
			var viewID = [];
			$scope.listData.messages.forEach(function(message){
				if (!message.viewed) {
					viewID.push(message.id);
					message.viewed = true;
				}
			});
			if (viewID.length > 0) {
				common.xhr('MsgViewed', {viewID: viewID}).then(function (msg) {
					if (msg) {
						$scope.showAlert = true;
						$scope.errorMsg = msg;
					} else {
						$scope.showAlert = true;
						$scope.errorMsg = 'Latest massages viewed!';
					}
				});
			}
		}
	]);

angular.element(document).ready(function () {
	if (window.cordova) {
		document.addEventListener('deviceready', function () {
			angular.bootstrap(document, ['content']);
		}, false);
	} else {
		angular.bootstrap(document, ['content']);
	}
});


text:
<!DOCTYPE html>
<!--
Copyright (C) 2016 The Android Open Source Project

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
<title>gr-diff-cursor</title>

<script src="../../../bower_components/webcomponentsjs/webcomponents-lite.min.js"></script>
<script src="../../../bower_components/web-component-tester/browser.js"></script>
<link rel="import" href="../../../test/common-test-setup.html"/>
<script src="../../../scripts/util.js"></script>

<link rel="import" href="../gr-diff/gr-diff.html">
<link rel="import" href="./gr-diff-cursor.html">
<link rel="import" href="../../shared/gr-rest-api-interface/mock-diff-response_test.html">

<script>void(0);</script>

<test-fixture id="basic">
  <template>
    <mock-diff-response></mock-diff-response>
    <gr-diff></gr-diff>
    <gr-diff-cursor></gr-diff-cursor>
  </template>
</test-fixture>

<script>
  suite('gr-diff-cursor tests', () => {
    let sandbox;
    let cursorElement;
    let diffElement;
    let mockDiffResponse;

    setup(done => {
      sandbox = sinon.sandbox.create();

      stub('gr-rest-api-interface', {
        getLoggedIn() { return Promise.resolve(false); },
      });

      const fixtureElems = fixture('basic');
      mockDiffResponse = fixtureElems[0];
      diffElement = fixtureElems[1];
      cursorElement = fixtureElems[2];

      // Register the diff with the cursor.
      cursorElement.push('diffs', diffElement);

      diffElement.comments = {left: [], right: []};
      diffElement.$.restAPI.getDiffPreferences().then(prefs => {
        diffElement.prefs = prefs;
      });

      sandbox.stub(diffElement, '_getDiff', () => {
        return Promise.resolve(mockDiffResponse.diffResponse);
      });

      const setupDone = () => {
        cursorElement._updateStops();
        cursorElement.moveToFirstChunk();
        diffElement.removeEventListener('render', setupDone);
        done();
      };
      diffElement.addEventListener('render', setupDone);

      diffElement.reload();
    });

    teardown(() => sandbox.restore());

    test('diff cursor functionality (side-by-side)', () => {
      // The cursor has been initialized to the first delta.
      assert.isOk(cursorElement.diffRow);

      const firstDeltaRow = diffElement.$$('.section.delta .diff-row');
      assert.equal(cursorElement.diffRow, firstDeltaRow);

      cursorElement.moveDown();

      assert.notEqual(cursorElement.diffRow, firstDeltaRow);
      assert.equal(cursorElement.diffRow, firstDeltaRow.nextSibling);

      cursorElement.moveUp();

      assert.notEqual(cursorElement.diffRow, firstDeltaRow.nextSibling);
      assert.equal(cursorElement.diffRow, firstDeltaRow);
    });

    test('cursor scroll behavior', () => {
      cursorElement._handleDiffRenderStart();
      assert.equal(cursorElement._scrollBehavior, 'keep-visible');
      assert.isTrue(cursorElement._focusOnMove);

      cursorElement._handleWindowScroll();
      assert.equal(cursorElement._scrollBehavior, 'never');
      assert.isFalse(cursorElement._focusOnMove);

      cursorElement.handleDiffUpdate();
      assert.equal(cursorElement._scrollBehavior, 'keep-visible');
      assert.isTrue(cursorElement._focusOnMove);
    });

    suite('unified diff', () => {
      setup(done => {
        // We must allow the diff to re-render after setting the viewMode.
        const renderHandler = function() {
          diffElement.removeEventListener('render', renderHandler);
          cursorElement.reInitCursor();
          done();
        };
        diffElement.addEventListener('render', renderHandler);
        diffElement.viewMode = 'UNIFIED_DIFF';
      });

      test('diff cursor functionality (unified)', () => {
        // The cursor has been initialized to the first delta.
        assert.isOk(cursorElement.diffRow);

        let firstDeltaRow = diffElement.$$('.section.delta .diff-row');
        assert.equal(cursorElement.diffRow, firstDeltaRow);

        firstDeltaRow = diffElement.$$('.section.delta .diff-row');
        assert.equal(cursorElement.diffRow, firstDeltaRow);

        cursorElement.moveDown();

        assert.notEqual(cursorElement.diffRow, firstDeltaRow);
        assert.equal(cursorElement.diffRow, firstDeltaRow.nextSibling);

        cursorElement.moveUp();

        assert.notEqual(cursorElement.diffRow, firstDeltaRow.nextSibling);
        assert.equal(cursorElement.diffRow, firstDeltaRow);
      });
    });

    test('cursor side functionality', () => {
      // The side only applies to side-by-side mode, which should be the default
      // mode.
      assert.equal(diffElement.viewMode, 'SIDE_BY_SIDE');

      const firstDeltaSection = diffElement.$$('.section.delta');
      const firstDeltaRow = firstDeltaSection.querySelector('.diff-row');

      // Because the first delta in this diff is on the right, it should be set
      // to the right side.
      assert.equal(cursorElement.side, 'right');
      assert.equal(cursorElement.diffRow, firstDeltaRow);
      const firstIndex = cursorElement.$.cursorManager.index;

      // Move the side to the left. Because this delta only has a right side, we
      // should be moved up to the previous line where there is content on the
      // right. The previous row is part of the previous section.
      cursorElement.moveLeft();

      assert.equal(cursorElement.side, 'left');
      assert.notEqual(cursorElement.diffRow, firstDeltaRow);
      assert.equal(cursorElement.$.cursorManager.index, firstIndex - 1);
      assert.equal(cursorElement.diffRow.parentElement,
          firstDeltaSection.previousSibling);

      // If we move down, we should skip everything in the first delta because
      // we are on the left side and the first delta has no content on the left.
      cursorElement.moveDown();

      assert.equal(cursorElement.side, 'left');
      assert.notEqual(cursorElement.diffRow, firstDeltaRow);
      assert.isTrue(cursorElement.$.cursorManager.index > firstIndex);
      assert.equal(cursorElement.diffRow.parentElement,
          firstDeltaSection.nextSibling);
    });

    test('chunk skip functionality', () => {
      const chunks = Polymer.dom(diffElement.root).querySelectorAll(
          '.section.delta');
      const indexOfChunk = function(chunk) {
        return Array.prototype.indexOf.call(chunks, chunk);
      };

      // We should be initialized to the first chunk. Since this chunk only has
      // content on the right side, our side should be right.
      let currentIndex = indexOfChunk(cursorElement.diffRow.parentElement);
      assert.equal(currentIndex, 0);
      assert.equal(cursorElement.side, 'right');

      // Move to the next chunk.
      cursorElement.moveToNextChunk();

      // Since this chunk only has content on the left side. we should have been
      // automatically mvoed over.
      const previousIndex = currentIndex;
      currentIndex = indexOfChunk(cursorElement.diffRow.parentElement);
      assert.equal(currentIndex, previousIndex + 1);
      assert.equal(cursorElement.side, 'left');
    });

    test('initialLineNumber disabled', done => {
      const moveToNumStub = sandbox.stub(cursorElement, 'moveToLineNumber');
      const moveToChunkStub = sandbox.stub(cursorElement, 'moveToFirstChunk');

      function renderHandler() {
        diffElement.removeEventListener('render', renderHandler);
        assert.isFalse(moveToNumStub.called);
        assert.isTrue(moveToChunkStub.called);
        done();
      }
      diffElement.addEventListener('render', renderHandler);
      diffElement.reload();
    });

    test('initialLineNumber enabled', done => {
      const moveToNumStub = sandbox.stub(cursorElement, 'moveToLineNumber');
      const moveToChunkStub = sandbox.stub(cursorElement, 'moveToFirstChunk');

      function renderHandler() {
        diffElement.removeEventListener('render', renderHandler);
        assert.isFalse(moveToChunkStub.called);
        assert.isTrue(moveToNumStub.called);
        assert.equal(moveToNumStub.lastCall.args[0], 10);
        assert.equal(moveToNumStub.lastCall.args[1], 'right');
        done();
      }
      diffElement.addEventListener('render', renderHandler);

      cursorElement.initialLineNumber = 10;
      cursorElement.side = 'right';

      diffElement.reload();
    });

    test('getAddress', () => {
      // It should initialize to the first chunk: line 5 of the revision.
      assert.deepEqual(cursorElement.getAddress(),
          {leftSide: false, number: 5});

      // Revision line 4 is up.
      cursorElement.moveUp();
      assert.deepEqual(cursorElement.getAddress(),
          {leftSide: false, number: 4});

      // Base line 4 is left.
      cursorElement.moveLeft();
      assert.deepEqual(cursorElement.getAddress(), {leftSide: true, number: 4});

      // Moving to the next chunk takes it back to the start.
      cursorElement.moveToNextChunk();
      assert.deepEqual(cursorElement.getAddress(),
          {leftSide: false, number: 5});

      // The following chunk is a removal starting on line 10 of the base.
      cursorElement.moveToNextChunk();
      assert.deepEqual(cursorElement.getAddress(),
          {leftSide: true, number: 10});

      // Should be null if there is no selection.
      cursorElement.$.cursorManager.unsetCursor();
      assert.isNotOk(cursorElement.getAddress());
    });

    test('_findRowByNumberAndFile', () => {
      // Get the first ab row after the first chunk.
      const row = Polymer.dom(diffElement.root).querySelectorAll('tr')[8];

      // It should be line 8 on the right, but line 5 on the left.
      assert.equal(cursorElement._findRowByNumberAndFile(8, 'right'), row);
      assert.equal(cursorElement._findRowByNumberAndFile(5, 'left'), row);
    });

    test('expand context updates stops', done => {
      sandbox.spy(cursorElement, 'handleDiffUpdate');
      MockInteractions.tap(diffElement.$$('.showContext'));
      flush(() => {
        assert.isTrue(cursorElement.handleDiffUpdate.called);
        done();
      });
    });
  });
</script>


text:
FinalCache uses LRU to evict entries. However it does not use access-history to compute LRU. Rather when objects become unused they become managed by LRU. Usage is determined by the garbage collector.

## .NET Core (Cross-Platform)

> dotnet build

> dotnet run

## Linux:

Required: Mono SDK

> dmcs Program.cs

> ./Program.exe

## Windows:

Required: Visual Studio or Microsoft Build Tools/SDK

> csc Program.cs

> .\Program.exe


text:
namespace v8 {
namespace internal {
namespace compiler {

typedef std::set<int> VirtualRegisterSet;

enum InstructionSelectorTesterMode { kTargetMode, kInternalMode };

class InstructionSelectorTester : public HandleAndZoneScope,
                                  public RawMachineAssembler {
 public:
  enum Mode { kTargetMode, kInternalMode };

  static const int kParameterCount = 3;
  static MachineType* BuildParameterArray(Zone* zone) {
    MachineType* array = zone->NewArray<MachineType>(kParameterCount);
    for (int i = 0; i < kParameterCount; ++i) {
      array[i] = kMachineWord32;
    }
    return array;
  }

  InstructionSelectorTester()
      : RawMachineAssembler(
            new (main_zone()) Graph(main_zone()), new (main_zone())
            MachineCallDescriptorBuilder(kMachineWord32, kParameterCount,
                                         BuildParameterArray(main_zone())),
            MachineOperatorBuilder::pointer_rep()) {}

  void SelectInstructions(CpuFeature feature) {
    SelectInstructions(InstructionSelector::Features(feature));
  }

  void SelectInstructions(CpuFeature feature1, CpuFeature feature2) {
    SelectInstructions(InstructionSelector::Features(feature1, feature2));
  }

  void SelectInstructions(Mode mode = kTargetMode) {
    SelectInstructions(InstructionSelector::Features(), mode);
  }

  void SelectInstructions(InstructionSelector::Features features,
                          Mode mode = kTargetMode) {
    OFStream out(stdout);
    Schedule* schedule = Export();
    CHECK_NE(0, graph()->NodeCount());
    CompilationInfo info(main_isolate(), main_zone());
    Linkage linkage(&info, call_descriptor());
    InstructionSequence sequence(&linkage, graph(), schedule);
    SourcePositionTable source_positions(graph());
    InstructionSelector selector(&sequence, &source_positions, features);
    selector.SelectInstructions();
    out << "--- Code sequence after instruction selection --- " << endl
        << sequence;
    for (InstructionSequence::const_iterator i = sequence.begin();
         i != sequence.end(); ++i) {
      Instruction* instr = *i;
      if (instr->opcode() < 0) continue;
      if (mode == kTargetMode) {
        switch (ArchOpcodeField::decode(instr->opcode())) {
#define CASE(Name) \
  case k##Name:    \
    break;
          TARGET_ARCH_OPCODE_LIST(CASE)
#undef CASE
          default:
            continue;
        }
      }
      code.push_back(instr);
    }
    for (int vreg = 0; vreg < sequence.VirtualRegisterCount(); ++vreg) {
      if (sequence.IsDouble(vreg)) {
        CHECK(!sequence.IsReference(vreg));
        doubles.insert(vreg);
      }
      if (sequence.IsReference(vreg)) {
        CHECK(!sequence.IsDouble(vreg));
        references.insert(vreg);
      }
    }
    immediates.assign(sequence.immediates().begin(),
                      sequence.immediates().end());
  }

  int32_t ToInt32(const InstructionOperand* operand) const {
    size_t i = operand->index();
    CHECK(i < immediates.size());
    CHECK_EQ(InstructionOperand::IMMEDIATE, operand->kind());
    return immediates[i].ToInt32();
  }

  std::deque<Instruction*> code;
  VirtualRegisterSet doubles;
  VirtualRegisterSet references;
  std::deque<Constant> immediates;
};

static inline void CheckSameVreg(InstructionOperand* exp,
                                 InstructionOperand* val) {
  CHECK_EQ(InstructionOperand::UNALLOCATED, exp->kind());
  CHECK_EQ(InstructionOperand::UNALLOCATED, val->kind());
  CHECK_EQ(UnallocatedOperand::cast(exp)->virtual_register(),
           UnallocatedOperand::cast(val)->virtual_register());
}

}  // namespace compiler
}  // namespace internal
}  // namespace v8

#endif  // V8_CCTEST_COMPILER_INSTRUCTION_SELECTOR_TEST_H_


text:
#include "mongoc/mongoc-prelude.h"

#ifndef MONGOC_URI_PRIVATE_H
#define MONGOC_URI_PRIVATE_H

#include "mongoc/mongoc-uri.h"

BSON_BEGIN_DECLS

bool
mongoc_uri_append_host (mongoc_uri_t *uri,
                        const char *host,
                        uint16_t port,
                        bson_error_t *error);
bool
mongoc_uri_parse_host (mongoc_uri_t *uri, const char *str);
bool
mongoc_uri_parse_options (mongoc_uri_t *uri,
                          const char *str,
                          bool from_dns,
                          bson_error_t *error);
int32_t
mongoc_uri_get_local_threshold_option (const mongoc_uri_t *uri);

bool
_mongoc_uri_requires_auth_negotiation (const mongoc_uri_t *uri);

BSON_END_DECLS

#endif /* MONGOC_URI_PRIVATE_H */


text:
class EmailValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
      record.errors[attribute] << (options[:message] || 'is not an email')
    end
  end
end

class Lead < ActiveRecord::Base
  # Validations
  validates :email, presence: true, email: true
end


text:
package freemarker.core;

import freemarker.template.TemplateException;

/**
 * For internal use only; don't depend on this, there's no backward compatibility guarantee at all!
 * {@link TemplateException}-s that don't fit into any category that warrant its own class. In fact, this was added
 * because the API of {@link TemplateException} is too simple for the purposes of the core, but it can't be
 * extended without breaking backward compatibility and exposing internals.
 */
public class _MiscTemplateException extends TemplateException {

    // -----------------------------------------------------------------------------------------------------------------
    // Permutation group:

    public _MiscTemplateException(String description) {
        super(description, null);
    }

    public _MiscTemplateException(Environment env, String description) {
        super(description, env);
    }

    // -----------------------------------------------------------------------------------------------------------------
    // Permutation group:

    public _MiscTemplateException(Throwable cause, String description) {
        this(cause, null, description);
    }

    public _MiscTemplateException(Throwable cause, Environment env) {
        this(cause, env, (String) null);
    }

    public _MiscTemplateException(Throwable cause) {
        this(cause, null, (String) null);
    }

    public _MiscTemplateException(Throwable cause, Environment env, String description) {
        super(description, cause, env);
    }

    // -----------------------------------------------------------------------------------------------------------------
    // Permutation group:

    public _MiscTemplateException(_ErrorDescriptionBuilder description) {
        this(null, description);
    }

    public _MiscTemplateException(Environment env, _ErrorDescriptionBuilder description) {
        this(null, env, description);
    }

    public _MiscTemplateException(Throwable cause, Environment env, _ErrorDescriptionBuilder description) {
        super(cause, env, null, description);
    }

    // -----------------------------------------------------------------------------------------------------------------
    // Permutation group:

    public _MiscTemplateException(Object... descriptionParts) {
        this((Environment) null, descriptionParts);
    }

    public _MiscTemplateException(Environment env, Object... descriptionParts) {
        this((Throwable) null, env, descriptionParts);
    }

    public _MiscTemplateException(Throwable cause, Object... descriptionParts) {
        this(cause, null, descriptionParts);
    }

    public _MiscTemplateException(Throwable cause, Environment env, Object... descriptionParts) {
        super(cause, env, null, new _ErrorDescriptionBuilder(descriptionParts));
    }

    // -----------------------------------------------------------------------------------------------------------------
    // Permutation group:

    public _MiscTemplateException(Expression blamed, Object... descriptionParts) {
        this(blamed, null, descriptionParts);
    }

    public _MiscTemplateException(Expression blamed, Environment env, Object... descriptionParts) {
        this(blamed, null, env, descriptionParts);
    }

    public _MiscTemplateException(Expression blamed, Throwable cause, Environment env, Object... descriptionParts) {
        super(cause, env, blamed, new _ErrorDescriptionBuilder(descriptionParts).blame(blamed));
    }

    // -----------------------------------------------------------------------------------------------------------------
    // Permutation group:

    public _MiscTemplateException(Expression blamed, String description) {
        this(blamed, null, description);
    }

    public _MiscTemplateException(Expression blamed, Environment env, String description) {
        this(blamed, null, env, description);
    }

    public _MiscTemplateException(Expression blamed, Throwable cause, Environment env, String description) {
        super(cause, env, blamed, new _ErrorDescriptionBuilder(description).blame(blamed));
    }

}


text:
"""Auto-generated file, do not edit by hand. SO metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata

PHONE_METADATA_SO = PhoneMetadata(id='SO', country_code=None, international_prefix=None,
    general_desc=PhoneNumberDesc(national_number_pattern='[57-9]\\d\\d', possible_length=(3,)),
    toll_free=PhoneNumberDesc(national_number_pattern='555|888|999', example_number='555', possible_length=(3,)),
    emergency=PhoneNumberDesc(national_number_pattern='555|888|999', example_number='555', possible_length=(3,)),
    short_code=PhoneNumberDesc(national_number_pattern='555|777|888|999', example_number='555', possible_length=(3,)),
    short_data=True)


text:
import java.io.Serializable;

public class SerialChanged implements Serializable {
    private static final long serialVersionUID = 1L;

    private int f1;
}


text:
from .. utils import TranspileTestCase, UnaryOperationTestCase, BinaryOperationTestCase, InplaceOperationTestCase

class NotImplementedTests(TranspileTestCase):
    def test_truth(self):
        self.assertCodeExecution("""
            x = NotImplemented
            print(x == True)
            """)

class UnaryNotImplementedOperationTests(UnaryOperationTestCase, TranspileTestCase):
    data_type = 'NotImplemented'

class BinaryNotImplementedOperationTests(BinaryOperationTestCase, TranspileTestCase):
    data_type = 'NotImplemented'

    not_implemented = [
        'test_add_bytearray',
        'test_add_class',
        'test_add_complex',
        'test_add_frozenset',

        'test_and_bytearray',
        'test_and_class',
        'test_and_complex',
        'test_and_frozenset',

        'test_eq_bytearray',
        'test_eq_class',
        'test_eq_complex',
        'test_eq_frozenset',

        'test_floor_divide_bytearray',
        'test_floor_divide_class',
        'test_floor_divide_complex',
        'test_floor_divide_frozenset',

        'test_ge_bytearray',
        'test_ge_class',
        'test_ge_complex',
        'test_ge_frozenset',

        'test_gt_bytearray',
        'test_gt_class',
        'test_gt_complex',
        'test_gt_frozenset',

        'test_le_bytearray',
        'test_le_class',
        'test_le_complex',
        'test_le_frozenset',

        'test_lshift_bytearray',
        'test_lshift_class',
        'test_lshift_complex',
        'test_lshift_frozenset',

        'test_lt_bytearray',
        'test_lt_class',
        'test_lt_complex',
        'test_lt_frozenset',

        'test_modulo_bytearray',
        'test_modulo_class',
        'test_modulo_complex',
        'test_modulo_frozenset',

        'test_multiply_bytes',
        'test_multiply_bytearray',
        'test_multiply_class',
        'test_multiply_complex',
        'test_multiply_frozenset',

        'test_ne_bytearray',
        'test_ne_class',
        'test_ne_complex',
        'test_ne_frozenset',

        'test_or_bytearray',
        'test_or_class',
        'test_or_complex',
        'test_or_frozenset',

        'test_power_bytearray',
        'test_power_class',
        'test_power_complex',
        'test_power_frozenset',

        'test_rshift_bytearray',
        'test_rshift_class',
        'test_rshift_complex',
        'test_rshift_frozenset',

        'test_subscr_bytearray',
        'test_subscr_class',
        'test_subscr_complex',
        'test_subscr_frozenset',

        'test_subtract_bytearray',
        'test_subtract_class',
        'test_subtract_complex',
        'test_subtract_frozenset',

        'test_true_divide_bytearray',
        'test_true_divide_class',
        'test_true_divide_complex',
        'test_true_divide_frozenset',

        'test_xor_bytearray',
        'test_xor_class',
        'test_xor_complex',
        'test_xor_frozenset',
    ]

class InplaceNotImplementedOperationTests(InplaceOperationTestCase, TranspileTestCase):
    data_type = 'NotImplemented'

    not_implemented = [
        'test_add_bytearray',
        'test_add_class',
        'test_add_complex',
        'test_add_frozenset',

        'test_and_bytearray',
        'test_and_class',
        'test_and_complex',
        'test_and_frozenset',

        'test_eq_bytearray',
        'test_eq_class',
        'test_eq_complex',
        'test_eq_frozenset',

        'test_floor_divide_bytearray',
        'test_floor_divide_class',
        'test_floor_divide_complex',
        'test_floor_divide_frozenset',

        'test_ge_bytearray',
        'test_ge_class',
        'test_ge_complex',
        'test_ge_frozenset',

        'test_gt_bytearray',
        'test_gt_class',
        'test_gt_complex',
        'test_gt_frozenset',

        'test_le_bytearray',
        'test_le_class',
        'test_le_complex',
        'test_le_frozenset',

        'test_lshift_bytearray',
        'test_lshift_class',
        'test_lshift_complex',
        'test_lshift_frozenset',

        'test_lt_bytearray',
        'test_lt_class',
        'test_lt_complex',
        'test_lt_frozenset',

        'test_modulo_bytearray',
        'test_modulo_class',
        'test_modulo_complex',
        'test_modulo_frozenset',

        'test_multiply_bytes',
        'test_multiply_bytearray',
        'test_multiply_class',
        'test_multiply_complex',
        'test_multiply_frozenset',
        'test_multiply_list',
        'test_multiply_str',
        'test_multiply_tuple',

        'test_ne_bytearray',
        'test_ne_class',
        'test_ne_complex',
        'test_ne_frozenset',

        'test_or_bytearray',
        'test_or_class',
        'test_or_complex',
        'test_or_frozenset',

        'test_power_bytearray',
        'test_power_class',
        'test_power_complex',
        'test_power_frozenset',

        'test_rshift_bytearray',
        'test_rshift_class',
        'test_rshift_complex',
        'test_rshift_frozenset',

        'test_subscr_bytearray',
        'test_subscr_bytes',
        'test_subscr_class',
        'test_subscr_complex',
        'test_subscr_frozenset',

        'test_subtract_bytearray',
        'test_subtract_class',
        'test_subtract_complex',
        'test_subtract_frozenset',

        'test_true_divide_bytearray',
        'test_true_divide_class',
        'test_true_divide_complex',
        'test_true_divide_frozenset',

        'test_xor_bytearray',
        'test_xor_class',
        'test_xor_complex',
        'test_xor_frozenset',
    ]


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.12"/>
<title>OpenCV: imgproc/include/opencv2/imgproc/hal/interface.h File Reference</title>
<link href="../../opencv.ico" rel="shortcut icon" type="image/x-icon" />
<link href="../../tabs.css" rel="stylesheet" type="text/css"/>

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

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

OpenCV
    3.2.0

Open Source Computer Vision

imgproc

include

opencv2

imgproc

hal

interface.h File Reference

Macros

Interpolation modes

See also

cv::InterpolationFlags

#define 	CV_HAL_INTER_NEAREST   0

#define 	CV_HAL_INTER_LINEAR   1

#define 	CV_HAL_INTER_CUBIC   2

#define 	CV_HAL_INTER_AREA   3

#define 	CV_HAL_INTER_LANCZOS4   4

Morphology operations

See also

cv::MorphTypes

#define 	MORPH_ERODE   0

#define 	MORPH_DILATE   1

<address class="footer">
Generated on Fri Dec 23 2016 13:00:23 for OpenCV by

 1.8.12
</address>


text:
package stroom.legacy.model_6_1;

@Deprecated
public interface StatisticStore {
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Palest. J. Bot. , Jerusalem Series 1: 154 (1938)

#### Original name
Peronospora eigii Rayss

### Remarks
null


text:
		<?php echo set_breadcrumb(); ?>

<?php display_flashmsg($this->session->flashdata()); ?>
<?=$grid;?>


text:
namespace HyperMock
{
    /// <summary>
    /// Defines the mock behaviors available.
    /// </summary>
    public enum MockBehavior
    {
        /// <summary>
        /// Any calls that are not setup will return their default behavior if applicable. This is the default.
        /// </summary>
        Loose,

        /// <summary>
        /// Making a call on a mock that has no setup defined raises a
        /// <see cref="HyperMock.Exceptions.StrictMockViolationException"/>.
        /// </summary>
        Strict
    }
}


text:
title: Configuration
---
You can modify most options in `_config.yml`.

## Configuration

### Site

Setting | Description
--- | ---
`title` | The title of your website
`subtitle` | The subtitle of your website
`description` | The description of your website
`author` | Your name
`email` | Your email address
`language` | The language used in your website. Use [IETF format](http://www.w3.org/International/articles/language-tags/). (e.g. Traditional Chinese: `zh-TW`)

### URL

Setting | Description | Default
--- | --- | ---
`url` | The URL of your website |
`root` | The root directory of your website |
`permalink` | The [permalink](permalinks.html) format of articles | :year/:month/:day/:title/
`tag_dir` | Tag directory | tags
`archive_dir` | Archive directory | archives
`category_dir` | Category directory | categories
`code_dir` | Include code directory | downloads/code

{% note info Website in subdirectory %}
If your website is put in a subdirectory such as `http://yoursite.com/blog`, set `url` to `http://yoursite.com/blog` and set `root` to `/blog/`.
{% endnote %}

### Writing

Setting | Description | Default
--- | --- | ---
`new_post_name` | The filename of the new post | :title.md
`default_layout` | Default layout | post
`auto_spacing` | Add a space between eastern and western characters | false
`titlecase` | Transform title into proper title case | false
`external_link` | Open external links in new tab | true
`filename_case` | Transform filename into (1) lower case or (2) upper case | 0
`render_drafts` | Serve drafts as normal posts in server | false
`post_asset_folder` | Enables [Asset Folder](writing.html#Asset_Folder) | false
`relative_link` | Make links relative to root folder | false
`highlight` | Code block settings |

### Category & Tag

Setting | Description | Default
--- | --- | ---
`default_category` | Default category | uncategorized
`category_map` | Category slugs |
`tag_map` | Tag slugs |

### Archives

Setting | Description | Default
--- | --- | ---
`archive` | 2: Enable pagination, 1: Disable pagination, 0: Fully disable | 2
`category` | 2: Enable pagination, 1: Disable pagination, 0: Fully disable | 2
`tag` | 2: Enable pagination, 1: Disable pagination, 0: Fully disable | 2

### Server

Setting | Description | Default
--- | --- | ---
`port` | Server port | 4000
`logger` | Display request info on the console. Always enabled in debug mode. | false
`logger_format` | Logger format |
`server_ip` | Customize server IP | 0.0.0.0

### Date / Time format

Hexo uses [Moment.js](http://momentjs.com/) to parse and display date.

Setting | Description | Default
--- | --- | ---
`date_format` | Date format | MMM D YYYY
`time_format` | Time format | H:mm:ss

### Pagination

Setting | Description | Default
--- | --- | ---
`per_page` | The amount of the posts displayed in a single page (0 = Disable pagination) | 10
`pagination_dir` | Pagination directory | page

### Comment

Setting | Description
--- | ---
`disqus_shortname` | [Disqus](http://disqus.com/) shortname

### Extensions

Setting | Description
--- | ---
`theme` | Current theme
`exclude_generator` | Disabled generators (archive, category, home, page, post, tag)

{% note warn YAML format %}
Don't use tabs in configuration files, use spaces instead. Also, add a space after colons. Configuration file parsing errors may cause Hexo to not run properly.
{% endnote %}

## Default Configuration

``` yaml _config.yml
title: Hexo
subtitle:
description:
author: John Doe
email:
language:

url: http://yoursite.com
root: /
permalink: :year/:month/:day/:title/
tag_dir: tags
archive_dir: archives
category_dir: categories
code_dir: downloads/code

new_post_name: :title.md
default_layout: post
auto_spacing: false
titlecase: false
filename_case: 0
render_drafts: false
post_asset_folder: false
relative_link: false
highlight:
  enable: true
  line_number: true
  tab_replace:

default_category: uncategorized
category_map:
tag_map:

archive: 2
category: 2
tag: 2

port: 4000
logger: false
logger_format:

date_format: MMM D YYYY
time_format: H:mm:ss

per_page: 10
pagination_dir: page

disqus_shortname:

theme: light
exclude_generator:

deploy:
  type:
```


text:
using System.Collections.Generic;
using System.Windows.Forms;
using SharpCrop.Forms;

namespace SharpCrop.Services
{
    public static class FormService
    {
        private static readonly List<Form> cropForms = new List<Form>();
        private static Form configForm;

        public static void Init(Controller controller)
        {
            // Create a new ConfigForm
            configForm = new ConfigForm();
            configForm.FormClosed += (s, e) => Application.Exit();
            configForm.Load += async (s, e) => await controller.RestoreProviders();

            // If there are any registered providers, the config will be hidden
            // Else the config will be closed (along with the whole application)
            configForm.FormClosing += (s, e) =>
            {
                if (e.CloseReason == CloseReason.UserClosing && ProviderService.Loaded.Count > 0)
                {
                    e.Cancel = true;
                    configForm.Hide();
                }
            };

            // Show crop forms if the config is hidden
            configForm.VisibleChanged += (s, e) =>
            {
                if (!configForm.Visible)
                {
                    ShowCropForms();
                }
            };

            // Create a CropForm for every screen and show them
            foreach (var screen in Screen.AllScreens)
            {
                var form = new CropForm(controller, screen.Bounds);

                form.FormClosed += (s, e) => Application.Exit();

                cropForms.Add(form);
            }
        }

        /// <summary>
        /// Hide every CropForm - if more than one monitor is used.
        /// </summary>
        public static void HideCropForms() => cropForms.ForEach(e => e.Hide());

        /// <summary>
        /// Show every CropForm.
        /// </summary>
        public static void ShowCropForms() => cropForms.ForEach(e => e.Show());

        /// <summary>
        /// Protect list from external modification.
        /// </summary>
        public static IReadOnlyList<Form> CropForms => cropForms;

        /// <summary>
        /// Protect variable from external modification.
        /// </summary>
        public static Form ConfigForm => configForm;
    }
}


text:
<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Note
 *
 * @ORM\Table(name="note", indexes={@ORM\Index(name="user", columns={"user"}), @ORM\Index(name="juge", columns={"juge"})})
 * @ORM\Entity
 */
class Note
{
    /**
     * @var float
     *
     * @ORM\Column(name="note", type="float", precision=10, scale=0, nullable=false)
     */
    private $note;

    /**
     * @var string
     *
     * @ORM\Column(name="commentaire", type="text", length=65535, nullable=false)
     */
    private $commentaire;

    /**
     * @var \AppBundle\Entity\User
     *
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONE")
     * @ORM\OneToOne(targetEntity="AppBundle\Entity\User")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="user", referencedColumnName="ID")
     * })
     */
    private $user;

    /**
     * @var \AppBundle\Entity\User
     *
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\User")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="juge", referencedColumnName="ID")
     * })
     */
    private $juge;

    /**
     * Set note
     *
     * @param float $note
     * @return Note
     */
    public function setNote($note)
    {
        $this->note = $note;

        return $this;
    }

    /**
     * Get note
     *
     * @return float
     */
    public function getNote()
    {
        return $this->note;
    }

    /**
     * Set commentaire
     *
     * @param string $commentaire
     * @return Note
     */
    public function setCommentaire($commentaire)
    {
        $this->commentaire = $commentaire;

        return $this;
    }

    /**
     * Get commentaire
     *
     * @return string
     */
    public function getCommentaire()
    {
        return $this->commentaire;
    }

    /**
     * Set user
     *
     * @param \AppBundle\Entity\User $user
     * @return Note
     */
    public function setUser(\AppBundle\Entity\User $user)
    {
        $this->user = $user;

        return $this;
    }

    /**
     * Get user
     *
     * @return \AppBundle\Entity\User
     */
    public function getUser()
    {
        return $this->user;
    }

    /**
     * Set juge
     *
     * @param \AppBundle\Entity\User $juge
     * @return Note
     */
    public function setJuge(\AppBundle\Entity\User $juge = null)
    {
        $this->juge = $juge;

        return $this;
    }

    /**
     * Get juge
     *
     * @return \AppBundle\Entity\User
     */
    public function getJuge()
    {
        return $this->juge;
    }
}


text:
<?php

namespace Mongoeat\Bundle\FoursquareBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('mongoeat_foursquare');

        $rootNode
            ->children()
                ->arrayNode('authentification')
                    ->children()
                        ->scalarNode('id')->isRequired()->end()
                        ->scalarNode('secret')->isRequired()->end()
                        ->scalarNode('url_auth')->isRequired()->end()
                        ->scalarNode('url_api')->isRequired()->end()
                    ->end()
                ->end()
            ->end()
        ;

        return $treeBuilder;
    }
}


text:
import base64
import hashlib
import hmac
import os
import struct
import time

from set2 import xor, aes_cbc_encrypt, aes_ecb_decrypt_no_padding
from set3 import aes_ctr

from sha1 import sha1, sha1_md_padding, sha1_extension
from md4 import MD4, md4_md_padding, md4_len_ext

## Challenge 25
#
def aes_ctr_get_edit_func(plaintext):

	k = os.urandom(16)
	nonce = os.urandom(8)

	ciphertext = aes_ctr(k, plaintext, nonce)

	def edit_func(offset, newtext):
		assert offset <= len(ciphertext)

		new_p = plaintext[:offset] + newtext + plaintext[offset+len(newtext):]
		#print "New plaintext: %s" % new_p

		return aes_ctr(k, new_p, nonce)

	return ciphertext, edit_func

def break_rand_access_aes_ctr(ciphertext, edit_func):

	plaintext = []
	print "Length of ciphertext is %d" % len(ciphertext)
	for i in xrange(len(ciphertext)):
		if i % 100 == 0:
			print "Broke %d characters" % i
			#print "".join(plaintext)
		for p in range(256):
			p = struct.pack('B', p)
			if ciphertext[i] == edit_func(i, p)[i]:
				plaintext.append(p)
				break

	return "".join(plaintext)

## Challenge 26
#

def aes_ctr_oracle(k, plaintext, nonce):
	s1 = "comment1=cooking%20MCs;userdata="
	s2 = ";comment2=%20like%20a%20pound%20of%20bacon"

	# strip ';' and '=' from plaintext
	plaintext = plaintext.replace(';','')
	plaintext = plaintext.replace('=','')

	return aes_ctr(k, s1 + plaintext + s2, nonce)

def check_ctr_bitflip(k, ciphertext, nonce):
	plaintext = aes_ctr(k, ciphertext, nonce)
	print "decrypted: ", repr(plaintext)
	pieces = plaintext.split(';')
	for p in pieces:
		if p == 'admin=true':
			return True

	return False

def ctr_bitflip_attack():

	k = os.urandom(16)
	nonce = os.urandom(8)

	#"comment1=cooking" "%20MCs;userdata="
	#";comment2=%%0lik" "e%20a%20pound%20of%20bacon"

	# ctr mode is a simple XOR of keystream byte and plaintext byte

	# If we use this: "0admin0true" as the plaintext
	# We want to flip the first 0 to ';' and the second 0 to '='
	# So if we use \x00 as 0, then we will get the keystream byte
	# in the ciphertext.  Then we just XOR with the desired byte.

	s1 = "comment1=cooking%20MCs;userdata="
	s2 = ";comment2=%20like%20a%20pound%20of%20bacon"

	plaintext = 'A' + "\x00admin\x00true"
	print "plaintext: ", repr(s1 + plaintext + s2)

	ciphertext = aes_ctr_oracle(k, plaintext, nonce)

	# offsets are len(s1)+1 and len(s1)+8
	off1 = len(s1)+1
	off2 = len(s1)+7
	ciphertext = ciphertext[:off1] + xor(ciphertext[off1], ';') + ciphertext[off1+1:off2] + xor(ciphertext[off2], '=') + ciphertext[off2+1:]

	assert len(ciphertext) == len(s1+plaintext+s2)

	print "Check returns ", check_ctr_bitflip(k, ciphertext, nonce)

## Challenge 27
#
def aes_cbc_enc_oracle(k, plaintext):
	s1 = "comment1=cooking%20MCs;userdata="
	s2 = ";comment2=%20like%20a%20pound%20of%20bacon"

	# strip ';' and '=' from plaintext
	plaintext = plaintext.replace(';','')
	plaintext = plaintext.replace('=','')

	iv = k

	return aes_cbc_encrypt(k, s1 + plaintext + s2, iv)

def aes_cbc_dec_oracle(k, ciphertext):
	iv = k

	def aes_cbc_decrypt(key, text, iv):
		block_size = len(key)
		if block_size != 16:
			raise "Block size for AES must be 16"

		out = []
		assert len(iv) == 16
		carry = iv
		for i in range(0, len(text), block_size):
			block = text[i:i+block_size]

			# do the crypto
			out_block = aes_ecb_decrypt_no_padding(key, block)

			# take out the carry over
			out_block = xor(carry, out_block)

			out.append(out_block)

			# new carry
			carry = block

		return "".join(out)

	return aes_cbc_decrypt(k, ciphertext, iv)

def recover_key_from_iv_equals_key():

	k = os.urandom(16)
	print "Key is ", repr(k)
	ciphertext = aes_cbc_enc_oracle(k, 'A')

	#print aes_cbc_dec_oracle(k, ciphertext)

	c1 = ciphertext[:16]
	c2 = '\x00'*16
	c3 = c1

	# receiver would throw an error here
	p = aes_cbc_dec_oracle(k, c1+c2+c3)

	p1 = p[:16]
	p3 = p[32:48]

	recovered_key = xor(p1,p3)
	print "Recovered key ", repr(recovered_key)

	return k == recovered_key

## Challenge 28
#
def sha1_mac(k, message):
	return sha1(k + message)

## Challenge 29
#
def cha29():
	k = "foobarbaz"

	msg = "comment1=cooking%20MCs;userdata=foo;comment2=%20like%20a%20pound%20of%20bacon"
	ext = ";admin=true"

	print "Message is: %s" % msg
	print "Extra is: %s" % ext

	mac = sha1_mac(k, msg)

	print ""
	print "SHA-1 mac of message: ", repr(mac)

	extension = sha1_extension(len(k+msg), mac, ext)
	print "SHA-1 extension attack: ", repr(extension)

	print "Expected value: ", repr(sha1_mac(k, msg + sha1_md_padding(len(k+msg)) + ext))

## Challenge 30
#
def md4_mac(k, msg):
	m = MD4()
	m.update(k+msg)
	return m.digest_bytes()

def cha30():
	k = "foobarbaz"

	msg = "comment1=cooking%20MCs;userdata=foo;comment2=%20like%20a%20pound%20of%20bacon"
	ext = ";admin=true"

	print "Message is: %s" % msg
	print "Extra is: %s" % ext

	mac = md4_mac(k, msg)

	print ""
	print "MD4 mac of message: ", repr(mac)

	extension = md4_len_ext(len(k+msg), mac, ext)
	print "MD4 extension attack: ", repr(extension)

	print "Expected value: ", repr(md4_mac(k, msg + md4_md_padding(k+msg) + ext))

## Challenge 31 and 32
#
def hmac_sha1(k, msg):
	return hmac.HMAC(k, msg, hashlib.sha1).digest()

# comparison function with artificial timing leak
def insecure_compare(a, b, delay):
	assert a
	assert b

	for i in xrange(min(len(a), len(b))):
		if i == len(a) and i < len(b):
			return False
		if i == len(b) and i < len(a):
			return False

		if a[i] != b[i]:
			return False

		time.sleep(delay)

	return True

# server oracle
def get_hmac_oracle(delay):
	k = "YELLOW SUBMARINE"

	def oracle(filename, mac):
		correct_mac = hmac_sha1(k, filename)
		return insecure_compare(mac, correct_mac, delay)

	return oracle

# timing attack to compute a valid mac for a given filename
# timing threshold used to differentiate between guessed bytes
# whose timings are too close (might pick the wrong one)
def hmac_timing_attack(hmac_oracle, filename, timing_threshold):

	mac = ''
	all_comp_times = []
	delays = []
	for i in xrange(20):

		# recover comparison times of different guessed bytes
		comp_dict = {}

		# check if we need to move on b/c
		# we added a byte we're confident about
		# to the mac
		while len(mac) <= i:
			for g in range(256):
				guess = mac + chr(g) + 'A'*(20-1-len(mac))

				ts = comp_dict.get(chr(g), [])

				for j in range(5):
					t0 = time.time()
					hmac_oracle(filename, guess)
					ts.append(time.time() - t0)

				comp_dict[chr(g)] = ts

			# compute averages
			avg_comp_times = [(sum(ts)/len(ts), b) for (b, ts) in comp_dict.iteritems()]

			# sort guessed bytes by how long the comparison took
			s = sorted(avg_comp_times, reverse=True, key=lambda x: x[0])

			# check if there is a clear winner, i.e. difference in time
			# between first and second > timing threshold.
			# if not, we collect more timing info and try again
			if s[0][0] - s[1][0] <= timing_threshold:
				print "Winning bytes %s and %s were too close: %.5f s, %.5f s" % (repr(s[0][1]), repr(s[1][1]), s[0][0], s[1][0])
				continue

			# check if the added delay from this byte makes sense
			# given the average delay so far
			if len(all_comp_times) > 0:
				delay = s[0][0] - all_comp_times[-1]
				if delay >= 2*sum(delays)/len(delays):
					print "Delay %.5f s for byte %s was much larger than average delay so far %.5f s" % (delay, repr(s[0][1]), sum(delays)/len(delays))
					# start over with compt_dict
					comp_dict.clear()
					continue

			# otherwise, we're pretty confident this byte is correct
			print "Guessed byte %s which took %.5f s" % (repr(s[0][1]), s[0][0])
			mac += s[0][1]

			all_comp_times.append(s[0][0])
			delays.append(s[0][0])

	print "Checking hmac: ", repr(mac)
	print hmac_oracle(filename, mac)
	return mac

def main():
	# print "Testing Challenge 25:"
	# print "---------------------"

	# f = open('25.txt')
	# plaintext = f.read()
	# f.close()
	# #print "Plaintext: "
	# #print plaintext

	# ciphertext, edit_func = aes_ctr_get_edit_func(plaintext)
	# print "Breaking random access read/write AES CTR mode:"
	# print break_rand_access_aes_ctr(ciphertext, edit_func)

	# print "\n\n"

	print "Testing Challenge 26:"
	print "---------------------"

	ctr_bitflip_attack()

	print "\n\n"

	print "Testing Challenge 27:"
	print "---------------------"

	print recover_key_from_iv_equals_key()

	print "Testing Challenge 28:"
	print "---------------------"

	k = os.urandom(16)
	msg = 'Foo Bar Baz'
	print "k = ", repr(k)
	print "msg = ", msg

	s = hashlib.sha1()
	s.update(k+msg)
	print "Python Lib: ", repr(s.digest())

	print "My Impl: ", repr(sha1_mac(k, msg))

	print "\n\n"

	print "Testing Challenge 29:"
	print "---------------------"

	cha29()

	print "\n\n"

	print "Testing Challenge 30:"
	print "---------------------"

	cha30()

	print "\n\n"

	print "Testing Challenge 31 and 32:"
	print "---------------------"

	hmac_oracle = get_hmac_oracle(0.005)
	print "Expected hmac: ", repr(hmac_sha1("YELLOW SUBMARINE", 'foo'))
	hmac_timing_attack(hmac_oracle, 'foo', 0.003)

if __name__=="__main__":
	main()


text:
using NUnit.Framework;

using System;
using System.Data;

using GHTUtils;
using GHTUtils.Base;

namespace tests.system_data_dll.System_Data
{
[TestFixture] public class DataSet_extendedProperties : GHTBase
{
	[Test] public void Main()
	{
		DataSet_extendedProperties tc = new DataSet_extendedProperties();
		Exception exp = null;
		try
		{
			tc.BeginTest("DataSet_extendedProperties");
			tc.run();
		}
		catch(Exception ex)
		{
			exp = ex;
		}
		finally
		{
			tc.EndTest(exp);
		}
	}

	//Activate This Construntor to log All To Standard output
	//public TestClass():base(true){}

	//Activate this constructor to log Failures to a log file
	//public TestClass(System.IO.TextWriter tw):base(tw, false){}

	//Activate this constructor to log All to a log file
	//public TestClass(System.IO.TextWriter tw):base(tw, true){}

	//BY DEFAULT LOGGING IS DONE TO THE STANDARD OUTPUT ONLY FOR FAILURES

	public void run()
	{
		Exception exp = null;
		DataSet ds = new DataSet();
		PropertyCollection pc;

		pc = ds.ExtendedProperties ;

		try
		{
			base.BeginCase("Checking ExtendedProperties default ");
			base.Compare(pc != null,true);
		}
		catch(Exception ex)	{exp = ex;}
		finally	{EndCase(exp); exp = null;}

		try
		{
			base.BeginCase("Checking ExtendedProperties count ");
			base.Compare(pc.Count ,0);
		}
		catch(Exception ex)	{exp = ex;}
		finally	{EndCase(exp); exp = null;}
	}
}
}


text:
'''
Icon generator
==============

This tool will help you to generate all the icons wanted for Google Play Store,
App Store, Amazon store.
'''

import sys
from PIL import Image
from os.path import exists, join, realpath, basename, dirname
from os import makedirs
from argparse import ArgumentParser

class Converter(object):

    converters = {
        'appstore': {
            'directory_name': 'ios',
            'sizes': [
                ('App store high resolution', '{}-appstore-1024.png', 1024),
                ('App store normal resolution', '{}-appstore-512.png', 512),
                # iOS 7
                ('iPhone (iOS 7)', '{}-60.png', 120),
                ('iPhone @2 (iOS 7)', '{}-60@2x.png', 120),
                ('iPad (iOS 7)', '{}-76.png', 76),
                ('iPad @2 (iOS 7)', '{}-60@2x.png', 152),
                # iOS 6.1 and earlier
                ('iPhone (iOS >= 6.1)', '{}-57.png', 57),
                ('iPhone @2 (iOS >= 6.1)', '{}-57@2x.png', 114),
                ('iPad (iOS >= 6.1)', '{}-72.png', 72),
                ('iPad @2 (iOS >= 6.1)', '{}-72@2x.png', 114),
                # iTunes artwork (ad-hoc)
                ('iTunes Artwork (ad-hoc)', 'iTunesArtwork', 512),
                ('iTunes Artwork @2 (ad-hoc)', 'iTunesArtwork@2x', 1024),
            ]},
        'playstore': {
            'directory_name': 'android',
            'sizes': [
                ('Google Play icon', '{}-googleplay-512.png', 512),
                ('Launcher icon MDPI', '{}-48.png', 48),
                ('Launcher icon HDPI', '{}-72.png', 72),
                ('Launcher icon XHDPI', '{}-96.png', 96),
                ('Launcher icon XXHDPI', '{}-144.png', 48),
                ('Launcher icon XXXHDPI', '{}-192.png', 192),
            ]},
        'amazonstore': {
            'directory_name': 'amazon',
            'sizes': [
                ('Small icon', '{}-114.png', 114),
                ('Large icon', '{}-512.png', 512),
            ]}}

    def run(self):
        parser = ArgumentParser(
                description='Generate icons for various stores')
        parser.add_argument('--dir', type=str, default=None,
                help=('Output directory to generate all the icons,'
                      'defaults to the directory of the source icon'))
        parser.add_argument('--force', type=bool, default=False,
                help=('Generate all icons even if the source is not perfect.'))
        parser.add_argument('icon', type=str,
                help='Base icon (must be 1024x1024 or 512x512)')

        args = parser.parse_args()
        if not exists(args.icon):
            print('Error: No such icon file')
            sys.exit(1)

        # ensure the destination directory will be set
        if args.dir is None:
            args.dir = dirname(args.icon)

        # read the source image, and do some quality checks
        base_fn = basename(args.icon).rsplit('.', 1)[0]
        source = Image.open(args.icon)
        self.ensure_quality(source, args.force)

        for directory_name, sizeinfo in self.iterate():
            description, pattern_fn, size = sizeinfo
            print('Generate {}: {}x{}'.format(description, size, size))
            dest_dir = realpath(join(args.dir, directory_name))
            if not exists(dest_dir):
                makedirs(dest_dir)
            icon_fn = join(dest_dir, pattern_fn.format('Icon'))
            self.convert_to(source, icon_fn, size)

    def convert_to(self, source, icon_fn, size):
        dest = source.resize((size, size))
        dest.save(icon_fn, 'png')

    def ensure_quality(self, image, force=False):
        messages = []
        w, h = image.size
        if w != h:
            messages.append('Width and height should be the same')
        if w not in (512, 1024):
            messages.append(
                'Source image is recommended to be 1024 (512 minimum)')
        if not messages:
            return

        print('Quality check failed')
        for message in messages:
            print('- {}'.format(message))
        if not force:
            sys.exit(1)

    def iterate(self):
        for store, infos in Converter.converters.items():
            for size in infos['sizes']:
                yield infos['directory_name'], size

if __name__ == '__main__':
    Converter().run()