/* package for testing
518810
Bucket getCurrentBucket() {
        long currentTime = time.getCurrentTimeInMillis();

        /* a shortcut to try and get the most common result of immediately finding the current bucket */

        /**
         * Retrieve the latest bucket if the given time is BEFORE the end of the bucket window, otherwise it returns NULL.
         * 
         * NOTE: This is thread-safe because it's accessing 'buckets' which is a LinkedBlockingDeque
         */
        Bucket currentBucket = buckets.peekLast();
        if (currentBucket != null && currentTime < currentBucket.windowStart + this.bucketSizeInMillseconds) {
            // if we're within the bucket 'window of time' return the current one
            // NOTE: We do not worry if we are BEFORE the window in a weird case of where thread scheduling causes that to occur,
            // we'll just use the latest as long as we're not AFTER the window
            return currentBucket;
        }

        /* if we didn't find the current bucket above, then we have to create one */

        /**
         * The following needs to be synchronized/locked even with a synchronized/thread-safe data structure such as LinkedBlockingDeque because
         * the logic involves multiple steps to check existence, create an object then insert the object. The 'check' or 'insertion' themselves
         * are thread-safe by themselves but not the aggregate algorithm, thus we put this entire block of logic inside synchronized.
         * 
         * I am using a tryLock if/then (http://download.oracle.com/javase/6/docs/api/java/util/concurrent/locks/Lock.html#tryLock())
         * so that a single thread will get the lock and as soon as one thread gets the lock all others will go the 'else' block
         * and just return the currentBucket until the newBucket is created. This should allow the throughput to be far higher
         * and only slow down 1 thread instead of blocking all of them in each cycle of creating a new bucket based on some testing
         * (and it makes sense that it should as well).
         * 
         * This means the timing won't be exact to the millisecond as to what data ends up in a bucket, but that's acceptable.
         * It's not critical to have exact precision to the millisecond, as long as it's rolling, if we can instead reduce the impact synchronization.
         * 
         * More importantly though it means that the 'if' block within the lock needs to be careful about what it changes that can still
         * be accessed concurrently in the 'else' block since we're not completely synchronizing access.
         * 
         * For example, we can't have a multi-step process to add a bucket, remove a bucket, then update the sum since the 'else' block of code
         * can retrieve the sum while this is all happening. The trade-off is that we don't maintain the rolling sum and let readers just iterate
         * bucket to calculate the sum themselves. This is an example of favoring write-performance instead of read-performance and how the tryLock
         * versus a synchronized block needs to be accommodated.
         */
        if (newBucketLock.tryLock()) {
            try {
                if (buckets.peekLast() == null) {
                    // the list is empty so create the first bucket
                    Bucket newBucket = new Bucket(currentTime);
                    buckets.addLast(newBucket);
                    return newBucket;
                } else {
                    // We go into a loop so that it will create as many buckets as needed to catch up to the current time
                    // as we want the buckets complete even if we don't have transactions during a period of time.
                    for (int i = 0; i < numberOfBuckets; i++) {
                        // we have at least 1 bucket so retrieve it
                        Bucket lastBucket = buckets.peekLast();
                        if (currentTime < lastBucket.windowStart + this.bucketSizeInMillseconds) {
                            // if we're within the bucket 'window of time' return the current one
                            // NOTE: We do not worry if we are BEFORE the window in a weird case of where thread scheduling causes that to occur,
                            // we'll just use the latest as long as we're not AFTER the window
                            return lastBucket;
                        } else if (currentTime - (lastBucket.windowStart + this.bucketSizeInMillseconds) > timeInMilliseconds) {
                            // the time passed is greater than the entire rolling counter so we want to clear it all and start from scratch
                            reset();
                            // recursively call getCurrentBucket which will create a new bucket and return it
                            return getCurrentBucket();
                        } else { // we're past the window so we need to create a new bucket
                            // create a new bucket and add it as the new 'last'
                            buckets.addLast(new Bucket(lastBucket.windowStart + this.bucketSizeInMillseconds));
                            // add the lastBucket values to the cumulativeSum
                            cumulativeSum.addBucket(lastBucket);
                        }
                    }
                    // we have finished the for-loop and created all of the buckets, so return the lastBucket now
                    return buckets.peekLast();
                }
            } finally {
                newBucketLock.unlock();
            }
        } else {
            currentBucket = buckets.peekLast();
            if (currentBucket != null) {
                // we didn't get the lock so just return the latest bucket while another thread creates the next one
                return currentBucket;
            } else {
                // the rare scenario where multiple threads raced to create the very first bucket
                // wait slightly and then use recursion while the other thread finishes creating a bucket
                try {
                    Thread.sleep(5);
                } catch (Exception e) {
                    // ignore
                }
                return getCurrentBucket();
            }
        }
    }
