问:
Cannot invoke method doFirst() on null object : react.gradle
Can somebody help me.

I tried to create android dependency using a react native compiled to android studio.
and I encountered some error that says : Cannot invoke method doFirst() on null object and its directing to my react.gradle file.

Here's environment specs:

```<code>Android studio build gradle version : 4.0.0
distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip

</code>```

Here's the detailed error

```<code>FAILURE: Build failed with an exception.

* Where:
Script 'C:\Users\Nhick\esports-gameclient-mobile-v1.0\node_modules\react-native\react.gradle' line: 312

* What went wrong:
A problem occurred configuring project ':app'.
> Failed to notify project evaluation listener.
   > Cannot invoke method doFirst() on null object
   > Could not get unknown property 'applicationVariants' for extension 'android' of type com.android.build.gradle.LibraryExtension.
</code>```

Here's my react.gradle

```<code>// Copyright (c) Facebook, Inc. and its affiliates.

// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.

import org.apache.tools.ant.taskdefs.condition.Os

def config = project.hasProperty("react") ? project.react : [];

def cliPath = config.cliPath ?: "node_modules/react-native/cli.js"
def composeSourceMapsPath = config.composeSourceMapsPath ?: "node_modules/react-native/scripts/compose-source-maps.js"
def bundleAssetName = config.bundleAssetName ?: "index.android.bundle"
def entryFile = config.entryFile ?: "index.android.js"
def bundleCommand = config.bundleCommand ?: "bundle"
def reactRoot = file(config.root ?: "../../")
def inputExcludes = config.inputExcludes ?: ["android/**", "ios/**"]
def bundleConfig = config.bundleConfig ? "${reactRoot}/${config.bundleConfig}" : null ;
def enableVmCleanup = config.enableVmCleanup == null ? true : config.enableVmCleanup
def hermesCommand = config.hermesCommand ?: "../../node_modules/hermes-engine/%OS-BIN%/hermes"

def reactNativeDevServerPort() {
    def value = project.getProperties().get("reactNativeDevServerPort")
    return value != null ? value : "8081"
}

def reactNativeInspectorProxyPort() {
    def value = project.getProperties().get("reactNativeInspectorProxyPort")
    return value != null ? value : reactNativeDevServerPort()
}

def getHermesOSBin() {
    if (Os.isFamily(Os.FAMILY_WINDOWS)) return "win64-bin";
    if (Os.isFamily(Os.FAMILY_MAC)) return "osx-bin";
    if (Os.isOs(null, "linux", "amd64", null)) return "linux64-bin";
    throw new Exception("OS not recognized. Please set project.ext.react.hermesCommand " +
                        "to the path of a working Hermes compiler.");
}

// Make sure not to inspect the Hermes config unless we need it,
// to avoid breaking any JSC-only setups.
def getHermesCommand = {
    // If the project specifies a Hermes command, don't second guess it.
    if (!hermesCommand.contains("%OS-BIN%")) {
        return hermesCommand
    }

    // Execution on Windows fails with / as separator
    return hermesCommand
            .replaceAll("%OS-BIN%", getHermesOSBin())
            .replace('/' as char, File.separatorChar);
}

// Set enableHermesForVariant to a function to configure per variant,
// or set `enableHermes` to True/False to set all of them
def enableHermesForVariant = config.enableHermesForVariant ?: {
    def variant -> config.enableHermes ?: false
}

android {
    buildTypes.all {
        resValue "integer", "react_native_dev_server_port", reactNativeDevServerPort()
        resValue "integer", "react_native_inspector_proxy_port", reactNativeInspectorProxyPort()
    }
}

afterEvaluate {
    def isAndroidLibrary = plugins.hasPlugin("com.android.library")
    def variants = isAndroidLibrary ? android.libraryVariants : android.applicationVariants
    variants.all { def variant ->
        // Create variant and target names
        def targetName = variant.name.capitalize()
        def targetPath = variant.dirName

        // React js bundle directories
        def jsBundleDir = file("$buildDir/generated/assets/react/${targetPath}")
        def resourcesDir = file("$buildDir/generated/res/react/${targetPath}")

        def jsBundleFile = file("$jsBundleDir/$bundleAssetName")
        def jsSourceMapsDir = file("$buildDir/generated/sourcemaps/react/${targetPath}")
        def jsIntermediateSourceMapsDir = file("$buildDir/intermediates/sourcemaps/react/${targetPath}")
        def jsPackagerSourceMapFile = file("$jsIntermediateSourceMapsDir/${bundleAssetName}.packager.map")
        def jsCompilerSourceMapFile = file("$jsIntermediateSourceMapsDir/${bundleAssetName}.compiler.map")
        def jsOutputSourceMapFile = file("$jsSourceMapsDir/${bundleAssetName}.map")

        // Additional node and packager commandline arguments
        def nodeExecutableAndArgs = config.nodeExecutableAndArgs ?: ["node"]
        def extraPackagerArgs = config.extraPackagerArgs ?: []

        def enableHermes = enableHermesForVariant(variant)

        def currentBundleTask = tasks.create(
            name: "bundle${targetName}JsAndAssets",
            type: Exec) {
            group = "react"
            description = "bundle JS and assets for ${targetName}."

            // Create dirs if they are not there (e.g. the "clean" task just ran)
            doFirst {
                jsBundleDir.deleteDir()
                jsBundleDir.mkdirs()
                resourcesDir.deleteDir()
                resourcesDir.mkdirs()
                jsIntermediateSourceMapsDir.deleteDir()
                jsIntermediateSourceMapsDir.mkdirs()
                jsSourceMapsDir.deleteDir()
                jsSourceMapsDir.mkdirs()
            }

            // Set up inputs and outputs so gradle can cache the result
            inputs.files fileTree(dir: reactRoot, excludes: inputExcludes)
            outputs.dir(jsBundleDir)
            outputs.dir(resourcesDir)

            // Set up the call to the react-native cli
            workingDir(reactRoot)

            // Set up dev mode
            def devEnabled = !(config."devDisabledIn${targetName}"
                || targetName.toLowerCase().contains("release"))

            def extraArgs = extraPackagerArgs;

            if (bundleConfig) {
                extraArgs = extraArgs.clone()
                extraArgs.add("--config");
                extraArgs.add(bundleConfig);
            }

            if (Os.isFamily(Os.FAMILY_WINDOWS)) {
                commandLine("cmd", "/c", *nodeExecutableAndArgs, cliPath, bundleCommand, "--platform", "android", "--dev", "${devEnabled}",
                    "--reset-cache", "--entry-file", entryFile, "--bundle-output", jsBundleFile, "--assets-dest", resourcesDir,
                    "--sourcemap-output", enableHermes ? jsPackagerSourceMapFile : jsOutputSourceMapFile, *extraArgs)
            } else {
                commandLine(*nodeExecutableAndArgs, cliPath, bundleCommand, "--platform", "android", "--dev", "${devEnabled}",
                    "--reset-cache", "--entry-file", entryFile, "--bundle-output", jsBundleFile, "--assets-dest", resourcesDir,
                    "--sourcemap-output", enableHermes ? jsPackagerSourceMapFile : jsOutputSourceMapFile, *extraArgs)
            }

            if (enableHermes) {
                doLast {
                    def hermesFlags;
                    def hbcTempFile = file("${jsBundleFile}.hbc")
                    exec {
                        if (targetName.toLowerCase().contains("release")) {
                            // Can't use ?: since that will also substitute valid empty lists
                            hermesFlags = config.hermesFlagsRelease
                            if (hermesFlags == null) hermesFlags = ["-O", "-output-source-map"]
                        } else {
                            hermesFlags = config.hermesFlagsDebug
                            if (hermesFlags == null) hermesFlags = []
                        }

                        if (Os.isFamily(Os.FAMILY_WINDOWS)) {
                            commandLine("cmd", "/c", getHermesCommand(), "-emit-binary", "-out", hbcTempFile, jsBundleFile, *hermesFlags)
                        } else {
                            commandLine(getHermesCommand(), "-emit-binary", "-out", hbcTempFile, jsBundleFile, *hermesFlags)
                        }
                    }
                    ant.move(
                        file: hbcTempFile,
                        toFile: jsBundleFile
                    );
                    if (hermesFlags.contains("-output-source-map")) {
                        ant.move(
                            // Hermes will generate a source map with this exact name
                            file: "${jsBundleFile}.hbc.map",
                            tofile: jsCompilerSourceMapFile
                        );
                        exec {
                            // TODO: set task dependencies for caching

                            // Set up the call to the compose-source-maps script
                            workingDir(reactRoot)
                            if (Os.isFamily(Os.FAMILY_WINDOWS)) {
                                commandLine("cmd", "/c", *nodeExecutableAndArgs, composeSourceMapsPath, jsPackagerSourceMapFile, jsCompilerSourceMapFile, "-o", jsOutputSourceMapFile)
                            } else {
                                commandLine(*nodeExecutableAndArgs, composeSourceMapsPath, jsPackagerSourceMapFile, jsCompilerSourceMapFile, "-o", jsOutputSourceMapFile)
                            }
                        }
                    }
                }
            }

            enabled config."bundleIn${targetName}" != null
                ? config."bundleIn${targetName}"
                : config."bundleIn${variant.buildType.name.capitalize()}" != null
                    ? config."bundleIn${variant.buildType.name.capitalize()}"
                    : targetName.toLowerCase().contains("release")
        }

        // Expose a minimal interface on the application variant and the task itself:
        variant.ext.bundleJsAndAssets = currentBundleTask
        currentBundleTask.ext.generatedResFolders = files(resourcesDir).builtBy(currentBundleTask)
        currentBundleTask.ext.generatedAssetsFolders = files(jsBundleDir).builtBy(currentBundleTask)

        // registerGeneratedResFolders for Android plugin 3.x
        if (variant.respondsTo("registerGeneratedResFolders")) {
            variant.registerGeneratedResFolders(currentBundleTask.generatedResFolders)
        } else {
            variant.registerResGeneratingTask(currentBundleTask)
        }
        variant.mergeResourcesProvider.get().dependsOn(currentBundleTask)

        // packageApplication for Android plugin 3.x
        def packageTask = variant.hasProperty("packageApplication")
            ? variant.packageApplicationProvider.get()
            : tasks.findByName("package${targetName}")
        if (variant.hasProperty("packageLibrary")) {
            packageTask = variant.packageLibrary
        }

        // pre bundle build task for Android plugin 3.2+
        def buildPreBundleTask = tasks.findByName("build${targetName}PreBundle")

        def resourcesDirConfigValue = config."resourcesDir${targetName}"
        if (resourcesDirConfigValue) {
            def currentCopyResTask = tasks.create(
                name: "copy${targetName}BundledResources",
                type: Copy) {
                group = "react"
                description = "copy bundled resources into custom location for ${targetName}."

                from(resourcesDir)
                into(file(resourcesDirConfigValue))

                dependsOn(currentBundleTask)

                enabled(currentBundleTask.enabled)
            }

            packageTask.dependsOn(currentCopyResTask)
            if (buildPreBundleTask != null) {
                buildPreBundleTask.dependsOn(currentCopyResTask)
            }
        }

        def currentAssetsCopyTask = tasks.create(
            name: "copy${targetName}BundledJs",
            type: Copy) {
            group = "react"
            description = "copy bundled JS into ${targetName}."

            if (config."jsBundleDir${targetName}") {
                from(jsBundleDir)
                into(file(config."jsBundleDir${targetName}"))
            } else {
                into ("$buildDir/intermediates")
                into ("assets/${targetPath}") {
                    from(jsBundleDir)
                }

                // Workaround for Android Gradle Plugin 3.2+ new asset directory
                into ("merged_assets/${variant.name}/merge${targetName}Assets/out") {
                    from(jsBundleDir)
                }

                // Workaround for Android Gradle Plugin 3.4+ new asset directory
                into ("merged_assets/${variant.name}/out") {
                    from(jsBundleDir)
                }
            }

            // mergeAssets must run first, as it clears the intermediates directory
            dependsOn(variant.mergeAssetsProvider.get())

            enabled(currentBundleTask.enabled)
        }

        packageTask.dependsOn(currentAssetsCopyTask)
        if (buildPreBundleTask != null) {
            buildPreBundleTask.dependsOn(currentAssetsCopyTask)
        }

        // Delete the VM related libraries that this build doesn't need.
        // The application can manage this manually by setting 'enableVmCleanup: false'
        //
        // This should really be done by packaging all Hermes releated libs into
        // two separate HermesDebug and HermesRelease AARs, but until then we'll
        // kludge it by deleting the .so files out of the /transforms/ directory.
        def isRelease = targetName.toLowerCase().contains("release")
        def libDir = "$buildDir/intermediates/transforms/"
        def vmSelectionAction = {
            fileTree(libDir).matching {
                if (enableHermes) {
                    // For Hermes, delete all the libjsc* files
                    include "**/libjsc*.so"

                    if (isRelease) {
                        // Reduce size by deleting the debugger/inspector
                        include '**/libhermes-inspector.so'
                        include '**/libhermes-executor-debug.so'
                    } else {
                        // Release libs take precedence and must be removed
                        // to allow debugging
                        include '**/libhermes-executor-release.so'
                    }
                } else {
                    // For JSC, delete all the libhermes* files
                    include "**/libhermes*.so"
                }
            }.visit { details ->
                def targetVariant = ".*/transforms/[^/]*/${targetPath}/.*"
                def path = details.file.getAbsolutePath().replace(File.separatorChar, '/' as char)
                if (path.matches(targetVariant) && details.file.isFile()) {
                    details.file.delete()
                }
            }
        }

        if (enableVmCleanup) {
            def task = tasks.findByName("package${targetName}")
            task.doFirst(vmSelectionAction)
        }
    }
}

</code>```

