text:
from k5test import *
import time
from itertools import imap

# Run kdbtest against the BDB module.
realm = K5Realm(create_kdb=False)
realm.run(['./kdbtest'])

# Set up an OpenLDAP test server if we can.

if (not os.path.exists(os.path.join(plugins, 'kdb', 'kldap.so')) and
    not os.path.exists(os.path.join(buildtop, 'lib', 'libkdb_ldap.a'))):
    skip_rest('LDAP KDB tests', 'LDAP KDB module not built')

if 'SLAPD' not in os.environ and not which('slapd'):
    skip_rest('LDAP KDB tests', 'slapd not found')

slapadd = which('slapadd')
if not slapadd:
    skip_rest('LDAP KDB tests', 'slapadd not found')

ldapdir = os.path.abspath('ldap')
dbdir = os.path.join(ldapdir, 'ldap')
slapd_conf = os.path.join(ldapdir, 'slapd.d')
slapd_out = os.path.join(ldapdir, 'slapd.out')
slapd_pidfile = os.path.join(ldapdir, 'pid')
ldap_pwfile = os.path.join(ldapdir, 'pw')
ldap_sock = os.path.join(ldapdir, 'sock')
ldap_uri = 'ldapi://%s/' % ldap_sock.replace(os.path.sep, '%2F')
schema = os.path.join(srctop, 'plugins', 'kdb', 'ldap', 'libkdb_ldap',
                      'kerberos.openldap.ldif')
top_dn = 'cn=krb5'
admin_dn = 'cn=admin,cn=krb5'
admin_pw = 'admin'

shutil.rmtree(ldapdir, True)
os.mkdir(ldapdir)
os.mkdir(slapd_conf)
os.mkdir(dbdir)

if 'SLAPD' in os.environ:
    slapd = os.environ['SLAPD']
else:
    # Some Linux installations have AppArmor or similar restrictions
    # on the slapd binary, which would prevent it from accessing the
    # build directory.  Try to defeat this by copying the binary.
    system_slapd = which('slapd')
    slapd = os.path.join(ldapdir, 'slapd')
    shutil.copy(system_slapd, slapd)

def slap_add(ldif):
    proc = subprocess.Popen([slapadd, '-b', 'cn=config', '-F', slapd_conf],
                            stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                            stderr=subprocess.STDOUT)
    (out, dummy) = proc.communicate(ldif)
    output(out)
    return proc.wait()

# Configure the pid file and some authorization rules we will need for
# SASL testing.
if slap_add('dn: cn=config\n'
            'objectClass: olcGlobal\n'
            'olcPidFile: %s\n'
            'olcAuthzRegexp: '
            '".*uidNumber=%d,cn=peercred,cn=external,cn=auth" "%s"\n'
            'olcAuthzRegexp: "uid=digestuser,cn=digest-md5,cn=auth" "%s"\n' %
            (slapd_pidfile, os.geteuid(), admin_dn, admin_dn)) != 0:
    skip_rest('LDAP KDB tests', 'slapd basic configuration failed')

# Find a working writable database type, trying mdb (added in OpenLDAP
# 2.4.27) and bdb (deprecated and sometimes not built due to licensing
# incompatibilities).
for dbtype in ('mdb', 'bdb'):
    # Try to load the module.  This could fail if OpenLDAP is built
    # without module support, so ignore errors.
    slap_add('dn: cn=module,cn=config\n'
             'objectClass: olcModuleList\n'
             'olcModuleLoad: back_%s\n' % dbtype)

    dbclass = 'olc%sConfig' % dbtype.capitalize()
    if slap_add('dn: olcDatabase=%s,cn=config\n'
                'objectClass: olcDatabaseConfig\n'
                'objectClass: %s\n'
                'olcSuffix: %s\n'
                'olcRootDN: %s\n'
                'olcRootPW: %s\n'
                'olcDbDirectory: %s\n' %
                (dbtype, dbclass, top_dn, admin_dn, admin_pw, dbdir)) == 0:
        break
else:
    skip_rest('LDAP KDB tests', 'could not find working slapd db type')

if slap_add('include: file://%s\n' % schema) != 0:
    skip_rest('LDAP KDB tests', 'failed to load Kerberos schema')

# Load the core schema if we can.
ldap_homes = ['/etc/ldap', '/etc/openldap', '/usr/local/etc/openldap',
              '/usr/local/etc/ldap']
local_schema_path = '/schema/core.ldif'
core_schema = next((i for i in imap(lambda x:x+local_schema_path, ldap_homes)
                    if os.path.isfile(i)), None)
if core_schema:
    if slap_add('include: file://%s\n' % core_schema) != 0:
        core_schema = None

slapd_pid = -1
def kill_slapd():
    global slapd_pid
    if slapd_pid != -1:
        os.kill(slapd_pid, signal.SIGTERM)
        slapd_pid = -1
atexit.register(kill_slapd)

out = open(slapd_out, 'w')
subprocess.call([slapd, '-h', ldap_uri, '-F', slapd_conf], stdout=out,
                stderr=out)
out.close()
pidf = open(slapd_pidfile, 'r')
slapd_pid = int(pidf.read())
pidf.close()
output('*** Started slapd (pid %d, output in %s)\n' % (slapd_pid, slapd_out))

# slapd detaches before it finishes setting up its listener sockets
# (they are bound but listen() has not been called).  Give it a second
# to finish.
time.sleep(1)

# Run kdbtest against the LDAP module.
conf = {'realms': {'$realm': {'database_module': 'ldap'}},
        'dbmodules': {'ldap': {'db_library': 'kldap',
                               'ldap_kerberos_container_dn': top_dn,
                               'ldap_kdc_dn': admin_dn,
                               'ldap_kadmind_dn': admin_dn,
                               'ldap_service_password_file': ldap_pwfile,
                               'ldap_servers': ldap_uri}}}
realm = K5Realm(create_kdb=False, kdc_conf=conf)
input = admin_pw + '\n' + admin_pw + '\n'
realm.run([kdb5_ldap_util, 'stashsrvpw', admin_dn], input=input)
realm.run(['./kdbtest'])

# Run a kdb5_ldap_util command using the test server's admin DN and password.
def kldaputil(args, **kw):
    return realm.run([kdb5_ldap_util, '-D', admin_dn, '-w', admin_pw] + args,
                     **kw)

# kdbtest can't currently clean up after itself since the LDAP module
# doesn't support krb5_db_destroy.  So clean up after it with
# kdb5_ldap_util before proceeding.
kldaputil(['destroy', '-f'])

ldapmodify = which('ldapmodify')
ldapsearch = which('ldapsearch')
if not ldapmodify or not ldapsearch:
    skip_rest('some LDAP KDB tests', 'ldapmodify or ldapsearch not found')

def ldap_search(args):
    proc = subprocess.Popen([ldapsearch, '-H', ldap_uri, '-b', top_dn,
                             '-D', admin_dn, '-w', admin_pw, args],
                            stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                            stderr=subprocess.STDOUT)
    (out, dummy) = proc.communicate()
    return out

def ldap_modify(ldif, args=[]):
    proc = subprocess.Popen([ldapmodify, '-H', ldap_uri, '-D', admin_dn,
                             '-x', '-w', admin_pw] + args,
                            stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                            stderr=subprocess.STDOUT)
    (out, dummy) = proc.communicate(ldif)
    output(out)

def ldap_add(dn, objectclass, attrs=[]):
    in_data = 'dn: %s\nobjectclass: %s\n' % (dn, objectclass)
    in_data += '\n'.join(attrs) + '\n'
    ldap_modify(in_data, ['-a'])

# Create krbContainer objects for use as subtrees.
ldap_add('cn=t1,cn=krb5', 'krbContainer')
ldap_add('cn=t2,cn=krb5', 'krbContainer')
ldap_add('cn=x,cn=t1,cn=krb5', 'krbContainer')
ldap_add('cn=y,cn=t2,cn=krb5', 'krbContainer')

# Create a realm, exercising all of the realm options.
kldaputil(['create', '-s', '-P', 'master', '-subtrees', 'cn=t2,cn=krb5',
           '-containerref', 'cn=t2,cn=krb5', '-sscope', 'one',
           '-maxtktlife', '5min', '-maxrenewlife', '10min', '-allow_svr'])

# Modify the realm, exercising overlapping subtree pruning.
kldaputil(['modify', '-subtrees',
           'cn=x,cn=t1,cn=krb5:cn=t1,cn=krb5:cn=t2,cn=krb5:cn=y,cn=t2,cn=krb5',
           '-containerref', 'cn=t1,cn=krb5', '-sscope', 'sub',
           '-maxtktlife', '5hour', '-maxrenewlife', '10hour', '+allow_svr'])

out = kldaputil(['list'])
if out != 'KRBTEST.COM\n':
    fail('Unexpected kdb5_ldap_util list output')

# Create a principal at a specified DN.  This is a little dodgy
# because we're sticking a krbPrincipalAux objectclass onto a subtree
# krbContainer, but it works and it avoids having to load core.schema
# in the test LDAP server.
realm.run([kadminl, 'ank', '-randkey', '-x', 'dn=cn=krb5', 'princ1'],
          expected_code=1, expected_msg='DN is out of the realm subtree')
realm.run([kadminl, 'ank', '-randkey', '-x', 'dn=cn=t2,cn=krb5', 'princ1'])
realm.run([kadminl, 'getprinc', 'princ1'], expected_msg='Principal: princ1')
realm.run([kadminl, 'ank', '-randkey', '-x', 'dn=cn=t2,cn=krb5', 'again'],
          expected_code=1, expected_msg='ldap object is already kerberized')
# Check that we can't set linkdn on a non-standalone object.
realm.run([kadminl, 'modprinc', '-x', 'linkdn=cn=t1,cn=krb5', 'princ1'],
          expected_code=1, expected_msg='link information can not be set')

# Create a principal with a specified linkdn.
realm.run([kadminl, 'ank', '-randkey', '-x', 'linkdn=cn=krb5', 'princ2'],
          expected_code=1, expected_msg='DN is out of the realm subtree')
realm.run([kadminl, 'ank', '-randkey', '-x', 'linkdn=cn=t1,cn=krb5', 'princ2'])
# Check that we can't reset linkdn.
realm.run([kadminl, 'modprinc', '-x', 'linkdn=cn=t2,cn=krb5', 'princ2'],
          expected_code=1, expected_msg='kerberos principal is already linked')

# Create a principal with a specified containerdn.
realm.run([kadminl, 'ank', '-randkey', '-x', 'containerdn=cn=krb5', 'princ3'],
          expected_code=1, expected_msg='DN is out of the realm subtree')
realm.run([kadminl, 'ank', '-randkey', '-x', 'containerdn=cn=t1,cn=krb5',
           'princ3'])
realm.run([kadminl, 'modprinc', '-x', 'containerdn=cn=t2,cn=krb5', 'princ3'],
          expected_code=1, expected_msg='containerdn option not supported')

# Create and modify a ticket policy.
kldaputil(['create_policy', '-maxtktlife', '3hour', '-maxrenewlife', '6hour',
           '-allow_forwardable', 'tktpol'])
kldaputil(['modify_policy', '-maxtktlife', '4hour', '-maxrenewlife', '8hour',
           '+requires_preauth', 'tktpol'])
out = kldaputil(['view_policy', 'tktpol'])
if ('Ticket policy: tktpol\n' not in out or
    'Maximum ticket life: 0 days 04:00:00\n' not in out or
    'Maximum renewable life: 0 days 08:00:00\n' not in out or
    'Ticket flags: DISALLOW_FORWARDABLE REQUIRES_PRE_AUTH' not in out):
    fail('Unexpected kdb5_ldap_util view_policy output')

out = kldaputil(['list_policy'])
if out != 'tktpol\n':
    fail('Unexpected kdb5_ldap_util list_policy output')

# Associate the ticket policy to a principal.
realm.run([kadminl, 'ank', '-randkey', '-x', 'tktpolicy=tktpol', 'princ4'])
out = realm.run([kadminl, 'getprinc', 'princ4'])
if ('Maximum ticket life: 0 days 04:00:00\n' not in out or
    'Maximum renewable life: 0 days 08:00:00\n' not in out or
    'Attributes: DISALLOW_FORWARDABLE REQUIRES_PRE_AUTH\n' not in out):
    fail('Unexpected getprinc output with ticket policy')

# Destroying the policy should fail while a principal references it.
kldaputil(['destroy_policy', '-force', 'tktpol'], expected_code=1)

# Dissociate the ticket policy from the principal.
realm.run([kadminl, 'modprinc', '-x', 'tktpolicy=', 'princ4'])
out = realm.run([kadminl, 'getprinc', 'princ4'])
if ('Maximum ticket life: 0 days 05:00:00\n' not in out or
    'Maximum renewable life: 0 days 10:00:00\n' not in out or
    'Attributes:\n' not in out):
    fail('Unexpected getprinc output without ticket policy')

