问:
Need help getting this batch to VBS conversion to work properly
I am trying to convert a batch file to VBS. This is what I have so far. Looking for advice on proper formatting, as well as any help as to why this VBS script isn't working at the moment. Here's what I've got so far:

```<code>OPTION EXPLICIT
DIM strComputer,strSCVA,strDOSBox

strComputer = "." ' local computer
strSCVA = "scva.exe"
strDOSBox = "dosbox.exe"

' Check if scva.exe is running at startup (. = local computer)
IF isProcessRunning(strComputer,strSCVA) THEN
    Call LoopStart
ELSE
    cd "%~dp0../"
    start /min "" "scva.exe"
    Call LoopStart
END IF

Sub LoopStart
' Exits script if scva.exe is manually terminated, otherwise, calls CheckDOSBox
IF isProcessRunning(strComputer,strSCVA) THEN
    Call CheckDOSBox
ELSE
    WScript.Quit
END IF

Sub CheckDOSBox
' Goes to LoopStart while dosbox.exe is running, otherwise, calls Kill
IF isProcessRunning(strComputer,strDOSBox) THEN
    Call LoopStart
ELSE
    Call Kill
END IF

Sub Kill
' Sends command to terminate scva.exe while scva.exe is running, otherwise, exits script
IF isProcessRunning(strComputer,strSCVA) THEN
    taskkill /IM scva.exe
    Call Kill
ELSE
    WScript.Quit
END IF

' Function to check if a process is running
FUNCTION isProcessRunning(BYVAL strComputer,BYVAL strProcessName)

    DIM objWMIService, strWMIQuery

    strWMIQuery = "Select * from Win32_Process where name like '" & strProcessName & "'"

    SET objWMIService = GETOBJECT("winmgmts:" _
        & "{impersonationLevel=impersonate}!\\" _
            & strComputer & "\root\cimv2")

    IF objWMIService.ExecQuery(strWMIQuery).Count > 0 THEN
        isProcessRunning = TRUE
    ELSE
        isProcessRunning = FALSE
    END IF

END FUNCTION
</code>```

And here's the original batch file that's being converted (which I also wrote):

```<code>REM Runs scva.exe if it is not running; kills process after dosbox.exe is terminated

tasklist /FI "IMAGENAME eq scva.exe" 2>NUL | find /I /N "scva.exe">NUL
if "%ERRORLEVEL%"=="0" (
    goto LoopStart
) else (
    cd "%~dp0../"
    start /min "" "scva.exe"
    goto LoopStart
)

:LoopStart
REM Exits script if scva.exe is manually terminated, otherwise, goes to CheckDOSBox

tasklist /FI "IMAGENAME eq scva.exe" 2>NUL | find /I /N "scva.exe">NUL
if "%ERRORLEVEL%"=="0" (
    goto CheckDOSBox
) else (
    exit
)

:CheckDOSBox
REM Goes to LoopStart while dosbox.exe is running, otherwise, goes to Kill

tasklist /FI "IMAGENAME eq dosbox.exe" 2>NUL | find /I /N "dosbox.exe">NUL
if "%ERRORLEVEL%"=="0" (
    goto LoopStart
) else (
    goto Kill
)

:Kill
REM Sends command to terminate scva.exe while scva.exe is running, otherwise, exits script

tasklist /FI "IMAGENAME eq scva.exe" 2>NUL | find /I /N "scva.exe">NUL
if "%ERRORLEVEL%"=="0" (
    taskkill /IM scva.exe
    goto Kill
)
exit
</code>```

I think that my problem area is not knowing how to properly start a program in VBS. I have googled this but I don't understand the implementation and it would help if someone could show me how it works in my own code. Additionally, what is the equivalent of cd "%~dp0../" in VBS? In other words, the equivalent to relatively setting the working directory to the current directory of the VBS script?

答:
This doesn't answer your question, it is a rewritten batch file to hopefully replicate my assessment of what you intend your vbscript to do:

```<code>@Echo Off
Set "_=0"
TaskList /FI "IMAGENAME eq dosbox.exe" 2>Nul|Find /I "dosbox.exe">Nul&&Set/A _+=1
TaskList /FI "IMAGENAME eq scva.exe" 2>Nul|Find /I "scva.exe">Nul&&Set/A _+=2

If %_% Equ 3 Exit/B

If %_% Equ 2 TaskKill /IM "scva.exe"&&Set/A _-=2

If %_% Equ 0 Start "" "DOSBox.exe"&&Set/A _+=1

If %_% Equ 1 Start "" /D "%~dp0.." /MIN "scva.exe"
</code>```