823516
public static void main(String[] args){
        System.out.println(new TemplateMatcher("${", "}").replace("this is ${santhosh}ghgjh\n ${kumar} sdf ${tekuri}abc", new VariableResolver(){
            @Override
            public String resolve(String variable){
                if(variable.equals("santhosh"))
                    return null;
                return variable.toUpperCase();
            }
        }));

        System.out.println(new TemplateMatcher("$").replace("this is $santhosh ghgjh\n $kumar sdf $tekuri\n$ abc", new VariableResolver(){
            @Override
            public String resolve(String variable){
                return variable.toUpperCase();
            }
        }));
    }
1267687
function compile(fileNames, options, verbose) {
  const program = ts.createProgram(fileNames, options)
  const emitResult = program.emit()

  /* istanbul ignore next */
  if (verbose) {
    const allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics)

    allDiagnostics.forEach((diagnostic) => {
      if (diagnostic.file) {
        const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(
          diagnostic.start
        )
        const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n")
        console.log(
          `${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`
        )
      } else {
        console.log(`${ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n")}`)
      }
    })
  }
}
499454
function evaluateModule(id, input, type) {
		if (/javascript/.test(type)) {
			var fn = new Function("module", "exports", input);
			var moduleExports = {};
			var moduleObject = { exports: moduleExports };
			fn(moduleObject, moduleExports);
			return moduleObject.exports;
		}
		/* @if jsonLoader  */
		if (/json/.test(type)) {
			return JSON.parse(input);
		}
		/* @end */

		return input;
	}