# Destroy the ticket policy.
kldaputil(['destroy_policy', '-force', 'tktpol'])
kldaputil(['view_policy', 'tktpol'], expected_code=1)
out = kldaputil(['list_policy'])
if out:
    fail('Unexpected kdb5_ldap_util list_policy output after destroy')

# Create another ticket policy to be destroyed with the realm.
kldaputil(['create_policy', 'tktpol2'])

# Try to create a password policy conflicting with a ticket policy.
realm.run([kadminl, 'addpol', 'tktpol2'], expected_code=1,
          expected_msg='Already exists while creating policy "tktpol2"')

# Try to create a ticket policy conflicting with a password policy.
realm.run([kadminl, 'addpol', 'pwpol'])
out = kldaputil(['create_policy', 'pwpol'], expected_code=1)
if 'Already exists while creating policy object' not in out:
    fail('Expected error not seen in kdb5_ldap_util output')

# Try to use a password policy as a ticket policy.
realm.run([kadminl, 'modprinc', '-x', 'tktpolicy=pwpol', 'princ4'],
          expected_code=1, expected_msg='Object class violation')

# Use a ticket policy as a password policy (CVE-2014-5353).  This
# works with a warning; use kadmin.local -q so the warning is shown.
realm.run([kadminl, '-q', 'modprinc -policy tktpol2 princ4'],
          expected_msg='WARNING: policy "tktpol2" does not exist')

# Do some basic tests with a KDC against the LDAP module, exercising the
# db_args processing code.
realm.start_kdc(['-x', 'nconns=3', '-x', 'host=' + ldap_uri,
                 '-x', 'binddn=' + admin_dn, '-x', 'bindpwd=' + admin_pw])
realm.addprinc(realm.user_princ, password('user'))
realm.addprinc(realm.host_princ)
realm.extract_keytab(realm.host_princ, realm.keytab)
realm.kinit(realm.user_princ, password('user'))
realm.run([kvno, realm.host_princ])
realm.klist(realm.user_princ, realm.host_princ)

# Test auth indicator support
realm.addprinc('authind', password('authind'))
realm.run([kadminl, 'setstr', 'authind', 'require_auth', 'otp radius'])

out = ldap_search('(krbPrincipalName=authind*)')
if 'krbPrincipalAuthInd: otp' not in out:
    fail('Expected krbPrincipalAuthInd value not in output')
if 'krbPrincipalAuthInd: radius' not in out:
    fail('Expected krbPrincipalAuthInd value not in output')

realm.run([kadminl, 'getstrs', 'authind'],
          expected_msg='require_auth: otp radius')

# Test service principal aliases.
realm.addprinc('canon', password('canon'))
ldap_modify('dn: krbPrincipalName=canon@KRBTEST.COM,cn=t1,cn=krb5\n'
            'changetype: modify\n'
            'add: krbPrincipalName\n'
            'krbPrincipalName: alias@KRBTEST.COM\n'
            '-\n'
            'add: krbCanonicalName\n'
            'krbCanonicalName: canon@KRBTEST.COM\n')
realm.run([kadminl, 'getprinc', 'alias'],
          expected_msg='Principal: canon@KRBTEST.COM\n')
realm.run([kadminl, 'getprinc', 'canon'],
          expected_msg='Principal: canon@KRBTEST.COM\n')
realm.run([kvno, 'alias', 'canon'])
out = realm.run([klist])
if 'alias@KRBTEST.COM\n' not in out or 'canon@KRBTEST.COM' not in out:
    fail('After fetching alias and canon, klist is missing one or both')
realm.kinit(realm.user_princ, password('user'), ['-S', 'alias'])
realm.klist(realm.user_princ, 'alias@KRBTEST.COM')

# Make sure an alias to the local TGS is still treated like an alias.
ldap_modify('dn: krbPrincipalName=krbtgt/KRBTEST.COM@KRBTEST.COM,'
            'cn=KRBTEST.COM,cn=krb5\n'
            'changetype: modify\n'
            'add:krbPrincipalName\n'
            'krbPrincipalName: tgtalias@KRBTEST.COM\n'
            '-\n'
            'add: krbCanonicalName\n'
            'krbCanonicalName: krbtgt/KRBTEST.COM@KRBTEST.COM\n')
realm.run([kadminl, 'getprinc', 'tgtalias'],
          expected_msg='Principal: krbtgt/KRBTEST.COM@KRBTEST.COM')
realm.kinit(realm.user_princ, password('user'))
realm.run([kvno, 'tgtalias'])
realm.klist(realm.user_princ, 'tgtalias@KRBTEST.COM')

# Make sure aliases work in header tickets.
realm.run([kadminl, 'modprinc', '-maxrenewlife', '3 hours', 'user'])
realm.run([kadminl, 'modprinc', '-maxrenewlife', '3 hours',
           'krbtgt/KRBTEST.COM'])
realm.kinit(realm.user_princ, password('user'), ['-l', '1h', '-r', '2h'])
realm.run([kvno, 'alias'])
realm.kinit(realm.user_princ, flags=['-R', '-S', 'alias'])
realm.klist(realm.user_princ, 'alias@KRBTEST.COM')

# Test client principal aliases, with and without preauth.
realm.kinit('canon', password('canon'))
realm.kinit('alias', password('canon'), expected_code=1,
            expected_msg='not found in Kerberos database')
realm.kinit('alias', password('canon'), ['-C'])
realm.run([kvno, 'alias'])
realm.klist('canon@KRBTEST.COM', 'alias@KRBTEST.COM')
realm.run([kadminl, 'modprinc', '+requires_preauth', 'canon'])
realm.kinit('canon', password('canon'))
realm.kinit('alias', password('canon'), ['-C'])

# Test password history.
def test_pwhist(nhist):
    def cpw(n, **kwargs):
        realm.run([kadminl, 'cpw', '-pw', str(n), princ], **kwargs)
    def cpw_fail(n):
        cpw(n, expected_code=1)
    output('*** Testing password history of size %d\n' % nhist)
    princ = 'pwhistprinc' + str(nhist)
    pol = 'pwhistpol' + str(nhist)
    realm.run([kadminl, 'addpol', '-history', str(nhist), pol])
    realm.run([kadminl, 'addprinc', '-policy', pol, '-nokey', princ])
    for i in range(nhist):
        # Set a password, then check that all previous passwords fail.
        cpw(i)
        for j in range(i + 1):
            cpw_fail(j)
    # Set one more new password, and make sure the oldest key is
    # rotated out.
    cpw(nhist)
    cpw_fail(1)
    cpw(0)

for n in (1, 2, 3, 4, 5):
    test_pwhist(n)

# Regression test for #8193: test password character class requirements.
princ = 'charclassprinc'
pol = 'charclasspol'
realm.run([kadminl, 'addpol', '-minclasses', '3', pol])
realm.run([kadminl, 'addprinc', '-policy', pol, '-nokey', princ])
realm.run([kadminl, 'cpw', '-pw', 'abcdef', princ], expected_code=1)
realm.run([kadminl, 'cpw', '-pw', 'Abcdef', princ], expected_code=1)
realm.run([kadminl, 'cpw', '-pw', 'Abcdef1', princ])

# Test principal renaming and make sure last modified is changed
def get_princ(princ):
    out = realm.run([kadminl, 'getprinc', princ])
    return dict(map(str.strip, x.split(":", 1)) for x in out.splitlines())

realm.addprinc("rename", password('rename'))
renameprinc = get_princ("rename")
realm.run([kadminl, '-p', 'fake@KRBTEST.COM', 'renprinc', 'rename', 'renamed'])
renamedprinc = get_princ("renamed")
if renameprinc['Last modified'] == renamedprinc['Last modified']:
    fail('Last modified data not updated when principal was renamed')

# Regression test for #7980 (fencepost when dividing keys up by kvno).
realm.run([kadminl, 'addprinc', '-randkey', '-e', 'aes256-cts,aes128-cts',
           'kvnoprinc'])
realm.run([kadminl, 'cpw', '-randkey', '-keepold', '-e',
           'aes256-cts,aes128-cts', 'kvnoprinc'])
realm.run([kadminl, 'getprinc', 'kvnoprinc'], expected_msg='Number of keys: 4')
realm.run([kadminl, 'cpw', '-randkey', '-keepold', '-e',
           'aes256-cts,aes128-cts', 'kvnoprinc'])
realm.run([kadminl, 'getprinc', 'kvnoprinc'], expected_msg='Number of keys: 6')

# Regression test for #8041 (NULL dereference on keyless principals).
realm.run([kadminl, 'addprinc', '-nokey', 'keylessprinc'])
realm.run([kadminl, 'getprinc', 'keylessprinc'],
          expected_msg='Number of keys: 0')
realm.run([kadminl, 'cpw', '-randkey', '-e', 'aes256-cts,aes128-cts',
           'keylessprinc'])
realm.run([kadminl, 'cpw', '-randkey', '-keepold', '-e',
           'aes256-cts,aes128-cts', 'keylessprinc'])
realm.run([kadminl, 'getprinc', 'keylessprinc'],
          expected_msg='Number of keys: 4')
realm.run([kadminl, 'purgekeys', '-all', 'keylessprinc'])
realm.run([kadminl, 'getprinc', 'keylessprinc'],
          expected_msg='Number of keys: 0')

# Test for 8354 (old password history entries when -keepold is used)
realm.run([kadminl, 'addpol', '-history', '2', 'keepoldpasspol'])
realm.run([kadminl, 'addprinc', '-policy', 'keepoldpasspol', '-pw', 'aaaa',
           'keepoldpassprinc'])
for p in ('bbbb', 'cccc', 'aaaa'):
    realm.run([kadminl, 'cpw', '-keepold', '-pw', p, 'keepoldpassprinc'])

if runenv.sizeof_time_t <= 4:
    skipped('y2038 LDAP test', 'platform has 32-bit time_t')
else:
    # Test storage of timestamps after y2038.
    realm.run([kadminl, 'modprinc', '-pwexpire', '2040-02-03', 'user'])
    realm.run([kadminl, 'getprinc', 'user'], expected_msg=' 2040\n')

realm.stop()

# Briefly test dump and load.
dumpfile = os.path.join(realm.testdir, 'dump')
realm.run([kdb5_util, 'dump', dumpfile])
realm.run([kdb5_util, 'load', dumpfile], expected_code=1,
          expected_msg='KDB module requires -update argument')
realm.run([kdb5_util, 'load', '-update', dumpfile])

# Destroy the realm.
kldaputil(['destroy', '-f'])
out = kldaputil(['list'])
if out:
    fail('Unexpected kdb5_ldap_util list output after destroy')

if not core_schema:
    skip_rest('LDAP SASL tests', 'core schema not found')

if runenv.have_sasl != 'yes':
    skip_rest('LDAP SASL tests', 'SASL support not built')

# Test SASL EXTERNAL auth.  Remove the DNs and service password file
# from the DB module config.
os.remove(ldap_pwfile)
dbmod = conf['dbmodules']['ldap']
dbmod['ldap_kdc_sasl_mech'] = dbmod['ldap_kadmind_sasl_mech'] = 'EXTERNAL'
del dbmod['ldap_service_password_file']
del dbmod['ldap_kdc_dn'], dbmod['ldap_kadmind_dn']
realm = K5Realm(create_kdb=False, kdc_conf=conf)
realm.run([kdb5_ldap_util, 'create', '-s', '-P', 'master'])
realm.start_kdc()
realm.addprinc(realm.user_princ, password('user'))
realm.kinit(realm.user_princ, password('user'))
realm.stop()
realm.run([kdb5_ldap_util, 'destroy', '-f'])

# Test SASL DIGEST-MD5 auth.  We need to set a clear-text password for
# the admin DN, so create a person entry (requires the core schema).
# Restore the service password file in the config and set authcids.
ldap_add('cn=admin,cn=krb5', 'person',
         ['sn: dummy', 'userPassword: admin'])
dbmod['ldap_kdc_sasl_mech'] = dbmod['ldap_kadmind_sasl_mech'] = 'DIGEST-MD5'
dbmod['ldap_kdc_sasl_authcid'] = 'digestuser'
dbmod['ldap_kadmind_sasl_authcid'] = 'digestuser'
dbmod['ldap_service_password_file'] = ldap_pwfile
realm = K5Realm(create_kdb=False, kdc_conf=conf)
input = admin_pw + '\n' + admin_pw + '\n'
realm.run([kdb5_ldap_util, 'stashsrvpw', 'digestuser'], input=input)
realm.run([kdb5_ldap_util, 'create', '-s', '-P', 'master'])
realm.start_kdc()
realm.addprinc(realm.user_princ, password('user'))
realm.kinit(realm.user_princ, password('user'))
realm.stop()
# Exercise DB options, which should cause binding to fail.
realm.run([kadminl, '-x', 'sasl_authcid=ab', 'getprinc', 'user'],
          expected_code=1, expected_msg='Cannot bind to LDAP server')