Could you please comment as to whether my assessment is correct.

I would also be interested to know why you feel the need to recreate this in a different scripting language.

Body:
I am trying to convert a batch file to VBS. This is what I have so far. Looking for advice on proper formatting, as well as any help as to why this VBS script isn't working at the moment. Here's what I've got so far:

OPTION EXPLICIT
DIM strComputer,strSCVA,strDOSBox

strComputer = "." ' local computer
strSCVA = "scva.exe"
strDOSBox = "dosbox.exe"

' Check if scva.exe is running at startup (. = local computer)
IF isProcessRunning(strComputer,strSCVA) THEN
    Call LoopStart
ELSE
    cd "%~dp0../"
    start /min "" "scva.exe"
    Call LoopStart
END IF

Sub LoopStart
' Exits script if scva.exe is manually terminated, otherwise, calls CheckDOSBox
IF isProcessRunning(strComputer,strSCVA) THEN
    Call CheckDOSBox
ELSE
    WScript.Quit
END IF

Sub CheckDOSBox
' Goes to LoopStart while dosbox.exe is running, otherwise, calls Kill
IF isProcessRunning(strComputer,strDOSBox) THEN
    Call LoopStart
ELSE
    Call Kill
END IF

Sub Kill
' Sends command to terminate scva.exe while scva.exe is running, otherwise, exits script
IF isProcessRunning(strComputer,strSCVA) THEN
    taskkill /IM scva.exe
    Call Kill
ELSE
    WScript.Quit
END IF

' Function to check if a process is running
FUNCTION isProcessRunning(BYVAL strComputer,BYVAL strProcessName)

    DIM objWMIService, strWMIQuery

    strWMIQuery = "Select * from Win32_Process where name like '" & strProcessName & "'"

    SET objWMIService = GETOBJECT("winmgmts:" _
        & "{impersonationLevel=impersonate}!\\" _
            & strComputer & "\root\cimv2")

    IF objWMIService.ExecQuery(strWMIQuery).Count > 0 THEN
        isProcessRunning = TRUE
    ELSE
        isProcessRunning = FALSE
    END IF

END FUNCTION

And here's the original batch file that's being converted (which I also wrote):

REM Runs scva.exe if it is not running; kills process after dosbox.exe is terminated

tasklist /FI "IMAGENAME eq scva.exe" 2>NUL | find /I /N "scva.exe">NUL
if "%ERRORLEVEL%"=="0" (
    goto LoopStart
) else (
    cd "%~dp0../"
    start /min "" "scva.exe"
    goto LoopStart
)

:LoopStart
REM Exits script if scva.exe is manually terminated, otherwise, goes to CheckDOSBox

tasklist /FI "IMAGENAME eq scva.exe" 2>NUL | find /I /N "scva.exe">NUL
if "%ERRORLEVEL%"=="0" (
    goto CheckDOSBox
) else (
    exit
)

:CheckDOSBox
REM Goes to LoopStart while dosbox.exe is running, otherwise, goes to Kill

tasklist /FI "IMAGENAME eq dosbox.exe" 2>NUL | find /I /N "dosbox.exe">NUL
if "%ERRORLEVEL%"=="0" (
    goto LoopStart
) else (
    goto Kill
)

:Kill
REM Sends command to terminate scva.exe while scva.exe is running, otherwise, exits script

tasklist /FI "IMAGENAME eq scva.exe" 2>NUL | find /I /N "scva.exe">NUL
if "%ERRORLEVEL%"=="0" (
    taskkill /IM scva.exe
    goto Kill
)
exit

I think that my problem area is not knowing how to properly start a program in VBS. I have googled this but I don't understand the implementation and it would help if someone could show me how it works in my own code. Additionally, what is the equivalent of cd "%~dp0../" in VBS? In other words, the equivalent to relatively setting the working directory to the current directory of the VBS script?

Body:
This doesn't answer your question, it is a rewritten batch file to hopefully replicate my assessment of what you intend your vbscript to do:

@Echo Off
Set "_=0"
TaskList /FI "IMAGENAME eq dosbox.exe" 2>Nul|Find /I "dosbox.exe">Nul&&Set/A _+=1
TaskList /FI "IMAGENAME eq scva.exe" 2>Nul|Find /I "scva.exe">Nul&&Set/A _+=2

If %_% Equ 3 Exit/B

If %_% Equ 2 TaskKill /IM "scva.exe"&&Set/A _-=2