105032
function main() {
	var snippet;
	var header;
	var fpath;
	var keys;
	var lang;
	var conf;
	var len;
	var i;

	keys = objectKeys( LANGS );
	len = keys.length;

	debug( 'Generating %d license header snippets...', len );
	for ( i = 0; i < len; i++ ) {
		lang = keys[ i ];

		debug( 'Generating license header for `%s`...', lang );
		if ( lang === 'default' ) {
			header = licenseHeader( SPDX, DEFAULT_HEADER_LANG, OPTS );
		} else {
			header = licenseHeader( SPDX, lang, OPTS );
		}
		if ( header === null ) {
			debug( 'Failed to generate a license header for `%s`.', lang );
			continue;
		}
		conf = LANGS[ lang ];

		debug( 'Generating license header snippet...' );
		snippet = createSnippet( header, conf );

		debug( 'Writing license header snippet to file...' );
		if ( lang === 'default' ) {
			fpath = join( OUT_DIR, 'stdlib-license.sublime-snippet' );
		} else {
			fpath = join( OUT_DIR, 'stdlib-license-'+lang+'.sublime-snippet' );
		}
		writeFileSync( fpath, snippet, FOPTS );

		debug( 'Successfully generated license header snippet.' );
	}
	debug( 'Finished generating snippets.' );
}
1199126
function assertArrayOfStrings(identifier, value) {
    if (!__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__angular_core__["t" /* isDevMode */])() || value == null) {
        return;
    }
    if (!Array.isArray(value)) {
        throw new Error("Expected '" + identifier + "' to be an array of strings.");
    }
    for (var /** @type {?} */ i = 0; i < value.length; i += 1) {
        if (typeof value[i] !== 'string') {
            throw new Error("Expected '" + identifier + "' to be an array of strings.");
        }
    }
}
954497
function Detect(config) {
	var events = [];
	var api = {};
	var sysPackages = [];
	var numSysCmds = config.sysCmds.length;
	var numTests = 0;	// test counter

	// require detectionizr module(s)
	config.use.forEach(r, api);

	process.on("exit", function cleanup() {
		events.forEach(function(e,i,all) {
			all[i] = null;	// explicitly de-reference
		})
		events.splice(0, events.length);	// empty array
	});

	// public api
	api.require = r;
	api.detect = function(tests) {
		numTests = tests.length;
  		tests.forEach(detect, api);
  		return api;
	}
	api.on = function(event, fn, scope) {
		events.push([event, fn, scope]);
		return api;
	}
	api.overwrite = function(event, fn, scope) {
		events.forEach(function(e,i,all) {
			if(event === e)
				all.splice(i,1);
		});
		return api.on(event, fn, scope);
	}

	api.on("detect", function() {
		if(numTests === 1)
			events.forEach(function(event) {
				if(event[0] === "finally")
					event[1].call(event[2], api);
			});
	});

	return api;

	function detect(package) {
		//console.log(test);
		if(!r(package)) {
			if(api.child_process) {
				sysPackages.push([package, 0]);
				config.sysCmds.forEach(function(cmd) {
					sysProcess(package, cmd);
				});
			} else {
				console.warn("Weird butt nodejs distro - can not test non NPM packages.");
			}
		} else {
			numTests--;	// reduce test counter
			events.forEach(function(event) {
				if(event[0] === "detect")
					event[1].call(event[2], package, true);
			});
		}
	}

	function sysProcess(package, cmd) {
		var proc = api.child_process.spawn(cmd[0], cmd[1] ? [cmd[1], package] : [package]);
		proc.stdout.setEncoding("utf8");
		proc.stdout.on("data", sysHandler);
//		proc.stderr.on("data", sysHandler);
		proc.stdout.on('end', sysCounter);

		function sysHandler(input) {
			//console.log(input);
			if(input.length > 0) api[package] = true;
		}

		function sysCounter() {
			sysPackages.some(function find(syspackage) {
				if( syspackage[0] === package ) {
					syspackage[1]++;
//console.dir(sysPackages)
//console.log("%s has been tested %d times out of %d", package, syspackage[1], numSysCmds);
					if( numSysCmds === syspackage[1] ) {
						events.forEach(function(event) {
							if(event[0] === "detect")
								event[1].call(event[2], package, api[package]);
						});
						numTests--;	// reduce test counter
						return true;	// stop loop
					}
				}
			});
		}
	}

	function r(package) {
		try {
			api[package] = require(package);
		} catch(err) {
			//console.warn(err.toString());
			api[package] = false;
		} finally {
			return api[package];
		}
	}
}
106080
private void recursiveSpecificationsFinder(final File dir, final String packageNamePrefix) throws CodeGenException {
        if (dir.equals(null)) {
            throw new CodeGenException("recursiveSpecificationsFinder called with null pointer");
        }
        final File[] files = dir.listFiles();
        if (files == null) {
            return;
        }
        for(final File entry : files) {
            try {
                if (entry.isDirectory()) {
                    recursiveSpecificationsFinder(entry, (packageNamePrefix == null) ? entry.getName() : packageNamePrefix + "/" + entry.getName());
                } else if (entry.getName().endsWith(".json") && ProctorUtils.readJsonFromFile(entry).has("tests")) {
                    processFile(
                            entry,
                            packageNamePrefix == null ? "" : packageNamePrefix.replace("/", "."),
                            entry.getName().substring(0, entry.getName().lastIndexOf(".json")));
                }

            } catch (IOException e) {
                throw new CodeGenException("Could not read from file " + entry.getName(),e);
            }
        }
    }
451749
function commitPackageChangelog( $package, $http, $step, &$persistentData, $tpl )
    {
        $changelogEntries = array();
        $changelogText = $persistentData['changelog_text'];
        $lines = preg_split( "#\r\n|\n|\r#", $changelogText );
        $currentEntries = false;
        foreach ( $lines as $line )
        {
            if ( strlen( $line ) > 0 and
                 ( $line[0] == '-' or $line[0] == '*' ) )
            {
                if ( $currentEntries !== false )
                {
                    $changelogEntries[] = implode( ' ', $currentEntries );
                }
                $currentEntries = array();
                $currentEntries[] = trim( substr( $line, 1 ) );
            }
            else
            {
                if ( $currentEntries === false )
                {
                    $changelogEntries = array();
                }
                $currentEntries[] = trim( $line );
            }
        }
        if ( $currentEntries !== false )
        {
            $changelogEntries[] = implode( ' ', $currentEntries );
        }
        $persistentData['changelog_entries'] = $changelogEntries;
    }