realm.run([kadminl, '-x', 'bindpwd=wrong', 'getprinc', 'user'],
          expected_code=1, expected_msg='Cannot bind to LDAP server')
realm.run([kdb5_ldap_util, 'destroy', '-f'])

# We could still use tests to exercise:
# * DB arg handling in krb5_ldap_create
# * krbAllowedToDelegateTo attribute processing
# * A load operation overwriting a standalone principal entry which
#   already exists but doesn't have a krbPrincipalName attribute
#   matching the principal name.
# * A bunch of invalid-input error conditions
#
# There is no coverage for the following because it would be difficult:
# * Out-of-memory error conditions
# * Handling of failures from slapd (including krb5_retry_get_ldap_handle)
# * Handling of servers which don't support mod-increment
# * krb5_ldap_delete_krbcontainer (only happens if krb5_ldap_create fails)

success('LDAP and DB2 KDB tests')


text:
/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; see the file COPYING.  If not, write to
 * the Free Software Foundation, 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

#include <CoreFoundation/CoreFoundation.h>
#include <CoreServices/CoreServices.h>
#include <QuickLook/QuickLook.h>
#import <Cocoa/Cocoa.h>
#import <WebKit/WebKit.h>

/* -----------------------------------------------------------------------------
    Generate a thumbnail for file

   This function's job is to create thumbnail for designated file as fast as possible
   ----------------------------------------------------------------------------- */
#include "HTMLFromSourceCode.h"

//The minimum aspect ratio (width / height) of a thumbnail.
#define MINIMUM_ASPECT_RATIO (1.0/2.0)

OSStatus GenerateThumbnailForURL(void *thisInterface, QLThumbnailRequestRef thumbnail, CFURLRef url, CFStringRef contentTypeUTI, CFDictionaryRef options, CGSize maxSize)
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSData *data = [(NSData *) createHTMLDataFromSourceCodeFile(url) autorelease];
    if (data)
    {
        CGImageRef image = NULL;

        //Render the HTML into an attributed string, for easy sizing as well as drawing.
#if 0
        NSAttributedString *attrStr = [[[NSAttributedString alloc] initWithHTML:data baseURL:(NSURL *) url documentAttributes:NULL] autorelease];

        NSSize webViewFrameSize = [attrStr size];
        //Adjust the frame size, in order to avoid a large source file being thumbnailed as a very tall image of unreadable text.
        CGFloat aspectRatio = webViewFrameSize.width / webViewFrameSize.height;
        if (aspectRatio < MINIMUM_ASPECT_RATIO)
        {
            //We simply crop it.
            //If the minimum aspect ratio is less than 1, this division will result in the height being longer than the width; if it's greater than 1, it will result in the height being shorter than the width.
            //Room for improvement: Currently, it's possible for all the lines of text that are above the crop line to not completely use the horizontal space (caused by a longer line of text below the crop line). For this reason, it would be better to cut off the original source code somehow, to avoid the risk of wasted horizontal space.
            webViewFrameSize.height = webViewFrameSize.width / MINIMUM_ASPECT_RATIO;
        }
#else
        NSSize webViewFrameSize = NSMakeSize(800, 800);
#endif

        //Create a WebView to render the HTML.
        WebView *webView = [[[WebView alloc] initWithFrame:NSMakeRect(0.0, 0.0, webViewFrameSize.width, webViewFrameSize.height)] autorelease];
        //We don't want scroll-bars.
        [[[webView mainFrame] frameView] setAllowsScrolling:NO];
        [[webView mainFrame] loadData: data
                             MIMEType: @"text/html"
                     textEncodingName: @"utf-8"
                              baseURL: nil];

        while ([webView isLoading])
        {
#if 0
            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:1.0]];
#else
            [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
                                     beforeDate: [NSDate date]];
#endif
        }
        [webView display];

        //Generate a PDF document from the HTML.
        CFDataRef pdfData = (CFDataRef) [webView dataWithPDFInsideRect:[webView bounds]];
        if (pdfData)
        {
            //Create a CGImageSource to turn our PDF document into a CGImage.
            CGImageSourceRef source = CGImageSourceCreateWithData(pdfData, /*options*/ NULL);
            if (source) {
                NSDictionary *sourceOptions = [NSDictionary dictionaryWithObjectsAndKeys:
                    //CGImageSource creates square thumbnails, so our maximum size should be either the max width or max height, whichever is less.
                    [NSNumber numberWithDouble:(maxSize.width < maxSize.height) ? maxSize.width : maxSize.height], kCGImageSourceThumbnailMaxPixelSize,
                    //PDF documents don't ordinaily have thumbnails, so we need to tell CGImageSource to create one.
                    (id) kCFBooleanTrue, kCGImageSourceCreateThumbnailFromImageIfAbsent,
                    nil];
                image = CGImageSourceCreateThumbnailAtIndex(source, /*index*/ 0, (CFDictionaryRef) sourceOptions);
                if (image)
                    QLThumbnailRequestSetImage(thumbnail, image, /*properties*/ NULL);

                CFRelease(source);
            }
        }

    }
    [pool release];
    return noErr;
}