If %_% Equ 0 Start "" "DOSBox.exe"&&Set/A _+=1

If %_% Equ 1 Start "" /D "%~dp0.." /MIN "scva.exe"

Could you please comment as to whether my assessment is correct.

I would also be interested to know why you feel the need to recreate this in a different scripting language.


来源: stackexchange

问:
How to execute Set-GPPermissions command without confirmation prompt
```<code>Set-GPPermissions -Guid <Guid> -TargetName "Authenticated Users" -PermissionLevel None -TargetType Group -Replace -Confirm:$false
</code>```

Used to work fine, but when KB3163622 patch was installed it now asks me confirmation prompt:

"Group Policy requires each computer account to have permission to read GPO data from a domain controller in order for
  User Group Policy settings to be successfully applied. Removing the Authenticated Users group may prevent processing of
   User Group Policies. For more information, please see https://support.microsoft.com/en-us/kb/3163622
  Do you want to continue ?"

I execute this command from Powershell and C#.

There is any way to skip this confirmation prompt?

答:
Since it worked on a different machine, check the PowerShell version. If they are not the same, get the non-working machine on the same version. If that doesn't work, I'd recommend uninstalling and reinstalling the patch. Finally, if you're still having issues, take an inventory of both machines to see what is different on them. Software, .NET version, etc. </p>

<p>If that still doesn't work, it would seem that something is corrupt or misconfigured on the bad machine. If you can figure out what it is, then fix it. Otherwise, just use the other one if you can, or re-image the non-working machine. </p>

ContentLicense: CC BY-SA 3.0

Body:
Set-GPPermissions -Guid <Guid> -TargetName "Authenticated Users" -PermissionLevel None -TargetType Group -Replace -Confirm:$false

Used to work fine, but when KB3163622 patch was installed it now asks me confirmation prompt:

"Group Policy requires each computer account to have permission to read GPO data from a domain controller in order for
  User Group Policy settings to be successfully applied. Removing the Authenticated Users group may prevent processing of
   User Group Policies. For more information, please see https://support.microsoft.com/en-us/kb/3163622
  Do you want to continue ?"

I execute this command from Powershell and C#.

There is any way to skip this confirmation prompt?

Body:
Since it worked on a different machine, check the PowerShell version. If they are not the same, get the non-working machine on the same version. If that doesn't work, I'd recommend uninstalling and reinstalling the patch. Finally, if you're still having issues, take an inventory of both machines to see what is different on them. Software, .NET version, etc.

If that still doesn't work, it would seem that something is corrupt or misconfigured on the bad machine. If you can figure out what it is, then fix it. Otherwise, just use the other one if you can, or re-image the non-working machine.


问:
Taskdef class com.temp.install.common.action.UserInstallDirRule cannot be found using the classloader AntClassLoader
I have created a jar with the .class files and the dependency libraries which are required for executing the class files using the below jar code

```<code><target name="jar" depends="clean">
    <jar destfile="${basedir}/lib/HelloWorld.jar">
        <zipgroupfileset dir="${basedir}/lib" includes="*.jar" />
        <fileset dir="${basedir}" includes="/com/temp/**" />
        <fileset dir="${basedir}" includes="build.properties"/>
        <manifest>
        <attribute name="Class-Path" value="./HelloWorld.jar"/>
        </manifest>
    </jar>
</target>
</code>```

Now i have written other build.xml to run taskdef actions using this jar but the following error occurs when i try to invoke the class files using the taskdef actions even though the class files and their dependencies are present in the same jar.

BUILD FAILED
  C:\Users\kh2139\Desktop\New folder\build.xml:4: taskdef class com.temp.install.common.action.UserInstallDirRule cannot be found
   using the classloader AntClassLoader[C:\Users\kh2139\Desktop\New folder\HelloWorld.jar]

Attaching my build.xml code below which is used to run taskdef actions on the HelloWorld.jar

```<code><?xml version="1.0" encoding="ISO-8859-1"?>
    <project name="MyTask" basedir="." default="use">
<target name="use" description="Use the Task" >
    <taskdef name="helloworld1" classname="com.temp.install.common.action.UserInstallDirRule" classpath="HelloWorld.jar"/>
    <helloworld1/>
    <taskdef name="helloworld" classname="com.temp.install.common.action.EncryptionGUID" classpath="HelloWorld.jar"/>
    <helloworld/>
</target>
</project>
</code>```