1182940
async function build() {
    const clientConfig = await webpackConfig({target: 'web', env: 'prod'});
    const serverConfig = await webpackConfig({target: 'node', env: 'prod'});

    return new Promise((resolve, reject) => {
        console.log('Compiling client...');

        // eslint-disable-next-line consistent-return
        webpack(clientConfig, (clientError, clientStats) => {
            if (clientError) {
                return reject(clientError);
            }

            const clientMessages = formatWebpackMessages(clientStats.toJson({}, true));
            if (clientMessages.errors.length) {
                return reject(new Error(clientMessages.errors.join('\n\n')));
            }

            if (
                process.env.CI &&
                (typeof process.env.CI !== 'string' || process.env.CI.toLowerCase() !== 'false') &&
                clientMessages.warnings.length
            ) {
                console.log(
                    chalk.yellow(
                        '\nTreating warnings as errors because process.env.CI = true.\n' +
                            'Most CI servers set it automatically.\n'
                    )
                );
                return reject(new Error(clientMessages.warnings.join('\n\n')));
            }

            console.log(chalk.green('Compiled client successfully.'), '\n');
            console.log('Compiling server...');
            webpack(serverConfig, (serverError, serverStats) => {
                if (serverError) {
                    return reject(serverError);
                }

                const serverMessages = formatWebpackMessages(serverStats.toJson({}, true));
                if (serverMessages.errors.length) {
                    return reject(new Error(serverMessages.errors.join('\n\n')));
                }

                if (
                    process.env.CI &&
                    (typeof process.env.CI !== 'string' || process.env.CI.toLowerCase() !== 'false') &&
                    serverMessages.warnings.length
                ) {
                    console.log(
                        chalk.yellow(
                            '\nTreating warnings as errors because process.env.CI = true.\n' +
                                'Most CI servers set it automatically.\n'
                        )
                    );
                    return reject(new Error(serverMessages.warnings.join('\n\n')));
                }

                console.log(chalk.green('Compiled server successfully.'), '\n');
                return resolve({
                    stats: clientStats,
                    warnings: Object.assign({}, clientMessages.warnings, serverMessages.warnings),
                });
            });
        });
    });
}
768485
function (test) {
                const bits = QRUtil.getBCHTypeNumber(_typeNumber);

                for (var i = 0; i < 18; i += 1) {
                    var mod = (!test && ((bits >> i) & 1) == 1);
                    /** @type {(boolean|null)[][]} */
                    (_modules)[Math.floor(i / 3)][i % 3 + _moduleCount - 8 - 3] = mod;
                }

                for (var i = 0; i < 18; i += 1) {
                    var mod = (!test && ((bits >> i) & 1) == 1);
                    /** @type {(boolean|null)[][]} */
                    (_modules)[i % 3 + _moduleCount - 8 - 3][Math.floor(i / 3)] = mod;
                }
            }
25115
function install( $package, $installType, $parameters,
                      $name, $os, $filename, $subdirectory,
                      $content, &$installParameters,
                      &$installData )
    {
        //$this->Package =& $package;

        $trans = eZCharTransform::instance();
        $name = $content->getAttribute( 'name' );
        $extensionName = $trans->transformByGroup( $name, 'urlalias' );
        if ( strcmp( $name, $extensionName ) !== 0 )
        {
            $description = ezpI18n::tr( 'kernel/package', 'Package contains an invalid extension name: %extensionname', false, array( '%extensionname' => $name ) );
            $installParameters['error'] = array( 'error_code' => false,
                                                 'element_id' => $name,
                                                 'description' => $description );
            return false;
        }

        $siteINI = eZINI::instance();
        $extensionRootDir = $siteINI->variable( 'ExtensionSettings', 'ExtensionDirectory' );
        $extensionDir = $extensionRootDir . '/' . $extensionName;
        $packageExtensionDir = $package->path() . '/' . $parameters['sub-directory'] . '/' . $extensionName;

        // Error: extension already exists.
        if ( file_exists( $extensionDir ) )
        {
            $description = ezpI18n::tr( 'kernel/package', "Extension '%extensionname' already exists.",
                                   false, array( '%extensionname' => $extensionName ) );
            $choosenAction = $this->errorChoosenAction( self::ERROR_EXISTS,
                                                        $installParameters, $description, $this->HandlerType );
            switch( $choosenAction )
            {
            case self::ACTION_SKIP:
                return true;

            case eZPackage::NON_INTERACTIVE:
            case self::ACTION_REPLACE:
                eZDir::recursiveDelete( $extensionDir );
                break;

            default:
                $installParameters['error'] = array( 'error_code' => self::ERROR_EXISTS,
                                                     'element_id' => $extensionName,
                                                     'description' => $description,
                                                     'actions' => array( self::ACTION_REPLACE => ezpI18n::tr( 'kernel/package', "Replace extension" ),
                                                                         self::ACTION_SKIP => ezpI18n::tr( 'kernel/package', 'Skip' ) ) );
                return false;
            }
        }

        eZDir::mkdir( $extensionDir, false, true );
        eZDir::copy( $packageExtensionDir, $extensionRootDir );

        // Regenerate autoloads for extensions to pick up the newly created extension
        ezpAutoloader::updateExtensionAutoloadArray();

        // Activate extension
        $siteINI = eZINI::instance( 'site.ini', 'settings/override', null, null, false, true );

        if ( $siteINI->hasVariable( 'ExtensionSettings', "ActiveExtensions" ) )
        {
            $selectedExtensions = $siteINI->variable( 'ExtensionSettings', "ActiveExtensions" );
        }
        else
        {
            $selectedExtensions = array();
        }

        if ( !in_array( $extensionName, $selectedExtensions ) )
        {
            $selectedExtensions[] = $extensionName;
            $siteINI->setVariable( "ExtensionSettings", "ActiveExtensions", $selectedExtensions );
            $siteINI->save( 'site.ini.append', '.php', false, false );
        }
        return true;
    }