void CancelThumbnailGeneration(void* thisInterface, QLThumbnailRequestRef thumbnail)
{
    // implement only if supported
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * @author windy
 * @version 2.0
 * Created by windy on 2020/5/13
 */
describe("state_editor", function () {

    /**
     * test_author_windy
     */
    it("state-editor", function (done) {
        var editor = BI.Test.createWidget({
            type: "bi.state_editor",
            width: 300,
            value: "12345",
            watermark: "添加合法性判断",
            errorText: "长度必须大于4",
            validationChecker: function () {
                return this.getValue().length > 4;
            }
        });
        editor.setWaterMark("AAAAA");
        expect(editor.element.find(".bi-water-mark").text()).to.equal("AAAAA");
        expect(editor.element.find(".bi-input").val()).to.equal("12345");
        editor.focus();
        BI.Test.triggerKeyDown(editor.element.find(".bi-input"), "8", 56, function () {
            expect(editor.element.find(".bi-bubble .bubble-text:first-child").text()).to.equal("长度必须大于4");
            editor.destroy();
            done();
        })
    });

    /**
     * test_author_windy
     */
    it("setValue", function () {
        var editor = BI.Test.createWidget({
            type: "bi.state_editor",
            width: 300,
            watermark: "添加合法性判断",
            errorText: "长度必须大于4",
            validationChecker: function () {
                return this.getValue().length > 4;
            }
        });
        editor.setValue("12345");
        expect(editor.element.find(".bi-input").val()).to.equal("12345");
        editor.destroy();
    });

    /**
     * test_author_windy
     */
    it("getValue", function () {
        var editor = BI.Test.createWidget({
            type: "bi.state_editor",
            width: 300,
            value: "12346",
            watermark: "添加合法性判断",
            errorText: "长度必须大于4",
            validationChecker: function () {
                return this.getValue().length > 4;
            }
        });
        expect(editor.getValue()).to.equal("12346");
        editor.destroy();
    });

});


text:
#include "../../config.h"
#include "astnode.h"
#include "util.h"
#include <assert.h>

struct node_id_lookup
{
    cypher_astnode_t _astnode;
    const cypher_astnode_t *identifier;
    unsigned int nids;
    const cypher_astnode_t *ids[];
};

static cypher_astnode_t *clone(const cypher_astnode_t *self,
        cypher_astnode_t **children);
static ssize_t detailstr(const cypher_astnode_t *self, char *str, size_t size);

static const struct cypher_astnode_vt *parents[] =
    { &cypher_start_point_astnode_vt };

const struct cypher_astnode_vt cypher_node_id_lookup_astnode_vt =
    { .parents = parents,
      .nparents = 1,
      .name = "node id lookup",
      .detailstr = detailstr,
      .release = cypher_astnode_release,
      .clone = clone };

cypher_astnode_t *cypher_ast_node_id_lookup(const cypher_astnode_t *identifier,
        cypher_astnode_t * const *ids, unsigned int nids,
        cypher_astnode_t **children, unsigned int nchildren,
        struct cypher_input_range range)
{
    REQUIRE_CHILD(children, nchildren, identifier, CYPHER_AST_IDENTIFIER, NULL);
    REQUIRE(nids > 0, NULL);
    REQUIRE_CHILD_ALL(children, nchildren, ids, nids, CYPHER_AST_INTEGER, NULL);

    struct node_id_lookup *node = calloc(1, sizeof(struct node_id_lookup) +
            nids * sizeof(cypher_astnode_t *));
    if (node == NULL)
    {
        return NULL;
    }
    if (cypher_astnode_init(&(node->_astnode), CYPHER_AST_NODE_ID_LOOKUP,
            children, nchildren, range))
    {
        goto cleanup;
    }
    node->identifier = identifier;
    memcpy(node->ids, ids, nids * sizeof(cypher_astnode_t *));
    node->nids = nids;
    return &(node->_astnode);

    int errsv;
cleanup:
    errsv = errno;
    free(node);
    errno = errsv;
    return NULL;
}

cypher_astnode_t *clone(const cypher_astnode_t *self,
        cypher_astnode_t **children)
{
    REQUIRE_TYPE(self, CYPHER_AST_NODE_ID_LOOKUP, NULL);
    struct node_id_lookup *node =
            container_of(self, struct node_id_lookup, _astnode);

    cypher_astnode_t *identifier = children[child_index(self, node->identifier)];
    cypher_astnode_t **ids = calloc(node->nids, sizeof(cypher_astnode_t *));
    if (ids == NULL)
    {
        return NULL;
    }
    for (unsigned int i = 0; i < node->nids; ++i)
    {
        ids[i] = children[child_index(self, node->ids[i])];
    }

    cypher_astnode_t *clone = cypher_ast_node_id_lookup(identifier, ids,
            node->nids, children, self->nchildren, self->range);
    int errsv = errno;
    free(ids);
    errno = errsv;
    return clone;
}

const cypher_astnode_t *cypher_ast_node_id_lookup_get_identifier(
        const cypher_astnode_t *astnode)
{
    REQUIRE_TYPE(astnode, CYPHER_AST_NODE_ID_LOOKUP, NULL);
    struct node_id_lookup *node =
            container_of(astnode, struct node_id_lookup, _astnode);
    return node->identifier;
}

unsigned int cypher_ast_node_id_lookup_nids(const cypher_astnode_t *astnode)
{
    REQUIRE_TYPE(astnode, CYPHER_AST_NODE_ID_LOOKUP, 0);
    struct node_id_lookup *node =
            container_of(astnode, struct node_id_lookup, _astnode);
    return node->nids;
}

const cypher_astnode_t *cypher_ast_node_id_lookup_get_id(
        const cypher_astnode_t *astnode, unsigned int index)
{
    REQUIRE_TYPE(astnode, CYPHER_AST_NODE_ID_LOOKUP, NULL);
    struct node_id_lookup *node =
            container_of(astnode, struct node_id_lookup, _astnode);
    if (index >= node->nids)
    {
        return NULL;
    }
    return node->ids[index];
}

ssize_t detailstr(const cypher_astnode_t *self, char *str, size_t size)
{
    REQUIRE_TYPE(self, CYPHER_AST_NODE_ID_LOOKUP, -1);
    struct node_id_lookup *node =
            container_of(self, struct node_id_lookup, _astnode);

    size_t n = 0;
    ssize_t r = snprintf(str, size, "@%u = node(", node->identifier->ordinal);
    if (r < 0)
    {
        return -1;
    }
    n += r;

    for (unsigned int i = 0; i < node->nids; ++i)
    {
        r = snprintf(str+n, (n < size)? size-n : 0, "%s@%u",
                (i > 0)? ", " : "", node->ids[i]->ordinal);
        if (r < 0)
        {
            return -1;
        }
        n += r;
    }

    if ((n+1) < size)
    {
        str[n] = ')';
        str[size-1] = '\0';
    }
    ++n;
    return n;
}


text:
/*
// ------------------------------------------------------------------------
// Template path: src/defaultmarkups/gadgets/Text/Text.xml
// ------------------------------------------------------------------------
*/

/* JS-in-Template is empty */


text:
"""Unit tests for image utils."""

import contextlib
import tempfile

import mock
import mox
from oslo.config import cfg

from cinder import context
from cinder import exception
from cinder.image import image_utils
from cinder.openstack.common import fileutils
from cinder.openstack.common import processutils
from cinder.openstack.common import units
from cinder import test
from cinder import utils
from cinder.volume import utils as volume_utils

CONF = cfg.CONF

class FakeImageService:
    def __init__(self):
        self._imagedata = {}

    def download(self, context, image_id, data):
        self.show(context, image_id)
        data.write(self._imagedata.get(image_id, ''))

    def show(self, context, image_id):
        return {'size': 2 * units.Gi,
                'disk_format': 'qcow2',
                'container_format': 'bare'}

    def update(self, context, image_id, metadata, path):
        pass

class TestUtils(test.TestCase):
    TEST_IMAGE_ID = 321
    TEST_DEV_PATH = "/dev/ether/fake_dev"

    def setUp(self):
        super(TestUtils, self).setUp()
        self._mox = mox.Mox()
        self._image_service = FakeImageService()

        self.addCleanup(self._mox.UnsetStubs)

    def test_resize_image(self):
        mox = self._mox
        mox.StubOutWithMock(utils, 'execute')

        TEST_IMG_SOURCE = 'boobar.img'
        TEST_IMG_SIZE_IN_GB = 1

        utils.execute('qemu-img', 'resize', TEST_IMG_SOURCE,
                      '%sG' % TEST_IMG_SIZE_IN_GB, run_as_root=False)

        mox.ReplayAll()

        image_utils.resize_image(TEST_IMG_SOURCE, TEST_IMG_SIZE_IN_GB)

        mox.VerifyAll()

    @mock.patch('os.stat')
    def test_convert_image(self, mock_stat):

        mox = self._mox
        mox.StubOutWithMock(utils, 'execute')
        mox.StubOutWithMock(utils, 'is_blk_device')

        TEST_OUT_FORMAT = 'vmdk'
        TEST_SOURCE = 'img/qemu.img'
        TEST_DEST = '/img/vmware.vmdk'

        utils.is_blk_device(TEST_DEST).AndReturn(True)
        utils.execute('dd', 'count=0', 'if=img/qemu.img',
                      'of=/img/vmware.vmdk', 'oflag=direct',
                      run_as_root=True)
        utils.execute(
            'qemu-img', 'convert', '-t', 'none', '-O', TEST_OUT_FORMAT,
            TEST_SOURCE, TEST_DEST, run_as_root=True)

        mox.ReplayAll()

        image_utils.convert_image(TEST_SOURCE, TEST_DEST, TEST_OUT_FORMAT)

        mox.VerifyAll()

    def test_qemu_img_info(self):
        TEST_PATH = "img/qemu.qcow2"
        TEST_RETURN = "image: qemu.qcow2\n"\
                      "backing_file: qemu.qcow2 (actual path: qemu.qcow2)\n"\
                      "file_format: qcow2\n"\
                      "virtual_size: 50M (52428800 bytes)\n"\
                      "cluster_size: 65536\n"\
                      "disk_size: 196K (200704 bytes)\n"\
                      "Snapshot list:\n"\
                      "ID TAG  VM SIZE DATE VM CLOCK\n"\
                      "1  snap1 1.7G 2011-10-04 19:04:00 32:06:34.974"
        TEST_STR = "image: qemu.qcow2\n"\
                   "file_format: qcow2\n"\
                   "virtual_size: 52428800\n"\
                   "disk_size: 200704\n"\
                   "cluster_size: 65536\n"\
                   "backing_file: qemu.qcow2\n"\
                   "snapshots: [{'date': '2011-10-04', "\
                   "'vm_clock': '19:04:00 32:06:34.974', "\
                   "'vm_size': '1.7G', 'tag': 'snap1', 'id': '1'}]"

        mox = self._mox
        mox.StubOutWithMock(utils, 'execute')

        utils.execute(
            'env', 'LC_ALL=C', 'qemu-img', 'info',
            TEST_PATH, run_as_root=True).AndReturn(
                (TEST_RETURN, 'ignored'))

        mox.ReplayAll()

        inf = image_utils.qemu_img_info(TEST_PATH)

        self.assertEqual(inf.image, 'qemu.qcow2')
        self.assertEqual(inf.backing_file, 'qemu.qcow2')
        self.assertEqual(inf.file_format, 'qcow2')
        self.assertEqual(inf.virtual_size, 52428800)
        self.assertEqual(inf.cluster_size, 65536)
        self.assertEqual(inf.disk_size, 200704)

        self.assertEqual(inf.snapshots[0]['id'], '1')
        self.assertEqual(inf.snapshots[0]['tag'], 'snap1')
        self.assertEqual(inf.snapshots[0]['vm_size'], '1.7G')
        self.assertEqual(inf.snapshots[0]['date'], '2011-10-04')
        self.assertEqual(inf.snapshots[0]['vm_clock'], '19:04:00 32:06:34.974')

        self.assertEqual(str(inf), TEST_STR)

    def test_qemu_img_info_alt(self):
        """Test a slightly different variation of qemu-img output.

           (Based on Fedora 19's qemu-img 1.4.2.)
        """

        TEST_PATH = "img/qemu.qcow2"
        TEST_RETURN = "image: qemu.qcow2\n"\
                      "backing file: qemu.qcow2 (actual path: qemu.qcow2)\n"\
                      "file format: qcow2\n"\
                      "virtual size: 50M (52428800 bytes)\n"\
                      "cluster_size: 65536\n"\
                      "disk size: 196K (200704 bytes)\n"\
                      "Snapshot list:\n"\
                      "ID TAG  VM SIZE DATE VM CLOCK\n"\
                      "1  snap1 1.7G 2011-10-04 19:04:00 32:06:34.974"
        TEST_STR = "image: qemu.qcow2\n"\
                   "file_format: qcow2\n"\
                   "virtual_size: 52428800\n"\
                   "disk_size: 200704\n"\
                   "cluster_size: 65536\n"\
                   "backing_file: qemu.qcow2\n"\
                   "snapshots: [{'date': '2011-10-04', "\
                   "'vm_clock': '19:04:00 32:06:34.974', "\
                   "'vm_size': '1.7G', 'tag': 'snap1', 'id': '1'}]"

        mox = self._mox
        mox.StubOutWithMock(utils, 'execute')

        cmd = ['env', 'LC_ALL=C', 'qemu-img', 'info', TEST_PATH]
        utils.execute(*cmd, run_as_root=True).AndReturn(
            (TEST_RETURN, 'ignored'))

        mox.ReplayAll()

        inf = image_utils.qemu_img_info(TEST_PATH)

        self.assertEqual(inf.image, 'qemu.qcow2')
        self.assertEqual(inf.backing_file, 'qemu.qcow2')
        self.assertEqual(inf.file_format, 'qcow2')
        self.assertEqual(inf.virtual_size, 52428800)
        self.assertEqual(inf.cluster_size, 65536)
        self.assertEqual(inf.disk_size, 200704)

        self.assertEqual(inf.snapshots[0]['id'], '1')
        self.assertEqual(inf.snapshots[0]['tag'], 'snap1')
        self.assertEqual(inf.snapshots[0]['vm_size'], '1.7G')
        self.assertEqual(inf.snapshots[0]['date'], '2011-10-04')
        self.assertEqual(inf.snapshots[0]['vm_clock'],
                         '19:04:00 32:06:34.974')

        self.assertEqual(str(inf), TEST_STR)

    def _test_fetch_to_raw(self, has_qemu=True, src_inf=None, dest_inf=None,
                           bps_limit=0):
        mox = self._mox
        mox.StubOutWithMock(image_utils, 'create_temporary_file')
        mox.StubOutWithMock(utils, 'execute')
        mox.StubOutWithMock(image_utils, 'fetch')
        mox.StubOutWithMock(volume_utils, 'setup_blkio_cgroup')
        mox.StubOutWithMock(utils, 'is_blk_device')

        TEST_INFO = ("image: qemu.qcow2\n"
                     "file format: raw\n"
                     "virtual size: 0 (0 bytes)\n"
                     "disk size: 0")

        utils.is_blk_device(self.TEST_DEV_PATH).AndReturn(True)
        CONF.set_override('volume_copy_bps_limit', bps_limit)

        image_utils.create_temporary_file().AndReturn(self.TEST_DEV_PATH)

        test_qemu_img = utils.execute(
            'env', 'LC_ALL=C', 'qemu-img', 'info', self.TEST_DEV_PATH,
            run_as_root=True)

        if has_qemu:
            test_qemu_img.AndReturn((TEST_INFO, 'ignored'))
            image_utils.fetch(context, self._image_service, self.TEST_IMAGE_ID,
                              self.TEST_DEV_PATH, None, None)
        else:
            test_qemu_img.AndRaise(processutils.ProcessExecutionError())

        if has_qemu and src_inf:
            utils.execute(
                'env', 'LC_ALL=C', 'qemu-img', 'info',
                self.TEST_DEV_PATH, run_as_root=True).AndReturn(
                    (src_inf, 'ignored'))

        if has_qemu and dest_inf:
            if bps_limit:
                prefix = ('cgexec', '-g', 'blkio:test')
            else:
                prefix = ()

            utils.execute('dd', 'count=0', 'if=/dev/ether/fake_dev',
                          'of=/dev/ether/fake_dev', 'oflag=direct',
                          run_as_root=True)

            cmd = prefix + ('qemu-img', 'convert', '-t', 'none', '-O', 'raw',
                            self.TEST_DEV_PATH, self.TEST_DEV_PATH)

            volume_utils.setup_blkio_cgroup(
                self.TEST_DEV_PATH, self.TEST_DEV_PATH,
                bps_limit).AndReturn(prefix)

            utils.execute(*cmd, run_as_root=True)

            utils.execute(
                'env', 'LC_ALL=C', 'qemu-img', 'info',
                self.TEST_DEV_PATH, run_as_root=True).AndReturn(
                    (dest_inf, 'ignored'))

        self._mox.ReplayAll()

    @mock.patch('os.stat')
    def test_fetch_to_raw(self, mock_stat):

        SRC_INFO = ("image: qemu.qcow2\n"
                    "file_format: qcow2 \n"
                    "virtual_size: 50M (52428800 bytes)\n"
                    "cluster_size: 65536\n"
                    "disk_size: 196K (200704 bytes)")
        DST_INFO = ("image: qemu.raw\n"
                    "file_format: raw\n"
                    "virtual_size: 50M (52428800 bytes)\n"
                    "cluster_size: 65536\n"
                    "disk_size: 196K (200704 bytes)\n")

        self._test_fetch_to_raw(src_inf=SRC_INFO, dest_inf=DST_INFO)

        image_utils.fetch_to_raw(context, self._image_service,
                                 self.TEST_IMAGE_ID, self.TEST_DEV_PATH,
                                 mox.IgnoreArg())
        self._mox.VerifyAll()

    @mock.patch('os.stat')
    def test_fetch_to_raw_with_bps_limit(self, mock_stat):
        SRC_INFO = ("image: qemu.qcow2\n"
                    "file_format: qcow2 \n"
                    "virtual_size: 50M (52428800 bytes)\n"
                    "cluster_size: 65536\n"
                    "disk_size: 196K (200704 bytes)")
        DST_INFO = ("image: qemu.raw\n"
                    "file_format: raw\n"
                    "virtual_size: 50M (52428800 bytes)\n"
                    "cluster_size: 65536\n"
                    "disk_size: 196K (200704 bytes)\n")

        self._test_fetch_to_raw(src_inf=SRC_INFO, dest_inf=DST_INFO,
                                bps_limit=1048576)

        image_utils.fetch_to_raw(context, self._image_service,
                                 self.TEST_IMAGE_ID, self.TEST_DEV_PATH,
                                 mox.IgnoreArg())
        self._mox.VerifyAll()

    def test_fetch_to_raw_no_qemu_img(self):
        self._test_fetch_to_raw(has_qemu=False)

        self.assertRaises(exception.ImageUnacceptable,
                          image_utils.fetch_to_raw,
                          context, self._image_service,
                          self.TEST_IMAGE_ID, self.TEST_DEV_PATH,
                          mox.IgnoreArg())

    def test_fetch_to_raw_on_error_parsing_failed(self):
        SRC_INFO_NO_FORMAT = ("image: qemu.qcow2\n"
                              "virtual_size: 50M (52428800 bytes)\n"
                              "cluster_size: 65536\n"
                              "disk_size: 196K (200704 bytes)")

        self._test_fetch_to_raw(src_inf=SRC_INFO_NO_FORMAT)

        self.assertRaises(exception.ImageUnacceptable,
                          image_utils.fetch_to_raw,
                          context, self._image_service,
                          self.TEST_IMAGE_ID, self.TEST_DEV_PATH,
                          mox.IgnoreArg())

    def test_fetch_to_raw_on_error_backing_file(self):
        SRC_INFO_BACKING_FILE = ("image: qemu.qcow2\n"
                                 "backing_file: qemu.qcow2\n"
                                 "file_format: qcow2 \n"
                                 "virtual_size: 50M (52428800 bytes)\n"
                                 "cluster_size: 65536\n"
                                 "disk_size: 196K (200704 bytes)")

        self._test_fetch_to_raw(src_inf=SRC_INFO_BACKING_FILE)

        self.assertRaises(exception.ImageUnacceptable,
                          image_utils.fetch_to_raw,
                          context, self._image_service,
                          self.TEST_IMAGE_ID, self.TEST_DEV_PATH,
                          mox.IgnoreArg())

    @mock.patch('os.stat')
    def test_fetch_to_raw_on_error_not_convert_to_raw(self, mock_stat):

        IMG_INFO = ("image: qemu.qcow2\n"
                    "file_format: qcow2 \n"
                    "virtual_size: 50M (52428800 bytes)\n"
                    "cluster_size: 65536\n"
                    "disk_size: 196K (200704 bytes)")

        self._test_fetch_to_raw(src_inf=IMG_INFO, dest_inf=IMG_INFO)

        self.assertRaises(exception.ImageUnacceptable,
                          image_utils.fetch_to_raw,
                          context, self._image_service,
                          self.TEST_IMAGE_ID, self.TEST_DEV_PATH,
                          mox.IgnoreArg())

    def test_fetch_to_raw_on_error_image_size(self):
        TEST_VOLUME_SIZE = 1
        SRC_INFO = ("image: qemu.qcow2\n"
                    "file_format: qcow2 \n"
                    "virtual_size: 2G (2147483648 bytes)\n"
                    "cluster_size: 65536\n"
                    "disk_size: 196K (200704 bytes)")

        self._test_fetch_to_raw(src_inf=SRC_INFO)

        self.assertRaises(exception.ImageUnacceptable,
                          image_utils.fetch_to_raw,
                          context, self._image_service,
                          self.TEST_IMAGE_ID, self.TEST_DEV_PATH,
                          mox.IgnoreArg(), size=TEST_VOLUME_SIZE)

    def _test_fetch_verify_image(self, qemu_info, volume_size=1):
        fake_image_service = FakeImageService()
        mox = self._mox
        mox.StubOutWithMock(image_utils, 'fetch')
        mox.StubOutWithMock(utils, 'execute')
        image_utils.fetch(context, fake_image_service,
                          self.TEST_IMAGE_ID, self.TEST_DEV_PATH, None, None)

        utils.execute(
            'env', 'LC_ALL=C', 'qemu-img', 'info',
            self.TEST_DEV_PATH, run_as_root=True).AndReturn(
                (qemu_info, 'ignored'))

        self._mox.ReplayAll()
        self.assertRaises(exception.ImageUnacceptable,
                          image_utils.fetch_verify_image,
                          context, fake_image_service,
                          self.TEST_IMAGE_ID, self.TEST_DEV_PATH,
                          size=volume_size)

    def test_fetch_verify_image_with_backing_file(self):
        TEST_RETURN = "image: qemu.qcow2\n"\
                      "backing_file: qemu.qcow2 (actual path: qemu.qcow2)\n"\
                      "file_format: qcow2\n"\
                      "virtual_size: 50M (52428800 bytes)\n"\
                      "cluster_size: 65536\n"\
                      "disk_size: 196K (200704 bytes)\n"\
                      "Snapshot list:\n"\
                      "ID TAG  VM SIZE DATE VM CLOCK\n"\
                      "1  snap1 1.7G 2011-10-04 19:04:00 32:06:34.974"

        self._test_fetch_verify_image(TEST_RETURN)

    def test_fetch_verify_image_without_file_format(self):
        TEST_RETURN = "image: qemu.qcow2\n"\
                      "virtual_size: 50M (52428800 bytes)\n"\
                      "cluster_size: 65536\n"\
                      "disk_size: 196K (200704 bytes)\n"\
                      "Snapshot list:\n"\
                      "ID TAG  VM SIZE DATE VM CLOCK\n"\
                      "1  snap1 1.7G 2011-10-04 19:04:00 32:06:34.974"

        self._test_fetch_verify_image(TEST_RETURN)

    def test_fetch_verify_image_image_size(self):
        TEST_RETURN = "image: qemu.qcow2\n"\
                      "file_format: qcow2\n"\
                      "virtual_size: 2G (2147483648 bytes)\n"\
                      "cluster_size: 65536\n"\
                      "disk_size: 196K (200704 bytes)\n"\
                      "Snapshot list:\n"\
                      "ID TAG  VM SIZE DATE VM CLOCK\n"\
                      "1  snap1 1.7G 2011-10-04 19:04:00 32:06:34.974"

        self._test_fetch_verify_image(TEST_RETURN)

    @mock.patch('os.stat')
    def test_upload_volume(self, mock_stat, bps_limit=0):
        image_meta = {'id': 1, 'disk_format': 'qcow2'}
        TEST_RET = "image: qemu.qcow2\n"\
                   "file_format: qcow2 \n"\
                   "virtual_size: 50M (52428800 bytes)\n"\
                   "cluster_size: 65536\n"\
                   "disk_size: 196K (200704 bytes)"

        if bps_limit:
            CONF.set_override('volume_copy_bps_limit', bps_limit)
            prefix = ('cgexec', '-g', 'blkio:test')
        else:
            prefix = ()

        cmd = prefix + ('qemu-img', 'convert', '-O', 'qcow2',
                        mox.IgnoreArg(), mox.IgnoreArg())

        m = self._mox
        m.StubOutWithMock(utils, 'execute')
        m.StubOutWithMock(volume_utils, 'setup_blkio_cgroup')

        volume_utils.setup_blkio_cgroup(mox.IgnoreArg(), mox.IgnoreArg(),
                                        bps_limit).AndReturn(prefix)

        utils.execute(
            'env', 'LC_ALL=C', 'qemu-img', 'info',
            mox.IgnoreArg(), run_as_root=True).AndReturn(
                (TEST_RET, 'ignored'))
        utils.execute(*cmd, run_as_root=True)
        utils.execute(
            'env', 'LC_ALL=C', 'qemu-img', 'info',
            mox.IgnoreArg(), run_as_root=True).AndReturn(
                (TEST_RET, 'ignored'))

        m.ReplayAll()

        image_utils.upload_volume(context, FakeImageService(),
                                  image_meta, '/dev/loop1')
        m.VerifyAll()

    @mock.patch('os.stat')
    def test_upload_volume_with_bps_limit(self, mock_stat):
        bps_limit = 1048576
        image_meta = {'id': 1, 'disk_format': 'qcow2'}
        TEST_RET = "image: qemu.qcow2\n"\
                   "file_format: qcow2 \n"\
                   "virtual_size: 50M (52428800 bytes)\n"\
                   "cluster_size: 65536\n"\
                   "disk_size: 196K (200704 bytes)"

        CONF.set_override('volume_copy_bps_limit', bps_limit)
        prefix = ('cgexec', '-g', 'blkio:test')

        cmd = prefix + ('qemu-img', 'convert', '-O', 'qcow2',
                        mox.IgnoreArg(), mox.IgnoreArg())

        m = self._mox
        m.StubOutWithMock(utils, 'execute')
        m.StubOutWithMock(volume_utils, 'setup_blkio_cgroup')
        m.StubOutWithMock(volume_utils, 'check_for_odirect_support')

        volume_utils.setup_blkio_cgroup(mox.IgnoreArg(), mox.IgnoreArg(),
                                        bps_limit).AndReturn(prefix)

        utils.execute(
            'env', 'LC_ALL=C', 'qemu-img', 'info',
            mox.IgnoreArg(), run_as_root=True).AndReturn(
                (TEST_RET, 'ignored'))
        utils.execute(*cmd, run_as_root=True)
        utils.execute(
            'env', 'LC_ALL=C', 'qemu-img', 'info',
            mox.IgnoreArg(), run_as_root=True).AndReturn(
                (TEST_RET, 'ignored'))

        m.ReplayAll()
        image_utils.upload_volume(context, FakeImageService(),
                                  image_meta, '/dev/loop1')
        m.VerifyAll()

    def test_upload_volume_with_raw_image(self):
        image_meta = {'id': 1, 'disk_format': 'raw'}
        mox = self._mox

        mox.StubOutWithMock(image_utils, 'convert_image')

        mox.ReplayAll()

        with tempfile.NamedTemporaryFile() as f:
            image_utils.upload_volume(context, FakeImageService(),
                                      image_meta, f.name)
        mox.VerifyAll()

    @mock.patch('os.stat')
    def test_upload_volume_on_error(self, mock_stat):
        image_meta = {'id': 1, 'disk_format': 'qcow2'}
        TEST_RET = "image: qemu.vhd\n"\
                   "file_format: vhd \n"\
                   "virtual_size: 50M (52428800 bytes)\n"\
                   "cluster_size: 65536\n"\
                   "disk_size: 196K (200704 bytes)"

        m = self._mox
        m.StubOutWithMock(utils, 'execute')
        m.StubOutWithMock(volume_utils, 'check_for_odirect_support')

        utils.execute(
            'env', 'LC_ALL=C', 'qemu-img', 'info',
            mox.IgnoreArg(), run_as_root=True).AndReturn(
                (TEST_RET, 'ignored'))
        utils.execute('qemu-img', 'convert', '-O', 'qcow2',
                      mox.IgnoreArg(), mox.IgnoreArg(), run_as_root=True)
        utils.execute(
            'env', 'LC_ALL=C', 'qemu-img', 'info',
            mox.IgnoreArg(), run_as_root=True).AndReturn(
                (TEST_RET, 'ignored'))

        m.ReplayAll()

        self.assertRaises(exception.ImageUnacceptable,
                          image_utils.upload_volume,
                          context, FakeImageService(),
                          image_meta, '/dev/loop1')
        m.VerifyAll()

class TestExtractTo(test.TestCase):
    def test_extract_to_calls_tar(self):
        mox = self.mox
        mox.StubOutWithMock(utils, 'execute')

        utils.execute(
            'tar', '-xzf', 'archive.tgz', '-C', 'targetpath').AndReturn(
                ('ignored', 'ignored'))

        mox.ReplayAll()

        image_utils.extract_targz('archive.tgz', 'targetpath')
        mox.VerifyAll()

class TestSetVhdParent(test.TestCase):
    def test_vhd_util_call(self):
        mox = self.mox
        mox.StubOutWithMock(utils, 'execute')

        utils.execute(
            'vhd-util', 'modify', '-n', 'child', '-p', 'parent').AndReturn(
                ('ignored', 'ignored'))

        mox.ReplayAll()

        image_utils.set_vhd_parent('child', 'parent')
        mox.VerifyAll()

class TestFixVhdChain(test.TestCase):
    def test_empty_chain(self):
        mox = self.mox
        mox.StubOutWithMock(image_utils, 'set_vhd_parent')

        mox.ReplayAll()
        image_utils.fix_vhd_chain([])

    def test_single_vhd_file_chain(self):
        mox = self.mox
        mox.StubOutWithMock(image_utils, 'set_vhd_parent')

        mox.ReplayAll()
        image_utils.fix_vhd_chain(['0.vhd'])

    def test_chain_with_two_elements(self):
        mox = self.mox
        mox.StubOutWithMock(image_utils, 'set_vhd_parent')

        image_utils.set_vhd_parent('0.vhd', '1.vhd')

        mox.ReplayAll()
        image_utils.fix_vhd_chain(['0.vhd', '1.vhd'])

class TestGetSize(test.TestCase):
    def test_vhd_util_call(self):
        mox = self.mox
        mox.StubOutWithMock(utils, 'execute')

        utils.execute(
            'vhd-util', 'query', '-n', 'vhdfile', '-v').AndReturn(
                ('1024', 'ignored'))

        mox.ReplayAll()

        result = image_utils.get_vhd_size('vhdfile')
        mox.VerifyAll()

        self.assertEqual(1024, result)

class TestResize(test.TestCase):
    def test_vhd_util_call(self):
        mox = self.mox
        mox.StubOutWithMock(utils, 'execute')

        utils.execute(
            'vhd-util', 'resize', '-n', 'vhdfile', '-s', '1024',
            '-j', 'journal').AndReturn(('ignored', 'ignored'))

        mox.ReplayAll()

        image_utils.resize_vhd('vhdfile', 1024, 'journal')
        mox.VerifyAll()

class TestCoalesce(test.TestCase):
    def test_vhd_util_call(self):
        mox = self.mox
        mox.StubOutWithMock(utils, 'execute')

        utils.execute(
            'vhd-util', 'coalesce', '-n', 'vhdfile'
        ).AndReturn(('ignored', 'ignored'))

        mox.ReplayAll()

        image_utils.coalesce_vhd('vhdfile')
        mox.VerifyAll()

@contextlib.contextmanager
def fake_context(return_value):
    yield return_value

class TestTemporaryFile(test.TestCase):
    def test_file_unlinked(self):
        mox = self.mox
        mox.StubOutWithMock(image_utils, 'create_temporary_file')
        mox.StubOutWithMock(fileutils, 'delete_if_exists')

        image_utils.create_temporary_file().AndReturn('somefile')
        fileutils.delete_if_exists('somefile')

        mox.ReplayAll()

        with image_utils.temporary_file():
            pass

    def test_file_unlinked_on_error(self):
        mox = self.mox
        mox.StubOutWithMock(image_utils, 'create_temporary_file')
        mox.StubOutWithMock(fileutils, 'delete_if_exists')

        image_utils.create_temporary_file().AndReturn('somefile')
        fileutils.delete_if_exists('somefile')

        mox.ReplayAll()

        def sut():
            with image_utils.temporary_file():
                raise test.TestingException()

        self.assertRaises(test.TestingException, sut)

class TestCoalesceChain(test.TestCase):
    def test_single_vhd(self):
        mox = self.mox
        mox.StubOutWithMock(image_utils, 'get_vhd_size')
        mox.StubOutWithMock(image_utils, 'resize_vhd')
        mox.StubOutWithMock(image_utils, 'coalesce_vhd')

        mox.ReplayAll()

        result = image_utils.coalesce_chain(['0.vhd'])
        mox.VerifyAll()

        self.assertEqual('0.vhd', result)

    def test_chain_of_two_vhds(self):
        self.mox.StubOutWithMock(image_utils, 'get_vhd_size')
        self.mox.StubOutWithMock(image_utils, 'temporary_dir')
        self.mox.StubOutWithMock(image_utils, 'resize_vhd')
        self.mox.StubOutWithMock(image_utils, 'coalesce_vhd')
        self.mox.StubOutWithMock(image_utils, 'temporary_file')

        image_utils.get_vhd_size('0.vhd').AndReturn(1024)
        image_utils.temporary_dir().AndReturn(fake_context('tdir'))
        image_utils.resize_vhd('1.vhd', 1024, 'tdir/vhd-util-resize-journal')
        image_utils.coalesce_vhd('0.vhd')
        self.mox.ReplayAll()

        result = image_utils.coalesce_chain(['0.vhd', '1.vhd'])
        self.mox.VerifyAll()
        self.assertEqual('1.vhd', result)

class TestDiscoverChain(test.TestCase):
    def test_discovery_calls(self):
        mox = self.mox
        mox.StubOutWithMock(image_utils, 'file_exist')

        image_utils.file_exist('some/path/0.vhd').AndReturn(True)
        image_utils.file_exist('some/path/1.vhd').AndReturn(True)
        image_utils.file_exist('some/path/2.vhd').AndReturn(False)

        mox.ReplayAll()
        result = image_utils.discover_vhd_chain('some/path')
        mox.VerifyAll()

        self.assertEqual(
            ['some/path/0.vhd', 'some/path/1.vhd'], result)

class TestXenServerImageToCoalescedVhd(test.TestCase):
    def test_calls(self):
        mox = self.mox
        mox.StubOutWithMock(image_utils, 'temporary_dir')
        mox.StubOutWithMock(image_utils, 'extract_targz')
        mox.StubOutWithMock(image_utils, 'discover_vhd_chain')
        mox.StubOutWithMock(image_utils, 'fix_vhd_chain')
        mox.StubOutWithMock(image_utils, 'coalesce_chain')
        mox.StubOutWithMock(image_utils.os, 'unlink')
        mox.StubOutWithMock(fileutils, 'delete_if_exists')
        mox.StubOutWithMock(image_utils, 'rename_file')

        image_utils.temporary_dir().AndReturn(fake_context('somedir'))
        image_utils.extract_targz('image', 'somedir')
        image_utils.discover_vhd_chain('somedir').AndReturn(
            ['somedir/0.vhd', 'somedir/1.vhd'])
        image_utils.fix_vhd_chain(['somedir/0.vhd', 'somedir/1.vhd'])
        image_utils.coalesce_chain(
            ['somedir/0.vhd', 'somedir/1.vhd']).AndReturn('somedir/1.vhd')
        fileutils.delete_if_exists('image')
        image_utils.rename_file('somedir/1.vhd', 'image')

        mox.ReplayAll()
        image_utils.replace_xenserver_image_with_coalesced_vhd('image')
        mox.VerifyAll()


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Thank you!</title>

    <link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">

            Thank you for your feedback!


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using Microsoft.Azure.Management.Network.Models;
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Rest.Azure;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using Xunit;

namespace Compute.Tests
{
    public class CloudServiceRoleInstanceTests : CloudServiceTestsBase
    {
        [Fact]
        [Trait("Name", "Test_CloudServiceRoleInstanceOperations")]
        public void Test_CloudServiceRoleInstanceOperations()
        {
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                EnsureClientsInitialized(context);

                // Create resource group
                var rgName = TestUtilities.GenerateName(TestPrefix);
                var csName = TestUtilities.GenerateName("cs");
                string cloudServiceName = "HelloWorldTest_WebRole";
                string publicIPAddressName = TestUtilities.GenerateName("cspip");
                string vnetName = TestUtilities.GenerateName("csvnet");
                string subnetName = TestUtilities.GenerateName("subnet");
                string dnsName = TestUtilities.GenerateName("dns");
                string lbName = TestUtilities.GenerateName("lb");
                string lbfeName = TestUtilities.GenerateName("lbfe");

                try
                {
                    CreateVirtualNetwork(rgName, vnetName, subnetName);
                    PublicIPAddress publicIPAddress = CreatePublicIP(publicIPAddressName, rgName, dnsName);

                    // Define Configurations
                    List<string> supportedRoleInstanceSizes = GetSupportedRoleInstanceSizes();
                    Dictionary<string, RoleConfiguration> roleNameToPropertiesMapping = new Dictionary<string, RoleConfiguration>
                    {
                        { "HelloWorldTest1", new RoleConfiguration { InstanceCount = 2, RoleInstanceSize = supportedRoleInstanceSizes[0] } }
                    };

                    CloudService cloudService = GenerateCloudServiceWithNetworkProfile(
                        resourceGroupName: rgName,
                        serviceName: cloudServiceName,
                        cspkgSasUri: CreateCspkgSasUrl(rgName, WebRoleSasUri),
                        roleNameToPropertiesMapping: roleNameToPropertiesMapping,
                                publicIPAddressName: publicIPAddressName,
                                vnetName: vnetName,
                                subnetName: subnetName,
                                lbName: lbName,
                                lbFrontendName: lbfeName);

                    CloudService getResponse = CreateCloudService_NoAsyncTracking(
                    rgName,
                    csName,
                    cloudService);

                    string roleInstanceName = getResponse.Properties.RoleProfile.Roles[0].Name + "_IN_0";
                    //Get the roleInstance
                    var roleInstance = m_CrpClient.CloudServiceRoleInstances.Get(roleInstanceName, rgName, csName);
                    verifyRoleInstance(roleInstanceName, supportedRoleInstanceSizes[0], roleInstance);

                    //Get the roleInstance InstanceView
                    var roleInstanceInstanceView = m_CrpClient.CloudServiceRoleInstances.GetInstanceView(roleInstanceName, rgName, csName);
                    verifyRoleInstanceInstanceView(roleInstanceInstanceView);

                    //Restart the roleInstance and verify response
                    m_CrpClient.CloudServiceRoleInstances.Restart(roleInstanceName, rgName, csName);
                    roleInstance = m_CrpClient.CloudServiceRoleInstances.Get(roleInstanceName, rgName, csName);
                    verifyRoleInstance(roleInstanceName, supportedRoleInstanceSizes[0], roleInstance);

                    //Reimage the roleInstance and verify response
                    m_CrpClient.CloudServiceRoleInstances.Reimage(roleInstanceName, rgName, csName);
                    roleInstance = m_CrpClient.CloudServiceRoleInstances.Get(roleInstanceName, rgName, csName);
                    verifyRoleInstance(roleInstanceName, supportedRoleInstanceSizes[0], roleInstance);

                    //Rebuild the roleInstance and verify response
                    m_CrpClient.CloudServiceRoleInstances.Rebuild(roleInstanceName, rgName, csName);
                    roleInstance = m_CrpClient.CloudServiceRoleInstances.Get(roleInstanceName, rgName, csName);
                    verifyRoleInstance(roleInstanceName, supportedRoleInstanceSizes[0], roleInstance);

                     //Delete the RoleInstance
                    m_CrpClient.CloudServiceRoleInstances.Delete(roleInstanceName, rgName, csName);
                    IPage<RoleInstance> roleInstanceList = m_CrpClient.CloudServiceRoleInstances.List(rgName, csName);
                    Assert.True(roleInstanceList.Count() == 1, "Returned CloudService does not have 1 RoleInstance. Postcondition failed.");

                    // Delete the cloud Service
                    m_CrpClient.CloudServices.Delete(rgName, csName);
                }
                finally
                {
                    // Fire and forget. No need to wait for RG deletion completion
                    try
                    {
                        m_ResourcesClient.ResourceGroups.BeginDelete(rgName);
                    }
                    catch (Exception e)
                    {
                        // Swallow this exception so that the original exception is thrown
                        Console.WriteLine(e);
                    }
                }
            }
        }
    }
}