PS: I could able to run the build.xml file successfully without errors when i specify the lib folder in the location where i place HelloWorld.jar and give the classpath to the lib folder in the taskdef actions.

But my issue is i want to use the same jar to contain the dependencies that are used while executing the classes.

答:
The error indicates that Java cannot find UserInstallDirRule.class in HelloWorld.jar. To determine if HelloWorld.jar contains the class, try running the jar.exe program included with the JDK.

Here's an example of running jar.exe in a Windows Command Prompt:

```<code>C:\>jar.exe tf "C:\Users\kh2139\Desktop\New folder\HelloWorld.jar"
</code>```

The output will show whether UserInstallDirRule.class is in the JAR file.

Body:
I have created a jar with the .class files and the dependency libraries which are required for executing the class files using the below jar code

<target name="jar" depends="clean">
    <jar destfile="${basedir}/lib/HelloWorld.jar">
        <zipgroupfileset dir="${basedir}/lib" includes="*.jar" />
        <fileset dir="${basedir}" includes="/com/temp/**" />
        <fileset dir="${basedir}" includes="build.properties"/>
        <manifest>
        <attribute name="Class-Path" value="./HelloWorld.jar"/>
        </manifest>
    </jar>
</target>

Now i have written other build.xml to run taskdef actions using this jar but the following error occurs when i try to invoke the class files using the taskdef actions even though the class files and their dependencies are present in the same jar.

BUILD FAILED
  C:\Users\kh2139\Desktop\New folder\build.xml:4: taskdef class com.temp.install.common.action.UserInstallDirRule cannot be found
   using the classloader AntClassLoader[C:\Users\kh2139\Desktop\New folder\HelloWorld.jar]

Attaching my build.xml code below which is used to run taskdef actions on the HelloWorld.jar

<?xml version="1.0" encoding="ISO-8859-1"?>
    <project name="MyTask" basedir="." default="use">
<target name="use" description="Use the Task" >
    <taskdef name="helloworld1" classname="com.temp.install.common.action.UserInstallDirRule" classpath="HelloWorld.jar"/>
    <helloworld1/>
    <taskdef name="helloworld" classname="com.temp.install.common.action.EncryptionGUID" classpath="HelloWorld.jar"/>
    <helloworld/>
</target>
</project>

PS: I could able to run the build.xml file successfully without errors when i specify the lib folder in the location where i place HelloWorld.jar and give the classpath to the lib folder in the taskdef actions.

But my issue is i want to use the same jar to contain the dependencies that are used while executing the classes.

Body:
The error indicates that Java cannot find UserInstallDirRule.class in HelloWorld.jar. To determine if HelloWorld.jar contains the class, try running the jar.exe program included with the JDK.

Here's an example of running jar.exe in a Windows Command Prompt:

C:\>jar.exe tf "C:\Users\kh2139\Desktop\New folder\HelloWorld.jar"

The output will show whether UserInstallDirRule.class is in the JAR file.


问:
Troubles with: setConnection(Connection.AIRPLANE)
I try to set AIRPLANE mode on Android emulator, but after execution I get:

```<code>org.openqa.selenium.WebDriverException: undefined status object (WARNING: The server did not provide any stacktrace information)
</code>```

My code:

```<code>public static void enableAirplaneMode(){
        driver.setConnection(Connection.AIRPLANE);
        assertEquals(Connection.AIRPLANE, driver.getConnection());
        classLogger.log(Level.INFO, "Connection type is set: " + driver.getConnection());
    }
</code>```

After step --> driver.setConnection(Connection.AIRPLANE); --> on emulator two modes are enabled, I see it on emulator settings(AIRPLANE and DATA) instead of AIRPLANE. And execution is failing:

```<code>at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:216)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:168)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:635)
at io.appium.java_client.DefaultGenericMobileDriver.execute(DefaultGenericMobileDriver.java:40)
at io.appium.java_client.AppiumDriver.execute(AppiumDriver.java:1)
at io.appium.java_client.android.AndroidDriver.execute(AndroidDriver.java:1)
at io.appium.java_client.CommandExecutionHelper.execute(CommandExecutionHelper.java:32)
at io.appium.java_client.android.AndroidDriver.setConnection(AndroidDriver.java:230)
at core.screen_driver.ConfigureEmulatorOS.enableAirplaneMode(ConfigureEmulatorOS.java:33)
at step_definitions.GeneralDefs.enableAirplane(GeneralDefs.java:109)
</code>```

Maybe anybody has a solving for this case?

答:
Using Connection.AIRPLANE in