答: I didn't see you declare a task like package$..., so that maybe a reason, gradle can't find tasks.findByName("package${targetName}") and it return null.

Body:
Can somebody help me.

I tried to create android dependency using a react native compiled to android studio.
and I encountered some error that says : Cannot invoke method doFirst() on null object and its directing to my react.gradle file.

Here's environment specs:

Android studio build gradle version : 4.0.0
distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip

Here's the detailed error

FAILURE: Build failed with an exception.

* Where:
Script 'C:\Users\Nhick\esports-gameclient-mobile-v1.0\node_modules\react-native\react.gradle' line: 312

* What went wrong:
A problem occurred configuring project ':app'.
> Failed to notify project evaluation listener.
   > Cannot invoke method doFirst() on null object
   > Could not get unknown property 'applicationVariants' for extension 'android' of type com.android.build.gradle.LibraryExtension.

Here's my react.gradle

// Copyright (c) Facebook, Inc. and its affiliates.

// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.

import org.apache.tools.ant.taskdefs.condition.Os

def config = project.hasProperty("react") ? project.react : [];

def cliPath = config.cliPath ?: "node_modules/react-native/cli.js"
def composeSourceMapsPath = config.composeSourceMapsPath ?: "node_modules/react-native/scripts/compose-source-maps.js"
def bundleAssetName = config.bundleAssetName ?: "index.android.bundle"
def entryFile = config.entryFile ?: "index.android.js"
def bundleCommand = config.bundleCommand ?: "bundle"
def reactRoot = file(config.root ?: "../../")
def inputExcludes = config.inputExcludes ?: ["android/**", "ios/**"]
def bundleConfig = config.bundleConfig ? "${reactRoot}/${config.bundleConfig}" : null ;
def enableVmCleanup = config.enableVmCleanup == null ? true : config.enableVmCleanup
def hermesCommand = config.hermesCommand ?: "../../node_modules/hermes-engine/%OS-BIN%/hermes"