text:
package com.dongdongxia.my.patterns.abstractdocument.domain;

import java.util.Map;

import com.dongdongxia.my.patterns.abstractdocument.AbstractDocument;
/**
 *
 *
Description: 汽车部件实体

 * @ClassName: Part
 * @author java_liudong@163.com  2017年8月25日 上午9:59:41
 */
public class Part extends AbstractDocument implements HasType, HasModel, HasPrice {

    public Part(Map<String, Object> properties) {
        super(properties);
    }

}


text:
namespace fair_secretary {

using std::vector;

SecretaryInstance UnfairSecretaryAlgorithm::ComputeSolution(
    const vector<SecretaryInstance>& elements) {
  double max_value = 0;
  int th = elements.size() * (1.0 / std::exp(1.0));
  // Compute max values.
  for (int i = 0; i < th; i++) {
    max_value = std::max(max_value, elements[i].value);
  }
  for (int i = th; i < elements.size(); i++) {
    if (elements[i].value >= max_value) {
      return elements[i];
    }
  }
  return SecretaryInstance(-1, -1);
}

SecretaryInstance UnfairSecretaryAlgorithm::ComputeSolutionSingleColor(
    const vector<SecretaryInstance>& elements, const vector<double>& prob) {
  double max_value = 0;
  int rand_color = 0;
  int rand = RandomHandler::eng_() % 1000000;
  double rand_balanced = static_cast<double>(rand) / 1000000;
  for (int i = 0; i < prob.size(); i++) {
    if (rand_balanced <= prob[i]) {
      rand_color = i;
      break;
    }
    rand_balanced -= prob[i];
  }
  int th = elements.size() * (1.0 / std::exp(1.0));
  // Compute max values.
  for (int i = 0; i < th; i++) {
    if (rand_color == elements[i].color) {
      max_value = std::max(max_value, elements[i].value);
    }
  }
  for (int i = th; i < elements.size(); i++) {
    if (elements[i].value >= max_value && elements[i].color == rand_color) {
      return elements[i];
    }
  }
  return SecretaryInstance(-1, -1);
}

}  // namespace fair_secretary