```<code>driver.setConnection(Connection.AIRPLANE);
</code>```

Is only available from android Version 6.0 and above (For Emulators)

Please look at the appium docs for reference to driver.setConnection()

https://appium.readthedocs.io/en/stable/en/writing-running-appium/network_connection/

I would also advise to update to the latest java-client and appium server.

Body:
I try to set AIRPLANE mode on Android emulator, but after execution I get:

org.openqa.selenium.WebDriverException: undefined status object (WARNING: The server did not provide any stacktrace information)

My code:

public static void enableAirplaneMode(){
        driver.setConnection(Connection.AIRPLANE);
        assertEquals(Connection.AIRPLANE, driver.getConnection());
        classLogger.log(Level.INFO, "Connection type is set: " + driver.getConnection());
    }

After step --> driver.setConnection(Connection.AIRPLANE); --> on emulator two modes are enabled, I see it on emulator settings(AIRPLANE and DATA) instead of AIRPLANE. And execution is failing:

at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:216)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:168)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:635)
at io.appium.java_client.DefaultGenericMobileDriver.execute(DefaultGenericMobileDriver.java:40)
at io.appium.java_client.AppiumDriver.execute(AppiumDriver.java:1)
at io.appium.java_client.android.AndroidDriver.execute(AndroidDriver.java:1)
at io.appium.java_client.CommandExecutionHelper.execute(CommandExecutionHelper.java:32)
at io.appium.java_client.android.AndroidDriver.setConnection(AndroidDriver.java:230)
at core.screen_driver.ConfigureEmulatorOS.enableAirplaneMode(ConfigureEmulatorOS.java:33)
at step_definitions.GeneralDefs.enableAirplane(GeneralDefs.java:109)

Maybe anybody has a solving for this case?

Body:
Using Connection.AIRPLANE in

driver.setConnection(Connection.AIRPLANE);

Is only available from android Version 6.0 and above (For Emulators)

Please look at the appium docs for reference to driver.setConnection()

https://appium.readthedocs.io/en/stable/en/writing-running-appium/network_connection/

I would also advise to update to the latest java-client and appium server.


问:
How do I correct "Commit Failed. File xxx is out of date. xxx path not found."
I have recently run into a particularly sticky issue regarding committing the result of a merge in subversion.  Our Subversion server is @ 1.5.0 and my TortoiseSVN client is now @ 1.6.1.

I am trying to merge a feature branch back into my trunk. The merge appears to work okay; however, the commit fails with the following error message.

```<code>Commit failed (details follow):
File
'flex/src/com/penbay/invision/portal/services/http/soap/ReportServices/GetAllBldgsParamsByRegionBySiteResultEvent.as'
is out of date
'/svn/ibis/!svn/wrk/531d459d-80fa-ea46-bfb4-940d79ee6d2e/visualization/trunk/source/flex/src/com/penbay/invision/portal/services/http/soap/ReportServices/GetAllBldgsParamsByRegionBySiteResultEvent.as'
path not found
You have to update your working copy first.
</code>```

My working trunk is up to date.  I have even checked out a new one into a different folder to make sure there wasn't any local cruft messing with the merge. I have done some more research into this and I think part of the problem is user error.  I think our problems are:

We had some developers committing work with a subversion client before 1.5 and some after.  I believe this has the potential to corrupt the merge info.

In other branches we have performed partial merges.  That is, we did not always perform merges at the root of the branch.  This was to facilitate updating Flex and .NET efforts within the same branch.

We performed cyclic (reflexive) merges on our branch.  This was done because we had multiple parallel branches and we wanted to periodically update our branch with the latest code in trunk.

All of these things are explicitly not recommended by the Subversion book/team.  We have learned our lesson and now know the best practices.  However, we first need to merge and commit our latest branch.

What it the best way to correct the problems we are encountering?

Would deleting all the merge info in the trunk and branch be a viable solution?
No.  I have done this but it does not resolve the error that I am getting above.

答: Had similar problem with the SVN 1.6.5 on Mac 10.6.5, upgraded to SVN 1.6.9 and the commit succeeded.</p>

ContentLicense: CC BY-SA 2.5

Body:
I have recently run into a particularly sticky issue regarding committing the result of a merge in subversion.  Our Subversion server is @ 1.5.0 and my TortoiseSVN client is now @ 1.6.1.

I am trying to merge a feature branch back into my trunk. The merge appears to work okay; however, the commit fails with the following error message.