def reactNativeDevServerPort() {
    def value = project.getProperties().get("reactNativeDevServerPort")
    return value != null ? value : "8081"
}

def reactNativeInspectorProxyPort() {
    def value = project.getProperties().get("reactNativeInspectorProxyPort")
    return value != null ? value : reactNativeDevServerPort()
}

def getHermesOSBin() {
    if (Os.isFamily(Os.FAMILY_WINDOWS)) return "win64-bin";
    if (Os.isFamily(Os.FAMILY_MAC)) return "osx-bin";
    if (Os.isOs(null, "linux", "amd64", null)) return "linux64-bin";
    throw new Exception("OS not recognized. Please set project.ext.react.hermesCommand " +
                        "to the path of a working Hermes compiler.");
}

// Make sure not to inspect the Hermes config unless we need it,
// to avoid breaking any JSC-only setups.
def getHermesCommand = {
    // If the project specifies a Hermes command, don't second guess it.
    if (!hermesCommand.contains("%OS-BIN%")) {
        return hermesCommand
    }

    // Execution on Windows fails with / as separator
    return hermesCommand
            .replaceAll("%OS-BIN%", getHermesOSBin())
            .replace('/' as char, File.separatorChar);
}

// Set enableHermesForVariant to a function to configure per variant,
// or set `enableHermes` to True/False to set all of them
def enableHermesForVariant = config.enableHermesForVariant ?: {
    def variant -> config.enableHermes ?: false
}

android {
    buildTypes.all {
        resValue "integer", "react_native_dev_server_port", reactNativeDevServerPort()
        resValue "integer", "react_native_inspector_proxy_port", reactNativeInspectorProxyPort()
    }
}

afterEvaluate {
    def isAndroidLibrary = plugins.hasPlugin("com.android.library")
    def variants = isAndroidLibrary ? android.libraryVariants : android.applicationVariants
    variants.all { def variant ->
        // Create variant and target names
        def targetName = variant.name.capitalize()
        def targetPath = variant.dirName

        // React js bundle directories
        def jsBundleDir = file("$buildDir/generated/assets/react/${targetPath}")
        def resourcesDir = file("$buildDir/generated/res/react/${targetPath}")

        def jsBundleFile = file("$jsBundleDir/$bundleAssetName")
        def jsSourceMapsDir = file("$buildDir/generated/sourcemaps/react/${targetPath}")
        def jsIntermediateSourceMapsDir = file("$buildDir/intermediates/sourcemaps/react/${targetPath}")
        def jsPackagerSourceMapFile = file("$jsIntermediateSourceMapsDir/${bundleAssetName}.packager.map")
        def jsCompilerSourceMapFile = file("$jsIntermediateSourceMapsDir/${bundleAssetName}.compiler.map")
        def jsOutputSourceMapFile = file("$jsSourceMapsDir/${bundleAssetName}.map")

        // Additional node and packager commandline arguments
        def nodeExecutableAndArgs = config.nodeExecutableAndArgs ?: ["node"]
        def extraPackagerArgs = config.extraPackagerArgs ?: []

        def enableHermes = enableHermesForVariant(variant)

        def currentBundleTask = tasks.create(
            name: "bundle${targetName}JsAndAssets",
            type: Exec) {
            group = "react"
            description = "bundle JS and assets for ${targetName}."

            // Create dirs if they are not there (e.g. the "clean" task just ran)
            doFirst {
                jsBundleDir.deleteDir()
                jsBundleDir.mkdirs()
                resourcesDir.deleteDir()
                resourcesDir.mkdirs()
                jsIntermediateSourceMapsDir.deleteDir()
                jsIntermediateSourceMapsDir.mkdirs()
                jsSourceMapsDir.deleteDir()
                jsSourceMapsDir.mkdirs()
            }

            // Set up inputs and outputs so gradle can cache the result
            inputs.files fileTree(dir: reactRoot, excludes: inputExcludes)
            outputs.dir(jsBundleDir)
            outputs.dir(resourcesDir)

            // Set up the call to the react-native cli
            workingDir(reactRoot)

            // Set up dev mode
            def devEnabled = !(config."devDisabledIn${targetName}"
                || targetName.toLowerCase().contains("release"))

            def extraArgs = extraPackagerArgs;

            if (bundleConfig) {
                extraArgs = extraArgs.clone()
                extraArgs.add("--config");
                extraArgs.add(bundleConfig);
            }

            if (Os.isFamily(Os.FAMILY_WINDOWS)) {
                commandLine("cmd", "/c", *nodeExecutableAndArgs, cliPath, bundleCommand, "--platform", "android", "--dev", "${devEnabled}",
                    "--reset-cache", "--entry-file", entryFile, "--bundle-output", jsBundleFile, "--assets-dest", resourcesDir,
                    "--sourcemap-output", enableHermes ? jsPackagerSourceMapFile : jsOutputSourceMapFile, *extraArgs)
            } else {
                commandLine(*nodeExecutableAndArgs, cliPath, bundleCommand, "--platform", "android", "--dev", "${devEnabled}",
                    "--reset-cache", "--entry-file", entryFile, "--bundle-output", jsBundleFile, "--assets-dest", resourcesDir,
                    "--sourcemap-output", enableHermes ? jsPackagerSourceMapFile : jsOutputSourceMapFile, *extraArgs)
            }

            if (enableHermes) {
                doLast {
                    def hermesFlags;
                    def hbcTempFile = file("${jsBundleFile}.hbc")
                    exec {
                        if (targetName.toLowerCase().contains("release")) {
                            // Can't use ?: since that will also substitute valid empty lists
                            hermesFlags = config.hermesFlagsRelease
                            if (hermesFlags == null) hermesFlags = ["-O", "-output-source-map"]
                        } else {
                            hermesFlags = config.hermesFlagsDebug
                            if (hermesFlags == null) hermesFlags = []
                        }

                        if (Os.isFamily(Os.FAMILY_WINDOWS)) {
                            commandLine("cmd", "/c", getHermesCommand(), "-emit-binary", "-out", hbcTempFile, jsBundleFile, *hermesFlags)
                        } else {
                            commandLine(getHermesCommand(), "-emit-binary", "-out", hbcTempFile, jsBundleFile, *hermesFlags)
                        }
                    }
                    ant.move(
                        file: hbcTempFile,
                        toFile: jsBundleFile
                    );
                    if (hermesFlags.contains("-output-source-map")) {
                        ant.move(
                            // Hermes will generate a source map with this exact name
                            file: "${jsBundleFile}.hbc.map",
                            tofile: jsCompilerSourceMapFile
                        );
                        exec {
                            // TODO: set task dependencies for caching

                            // Set up the call to the compose-source-maps script
                            workingDir(reactRoot)
                            if (Os.isFamily(Os.FAMILY_WINDOWS)) {
                                commandLine("cmd", "/c", *nodeExecutableAndArgs, composeSourceMapsPath, jsPackagerSourceMapFile, jsCompilerSourceMapFile, "-o", jsOutputSourceMapFile)
                            } else {
                                commandLine(*nodeExecutableAndArgs, composeSourceMapsPath, jsPackagerSourceMapFile, jsCompilerSourceMapFile, "-o", jsOutputSourceMapFile)
                            }
                        }
                    }
                }
            }

            enabled config."bundleIn${targetName}" != null
                ? config."bundleIn${targetName}"
                : config."bundleIn${variant.buildType.name.capitalize()}" != null
                    ? config."bundleIn${variant.buildType.name.capitalize()}"
                    : targetName.toLowerCase().contains("release")
        }

        // Expose a minimal interface on the application variant and the task itself:
        variant.ext.bundleJsAndAssets = currentBundleTask
        currentBundleTask.ext.generatedResFolders = files(resourcesDir).builtBy(currentBundleTask)
        currentBundleTask.ext.generatedAssetsFolders = files(jsBundleDir).builtBy(currentBundleTask)

        // registerGeneratedResFolders for Android plugin 3.x
        if (variant.respondsTo("registerGeneratedResFolders")) {
            variant.registerGeneratedResFolders(currentBundleTask.generatedResFolders)
        } else {
            variant.registerResGeneratingTask(currentBundleTask)
        }
        variant.mergeResourcesProvider.get().dependsOn(currentBundleTask)

        // packageApplication for Android plugin 3.x
        def packageTask = variant.hasProperty("packageApplication")
            ? variant.packageApplicationProvider.get()
            : tasks.findByName("package${targetName}")
        if (variant.hasProperty("packageLibrary")) {
            packageTask = variant.packageLibrary
        }

        // pre bundle build task for Android plugin 3.2+
        def buildPreBundleTask = tasks.findByName("build${targetName}PreBundle")

        def resourcesDirConfigValue = config."resourcesDir${targetName}"
        if (resourcesDirConfigValue) {
            def currentCopyResTask = tasks.create(
                name: "copy${targetName}BundledResources",
                type: Copy) {
                group = "react"
                description = "copy bundled resources into custom location for ${targetName}."

                from(resourcesDir)
                into(file(resourcesDirConfigValue))

                dependsOn(currentBundleTask)

                enabled(currentBundleTask.enabled)
            }

            packageTask.dependsOn(currentCopyResTask)
            if (buildPreBundleTask != null) {
                buildPreBundleTask.dependsOn(currentCopyResTask)
            }
        }

        def currentAssetsCopyTask = tasks.create(
            name: "copy${targetName}BundledJs",
            type: Copy) {
            group = "react"
            description = "copy bundled JS into ${targetName}."

            if (config."jsBundleDir${targetName}") {
                from(jsBundleDir)
                into(file(config."jsBundleDir${targetName}"))
            } else {
                into ("$buildDir/intermediates")
                into ("assets/${targetPath}") {
                    from(jsBundleDir)
                }

                // Workaround for Android Gradle Plugin 3.2+ new asset directory
                into ("merged_assets/${variant.name}/merge${targetName}Assets/out") {
                    from(jsBundleDir)
                }

                // Workaround for Android Gradle Plugin 3.4+ new asset directory
                into ("merged_assets/${variant.name}/out") {
                    from(jsBundleDir)
                }
            }

            // mergeAssets must run first, as it clears the intermediates directory
            dependsOn(variant.mergeAssetsProvider.get())

            enabled(currentBundleTask.enabled)
        }

        packageTask.dependsOn(currentAssetsCopyTask)
        if (buildPreBundleTask != null) {
            buildPreBundleTask.dependsOn(currentAssetsCopyTask)
        }

        // Delete the VM related libraries that this build doesn't need.
        // The application can manage this manually by setting 'enableVmCleanup: false'
        //
        // This should really be done by packaging all Hermes releated libs into
        // two separate HermesDebug and HermesRelease AARs, but until then we'll
        // kludge it by deleting the .so files out of the /transforms/ directory.
        def isRelease = targetName.toLowerCase().contains("release")
        def libDir = "$buildDir/intermediates/transforms/"
        def vmSelectionAction = {
            fileTree(libDir).matching {
                if (enableHermes) {
                    // For Hermes, delete all the libjsc* files
                    include "**/libjsc*.so"

                    if (isRelease) {
                        // Reduce size by deleting the debugger/inspector
                        include '**/libhermes-inspector.so'
                        include '**/libhermes-executor-debug.so'
                    } else {
                        // Release libs take precedence and must be removed
                        // to allow debugging
                        include '**/libhermes-executor-release.so'
                    }
                } else {
                    // For JSC, delete all the libhermes* files
                    include "**/libhermes*.so"
                }
            }.visit { details ->
                def targetVariant = ".*/transforms/[^/]*/${targetPath}/.*"
                def path = details.file.getAbsolutePath().replace(File.separatorChar, '/' as char)
                if (path.matches(targetVariant) && details.file.isFile()) {
                    details.file.delete()
                }
            }
        }

        if (enableVmCleanup) {
            def task = tasks.findByName("package${targetName}")
            task.doFirst(vmSelectionAction)
        }
    }
}