1124271
function (urls) {

            if (this._typeUtils.isString(urls)) {
                urls = [urls];
            }

            var _getPackages = function (urls, urlMap, packages) {
                if (urls.length === 0) {
                    // everything has been found, leave back the recursive loop
                    return;
                }
                for (var key in urlMap) {
                    var value = urlMap[key];
                    if (typeof(value) == 'string') {
                        value = "/" + value;
                        // Check if something match
                        for (var i = 0, ii = urls.length; i < ii; i++) {
                            var file = urls[i];
                            if (value.substr(0, file.length) == file) {
                                packages[value] = true;
                                // remove found item from the url list, for performance reason
                                urls.slice(i, i);
                                break;
                            }
                        }
                    } else {
                        _getPackages(urls, urlMap[key], packages);
                    }
                }
            };

            // Clone urls array
            var urlClone = [];
            for (var i = 0, ii = urls.length; i < ii; i++) {
                urlClone.push(urls[i]);
            }

            var packages = {};
            _getPackages(urls, this._urlMap, packages);

            // return the keys only
            var keys = [];
            for (var key in packages) {
                keys.push(key);
            }
            return keys;
        }
1336594
function validatePackageChangelog( $package, $http, $currentStepID, &$stepMap, &$persistentData, &$errorList )
    {
        $changelogPerson = false;
        $changelogEmail = false;
        $changelogText = false;
        if ( $http->hasPostVariable( 'PackageChangelogPerson' ) )
            $changelogPerson = trim( $http->postVariable( 'PackageChangelogPerson' ) );
        if ( $http->hasPostVariable( 'PackageChangelogEmail' ) )
            $changelogEmail = $http->postVariable( 'PackageChangelogEmail' );
        if ( $http->hasPostVariable( 'PackageChangelogText' ) )
            $changelogText = $http->postVariable( 'PackageChangelogText' );

        $persistentData['changelog_person'] = $changelogPerson;
        $persistentData['changelog_email'] = $changelogEmail;
        $persistentData['changelog_text'] = $changelogText;

        $result = true;
        if ( trim( $changelogPerson ) == '' )
        {
            $errorList[] = array( 'field' => ezpI18n::tr( 'kernel/package', 'Name' ),
                                  'description' => ezpI18n::tr( 'kernel/package', 'You must enter a name for the changelog' ) );
            $result = false;
        }
        if ( trim( $changelogEmail ) == '' )
        {
            $errorList[] = array( 'field' => ezpI18n::tr( 'kernel/package', 'Email' ),
                                  'description' => ezpI18n::tr( 'kernel/package', 'You must enter an email for the changelog' ) );
            $result = false;
        }
        if ( trim( $changelogText ) == '' )
        {
            $errorList[] = array( 'field' => ezpI18n::tr( 'kernel/package', 'Changelog' ),
                                  'description' => ezpI18n::tr( 'kernel/package', 'You must supply some text for the changelog entry' ) );
            $result = false;
        }
        return $result;
    }