text:
package web

import (
	"encoding/hex"
	"fmt"
	"net/http"
	"sync"

	"github.com/go-kit/log"
	"golang.org/x/crypto/bcrypt"
)

// extraHTTPHeaders is a map of HTTP headers that can be added to HTTP
// responses.
// This is private on purpose to ensure consistency in the Prometheus ecosystem.
var extraHTTPHeaders = map[string][]string{
	"Strict-Transport-Security": nil,
	"X-Content-Type-Options":    {"nosniff"},
	"X-Frame-Options":           {"deny", "sameorigin"},
	"X-XSS-Protection":          nil,
	"Content-Security-Policy":   nil,
}

func validateUsers(configPath string) error {
	c, err := getConfig(configPath)
	if err != nil {
		return err
	}

	for _, p := range c.Users {
		_, err = bcrypt.Cost([]byte(p))
		if err != nil {
			return err
		}
	}

	return nil
}

// validateHeaderConfig checks that the provided header configuration is correct.
// It does not check the validity of all the values, only the ones which are
// well-defined enumerations.
func validateHeaderConfig(headers map[string]string) error {
HeadersLoop:
	for k, v := range headers {
		values, ok := extraHTTPHeaders[k]
		if !ok {
			return fmt.Errorf("HTTP header %q can not be configured", k)
		}
		for _, allowedValue := range values {
			if v == allowedValue {
				continue HeadersLoop
			}
		}
		if len(values) > 0 {
			return fmt.Errorf("invalid value for %s. Expected one of: %q, but got: %q", k, values, v)
		}
	}
	return nil
}

type webHandler struct {
	tlsConfigPath string
	handler       http.Handler
	logger        log.Logger
	cache         *cache
	// bcryptMtx is there to ensure that bcrypt.CompareHashAndPassword is run
	// only once in parallel as this is CPU intensive.
	bcryptMtx sync.Mutex
}