来源: stackexchange

问:
R: Import values from one dataframe to another by matching dates
Assume I have df1:

```<code>Start_Date    End_Date     Value
2001-01-01    2001-12-31   1
2002-01-01    2002-12-31   2
2003-01-01    2003-12-31   3
2004-01-01    2004-12-31   4
2005-01-01    2005-12-31   5
</code>```

& df2:

```<code>DateTime      Gain   People
2003-01-01    3      3
2003-05-09    5      4
2004-12-31    1      2
2005-01-31    -2     2
2005-08-13    9      7
2006-09-10    6      8
2007-10-03    7      5
</code>```

What I would like to do is to import Value from df1 into df2 by checking which DateTime in df2 falls in between Start_Date & End_Date in df1. If dates do not fall into any of periods in df1, return Value 0. A view of desired outcome:

```<code>DateTime      Gain   People   Value
2003-01-01    3      3        3
2003-05-09    5      4        3
2004-12-31    1      2        4
2005-01-31    -2     2        5
2005-08-13    9      7        5
2006-09-10    6      8        0
2007-10-03    7      5        0
</code>```

Please advise

答:
The underlying challenge is joining on inequality conditions. These are straightforward in sql, but not in R as dplyr only joins on equality. Here is the a link to the primary answer on S.O.

The best way I have found is to do a more general join and then filter for the inequalities.

df1 = df1 %>% mutate(join_id = 1)
df2 = df2 %>% mutate(join_id = 1)