1131916
function install( $package, $installType, $parameters,
                      $name, $os, $filename, $subdirectory,
                      $content, &$installParameters,
                      &$installData )
    {
        $serializedNameListNode = $content->getElementsByTagName( 'serialized-name-list' )->item( 0 );
        $serializedNameList = $serializedNameListNode ? $serializedNameListNode->textContent : false;
        $classNameList = new eZContentClassNameList( $serializedNameList );
        if ( $classNameList->isEmpty() )
        {
            $classNameList->initFromString( $content->getElementsByTagName( 'name' )->item( 0 )->textContent ); // for backward compatibility( <= 3.8 )
        }
        $classNameList->validate( );

        $serializedDescriptionListNode = $content->getElementsByTagName( 'serialized-description-list' )->item( 0 );
        $serializedDescriptionList = $serializedDescriptionListNode ? $serializedDescriptionListNode->textContent : false;
        $classDescriptionList = new eZSerializedObjectNameList( $serializedDescriptionList );

        $classIdentifier = $content->getElementsByTagName( 'identifier' )->item( 0 )->textContent;
        $classRemoteID = $content->getElementsByTagName( 'remote-id' )->item( 0 )->textContent;
        $classObjectNamePattern = $content->getElementsByTagName( 'object-name-pattern' )->item( 0 )->textContent;
        $classURLAliasPattern = is_object( $content->getElementsByTagName( 'url-alias-pattern' )->item( 0 ) ) ?
            $content->getElementsByTagName( 'url-alias-pattern' )->item( 0 )->textContent :
            null;
        $classIsContainer = $content->getAttribute( 'is-container' );
        if ( $classIsContainer !== false )
            $classIsContainer = $classIsContainer == 'true' ? 1 : 0;

        $classRemoteNode = $content->getElementsByTagName( 'remote' )->item( 0 );
        $classID = $classRemoteNode->getElementsByTagName( 'id' )->item( 0 )->textContent;
        $classGroupsNode = $classRemoteNode->getElementsByTagName( 'groups' )->item( 0 );
        $classCreated = $classRemoteNode->getElementsByTagName( 'created' )->item( 0 )->textContent;
        $classModified = $classRemoteNode->getElementsByTagName( 'modified' )->item( 0 )->textContent;
        $classCreatorNode = $classRemoteNode->getElementsByTagName( 'creator' )->item( 0 );
        $classModifierNode = $classRemoteNode->getElementsByTagName( 'modifier' )->item( 0 );

        $classAttributesNode = $content->getElementsByTagName( 'attributes' )->item( 0 );

        $dateTime = time();
        $classCreated = $dateTime;
        $classModified = $dateTime;

        $userID = false;
        if ( isset( $installParameters['user_id'] ) )
            $userID = $installParameters['user_id'];

        $class = eZContentClass::fetchByRemoteID( $classRemoteID );

        if ( $class )
        {
            $className = $class->name();
            $description = ezpI18n::tr( 'kernel/package', "Class '%classname' already exists.", false,
                                   array( '%classname' => $className ) );

            $choosenAction = $this->errorChoosenAction( self::ERROR_EXISTS,
                                                        $installParameters, $description, $this->HandlerType );
            switch( $choosenAction )
            {
            case eZPackage::NON_INTERACTIVE:
            case self::ACTION_REPLACE:
                if ( eZContentClassOperations::remove( $class->attribute( 'id' ) ) == false )
                {
                    eZDebug::writeWarning( "Unable to remove class '$className'." );
                    return true;
                }
                eZDebug::writeNotice( "Class '$className' will be replaced.", 'eZContentClassPackageHandler' );
                break;

            case self::ACTION_SKIP:
                return true;

            case self::ACTION_NEW:
                $class->setAttribute( 'remote_id', eZRemoteIdUtility::generate( 'class' ) );
                $class->store();
                $classNameList->appendGroupName( " (imported)" );
                break;

            default:
                $installParameters['error'] = array( 'error_code' => self::ERROR_EXISTS,
                                                     'element_id' => $classRemoteID,
                                                     'description' => $description,
                                                     'actions' => array() );
                if ( $class->isRemovable() )
                {
                    $errorMsg = ezpI18n::tr( 'kernel/package', "Replace existing class" );
                    $objectsCount = eZContentObject::fetchSameClassListCount( $class->attribute( 'id' ) );
                    if ( $objectsCount )
                        $errorMsg .= ' ' . ezpI18n::tr( 'kernel/package', "(Warning! $objectsCount content object(s) and their sub-items will be removed)" );
                    $installParameters['error']['actions'][self::ACTION_REPLACE] = $errorMsg;
                }
                $installParameters['error']['actions'][self::ACTION_SKIP] = ezpI18n::tr( 'kernel/package', 'Skip installing this class' );
                $installParameters['error']['actions'][self::ACTION_NEW] = ezpI18n::tr( 'kernel/package', 'Keep existing and create a new one' );
                return false;
            }
        }

        unset( $class );

        // Try to create a unique class identifier
        $currentClassIdentifier = $classIdentifier;
        $unique = false;

        while( !$unique )
        {
            $classList = eZContentClass::fetchByIdentifier( $currentClassIdentifier );
            if ( $classList )
            {
                // "increment" class identifier
                if ( preg_match( '/^(.*)_(\d+)$/', $currentClassIdentifier, $matches ) )
                    $currentClassIdentifier = $matches[1] . '_' . ( $matches[2] + 1 );
                else
                    $currentClassIdentifier = $currentClassIdentifier . '_1';
            }
            else
                $unique = true;

            unset( $classList );
        }

        $classIdentifier = $currentClassIdentifier;

        $values = array( 'version' => 0,
                         'serialized_name_list' => $classNameList->serializeNames(),
                         'serialized_description_list' => $classDescriptionList->serializeNames(),
                         'create_lang_if_not_exist' => true,
                         'identifier' => $classIdentifier,
                         'remote_id' => $classRemoteID,
                         'contentobject_name' => $classObjectNamePattern,
                         'url_alias_name' => $classURLAliasPattern,
                         'is_container' => $classIsContainer,
                         'created' => $classCreated,
                         'modified' => $classModified );

        if ( $content->hasAttribute( 'sort-field' ) )
        {
            $values['sort_field'] = eZContentObjectTreeNode::sortFieldID( $content->getAttribute( 'sort-field' ) );
        }
        else
        {
            eZDebug::writeNotice( 'The sort field was not specified in the content class package. ' .
                                  'This property is exported and imported since eZ Publish 4.0.2', __METHOD__ );
        }

        if ( $content->hasAttribute( 'sort-order' ) )
        {
            $values['sort_order'] = $content->getAttribute( 'sort-order' );
        }
        else
        {
            eZDebug::writeNotice( 'The sort order was not specified in the content class package. ' .
                                  'This property is exported and imported since eZ Publish 4.0.2', __METHOD__ );
        }

        if ( $content->hasAttribute( 'always-available' ) )
        {
            $values['always_available'] = ( $content->getAttribute( 'always-available' ) === 'true' ? 1 : 0 );
        }
        else
        {
            eZDebug::writeNotice( 'The default object availability was not specified in the content class package. ' .
                                  'This property is exported and imported since eZ Publish 4.0.2', __METHOD__ );
        }

        // create class
        $class = eZContentClass::create( $userID,
                                         $values );
        $class->store();

        $classID = $class->attribute( 'id' );

        if ( !isset( $installData['classid_list'] ) )
            $installData['classid_list'] = array();
        if ( !isset( $installData['classid_map'] ) )
            $installData['classid_map'] = array();
        $installData['classid_list'][] = $class->attribute( 'id' );
        $installData['classid_map'][$classID] = $class->attribute( 'id' );

        // create class attributes
        $classAttributeList = $classAttributesNode->getElementsByTagName( 'attribute' );
        foreach ( $classAttributeList as $classAttributeNode )
        {
            $isNotSupported = strtolower( $classAttributeNode->getAttribute( 'unsupported' ) ) == 'true';
            if ( $isNotSupported )
                continue;

            $attributeDatatype = $classAttributeNode->getAttribute( 'datatype' );
            $attributeIsRequired = strtolower( $classAttributeNode->getAttribute( 'required' ) ) == 'true';
            $attributeIsSearchable = strtolower( $classAttributeNode->getAttribute( 'searchable' ) ) == 'true';
            $attributeIsInformationCollector = strtolower( $classAttributeNode->getAttribute( 'information-collector' ) ) == 'true';
            $attributeIsTranslatable = strtolower( $classAttributeNode->getAttribute( 'translatable' ) ) == 'true';
            $attributeSerializedNameListNode = $classAttributeNode->getElementsByTagName( 'serialized-name-list' )->item( 0 );
            $attributeSerializedNameListContent = $attributeSerializedNameListNode ? $attributeSerializedNameListNode->textContent : false;
            $attributeSerializedNameList = new eZSerializedObjectNameList( $attributeSerializedNameListContent );
            if ( $attributeSerializedNameList->isEmpty() )
                $attributeSerializedNameList->initFromString( $classAttributeNode->getElementsByTagName( 'name' )->item( 0 )->textContent ); // for backward compatibility( <= 3.8 )
            $attributeSerializedNameList->validate( );

            $attributeSerializedDescriptionListNode = $classAttributeNode->getElementsByTagName( 'serialized-description-list' )->item( 0 );
            $attributeSerializedDescriptionListContent = $attributeSerializedDescriptionListNode ? $attributeSerializedDescriptionListNode->textContent : false;
            $attributeSerializedDescriptionList = new eZSerializedObjectNameList( $attributeSerializedDescriptionListContent );

            $attributeCategoryNode = $classAttributeNode->getElementsByTagName( 'category' )->item( 0 );
            $attributeCategory = $attributeCategoryNode ? $attributeCategoryNode->textContent : '';

            $attributeSerializedDataTextNode = $classAttributeNode->getElementsByTagName( 'serialized-description-text' )->item( 0 );
            $attributeSerializedDataTextContent = $attributeSerializedDataTextNode ? $attributeSerializedDataTextNode->textContent : false;
            $attributeSerializedDataText = new eZSerializedObjectNameList( $attributeSerializedDataTextContent );

            $attributeIdentifier = $classAttributeNode->getElementsByTagName( 'identifier' )->item( 0 )->textContent;
            $attributePlacement = $classAttributeNode->getElementsByTagName( 'placement' )->item( 0 )->textContent;
            $attributeDatatypeParameterNode = $classAttributeNode->getElementsByTagName( 'datatype-parameters' )->item( 0 );

            $classAttribute = $class->fetchAttributeByIdentifier( $attributeIdentifier );
            if ( !$classAttribute )
            {
                $classAttribute = eZContentClassAttribute::create( $class->attribute( 'id' ),
                                                                   $attributeDatatype,
                                                                   array( 'version' => 0,
                                                                          'identifier' => $attributeIdentifier,
                                                                          'serialized_name_list' => $attributeSerializedNameList->serializeNames(),
                                                                          'serialized_description_list' => $attributeSerializedDescriptionList->serializeNames(),
                                                                          'category' => $attributeCategory,
                                                                          'serialized_data_text' => $attributeSerializedDataText->serializeNames(),
                                                                          'is_required' => $attributeIsRequired,
                                                                          'is_searchable' => $attributeIsSearchable,
                                                                          'is_information_collector' => $attributeIsInformationCollector,
                                                                          'can_translate' => $attributeIsTranslatable,
                                                                          'placement' => $attributePlacement ) );

                $dataType = $classAttribute->dataType();
                $classAttribute->store();
                $dataType->unserializeContentClassAttribute( $classAttribute, $classAttributeNode, $attributeDatatypeParameterNode );
                $classAttribute->sync();
            }
        }

        // add class to a class group
        $classGroupsList = $classGroupsNode->getElementsByTagName( 'group' );
        foreach ( $classGroupsList as $classGroupNode )
        {
            $classGroupName = $classGroupNode->getAttribute( 'name' );
            $classGroup = eZContentClassGroup::fetchByName( $classGroupName );
            if ( !$classGroup )
            {
                $classGroup = eZContentClassGroup::create();
                $classGroup->setAttribute( 'name', $classGroupName );
                $classGroup->store();
            }
            $classGroup->appendClass( $class );
        }
        return true;
    }