func (u *webHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	c, err := getConfig(u.tlsConfigPath)
	if err != nil {
		u.logger.Log("msg", "Unable to parse configuration", "err", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	// Configure http headers.
	for k, v := range c.HTTPConfig.Header {
		w.Header().Set(k, v)
	}

	if len(c.Users) == 0 {
		u.handler.ServeHTTP(w, r)
		return
	}

	user, pass, auth := r.BasicAuth()
	if auth {
		hashedPassword, validUser := c.Users[user]

		if !validUser {
			// The user is not found. Use a fixed password hash to
			// prevent user enumeration by timing requests.
			// This is a bcrypt-hashed version of "fakepassword".
			hashedPassword = "$2y$10$QOauhQNbBCuQDKes6eFzPeMqBSjb7Mr5DUmpZ/VcEd00UAV/LDeSi"
		}

		cacheKey := hex.EncodeToString(append(append([]byte(user), []byte(hashedPassword)...), []byte(pass)...))
		authOk, ok := u.cache.get(cacheKey)

		if !ok {
			// This user, hashedPassword, password is not cached.
			u.bcryptMtx.Lock()
			err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(pass))
			u.bcryptMtx.Unlock()

			authOk = err == nil
			u.cache.set(cacheKey, authOk)
		}

		if authOk && validUser {
			u.handler.ServeHTTP(w, r)
			return
		}
	}

	w.Header().Set("WWW-Authenticate", "Basic")
	http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
}


text:
package org.flywaydb.core.util.jdbc;

/**
 * Callback for TransactionTemplate.
 *
 * @param <T> The type of the transaction code result.
 */
public interface TransactionCallback<T> {
    /**
     * Executes this code within a transaction.
     *
     * @return The result of the transaction code.
     */
    T doInTransaction();
}


text:
var container, scene, camera, renderer, controls, graph, env;
var sphereRadius, camera_z, pointLightPos, pointLights;
var keyboard = new THREEx.KeyboardState();
var projector, mouse = {
    x: 0,
    y: 0
  },
  INTERSECTED;

init();
animate();

var POINT_LIGHT_INTENSITY, CENTER;

function init() {
  camera_z = 600;
  sphereRadius = 200;
  CENTER = new THREE.Vector3(0, 0, 0);
  POINT_LIGHT_INTENSITY = 2;
  pointLightPos = new THREE.Vector3(300, 100, 200);

  // Scene
  scene = new THREE.Scene();
  // Camera
  var SCREEN_WIDTH = window.innerWidth,
    SCREEN_HEIGHT = window.innerHeight;
  var VIEW_ANGLE = 45,
    ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT,
    NEAR = 50,
    FAR = 20000;
  camera = new THREE.PerspectiveCamera(VIEW_ANGLE, ASPECT, NEAR, FAR);
  scene.add(camera);
  camera.position.set(0, 0, camera_z);
  camera.lookAt(scene.position);

  // Renderer
  if (Detector.webgl)
    renderer = new THREE.WebGLRenderer({
      antialias: true,
      alpha: true
    });
  else
    console.error("Cannot run WebGL here!");
    //renderer = new THREE.CanvasRenderer();

  renderer.setClearColor(0x000000, 1);
  renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);

  container = document.getElementById('w3-graph-main');
  container.appendChild(renderer.domElement);

  // Events.
  THREEx.WindowResize(renderer, camera);
  THREEx.FullScreen.bindKey({
    charCode: 'm'.charCodeAt(0)
  });

  // Controls.
  controls = new THREE.OrbitControls(camera, renderer.domElement);

  scene.fog = new THREE.FogExp2(0x9999ff, 0.00025);

  pointLights = [];
  pointLights.push(new THREE.PointLight(0xFFCCFF));
  pointLights[0].name = "w3-walrus-pointLight1";
  // Set its position.
  pointLights[0].position.x = -pointLightPos.x;
  pointLights[0].position.y = 600;
  pointLights[0].position.z = -pointLightPos.z;
  pointLights[0].intensity = POINT_LIGHT_INTENSITY;

  // Add to the scene.
  scene.add(pointLights[0]);

  pointLights.push(new THREE.PointLight(0xFFCCFF));
  pointLights[1].name = "w3-walrus-pointLight2";

  // Set its position.
  pointLights[1].position.x = pointLightPos.x;
  pointLights[1].position.y = pointLightPos.y;
  pointLights[1].position.z = pointLightPos.z;
  pointLights[1].intensity = POINT_LIGHT_INTENSITY;

  // Add to the scene.
  scene.add(pointLights[1]);

  projector = new THREE.Projector();
  document.addEventListener('mousemove', onDocumentMouseMove, false);

  env = new EnvironmentRender(CENTER, sphereRadius);
  env.initScene(scene);
}

function renderGraphOnScene(graphData) {
  if (!isEmpty(graph)) {
    removeFromScene(graph.obj, scene);
  }

  graph = new GraphRender(CENTER, "w3-graph", graphData);
  removeFromScene(env.obj, scene);

  // Refresh env
  env = new EnvironmentRender(CENTER, graph.radius);
  env.initScene(scene);

  // Refresh camera
  camera.position.set(0, 0, graph.radius*3);

  // refresh lights:
  for (var i in pointLights) {
    removeFromScene(pointLights[i], scene);
  }

  // Set its position.
  pointLights[0].position.x = -graph.radius*2;
  pointLights[0].position.y = graph.radius*3;
  pointLights[0].position.z = -graph.radius;
  pointLights[0].intensity = POINT_LIGHT_INTENSITY;

  // Add to the scene.
  scene.add(pointLights[0]);

  // Set its position.
  pointLights[1].position.x = graph.radius*2;
  pointLights[1].position.y = graph.radius/2;
  pointLights[1].position.z = graph.radius;
  pointLights[1].intensity = POINT_LIGHT_INTENSITY;

  // Add to the scene.
  scene.add(pointLights[1]);

  controls.userPanSpeed = graph.radius / 30;
  graph.initScene(scene);
}

function onDocumentMouseMove(event) {
  // the following line would stop any other event handler from firing
  // (such as the mouse's TrackballControls)
  // event.preventDefault();
  mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
  mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
}

var need_key_change = false;

function update() {
  var w_key = keyboard.pressed("w");
  if (w_key && !need_key_change) {
    need_key_change = true;
    // TODO!
  } else if (!w_key) {
    need_key_change = false;
  }

  // create a Ray with origin at the mouse position
  //   and direction into the scene (camera direction)
  if (!isEmpty(names) && !isEmpty(graphData) && !isEmpty(graph)) {
    var vector = new THREE.Vector3(mouse.x, mouse.y, 1);
    projector.unprojectVector(vector, camera);
    var ray = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize());

    // create an array containing all objects in the scene with which the ray intersects
    var intersects = ray.intersectObjects(graph.obj.children);

    // INTERSECTED = the object in the scene currently closest to the camera
    //		and intersected by the Ray projected from the mouse position

    // if there is one (or more) intersections
    if (intersects.length > 0) {
      // if the closest object intersected is not the currently stored intersection object
      if (intersects[0].object != INTERSECTED) {

        // restore previous intersection object (if it exists) to its original color
        if (INTERSECTED)
          INTERSECTED.material.color.setHex(INTERSECTED.currentHex);
        // store reference to closest object as current intersection object
        INTERSECTED = intersects[0].object;
        // store color of closest object (for later restoration)
        INTERSECTED.currentHex = INTERSECTED.material.color.getHex();
        // set a new color for closest object
        INTERSECTED.material.color.setHex(0x00ffff);

        // update text, if it has a "name" field.
        if (intersects[0].object.name) {
          var message = intersects[0].object.name;
          var div = document.getElementById("w3-graph-name");
          div.textContent = message;
        }

      }
    } else // there are no intersections
    {
      // restore previous intersection object (if it exists) to its original color
      if (INTERSECTED)
        INTERSECTED.material.color.setHex(INTERSECTED.currentHex);
      // remove previous intersection object reference
      //     by setting current intersection object to "nothing"
      INTERSECTED = null;
    }
  }
  controls.update();
}

function render() {
  renderer.render(scene, camera);
}

function animate() {

  requestAnimationFrame(animate);
  render();
  update();

}


text:
from __future__ import print_function
import click
import logging
import pprint
import requests
import urllib

from eventbot import settings, test, test_fixtures

log = logging.getLogger(__name__)
pp = pprint.PrettyPrinter(indent=4)

@click.command()
@click.option('--base_url', default='http://localhost:5000', help='Base URL for HTTP requests')
def run(base_url):
    data = test_fixtures.SLACK_ACTION_ENDPOINT_EXAMPLE_1
    email = urllib.quote(settings.MAILCHIMP_DEFAULT_EMAIL)
    data = data.replace('application_form_action', email)
    url = "{}/slack/action-endpoint".format(base_url)
    resp = requests.post(url, data=data)
    log.info(resp.status_code)
    print(resp.content)

if __name__ == '__main__':
    logging.basicConfig(format=settings.CLI_LOG_FORMAT, level=logging.DEBUG)
    run()


text:
using Newtonsoft.Json;
using System;

namespace IBM.Watson.Assistant.v1.Model
{
    /// <summary>
    /// Synonym.
    /// </summary>
    public class Synonym
    {
        /// <summary>
        /// The text of the synonym. This string must conform to the following restrictions:
        /// - It cannot contain carriage return, newline, or tab characters.
        /// - It cannot consist of only whitespace characters.
        /// </summary>
        [JsonProperty("synonym", NullValueHandling = NullValueHandling.Ignore)]
        public string _Synonym { get; set; }
        /// <summary>
        /// The timestamp for creation of the object.
        /// </summary>
        [JsonProperty("created", NullValueHandling = NullValueHandling.Ignore)]
        public virtual DateTime? Created { get; private set; }
        /// <summary>
        /// The timestamp for the most recent update to the object.
        /// </summary>
        [JsonProperty("updated", NullValueHandling = NullValueHandling.Ignore)]
        public virtual DateTime? Updated { get; private set; }
    }

}


text:
require 'faraday'

module BitBucket
  class Response::Helpers < Response

    def on_complete(env)
      env[:body].class.class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1

        def env
          @env
        end

      RUBY_EVAL
      env[:body].instance_eval { @env = env }
    end

  end # Response::Helpers
end # BitBucket


text:
using System;
using Windows.Foundation;
using Windows.Graphics.Display;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Xamarin.Forms.Controls;
using WControls = Windows.UI.Xaml.Controls;
using Xamarin.Forms.Platform.WinRT;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=391641

namespace Xamarin.Forms.ControlGallery.WindowsPhone
{
	/// <summary>
	/// An empty page that can be used on its own or navigated to within a Frame.
	/// </summary>
	public sealed partial class MainPage
	{
		public MainPage ()
		{
			InitializeComponent ();

			var app = new Controls.App ();

			// When the native control gallery loads up, it'll let us know so we can add the nested native controls
			MessagingCenter.Subscribe<NestedNativeControlGalleryPage>(this, NestedNativeControlGalleryPage.ReadyForNativeControlsMessage, AddNativeControls);

			LoadApplication (app);
		}

		void AddNativeControls (NestedNativeControlGalleryPage page)
		{
			if (page.NativeControlsAdded) {
				return;
			}

			StackLayout sl = page.Layout;

			// Create and add a native TextBlock
			var originalText = "I am a native TextBlock";
			var textBlock = new TextBlock {
				Text = originalText,
				FontSize = 14,
				FontFamily = new FontFamily ("HelveticaNeue")
			};

			sl?.Children.Add (textBlock);

			// Create and add a native Button
			var button = new WControls.Button { Content = "Click to toggle font size", Height = 80 };
			button.Click += (sender, args) => { textBlock.FontSize = textBlock.FontSize == 14 ? 24 : 14; };

			sl?.Children.Add (button.ToView ());

			// Create a control which we know doesn't behave correctly with regard to measurement
			var difficultControl = new BrokenNativeControl {
				Text = "Not Sized/Arranged Properly"
			};

			var difficultControl2 = new BrokenNativeControl {
				Text = "Fixed"
			};

			// Add the misbehaving controls, one with a custom delegate for ArrangeOverrideDelegate
			sl?.Children.Add (difficultControl);
			sl?.Children.Add (difficultControl2,
				arrangeOverrideDelegate: (renderer, finalSize) => {
					if (finalSize.Width <= 0 || double.IsInfinity (finalSize.Width)) {
						return null;
					}

					FrameworkElement frameworkElement = renderer.Control;

					frameworkElement.Measure (finalSize);

					// The broken control tries sizes itself to be the width of the screen
					var wrongSize = Window.Current.Bounds.Width * (int)DisplayProperties.ResolutionScale / 100;

					// The broken control always sizes itself to be 600 wide
					// We can re-center it by offsetting it during the Arrange call
					double diff = Math.Abs(finalSize.Width - wrongSize) / -2;
					frameworkElement.Arrange (new Rect (diff, 0, finalSize.Width - diff, finalSize.Height));

					// Arranging the control to the left will make it show up past the edge of the master page
					// We can fix that by clipping it manually
					var clip = new RectangleGeometry { Rect = new Rect (-diff, 0, finalSize.Width, finalSize.Height) };
					frameworkElement.Clip = clip;

					return finalSize;
				}
			);

			page.NativeControlsAdded = true;
		}

	}
}


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getDialogContentUtilityClass = getDialogContentUtilityClass;
exports.default = void 0;