output = left_join(df2, df1, by = 'join_id') %>%
  filter(Start_Date <= DateTime,
         DateTime <= End_Date) %>%
  select(DateTime, Gain, People, Value) %>%
  mutate(Value = ifelse(is.na(Value), 0, Value)
```

Explanation:

As your dataframes do not have an existing ID column we first create one. This is unnecessary if you want to join on some equality constraints and some inequality constraints.

We use a (much) more general join followed by a filter for the inequality constraints.

ifelse(is.na(... is used to replace the missing values.

In some cases this much more general join can create performance issues. But as R uses lazy-evaluation by default, if you filter immediately after the join then R should run both statements as part of the same join and avoid any performance problem.

ContentLicense: CC BY-SA 4.0

Body:
Assume I have df1:

Start_Date    End_Date     Value
2001-01-01    2001-12-31   1
2002-01-01    2002-12-31   2
2003-01-01    2003-12-31   3
2004-01-01    2004-12-31   4
2005-01-01    2005-12-31   5

& df2:

DateTime      Gain   People
2003-01-01    3      3
2003-05-09    5      4
2004-12-31    1      2
2005-01-31    -2     2
2005-08-13    9      7
2006-09-10    6      8
2007-10-03    7      5

What I would like to do is to import Value from df1 into df2 by checking which DateTime in df2 falls in between Start_Date & End_Date in df1. If dates do not fall into any of periods in df1, return Value 0. A view of desired outcome:

DateTime      Gain   People   Value
2003-01-01    3      3        3
2003-05-09    5      4        3
2004-12-31    1      2        4
2005-01-31    -2     2        5
2005-08-13    9      7        5
2006-09-10    6      8        0
2007-10-03    7      5        0

Please advise

Body:
The underlying challenge is joining on inequality conditions. These are straightforward in sql, but not in R as dplyr only joins on equality. Here is the a link to the primary answer on S.O.

The best way I have found is to do a more general join and then filter for the inequalities.

df1 = df1 %>% mutate(join_id = 1)
df2 = df2 %>% mutate(join_id = 1)

output = left_join(df2, df1, by = 'join_id') %>%
  filter(Start_Date <= DateTime,
         DateTime <= End_Date) %>%
  select(DateTime, Gain, People, Value) %>%
  mutate(Value = ifelse(is.na(Value), 0, Value)

Explanation:

As your dataframes do not have an existing ID column we first create one. This is unnecessary if you want to join on some equality constraints and some inequality constraints.

We use a (much) more general join followed by a filter for the inequality constraints.

ifelse(is.na(... is used to replace the missing values.

In some cases this much more general join can create performance issues. But as R uses lazy-evaluation by default, if you filter immediately after the join then R should run both statements as part of the same join and avoid any performance problem.


问:
SQL INSERT INTO help please
ok so i feel like im missing something so trivial but i dont know what im doing wrong.
Im just trying to insert some data into a table but im getting an error

```<code>INSERT INTO SHOPS
VALUES
('12345', '10 smith street', 'brunswick', '3030',
'0404123123', 'shop1@shop.com'**),**
('65435', '10 road street', 'fitzroy', '3030',
'0404546564', 'shop2@shop.com'),
('34232', '10 car street', 'carlton', '3030', '0404455432',
'shop3@shop.com');
</code>```

So im getting an error on the bracket and comma i bolded on the 4th line.

If anyone knows how to fix this i would be very grateful.

答:
If looks like you're using the MySQL format for a multi-row INSERT statement. This is not correct for use with Oracle. It should be

```<code>INSERT ALL
  INTO SHOPS  (FIELD1, FIELD2, FIELD3, FIELD4, FIELD5, FIELD6)
       VALUES ('12345', '10 smith street', 'brunswick', '3030', '0404123123',
               'shop1@shop.com'),
  INTO SHOPS  (FIELD1, FIELD2, FIELD3, FIELD4, FIELD5, FIELD6)
       VALUES ('65435', '10 road street', 'fitzroy', '3030', '0404546564',
               'shop2@shop.com'),
  INTO SHOPS  (FIELD1, FIELD2, FIELD3, FIELD4, FIELD5, FIELD6)
       VALUES ('34232', '10 car street', 'carlton', '3030', '0404455432',
               'shop3@shop.com')
SELECT * FROM DUAL;
</code>```

As an alternative you can use a different form of the INSERT statement:

```<code>INSERT INTO SHOPS (FIELD1, FIELD2, FIELD3, FIELD4, FIELD5, FIELD6)
  SELECT '12345', '10 smith street', 'brunswick', '3030', '0404123123',
               'shop1@shop.com' FROM DUAL UNION ALL
  SELECT '65435', '10 road street', 'fitzroy', '3030', '0404546564',
               'shop2@shop.com' FROM DUAL UNION ALL
  SELECT '34232', '10 car street', 'carlton', '3030', '0404455432',
               'shop3@shop.com' FROM DUAL
</code>```

Or you can use a MERGE statement:

```<code>MERGE INTO SHOPS s
  USING (SELECT '12345' AS FIELD1, '10 smith street' AS FIELD2, 'brunswick' AS FIELD3,
                '3030' AS FIELD4, '0404123123' AS FIELD5,
                'shop1@shop.com' AS FIELD6 FROM DUAL UNION ALL
         SELECT '65435', '10 road street', 'fitzroy', '3030', '0404546564',
               'shop2@shop.com' FROM DUAL UNION ALL
         SELECT '34232', '10 car street', 'carlton', '3030', '0404455432',
               'shop3@shop.com' FROM DUAL) d
     ON (d.FIELD1 = s.FIELD1)
  WHEN NOT MATCHED THEN
    INSERT (FIELD1, FIELD2, FIELD3, FIELD4, FIELD5, FIELD6)
    VALUES (d.FIELD1, d.FIELD2, d.FIELD3, d.FIELD4, d.FIELD5, d.FIELD6);
</code>```

I used FIELD1, FIELD2, ..., FIELD6 since you didn't includes a field list with your INSERT statement - replace these with the correct field names. The MERGE statement assumes that FIELD1 is the primary key on SHOPS - replace it with the correct field name.

Title: SQL INSERT INTO help please

Body:
ok so i feel like im missing something so trivial but i dont know what im doing wrong.
Im just trying to insert some data into a table but im getting an error

INSERT INTO SHOPS
VALUES
('12345', '10 smith street', 'brunswick', '3030',
'0404123123', 'shop1@shop.com'**),**
('65435', '10 road street', 'fitzroy', '3030',
'0404546564', 'shop2@shop.com'),
('34232', '10 car street', 'carlton', '3030', '0404455432',
'shop3@shop.com');

So im getting an error on the bracket and comma i bolded on the 4th line.

If anyone knows how to fix this i would be very grateful.

Body:
If looks like you're using the MySQL format for a multi-row INSERT statement. This is not correct for use with Oracle. It should be

INSERT ALL
  INTO SHOPS  (FIELD1, FIELD2, FIELD3, FIELD4, FIELD5, FIELD6)
       VALUES ('12345', '10 smith street', 'brunswick', '3030', '0404123123',
               'shop1@shop.com'),
  INTO SHOPS  (FIELD1, FIELD2, FIELD3, FIELD4, FIELD5, FIELD6)
       VALUES ('65435', '10 road street', 'fitzroy', '3030', '0404546564',
               'shop2@shop.com'),
  INTO SHOPS  (FIELD1, FIELD2, FIELD3, FIELD4, FIELD5, FIELD6)
       VALUES ('34232', '10 car street', 'carlton', '3030', '0404455432',
               'shop3@shop.com')
SELECT * FROM DUAL;

As an alternative you can use a different form of the INSERT statement:

INSERT INTO SHOPS (FIELD1, FIELD2, FIELD3, FIELD4, FIELD5, FIELD6)
  SELECT '12345', '10 smith street', 'brunswick', '3030', '0404123123',
               'shop1@shop.com' FROM DUAL UNION ALL
  SELECT '65435', '10 road street', 'fitzroy', '3030', '0404546564',
               'shop2@shop.com' FROM DUAL UNION ALL
  SELECT '34232', '10 car street', 'carlton', '3030', '0404455432',
               'shop3@shop.com' FROM DUAL

Or you can use a MERGE statement:

MERGE INTO SHOPS s
  USING (SELECT '12345' AS FIELD1, '10 smith street' AS FIELD2, 'brunswick' AS FIELD3,
                '3030' AS FIELD4, '0404123123' AS FIELD5,
                'shop1@shop.com' AS FIELD6 FROM DUAL UNION ALL
         SELECT '65435', '10 road street', 'fitzroy', '3030', '0404546564',
               'shop2@shop.com' FROM DUAL UNION ALL
         SELECT '34232', '10 car street', 'carlton', '3030', '0404455432',
               'shop3@shop.com' FROM DUAL) d
     ON (d.FIELD1 = s.FIELD1)
  WHEN NOT MATCHED THEN
    INSERT (FIELD1, FIELD2, FIELD3, FIELD4, FIELD5, FIELD6)
    VALUES (d.FIELD1, d.FIELD2, d.FIELD3, d.FIELD4, d.FIELD5, d.FIELD6);

I used FIELD1, FIELD2, ..., FIELD6 since you didn't includes a field list with your INSERT statement - replace these with the correct field names. The MERGE statement assumes that FIELD1 is the primary key on SHOPS - replace it with the correct field name.


问:
Timed out waiting for process to appear on device
I am having the following problem when running or debugging apps on a device or emulator with Android Studio. The application is installed but it is not started on the device (or emulator). In the Run window I can see the following:

Launching app on device.
Waiting for process to come online...

and after some time I see the following:
Timed out waiting for process to appear on 'device'...

I have attached a screenshot that shows the problem.

The problem started recently. I am using the latest version of Android studio (3.5.1) and a Google Pixel device running Android 10 but the problem happens on emulators and other devices running previous versions of Android. The problem also happens on two different computers, with different Android applications and devices - the common factor is Android studio. Finally, the problem seems to have started after I updated Android Studio to 3.5.

Does anyone know how to fix this problem? I have tried many things (clear cache, rebuild, invalidate and restart, etc) without success.

Any ideas?

答: I tried most of the answers from here and on YouTube. What worked for me is updating my Android studio to the latest version; 4.0.</p>


问:
How to add new pair with Map<DateTime, List<Event>> (Event is a random class)?
I am using a Map<DateTime, List<Event>> (Event is a random class). Every time I add a new pair, the key (DateTime) is correctly added, but the list is replaced in all keys. Any help? Any Ideas?

Here my code:

```<code>import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Event event1 = Event("Test Code", "Company");
  Event event2 = Event("Play Game", "Home");
  Event event3 = Event("Learn", "School");
  List<Event> list1 =[];
  List<Event> list2 =[];
  List<Event> list3 =[];
  List<DateTime> listDateTime =[];
  Map<DateTime,List<Event>> mapT = new Map<DateTime,List<Event>>();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: RaisedButton(onPressed: (){
            test();
          }),
        ),
      ),
    );
  }
  void test(){
    for(int i = 1; i<3;i++){
      list3.clear();
      for(int j = 0; j<i;j++){
        list3.add(Event("Test $j", "School"));
      }
      mapT[DateTime(2020, i , 3)]= list3;
      print(mapT.toString());
    }

  }

}
class Event{
  String name;
  String location;