1309444
function createPackage(tutorialName) {

  const tutorialFilePath = `${CONTENTS_PATH}/getting-started/${tutorialName}.md`;
  const tutorialFile = readFileSync(tutorialFilePath, 'utf8');
  const examples = [];
  tutorialFile.replace(/<code-(?:pane|example) [^>]*path="([^"]+)"/g, (_, path) => examples.push('examples/' + path));

  if (examples.length) {
    console.log('The following example files are referenced in this getting-started:');
    console.log(examples.map(example => ' - ' + example).join('\n'));
  }

  return new Package('author-getting-started', [contentPackage])
    .config(function(readFilesProcessor) {
      readFilesProcessor.sourceFiles = [
        {
          basePath: CONTENTS_PATH,
          include: tutorialFilePath,
          fileReader: 'contentFileReader'
        },
        {
          basePath: CONTENTS_PATH,
          include: examples.map(example => resolve(CONTENTS_PATH, example)),
          fileReader: 'exampleFileReader'
        }
      ];
    });
}
1170453
function checkPkg(pkgDir, scopes) {
  var errors;
  try {
    var config = {packageDir: pkgDir};
    if (scopes) {
      config.scopeList = scopes;
    }
    var checked = checkDeps.sync(config);
    if (checked.error.length) {
      errors = checked.error;
    }
  } finally {
    // eslint-disable-next-line no-unsafe-finally
    return errors;
  }
}