var _unstyled = require("@material-ui/unstyled");

function getDialogContentUtilityClass(slot) {
  return (0, _unstyled.generateUtilityClass)('MuiDialogContent', slot);
}

const dialogContentClasses = (0, _unstyled.generateUtilityClasses)('MuiDialogContent', ['root', 'dividers']);
var _default = dialogContentClasses;
exports.default = _default;


text:
package io.shardingsphere.core.parsing.antlr.rule.registry.statement;

import com.google.common.base.CaseFormat;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import io.shardingsphere.core.parsing.antlr.extractor.SQLSegmentExtractor;
import io.shardingsphere.core.parsing.antlr.optimizer.SQLStatementOptimizer;
import io.shardingsphere.core.parsing.antlr.rule.jaxb.entity.statement.SQLStatementRuleDefinitionEntity;
import io.shardingsphere.core.parsing.antlr.rule.jaxb.entity.statement.SQLStatementRuleEntity;
import io.shardingsphere.core.parsing.antlr.rule.registry.extractor.ExtractorRuleDefinition;
import io.shardingsphere.core.parsing.parser.sql.SQLStatement;
import lombok.Getter;
import lombok.SneakyThrows;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;

/**
 * SQL statement rule definition.
 *
 * @author zhangliang
 */
@Getter
public final class SQLStatementRuleDefinition {

    private final Map<String, SQLStatementRule> rules = new LinkedHashMap<>();

    /**
     * Initialize SQL statement rule definition.
     *
     * @param dialectRuleDefinitionEntity SQL dialect statement rule definition entity
     * @param extractorRuleDefinition extractor rule definition
     */
    @SuppressWarnings("unchecked")
    @SneakyThrows
    public void init(final SQLStatementRuleDefinitionEntity dialectRuleDefinitionEntity, final ExtractorRuleDefinition extractorRuleDefinition) {
        for (SQLStatementRuleEntity each : dialectRuleDefinitionEntity.getRules()) {
            SQLStatementRule sqlStatementRule = new SQLStatementRule(each.getContext(),
                    (Class<? extends SQLStatement>) Class.forName(each.getSqlStatementClass()),
                    (SQLStatementOptimizer) newClassInstance(each.getOptimizerClass()));
            sqlStatementRule.getExtractors().addAll(createExtractors(each.getExtractorRuleRefs(), extractorRuleDefinition));
            rules.put(getContextClassName(each.getContext()), sqlStatementRule);
        }
    }

    private Collection<SQLSegmentExtractor> createExtractors(final String sqlExtractorRuleRefs, final ExtractorRuleDefinition extractorRuleDefinition) {
        Collection<SQLSegmentExtractor> result = new LinkedList<>();
        if (sqlExtractorRuleRefs != null) {
            for (String each : Splitter.on(',').trimResults().splitToList(sqlExtractorRuleRefs)) {
                result.add(extractorRuleDefinition.getRules().get(each));
            }
        }
        return result;
    }

    private String getContextClassName(final String context) {
        return CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, context + "Context");
    }

    @SneakyThrows
    private Object newClassInstance(final String className) {
        return Strings.isNullOrEmpty(className) ? null : Class.forName(className).newInstance();
    }
}


text:
namespace Baskerville.App.Areas.Admin.Controllers
{
    using Models.ViewModels;
    using Services.Contracts;
    using System.Net;
    using System.Web.Mvc;

    [Authorize(Roles = "Admin,Owner")]
    public class UsersController : AuthorizedController
    {
        private IUsersService service;

        public UsersController(IUsersService service)
        {
            this.service = service;
        }

        [HttpGet]
        public ActionResult Index()
        {
            var model = this.service.GetAllUsers();

            return View("UsersList", model);
        }

        [HttpGet]
        public ActionResult Details(string id)
        {
            UserViewModel model = this.service.GetUser(id);
            if (model == null)
                return new HttpStatusCodeResult(HttpStatusCode.NotFound);

            return View(model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Save(UserViewModel model)
        {
            if (!this.ModelState.IsValid)
                return View("Details", model);

            this.service.UpdateUserRole(model);

            var usersListModel = this.service.GetAllUsers();
            return View("UsersList", usersListModel);
        }

        [HttpPost]
        public ActionResult Delete(string id)
        {
            var status = this.service.DeleteUser(id);

            return new HttpStatusCodeResult(status);
        }
    }
}


text:
from luminoso_api.v5_client import LuminosoClient
from luminoso_api.v5_upload import create_project_with_docs, BATCH_SIZE

from unittest.mock import patch
import pytest

BASE_URL = 'http://mock-api.localhost/api/v5/'
DOCS_TO_UPLOAD = [
    {'title': 'Document 1', 'text': 'Bonjour', 'extra': 'field'},
    {'title': 'Document 2', 'text': 'Au revoir'},
]

DOCS_UPLOADED = [
    {'title': 'Document 1', 'text': 'Bonjour', 'metadata': []},
    {'title': 'Document 2', 'text': 'Au revoir', 'metadata': []},
]

REPETITIVE_DOC = {'title': 'Yadda', 'text': 'yadda yadda', 'metadata': []}

def _build_info_response(ndocs, language, done):
    """
    Construct the expected response when we get the project's info after
    requesting a build.
    """
    response = {
        'json': {
            'project_id': 'projid',
            'document_count': ndocs,
            'language': language,
            'last_build_info': {
                'number': 1,
                'start_time': 0.,
                'stop_time': None,
            },
        }
    }
    if done:
        response['json']['last_build_info']['success'] = True
        response['json']['last_build_info']['stop_time'] = 1.
    return response

def test_project_creation(requests_mock):
    """
    Test creating a project by mocking what happens when it is successful.
    """
    # First, configure what the mock responses should be:

    # The initial response from creating the project
    requests_mock.post(
        BASE_URL + 'projects/',
        json={
            'project_id': 'projid',
            'document_count': 0,
            'language': 'fr',
            'last_build_info': None,
        },
    )
    # Empty responses from further build steps
    requests_mock.post(BASE_URL + 'projects/projid/upload/', json={})
    requests_mock.post(BASE_URL + 'projects/projid/build/', json={})

    # Build status response, which isn't done yet the first time it's checked,
    # and is done the second time
    requests_mock.get(
        BASE_URL + 'projects/projid/',
        [
            _build_info_response(2, 'fr', done=False),
            _build_info_response(2, 'fr', done=True),
        ],
    )

    # Now run the main uploader function and get the result
    client = LuminosoClient.connect(BASE_URL, token='fake')
    with patch('time.sleep', return_value=None):
        response = create_project_with_docs(
            client,
            DOCS_TO_UPLOAD,
            language='fr',
            name='Projet test',
            progress=False,
        )

    # Test that the right sequence of requests happened
    history = requests_mock.request_history

    assert history[0].method == 'POST'
    assert history[0].url == BASE_URL + 'projects/'
    params = history[0].json()
    assert params['name'] == 'Projet test'
    assert params['language'] == 'fr'

    assert history[1].method == 'POST'
    assert history[1].url == BASE_URL + 'projects/projid/upload/'
    params = history[1].json()
    assert params['docs'] == DOCS_UPLOADED

    assert history[2].method == 'POST'
    assert history[2].url == BASE_URL + 'projects/projid/build/'
    assert history[2].json() == {}

    assert history[3].method == 'GET'
    assert history[3].url == BASE_URL + 'projects/projid/'
    assert history[4].method == 'GET'
    assert history[4].url == BASE_URL + 'projects/projid/'

    assert len(history) == 5
    assert response['last_build_info']['success']

def test_missing_text(requests_mock):
    """
    Test a project that fails to be created, on the client side, because a bad
    document is supplied.
    """
    # The initial response from creating the project
    requests_mock.post(
        BASE_URL + 'projects/',
        json={
            'project_id': 'projid',
            'document_count': 0,
            'language': 'en',
            'last_build_info': None,
        },
    )

    with pytest.raises(ValueError):
        client = LuminosoClient.connect(BASE_URL, token='fake')
        create_project_with_docs(
            client,
            [{'bad': 'document'}],
            language='en',
            name='Bad project test',
            progress=False,
        )

def test_pagination(requests_mock):
    """
    Test that we can create a project whose documents would be broken into
    multiple pages, and when we iterate over its documents, we correctly
    request all the pages.
    """
    # The initial response from creating the project
    requests_mock.post(
        BASE_URL + 'projects/',
        json={
            'project_id': 'projid',
            'document_count': 0,
            'language': 'fr',
            'last_build_info': None,
        },
    )
    # Empty responses from further build steps
    requests_mock.post(BASE_URL + 'projects/projid/upload/', json={})
    requests_mock.post(BASE_URL + 'projects/projid/build/', json={})

    ndocs = BATCH_SIZE + 2

    # Build status response, which isn't done yet the first or second time
    # it's checked, and is done the third time
    requests_mock.get(
        BASE_URL + 'projects/projid/',
        [
            _build_info_response(ndocs, 'fr', done=False),
            _build_info_response(ndocs, 'fr', done=False),
            _build_info_response(ndocs, 'fr', done=True),
        ],
    )
    # Now run the main uploader function and get the result
    client = LuminosoClient.connect(BASE_URL, token='fake')
    with patch('time.sleep', return_value=None):
        create_project_with_docs(
            client,
            [REPETITIVE_DOC] * (BATCH_SIZE + 2),
            language='fr',
            name='Projet test',
            progress=False,
        )

    # Test that the right sequence of requests happened, this time just as
    # a list of URLs
    history = requests_mock.request_history
    reqs = [(req.method, req.url) for req in history]
    assert reqs == [
        ('POST', BASE_URL + 'projects/'),
        ('POST', BASE_URL + 'projects/projid/upload/'),
        ('POST', BASE_URL + 'projects/projid/upload/'),
        ('POST', BASE_URL + 'projects/projid/build/'),
        ('GET', BASE_URL + 'projects/projid/'),
        ('GET', BASE_URL + 'projects/projid/'),
        ('GET', BASE_URL + 'projects/projid/'),
    ]


text:
'use strict';

const test = require('ava');
const ps = require('./lib/parse-source');
const ea = require('./lib/extract-attributes');

test('lib/parse_source.js: must return an object', async t => {
	await ps('https://www.google.com')
	.then(response => {
		t.is(typeof response, 'object');
	}).catch(err => {
		t.is(typeof err, 'object');
	});
});

test('lib/parse_source.js: web sources must have the correct type (URI)', async t => {
	const web = await ps('https://gabrielmangiurea.github.io');
	t.is(web.type, 'URI');
});

test('lib/parse_source.js: file sources must have the correct type (FILE)', async t => {
	const file = await ps('./fixtures/page1.html');
	t.is(file.type, 'FILE');
});

test('lib/extract_attributes.js: must throw when content argument is not a string', t => {
	const error = t.throws(() => {
		ea(['html'], ['tag'], 'https://base');
	});

	t.is(error.message, 'Content argument must be a valid string');
});

test('lib/extract_attributes.js: must throw when attributes argument is not an array', t => {
	const error = t.throws(() => {
		ea('html', 'tag', 'https://base');
	});

	t.is(error.message, 'Attributes argument must be an array with at least 1 element');
});

test('lib/extract_attributes.js: must throw when baseUrl argument is not a valid URL', t => {
	const error = t.throws(() => {
		ea('html', ['tag'], 42);
	});

	t.is(error.message, 'Base URL argument must be a valid URL');
});

test('lib/extract_attributes.js: must return an object', t => {
	const f = ea('html', ['tag'], 'https://base');

	t.is(typeof f, 'object');
});

test('lib/extract_attributes.js: must return the correct format and data', t => {
	const f1 = ea('somepage', ['href'], 'https://baseurl.com');
	const f2 = ea('<image src="someimage.png" />', ['src'], 'https://baseurl.com');
	const f3 = ea(`

				<link href="somestylesheet.css" rel="stylesheet" />

		`,
		['href', 'src'], 'https://baseurl.com');

	t.deepEqual(f1, {href: ['https://baseurl.com/somepage.html']});
	t.deepEqual(f2, {src: ['https://baseurl.com/someimage.png']});
	t.deepEqual(f3,
		{href: ['https://baseurl.com/somestylesheet.css', 'https://baseurl.com/somelink.html'],
			src: ['https://baseurl.com/someimage.png', 'https://baseurl.com/somescript.js']}
	);
});


text:
<?php
global $output_path;
file_put_contents($output_path,lng::subdict1___subdict1_test());

?>


text:
<?xml version="1.0"?>
<config>
  <modules>
    <OrganicInternet_SimpleConfigurableProducts>
      <active>true</active>
      <codePool>community</codePool>
    </OrganicInternet_SimpleConfigurableProducts>
  </modules>
</config>