  Event(this.name, this.location);

  @override
  String toString() {
    return 'Event{name: $name, location: $location}';
  }
}

</code>```

Result:

```<code>I/flutter (19519): {2020-01-03 00:00:00.000: [Event{name: Test 0, location: School}]}
I/flutter (19519): {2020-01-03 00:00:00.000: [Event{name: Test 0, location: School}, Event{name: Test 1, location: School}], 2020-02-03 00:00:00.000: [Event{name: Test 0, location: School}, Event{name: Test 1, location: School}]}
</code>```

Why in 2nd loop key 2020-01-03 00:00:00.000 be updated! I don't want it to update?

答:
Answer
So after your code update: the reason mapT is updating the value for all keys is because you are storing the variable list3 (not the data inside list3)as a value for your keys in mapT

So using the same example below, you can test this case:

```<code>List<int> a = new List();
var test = Map<String, List<int>>();
a.add(1);
test["one"]= a;
print(test); // prints {one: [1]}
a.add(2);
test["two"]= a;
print (test); //prints {one: [1, 2], two: [1, 2]}
</code>```

So in your specific case change your code like this:

```<code> for(int i = 1; i<3;i++){
  list3.clear();
  for(int j = 0; j<i;j++){

    list3.add(Event("Test $j", "School"));
  }

  mapT[DateTime(2020, i , 3)] = List.from(list3); //this will create a new list, copy the value from list3 and add to mapT

  print(mapT);
}
</code>```

Generic Answer:
You haven't added any code so not sure what/where your problem is; but just for reference here is how to update values in a map:

```<code>var test = Map<String, int>();
test["one"]= 1;
test["two"]= 2;
print (test); // prints {one:1, two:2}
test.putIfAbsent("three",() => 56);
print(test); // prints {one:1, two:2, three: 56}
</code>```

Body:
I am using a Map<DateTime, List<Event>> (Event is a random class). Every time I add a new pair, the key (DateTime) is correctly added, but the list is replaced in all keys. Any help? Any Ideas?

Here my code:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Event event1 = Event("Test Code", "Company");
  Event event2 = Event("Play Game", "Home");
  Event event3 = Event("Learn", "School");
  List<Event> list1 =[];
  List<Event> list2 =[];
  List<Event> list3 =[];
  List<DateTime> listDateTime =[];
  Map<DateTime,List<Event>> mapT = new Map<DateTime,List<Event>>();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: RaisedButton(onPressed: (){
            test();
          }),
        ),
      ),
    );
  }
  void test(){
    for(int i = 1; i<3;i++){
      list3.clear();
      for(int j = 0; j<i;j++){
        list3.add(Event("Test $j", "School"));
      }
      mapT[DateTime(2020, i , 3)]= list3;
      print(mapT.toString());
    }

  }

}
class Event{
  String name;
  String location;

  Event(this.name, this.location);

  @override
  String toString() {
    return 'Event{name: $name, location: $location}';
  }
}

Result:

I/flutter (19519): {2020-01-03 00:00:00.000: [Event{name: Test 0, location: School}]}
I/flutter (19519): {2020-01-03 00:00:00.000: [Event{name: Test 0, location: School}, Event{name: Test 1, location: School}], 2020-02-03 00:00:00.000: [Event{name: Test 0, location: School}, Event{name: Test 1, location: School}]}

Why in 2nd loop key 2020-01-03 00:00:00.000 be updated! I don't want it to update?

Body:
Answer
So after your code update: the reason mapT is updating the value for all keys is because you are storing the variable list3 (not the data inside list3)as a value for your keys in mapT

So using the same example below, you can test this case:

List<int> a = new List();
var test = Map<String, List<int>>();
a.add(1);
test["one"]= a;
print(test); // prints {one: [1]}
a.add(2);
test["two"]= a;
print (test); //prints {one: [1, 2], two: [1, 2]}

So in your specific case change your code like this:

 for(int i = 1; i<3;i++){
  list3.clear();
  for(int j = 0; j<i;j++){

    list3.add(Event("Test $j", "School"));
  }

  mapT[DateTime(2020, i , 3)] = List.from(list3); //this will create a new list, copy the value from list3 and add to mapT

  print(mapT);
}

Generic Answer:
You haven't added any code so not sure what/where your problem is; but just for reference here is how to update values in a map:

var test = Map<String, int>();
test["one"]= 1;
test["two"]= 2;
print (test); // prints {one:1, two:2}
test.putIfAbsent("three",() => 56);
print(test); // prints {one:1, two:2, three: 56}


问:
When to use composite key instead of auto increment
I am creating a database and I am not sure about one of my tables. This table stores the users that are in each game, so one entry per user per game. The user is identified by their user_id which is a 36 character UUID4, and the game is identified by a session_id which is an 8 character alphanumeric string such as "ABK2RXN4". Currently, I have created an additional field just called id which is an integer that auto increments, and I have set that to be the primary key. These are the only 3 fields.

Since the combination of the session_id and the user_id will always result in a unique outcome, should I instead use those two as the composite private key and remove the id field?

Thanks.

EDIT:

Do things change if we have a more complicated table that will require more fields? Take this table for example.

```<code>| id  | voter    | voting_for | round    | category_id | acceptable |
|-----|----------|------------|----------|-------------|------------|
| int | char(36) | char(36)   | smallint | int         | boolean    |
</code>```

This is to do with votes within a game. Essentially after each round, the users in the game will vote on the answers of the other users within the game. So each entry has the user_id of the voter, the user_id of the person they are voting_for, the current round, the category_id of the category within the game and whether or not they agreed with the answer, acceptable. So, you could make a composite primary key using voter, voting_for, round and category_id. Is this any worse just because there are more fields, or should I still use the composite key instead of the existing auto increment id?

答:
"one entry per user per game" says that PRIMARY KEY(session_id, user_id) would be good for the table entry.  (The choice of which id to put first depends on what queries you run the most.)

However, since that adds up to 44 bytes, let's think again.

Each secondary index in the entry table has a copy of the PK silently tacked onto it.  This can get bulky if you have more than one secondary index.

Also, if you have other tables that link to entry, they (usually) need a copy of the entire PK, making them potentially fatter.

When we look at the actual performance of all these things, there are several factors, some say (id) would be faster, some say lead to (session_id, user_id) being faster.

So, speed and space would depend on many details that you have yet to present.

Meanwhile, you can speed help both speed and space by shrinking the UUID to BINARY(16), which is 20 bytes smaller.  (Strip the dashes, and use UNHEX(); reverse it do go the other way.  More details upon request.)

But there is another speed problem with UUIDs.  They are very random.  So, each insert and each row requested is a random lookup.  If you have enough RAM for all tables using UUIDs to be entirely in ram, then this is not a big deal.  Otherwise, performance will be bad, and get worse as the tables get bigger.

Shouldn't there be a session_id in the table with voting_for?  Will there be any JOINs to/from other tables?  Maybe all you need is PRIMARY KEY(session_id, voter, voting_for).  That at least clusters the game's information together.

Tips and more discussion:

* UUIDs:  http://mysql.rjweb.org/doc.php/uuid

* Many-to-many mapping:  http://mysql.rjweb.org/doc.php/index_cookbook_mysql#many_to_many_mapping_table

Body:
I am creating a database and I am not sure about one of my tables. This table stores the users that are in each game, so one entry per user per game. The user is identified by their user_id which is a 36 character UUID4, and the game is identified by a session_id which is an 8 character alphanumeric string such as "ABK2RXN4". Currently, I have created an additional field just called id which is an integer that auto increments, and I have set that to be the primary key. These are the only 3 fields.

Since the combination of the session_id and the user_id will always result in a unique outcome, should I instead use those two as the composite private key and remove the id field?

Thanks.

EDIT:

Do things change if we have a more complicated table that will require more fields? Take this table for example.

| id  | voter    | voting_for | round    | category_id | acceptable |
|-----|----------|------------|----------|-------------|------------|
| int | char(36) | char(36)   | smallint | int         | boolean    |

This is to do with votes within a game. Essentially after each round, the users in the game will vote on the answers of the other users within the game. So each entry has the user_id of the voter, the user_id of the person they are voting_for, the current round, the category_id of the category within the game and whether or not they agreed with the answer, acceptable. So, you could make a composite primary key using voter, voting_for, round and category_id. Is this any worse just because there are more fields, or should I still use the composite key instead of the existing auto increment id?


问:
Start x86_64 code on x86 (32bit) Linux, running on x86_64 CPU
?Is it possible to start an x86_64 code on i686 Linux (x86, 32-bit)? My CPU is modern Core 2 and it can run x86_64 64-bit code itself, but the OS is 32bit.

The code to start is pure mathematic, and it need almost no interaction with OS.

I want to measure, how fast will be my program in 64bit mode comparing with 32-bit mode. The program is to solve huge combinatoric problem and full size run is dozens of hours.

I can start 64bit code with qemu, but it will be not native execution and speed in qemu will be not related to real cpu speed.

答:
You won't be able to run x86_64 programs on a 32bit kernel without some form of emulation. (The other way around works just fine though, with no emulation.)

To be able to run 64bit code on x86_64, you have to enter "long mode" which requires the appropriate page tables to be set up (among other things). A 32bit kernel won't have done any 64bit page tables or mappings. So userspace code can't enter 64bit mode. It might be possible with some kernel help, but a 32bit kernel is simply not prepared for that kind of thing.

And since you can run 32bit code just fine with a 64bit kernel, there is no real reason not to use a 64bit kernel these days, especially if you have some code that could benefit from 64bit mode (more registers in particular).

Why don't you just boot from a 64bit live-cd? Or install a 64bit distribution on a separate disk or partition?

ContentLicense: CC BY-SA 3.0


问:
Jest - ReferenceError: define is not defined for a simple test file
I'm trying to use jest to test my project but upon running npm run test, I get ReferenceError: define is not defined even though my test file is extremely simple.

```<code>test("Adding 1 + 1 equals 2", () => {
  expect(1 + 1).toBe(2);
});
</code>```

This leads to me thinking that my setup configuration is wrong but I dont think I've done anything in my configurations that could have led to this (I think).

I'm confused as to why it's telling me define isn't defined when I'm not directly using define in my test case. I would appreciate any pointers!

Thanks!

EDIT: Here's my package.json

```<code>"jest": {
  "collectCoverageFrom": [
    "src/**/*.{js,jsx,mjs}"
  ],
  "testMatch": [
    "**/__tests__/**/*.js?(x)",
    "**/?(*.)+(spec|test).js?(x)"
  ],
  "testEnvironment": "node",
  "testURL": "http://localhost",
  "transform": {
    "^.+\\.(js|jsx|mjs)$": "./node_modules/babel-jest",
    "^.+\\.css$": "./config/jest/cssTransform.js",
    "^(?!.*\\.(js|jsx|mjs|css|json)$)": "./config/jest/fileTransform.js"
  },
  "transformIgnorePatterns": [
    "[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$"
  ],
  "moduleNameMapper": {
    "^react-native$": "react-native-web"
  },
  "moduleFileExtensions": [
    "web.js",
    "js",
    "json",
    "web.jsx",
    "jsx",
    "node",
    "mjs"
  ]
}
</code>```

EDIT 2: I've discovered that even if I had nothing in my test file, I get the same ReferenceError: define is not defined error

答:
That's because we have the @babel/plugin-transform-modules-amd so that while process test tasks the code will be transformed to define() AMD format, that's where the error's define from. Specify the babel config for jest test can solve this.

// babel.config.js
module.exports = api => {
  const commonConfig = {/* preset configs or something */};
  if( !api.env("test") ){
    commonConfigs.plugins.push("@babel/plugin-transform-modules-amd");
  }

  return commonConfig;
}
```