Commit failed (details follow):
File
'flex/src/com/penbay/invision/portal/services/http/soap/ReportServices/GetAllBldgsParamsByRegionBySiteResultEvent.as'
is out of date
'/svn/ibis/!svn/wrk/531d459d-80fa-ea46-bfb4-940d79ee6d2e/visualization/trunk/source/flex/src/com/penbay/invision/portal/services/http/soap/ReportServices/GetAllBldgsParamsByRegionBySiteResultEvent.as'
path not found
You have to update your working copy first.

My working trunk is up to date.  I have even checked out a new one into a different folder to make sure there wasn't any local cruft messing with the merge. I have done some more research into this and I think part of the problem is user error.  I think our problems are:

We had some developers committing work with a subversion client before 1.5 and some after.  I believe this has the potential to corrupt the merge info.

In other branches we have performed partial merges.  That is, we did not always perform merges at the root of the branch.  This was to facilitate updating Flex and .NET efforts within the same branch.

We performed cyclic (reflexive) merges on our branch.  This was done because we had multiple parallel branches and we wanted to periodically update our branch with the latest code in trunk.

All of these things are explicitly not recommended by the Subversion book/team.  We have learned our lesson and now know the best practices.  However, we first need to merge and commit our latest branch.

What it the best way to correct the problems we are encountering?

Would deleting all the merge info in the trunk and branch be a viable solution?
No.  I have done this but it does not resolve the error that I am getting above.


问:
Will garbage collect the parent class if one child is in use?
I am thinking, when I create a System struct, the builder system will cost much memory, but the result is simple, so if I return a address of result, will garbage know that it can collect the builder system memory?

How to test this?

I simulate the situation like this:

```<code>// Builder is used to build `System`, and it will cost much memory
type Builder struct {
    aux    [][]int
    system *System
}

// System is the result of `Builder.build`, this is relatively simple
type System struct {
    avg []float32
}

func NewSystem() *System {
    builder := &Builder{system: &System{}}
    builder.build()

    return builder.system
}

func (builder *Builder) build() {
    // mock initialize
    maxCnt := 10000
    builder.aux = make([][]int, maxCnt)
    for i := range builder.aux {
        builder.aux[i] = make([]int, maxCnt)
        for j := range builder.aux[i] {
            builder.aux[i][j] = rand.Intn(maxCnt)
        }
    }
    builder.system.avg = make([]float32, len(builder.aux))
    for i, col := range builder.aux {
        var sum float32
        for _, row := range col {
            sum += float32(row)
        }

        builder.system.avg[i] = sum / float32(len(builder.aux))
    }
}

func TestMem(t *testing.T) {
    system := NewSystem()
    // I want to know can garbage know that the memory cost by builder is able to be collected
    fmt.Println("do many things with system")
    fmt.Println(system.avg)
}
</code>```

答: Yes, it will be garbage collected once there is enough memory pressure to trigger garbage collection (assuming it's even put on the heap; anything allocated to the stack doesn't need to be garbage collected, as the entire stack is deallocated when no longer in use). The garbage collector will deallocate anything with no remaining references. After your processing finishes, the only thing with a reference is the []float32. If that were instead a slice of structs, and those structs had a pointer back to the parent object, that would prevent the parent being collected.

Body:
I am thinking, when I create a System struct, the builder system will cost much memory, but the result is simple, so if I return a address of result, will garbage know that it can collect the builder system memory?

How to test this?

I simulate the situation like this:

// Builder is used to build `System`, and it will cost much memory
type Builder struct {
    aux    [][]int
    system *System
}

// System is the result of `Builder.build`, this is relatively simple
type System struct {
    avg []float32
}

func NewSystem() *System {
    builder := &Builder{system: &System{}}
    builder.build()

    return builder.system
}

func (builder *Builder) build() {
    // mock initialize
    maxCnt := 10000
    builder.aux = make([][]int, maxCnt)
    for i := range builder.aux {
        builder.aux[i] = make([]int, maxCnt)
        for j := range builder.aux[i] {
            builder.aux[i][j] = rand.Intn(maxCnt)
        }
    }
    builder.system.avg = make([]float32, len(builder.aux))
    for i, col := range builder.aux {
        var sum float32
        for _, row := range col {
            sum += float32(row)
        }

        builder.system.avg[i] = sum / float32(len(builder.aux))
    }
}

func TestMem(t *testing.T) {
    system := NewSystem()
    // I want to know can garbage know that the memory cost by builder is able to be collected
    fmt.Println("do many things with system")
    fmt.Println(system.avg)
}