<p>Jest API Reference / Making your Babel config jest-aware</p>

<hr>

<p>About the transformed code
this command will show you cache directory of test code,</p>

<pre class="lang-sh prettyprint-override"><code>npx jest --showConfig | grep cacheDirectory
# /private/var/folders/dc/7gkfb6ns0c79ll9gv2y3m6_w0010gn/T/jest_dx
</code>```

open that folder you may see some files in jest_dx/jest-transform-cache-{HASH}/{QueueNumber}, the file is just there.

Body:
I'm trying to use jest to test my project but upon running npm run test, I get ReferenceError: define is not defined even though my test file is extremely simple.

test("Adding 1 + 1 equals 2", () => {
  expect(1 + 1).toBe(2);
});

This leads to me thinking that my setup configuration is wrong but I dont think I've done anything in my configurations that could have led to this (I think).

I'm confused as to why it's telling me define isn't defined when I'm not directly using define in my test case. I would appreciate any pointers!

Thanks!

EDIT: Here's my package.json

"jest": {
  "collectCoverageFrom": [
    "src/**/*.{js,jsx,mjs}"
  ],
  "testMatch": [
    "**/__tests__/**/*.js?(x)",
    "**/?(*.)+(spec|test).js?(x)"
  ],
  "testEnvironment": "node",
  "testURL": "http://localhost",
  "transform": {
    "^.+\\.(js|jsx|mjs)$": "./node_modules/babel-jest",
    "^.+\\.css$": "./config/jest/cssTransform.js",
    "^(?!.*\\.(js|jsx|mjs|css|json)$)": "./config/jest/fileTransform.js"
  },
  "transformIgnorePatterns": [
    "[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$"
  ],
  "moduleNameMapper": {
    "^react-native$": "react-native-web"
  },
  "moduleFileExtensions": [
    "web.js",
    "js",
    "json",
    "web.jsx",
    "jsx",
    "node",
    "mjs"
  ]
}

EDIT 2: I've discovered that even if I had nothing in my test file, I get the same ReferenceError: define is not defined error

Body:
That's because we have the @babel/plugin-transform-modules-amd so that while process test tasks the code will be transformed to define() AMD format, that's where the error's define from. Specify the babel config for jest test can solve this.

// babel.config.js
module.exports = api => {
  const commonConfig = {/* preset configs or something */};
  if( !api.env("test") ){
    commonConfigs.plugins.push("@babel/plugin-transform-modules-amd");
  }

  return commonConfig;
}

Jest API Reference / Making your Babel config jest-aware

About the transformed code
this command will show you cache directory of test code,

npx jest --showConfig | grep cacheDirectory
# /private/var/folders/dc/7gkfb6ns0c79ll9gv2y3m6_w0010gn/T/jest_dx

open that folder you may see some files in jest_dx/jest-transform-cache-{HASH}/{QueueNumber}, the file is just there.


问:
Pygame error 'pow expected 2 arguments, got 1'
They pygame game i made has run into an error i cannot figure out how to fix. I am new to pygame. I am using pycharm and python version 3.

The error is stopping me from doing anything and it won't even let me run it

Here is the error

```<code>TypeError: pow expected 2 arguments, got 1

</code>```

Here is the code:

```<code>import math
import random

import pygame

pygame.init()
# Screen (Pixels by Pixels (X and Y (X = right and left Y = up and down)))
screen = pygame.display.set_mode((800, 600))
running = True
# Title and Icon
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load('Icon.png')
pygame.display.set_icon(icon)
# Player Icon/Image
playerimg = pygame.image.load('Player.png')
playerX = 370
playerY = 480
playerX_change = 0

def player(x, y):
    # Blit means Draw
    screen.blit(playerimg, (x, y))

def enemy(x, y):
    # Blit means Draw
    screen.blit(enemyimg, (x, y))

def fire_bullet(x, y):
    global bullet_state
    bullet_state = "fire"
    screen.blit(bulletimg, (x + 16, y + 10))

def isCollision(enemyX, enemyY, bulletX, bulletY):
    distance = math.sqrt(math.pow(enemyX - bulletX, 2) + math.pow(math.pow(enemyY - bulletY,2)))
    if distance < 27:
        return True
    else:
        return False

background = pygame.image.load('247.jpg')

enemyimg = pygame.image.load('space-invaders.png')
enemyX = random.randint(0, 800)
enemyY = random.randint(50, 150)
enemyX_change = 4
enemyY_change = 40

bulletimg = pygame.image.load('bullet.png')
bulletX = 0
bulletY = 450
bulletX_change = 480
bulletY_change = 10
bullet_state = "ready"

score = 0
# Game loop (Put most of code for game in this loop)
while running:
    screen.fill((255, 0, 0))
    # BAckground
    screen.blit(background, (0, 0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        # if keystroke is pressed check whether is right or left
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                playerX_change = -5
            if event.key == pygame.K_RIGHT:
                playerX_change = 5
            if event.key == pygame.K_SPACE:
                if bullet_state == "ready":
                    bulletX = playerX
                    fire_bullet(playerX, bulletY)

        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                playerX_change = 0

    # RGB (screen.fill) = red green blue
    # 5 = 5 + - 0.1 -> 5 = 5 - 0.1
    # making so nothing can go out of bounds
    enemyX += enemyX_change
    if enemyX <= 0:
        enemyX_change = 4
        enemyY += enemyY_change
    elif enemyX >= 736:
        enemyX_change = -4
        enemyY += enemyY_change
    playerX += playerX_change
    if playerX <= 0:
        playerX = 0
    elif playerX >= 736:
        playerX = 736

    # Bullet movement
    if bulletY <= 0:
        bulletY = 480
        bullet_state = "ready"

    if bullet_state == "fire":
        fire_bullet(bulletX, bulletY)
        bulletY -= bulletY_change

    # Collison
    collision = isCollision(enemyX,enemyY,bulletX,bulletY)
    if collision:
        bulletY = 480
        bullet_state = "ready"
        score +=1

    player(playerX, playerY)
    enemy(enemyX, enemyY)
    pygame.display.update()

</code>```

答:
I believe you are trying to do this:

c = sqrt(pow(a,2) + pow(b,2))

But your code has one pow() too many. Happens to me too, when I make I make game sounds in my head, while coding (pew pew pew)

Try to remove one pow()

from
math.pow(math.pow(enemyY - bulletY,2))
to
math.pow(enemyY - bulletY,2)

Body:
They pygame game i made has run into an error i cannot figure out how to fix. I am new to pygame. I am using pycharm and python version 3.

The error is stopping me from doing anything and it won't even let me run it

Here is the error

TypeError: pow expected 2 arguments, got 1

Here is the code:

import math
import random

import pygame

pygame.init()
# Screen (Pixels by Pixels (X and Y (X = right and left Y = up and down)))
screen = pygame.display.set_mode((800, 600))
running = True
# Title and Icon
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load('Icon.png')
pygame.display.set_icon(icon)
# Player Icon/Image
playerimg = pygame.image.load('Player.png')
playerX = 370
playerY = 480
playerX_change = 0

def player(x, y):
    # Blit means Draw
    screen.blit(playerimg, (x, y))

def enemy(x, y):
    # Blit means Draw
    screen.blit(enemyimg, (x, y))

def fire_bullet(x, y):
    global bullet_state
    bullet_state = "fire"
    screen.blit(bulletimg, (x + 16, y + 10))

def isCollision(enemyX, enemyY, bulletX, bulletY):
    distance = math.sqrt(math.pow(enemyX - bulletX, 2) + math.pow(math.pow(enemyY - bulletY,2)))
    if distance < 27:
        return True
    else:
        return False

background = pygame.image.load('247.jpg')

enemyimg = pygame.image.load('space-invaders.png')
enemyX = random.randint(0, 800)
enemyY = random.randint(50, 150)
enemyX_change = 4
enemyY_change = 40

bulletimg = pygame.image.load('bullet.png')
bulletX = 0
bulletY = 450
bulletX_change = 480
bulletY_change = 10
bullet_state = "ready"

score = 0
# Game loop (Put most of code for game in this loop)
while running:
    screen.fill((255, 0, 0))
    # BAckground
    screen.blit(background, (0, 0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        # if keystroke is pressed check whether is right or left
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                playerX_change = -5
            if event.key == pygame.K_RIGHT:
                playerX_change = 5
            if event.key == pygame.K_SPACE:
                if bullet_state == "ready":
                    bulletX = playerX
                    fire_bullet(playerX, bulletY)

        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                playerX_change = 0

    # RGB (screen.fill) = red green blue
    # 5 = 5 + - 0.1 -> 5 = 5 - 0.1
    # making so nothing can go out of bounds
    enemyX += enemyX_change
    if enemyX <= 0:
        enemyX_change = 4
        enemyY += enemyY_change
    elif enemyX >= 736:
        enemyX_change = -4
        enemyY += enemyY_change
    playerX += playerX_change
    if playerX <= 0:
        playerX = 0
    elif playerX >= 736:
        playerX = 736

    # Bullet movement
    if bulletY <= 0:
        bulletY = 480
        bullet_state = "ready"

    if bullet_state == "fire":
        fire_bullet(bulletX, bulletY)
        bulletY -= bulletY_change

    # Collison
    collision = isCollision(enemyX,enemyY,bulletX,bulletY)
    if collision:
        bulletY = 480
        bullet_state = "ready"
        score +=1

    player(playerX, playerY)
    enemy(enemyX, enemyY)
    pygame.display.update()