问:
Where does Oracle SQL Developer store connections?
I have an application that I can't get connected to my Oracle Database 11g Express Edition. I created a test database in this edition, and I can connect to the database fine using Oracle SQL Developer, create tables, views etc. However, I'm having a hard time getting connected via my application. Where is the connection information? In what file? I wanted to compare my connection info with what is set up in the SQL Explorer's file. I found all the *.ora files and renamed them to see if I could find what file (through the process of elimination) the connections were stored in, but I wasn't successful. Any help would be appreciated.</p>

答:
for macOS </p>

```<code>/Users/joseluisbz/.sqldeveloper/system18.1.0.095.1630/o.jdeveloper.db.connection/connections.xml
</code>```

Body:
for macOS

/Users/joseluisbz/.sqldeveloper/system18.1.0.095.1630/o.jdeveloper.db.connection/connections.xml


来源: stackexchange

问:
Calculating the silhouette coefficient in python
I run a code taken from this website for calculating Silhouette Coefficient, but the code is running with error

Here is the code

```<code>from sklearn import datasets
from sklearn.metrics import *
iris = datasets.load_iris()
col = iris.feature_names
name = iris.target_names
X = pd.DataFrame(iris.data, columns = col)
y = iris.target
s = silhouette_score(X.values, y, metric='euclidean',sample_size=50)
</code>```

The error is

```<code>---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-2e1432d3b9ce> in <module>
      4 col = iris.feature_names
      5 name = iris.target_names
----> 6 X = pd.DataFrame(iris.data, columns = col)
      7 y = iris.target
      8 s = silhouette_score(X.values, y, metric='euclidean',sample_size=50)

NameError: name 'pd' is not defined
</code>```

Any help?

答:
You need to import pandas first

```<code>import pandas as pd
</code>```

If you don't have it installed you'll need to install pandas first. Run this in the command line

```<code>pip install pandas
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I run a code taken from this website for calculating Silhouette Coefficient, but the code is running with error

Here is the code

from sklearn import datasets
from sklearn.metrics import *
iris = datasets.load_iris()
col = iris.feature_names
name = iris.target_names
X = pd.DataFrame(iris.data, columns = col)
y = iris.target
s = silhouette_score(X.values, y, metric='euclidean',sample_size=50)

The error is

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-2e1432d3b9ce> in <module>
      4 col = iris.feature_names
      5 name = iris.target_names
----> 6 X = pd.DataFrame(iris.data, columns = col)
      7 y = iris.target
      8 s = silhouette_score(X.values, y, metric='euclidean',sample_size=50)

NameError: name 'pd' is not defined

Any help?

Body:
You need to import pandas first

import pandas as pd

If you don't have it installed you'll need to install pandas first. Run this in the command line

pip install pandas


问:
How I can read corner coordinates in degrees?
I have a geotiff, gdalinfo back me info like that:
.....

```<code>Pixel Size = (0.740750480607563,-0.740750480607565)  Metadata:   AREA_OR_POINT=Area
Corner Coordinates:  Upper Left  (  408834.576, 4521463.892) ( 13d55'7.11"E,40d50'20.93"N)
Lower Left (  408834.576, 4497345.057) (13d55'19.75"E, 40d37'18.87"N)
</code>```

.....
I am using python, and read info from tiff like that:

```<code>ds = gdal.Open("name.tiff")
xoff, a, b, yoff, d, e = ds.GetGeoTransform()
</code>```

xoff, a, b, yoff, d, e will be used in conversion functions(pixel to geo coordinates), but  GetGeoTransform() give me xoff and yoff in metrs(this is first number in corner coordinates), not in degrees. How I can read coordinates of Upeer Left corner in degrees? I understand that i can start gdalinfo and read a lot of info, may be in python there is some function for this?

答:
You need to convert the coordinates to the other projection, with GDAL this can be done by using the osr module.

It's important to be aware that with since GDAL 3 and above the order of coordinates depends on the projection. The example below shows how you can get the "old" behavior (always x,y), but this of course depends on your usecase. Remove those lines if you don't want that.

Get the properties from the dataset

```<code>wkt_srs = ds.GetProjection()
gt = ds.GetGeoTransform()
xs = ds.RasterXSize
ys = ds.RasterYSize
</code>```

Convert the geotransform to the corner coordinates:

```<code>ulx, uly = gdal.ApplyGeoTransform(gt, 0, 0)
lrx, lry = gdal.ApplyGeoTransform(gt, xs, ys)
</code>```

Set up a transformation object:

```<code>src_srs = gdal.osr.SpatialReference()
src_srs.ImportFromWkt(wkt_srs)

tar_srs = gdal.osr.SpatialReference()
tar_srs.ImportFromEPSG(4326)

# with recent versions of GDAL the axis order (x,y vs y,x) depends
# on the projection. Force "x,y" with:
src_srs.SetAxisMappingStrategy(gdal.osr.OAMS_TRADITIONAL_GIS_ORDER)
tar_srs.SetAxisMappingStrategy(gdal.osr.OAMS_TRADITIONAL_GIS_ORDER)

ct = gdal.osr.CoordinateTransformation(src_srs, tar_srs)
</code>```

Convert the coordinates:

```<code>ulx_deg, uly_deg = ct.TransformPoint(ulx, uly)
lrx_deg, lry_deg = ct.TransformPoint(lrx, lry)
</code>```

Body:
I have a geotiff, gdalinfo back me info like that:
.....

Pixel Size = (0.740750480607563,-0.740750480607565)  Metadata:   AREA_OR_POINT=Area
Corner Coordinates:  Upper Left  (  408834.576, 4521463.892) ( 13d55'7.11"E,40d50'20.93"N)
Lower Left (  408834.576, 4497345.057) (13d55'19.75"E, 40d37'18.87"N)

.....
I am using python, and read info from tiff like that:

ds = gdal.Open("name.tiff")
xoff, a, b, yoff, d, e = ds.GetGeoTransform()

xoff, a, b, yoff, d, e will be used in conversion functions(pixel to geo coordinates), but  GetGeoTransform() give me xoff and yoff in metrs(this is first number in corner coordinates), not in degrees. How I can read coordinates of Upeer Left corner in degrees? I understand that i can start gdalinfo and read a lot of info, may be in python there is some function for this?

Body:
You need to convert the coordinates to the other projection, with GDAL this can be done by using the osr module.

It's important to be aware that with since GDAL 3 and above the order of coordinates depends on the projection. The example below shows how you can get the "old" behavior (always x,y), but this of course depends on your usecase. Remove those lines if you don't want that.

Get the properties from the dataset

wkt_srs = ds.GetProjection()
gt = ds.GetGeoTransform()
xs = ds.RasterXSize
ys = ds.RasterYSize

Convert the geotransform to the corner coordinates:

ulx, uly = gdal.ApplyGeoTransform(gt, 0, 0)
lrx, lry = gdal.ApplyGeoTransform(gt, xs, ys)

Set up a transformation object:

src_srs = gdal.osr.SpatialReference()
src_srs.ImportFromWkt(wkt_srs)

tar_srs = gdal.osr.SpatialReference()
tar_srs.ImportFromEPSG(4326)

# with recent versions of GDAL the axis order (x,y vs y,x) depends
# on the projection. Force "x,y" with:
src_srs.SetAxisMappingStrategy(gdal.osr.OAMS_TRADITIONAL_GIS_ORDER)
tar_srs.SetAxisMappingStrategy(gdal.osr.OAMS_TRADITIONAL_GIS_ORDER)

ct = gdal.osr.CoordinateTransformation(src_srs, tar_srs)

Convert the coordinates:

ulx_deg, uly_deg = ct.TransformPoint(ulx, uly)
lrx_deg, lry_deg = ct.TransformPoint(lrx, lry)


问:
Xml and MS SQL Server 2019, insert
I am connecting to a Tcp socket and a receive xml feeds.
for an example lets say the xml is like the follow.

```<code>  <?xml version="1.0" encoding="UTF-8"?>
       <games>
           <game id="1000" name="warthunder"  score="987610" rank="1" users_online="17625"/>
           <game id="1001" name="american pool"  score="187610" rank="2" users_online="1122"/>
       ......
      ......
        <game id="2000" name="our world"  score="7610" rank="2000" users_online="37"/>
 </games>
</code>```

I receive this every 2-3 seconds and at the moment I store it in the database in an XML column.

So on my front end I read this column from the sql as XML and I parse it.

I would prefer to have all XML attributes stored as separate columns so it would be no need to parse the XML.
But then I need to to do 2000 Insert/Updates each time when I receive the XML.

Is there a way to shred the XML and insert into separate columns in SQL Server?

thank you.

答:
It is easy to implement by using XML data type .nodes() method. It allows to shred XML and convert it into a rectangular format.

SQL

```<code>-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, game_id INT, [name] VARCHAR(30), score INT, [rank] INT, users_online INT);

DECLARE @xml XML =
'<?xml version="1.0" encoding="UTF-8"?>
<games>
    <game id="1000" name="warthunder" score="987610" rank="1" users_online="17625"/>
    <game id="1001" name="american pool" score="187610" rank="2" users_online="1122"/>
    <game id="2000" name="our world" score="7610" rank="2000" users_online="37"/>
</games>';
-- DDL and sample data population, end

INSERT INTO @tbl (game_id,[name],score,[rank],users_online)
SELECT c.value('@id','INT') AS game_id
    , c.value('@name','VARCHAR(30)') AS [name]
    , c.value('@score','INT') AS score
    , c.value('@rank','INT') AS [rank]
    , c.value('@users_online','INT') AS users_online
FROM @xml.nodes('/games/game') AS t(c);

-- test
SELECT * FROM @tbl;
</code>```

Output

```<code>+----+---------+---------------+--------+------+--------------+
| ID | game_id |     name      | score  | rank | users_online |
+----+---------+---------------+--------+------+--------------+
|  1 |    1000 | warthunder    | 987610 |    1 |        17625 |
|  2 |    1001 | american pool | 187610 |    2 |         1122 |
|  3 |    2000 | our world     |   7610 | 2000 |           37 |
+----+---------+---------------+--------+------+--------------+
</code>```

Title: Xml and MS SQL Server 2019, insert

Body:
I am connecting to a Tcp socket and a receive xml feeds.
for an example lets say the xml is like the follow.

  <?xml version="1.0" encoding="UTF-8"?>
       <games>
           <game id="1000" name="warthunder"  score="987610" rank="1" users_online="17625"/>
           <game id="1001" name="american pool"  score="187610" rank="2" users_online="1122"/>
       ......
      ......
        <game id="2000" name="our world"  score="7610" rank="2000" users_online="37"/>
 </games>

I receive this every 2-3 seconds and at the moment I store it in the database in an XML column.

So on my front end I read this column from the sql as XML and I parse it.

I would prefer to have all XML attributes stored as separate columns so it would be no need to parse the XML.
But then I need to to do 2000 Insert/Updates each time when I receive the XML.

Is there a way to shred the XML and insert into separate columns in SQL Server?

thank you.

Body:
It is easy to implement by using XML data type .nodes() method. It allows to shred XML and convert it into a rectangular format.

SQL

-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, game_id INT, [name] VARCHAR(30), score INT, [rank] INT, users_online INT);

DECLARE @xml XML =
'<?xml version="1.0" encoding="UTF-8"?>
<games>
    <game id="1000" name="warthunder" score="987610" rank="1" users_online="17625"/>
    <game id="1001" name="american pool" score="187610" rank="2" users_online="1122"/>
    <game id="2000" name="our world" score="7610" rank="2000" users_online="37"/>
</games>';
-- DDL and sample data population, end

INSERT INTO @tbl (game_id,[name],score,[rank],users_online)
SELECT c.value('@id','INT') AS game_id
    , c.value('@name','VARCHAR(30)') AS [name]
    , c.value('@score','INT') AS score
    , c.value('@rank','INT') AS [rank]
    , c.value('@users_online','INT') AS users_online
FROM @xml.nodes('/games/game') AS t(c);

-- test
SELECT * FROM @tbl;

Output

+----+---------+---------------+--------+------+--------------+
| ID | game_id |     name      | score  | rank | users_online |
+----+---------+---------------+--------+------+--------------+
|  1 |    1000 | warthunder    | 987610 |    1 |        17625 |
|  2 |    1001 | american pool | 187610 |    2 |         1122 |
|  3 |    2000 | our world     |   7610 | 2000 |           37 |
+----+---------+---------------+--------+------+--------------+


问:
MS Access Dropdown List/Combo Box
This should probably be pretty simple but my Google-Fu is as yet unable to find an answer. I simply want to create a dropdown list in Access so that upon selection I can perform some action based on the value of the selection. For instance, I have a list of people and I would like to populate the combo box so that their names appear in the list but the "value" is set to their ID (the primary key).</p>

答:
You will need to hook into the onchange event for the dropdown list.

and from MSDN

OwnerDisplayName: noblethrasher

ContentLicense: CC BY-SA 2.5

Title: MS Access Dropdown List/Combo Box

LastEditorDisplayName: Chris Ballance

OwnerDisplayName: Chris Ballance


问:
java code to print alternate prime numbers in reverse order
The following is my java code to print 'n' prime no.s but i want to modify it such that i can print alternate prime numbers in reverse order.</p>

```<code>import java.util.Scanner;

class PrimeNumberDemo
{
   public static void main(String args[])
   {
      int n;
      int status = 1;
      int num = 3;
      //For capturing the value of n
      Scanner scanner = new Scanner(System.in);
      System.out.println("Enter the value of n:");
      //The entered value is stored in the var n
      n = scanner.nextInt();
      if (n >= 1)
      {
         System.out.println("First "+n+" prime numbers are:");
         //2 is a known prime number
         System.out.println(2);
      }

      for ( int i = 2 ; i <=n ;  )
      {
         for ( int j = 2 ; j <= Math.sqrt(num) ; j++ )
         {
            if ( num%j == 0 )
            {
               status = 0;
               break;
            }
         }
         if ( status != 0 )
         {
            System.out.println(num);
            i++;
         }
         status = 1;
         num++;
      }
   }
}
</code>```

答:
I would do it this way.

import java.util.Scanner;
class AlternatePrimeNumbers
{
    static Scanner input = new Scanner(System.in);
    public static void main(String[] args)
    {
        Main obj = new Main();
        System.out.print("Enter the value of n :- ");
        int num = input.nextInt();
        System.out.println("Alternate Prime numbers in reverse order upto "+num+" :- ");
        obj.alternatePrimeNumbers(num);
    }
}

class Main
{
    public void alternatePrimeNumbers(int n)
    {
        int i;
        boolean prime,flag=true;
        for(i=n; i>=1; i--)
        {
            prime = checkPrime(i);
            if(prime)
            {
                if(flag)
                {
                    System.out.print(i+" ");
                    flag = false;
                }
                else if(flag==false)
                    flag = true;
            }
        }
    }

    public boolean checkPrime(int n)
    {
        int i;
        boolean prime=true;
        for(i=2; i<=n/2; i++)
        {
            if(n%i==0) //condition for non-prime numbers
            {
                prime = false;
                break;
            }
        }
        return prime;
    }
}

```

ContentLicense: CC BY-SA 3.0

Body:
The following is my java code to print 'n' prime no.s but i want to modify it such that i can print alternate prime numbers in reverse order.

import java.util.Scanner;

class PrimeNumberDemo
{
   public static void main(String args[])
   {
      int n;
      int status = 1;
      int num = 3;
      //For capturing the value of n
      Scanner scanner = new Scanner(System.in);
      System.out.println("Enter the value of n:");
      //The entered value is stored in the var n
      n = scanner.nextInt();
      if (n >= 1)
      {
         System.out.println("First "+n+" prime numbers are:");
         //2 is a known prime number
         System.out.println(2);
      }

      for ( int i = 2 ; i <=n ;  )
      {
         for ( int j = 2 ; j <= Math.sqrt(num) ; j++ )
         {
            if ( num%j == 0 )
            {
               status = 0;
               break;
            }
         }
         if ( status != 0 )
         {
            System.out.println(num);
            i++;
         }
         status = 1;
         num++;
      }
   }
}


问:
Is there a better way to express nested namespaces in C++ within the header
I switched from C++ to Java and C# and think the usage of namespaces/packages is much better there (well structured). Then I came back to C++ and tried to use namespaces the same way but the required syntax is horrible within the header file.

```<code>namespace MyCompany
{
    namespace MyModule
    {
        namespace MyModulePart //e.g. Input
        {
            namespace MySubModulePart
            {
                namespace ...
                {
                    public class MyClass
</code>```

The following seems strange to me too (to avoid the deep indent):

```<code>namespace MyCompany
{
namespace MyModule
{
namespace MyModulePart //e.g. Input
{
namespace MySubModulePart
{
namespace ...
{
     public class MyClass
     {
</code>```

Is there a shorter Way to express the above thing? I am missing something like

```<code>namespace MyCompany::MyModule::MyModulePart::...
{
   public class MyClass
</code>```

Update

Ok, some say the concept of usage in Java/C# and C++ is different. Really? I think (dynamic) class loading is not the only purpose for namespaces (this is a very technical reasoned perspective). Why shouldn't I use it for a readability and structurization, e.g think of "IntelliSense".

Currently, there is no logic / glue between a namespace and what you can find there. Java and C# does this much better... Why including <iostream> and having namespace std?
Ok, if you say the logic should rely on the header to include, why does the #include  does not uses an "IntelliSense" friendly syntax like #include <std::io::stream> or <std/io/stream>? I think the missing structurization in the default libs is one weakness of C++ compared to Java/C#.

If uniqueness to avid conflicts is one Point (which is a point of C# and Java, too) a good idea is to use the project name or company name as namespace, don't you think so?

On the one hand it's said C++ is the most flexible... but everyone said "don't do this"?
It seems to me C++ can do many things but has a horrible syntax even for the easiest things in many cases compared to C#.

Update 2

Most users say it is nonsense to create a deeper nesting than two Levels. Ok, so what about Windows::UI::Xaml and Windows::UI::Xaml::Controls::Primitives namespaces in Win8 development? I think Microsoft's usage of namespaces makes sense and it is indeed deeper than just 2 Levels.
I think bigger libraries / projects need a deeper nesting (I hate class names like ExtraLongClassNameBecauseEveryThingIsInTheSameNameSpace... then you could put everything into the global namespace, too.)

Update 3 - Conclusion

Most say "don't do it", but... even boost has a deeper nesting then one or two levels. Yes, it is a library but: If you want reusable code - treat your own code like a library you would give someone else. I also use a deeper nesting for discovery purposes using namespaces.

答:
This paper covers the subject rather well: Namespace Paper

Which basically boils down this. The longer your namespaces are the more likely the chance that people are going to use the using namespace directive.

So looking at the following code you can see an example where this will hurt you:

namespace abc { namespace testing {
    class myClass {};
}}

namespace def { namespace testing {
    class defClass { };
}}

using namespace abc;
//using namespace def;

int main(int, char**) {
    testing::myClass classInit{};
}
```

This code will compile fine, however, if you uncomment the line //using namespace def; then the "testing" namespace will become ambiguous and you will have naming collisions. This means that your code base can go from stable to unstable by including a 3rd party library.

In C#, even if you were to use using abc; and using def; the compiler is able to recognize that testing::myClass or even just myClass is only in the abc::testing namespace, but C++ will not recognize this and it is detected as a collision.

Body:
I switched from C++ to Java and C# and think the usage of namespaces/packages is much better there (well structured). Then I came back to C++ and tried to use namespaces the same way but the required syntax is horrible within the header file.

namespace MyCompany
{
    namespace MyModule
    {
        namespace MyModulePart //e.g. Input
        {
            namespace MySubModulePart
            {
                namespace ...
                {
                    public class MyClass

The following seems strange to me too (to avoid the deep indent):

namespace MyCompany
{
namespace MyModule
{
namespace MyModulePart //e.g. Input
{
namespace MySubModulePart
{
namespace ...
{
     public class MyClass
     {

Is there a shorter Way to express the above thing? I am missing something like

namespace MyCompany::MyModule::MyModulePart::...
{
   public class MyClass

Update

Ok, some say the concept of usage in Java/C# and C++ is different. Really? I think (dynamic) class loading is not the only purpose for namespaces (this is a very technical reasoned perspective). Why shouldn't I use it for a readability and structurization, e.g think of "IntelliSense".

Currently, there is no logic / glue between a namespace and what you can find there. Java and C# does this much better... Why including <iostream> and having namespace std?
Ok, if you say the logic should rely on the header to include, why does the #include  does not uses an "IntelliSense" friendly syntax like #include <std::io::stream> or <std/io/stream>? I think the missing structurization in the default libs is one weakness of C++ compared to Java/C#.

If uniqueness to avid conflicts is one Point (which is a point of C# and Java, too) a good idea is to use the project name or company name as namespace, don't you think so?

On the one hand it's said C++ is the most flexible... but everyone said "don't do this"?
It seems to me C++ can do many things but has a horrible syntax even for the easiest things in many cases compared to C#.

Update 2

Most users say it is nonsense to create a deeper nesting than two Levels. Ok, so what about Windows::UI::Xaml and Windows::UI::Xaml::Controls::Primitives namespaces in Win8 development? I think Microsoft's usage of namespaces makes sense and it is indeed deeper than just 2 Levels.
I think bigger libraries / projects need a deeper nesting (I hate class names like ExtraLongClassNameBecauseEveryThingIsInTheSameNameSpace... then you could put everything into the global namespace, too.)

Update 3 - Conclusion

Most say "don't do it", but... even boost has a deeper nesting then one or two levels. Yes, it is a library but: If you want reusable code - treat your own code like a library you would give someone else. I also use a deeper nesting for discovery purposes using namespaces.

Body:
This paper covers the subject rather well: Namespace Paper

Which basically boils down this. The longer your namespaces are the more likely the chance that people are going to use the using namespace directive.

So looking at the following code you can see an example where this will hurt you:

namespace abc { namespace testing {
    class myClass {};
}}

namespace def { namespace testing {
    class defClass { };
}}

using namespace abc;
//using namespace def;

int main(int, char**) {
    testing::myClass classInit{};
}

This code will compile fine, however, if you uncomment the line //using namespace def; then the "testing" namespace will become ambiguous and you will have naming collisions. This means that your code base can go from stable to unstable by including a 3rd party library.

In C#, even if you were to use using abc; and using def; the compiler is able to recognize that testing::myClass or even just myClass is only in the abc::testing namespace, but C++ will not recognize this and it is detected as a collision.


问:
Use of plugins in gradle
I have a question on the usage of plugins in gradle in general. What features do they provide?

For example, why should I use an Idea plugin if my IDE is intelliJ. What if I don't use that will there be any difference.

答:
If you want to know about Gradle plugins in general, you should read the relevant part of the user guide. It does a good job of explaining the concept.

As for the IntelliJ plugin in particular: no you should generally not add it. IntelliJ can import Gradle projects just fine without it. The only time it makes sense to add it is if you need to customize the import process in a way that differs from the default. But even that is often better done through adding the specific IntelliJ configuration files to your VCS repository. If you like to know more about best practices for this, the Gradle forums are a better match for discussing the different approaches.

Title: Use of plugins in gradle


问:
History log won't get deleted when page is refreshed OR history log will stored it's value in spreadsheet
I've created a simple counter which has a single textbox, disabled box and a history to record all previous value in the disabled box.

It works perfectly, but somehow when the page is accidentally refreshed all the logs are deleted.

Is there a way to keeo that record even if the page reload? Or maybe store it in a spreadsheet?

```<code>let box1 = document.getElementById("box1");
let box2 = document.getElementById("box2");
let resetBtn = document.getElementById("reset");
let historyContainer = document.getElementById("history");
let history = [];

//listen key enter press on the input
box1.addEventListener("keyup", e => {
  if (e.key === "Enter" && e.target.value !== "") {
  const summedValue = (box2.value && box2.value.trim() === "")  ? Number(box2.value) : Number(box2.value) + Number(e.target.value)
  box2.value = summedValue;
  historyContainer.innerHTML += `<p>${box2.value}</p>`;
  box1.value = "";
  }
});
//reset the second box and
resetBtn.addEventListener("click", () => {
  box2.value = "";
  historyContainer.innerHTML = ""
});
<input type="number" id="box1" />
<input type="number" id="box2" disabled />
<div id="history">
</div>

<button type="button" id="reset">
Reset
</button>
</code>```

答: You can store and retrieve those data from the web browser's local storage. Learn more about it</p>

Body:
I've created a simple counter which has a single textbox, disabled box and a history to record all previous value in the disabled box.

It works perfectly, but somehow when the page is accidentally refreshed all the logs are deleted.

Is there a way to keeo that record even if the page reload? Or maybe store it in a spreadsheet?

let box1 = document.getElementById("box1");
let box2 = document.getElementById("box2");
let resetBtn = document.getElementById("reset");
let historyContainer = document.getElementById("history");
let history = [];

//listen key enter press on the input
box1.addEventListener("keyup", e => {
  if (e.key === "Enter" && e.target.value !== "") {
  const summedValue = (box2.value && box2.value.trim() === "")  ? Number(box2.value) : Number(box2.value) + Number(e.target.value)
  box2.value = summedValue;
  historyContainer.innerHTML += `<p>${box2.value}</p>`;
  box1.value = "";
  }
});
//reset the second box and
resetBtn.addEventListener("click", () => {
  box2.value = "";
  historyContainer.innerHTML = ""
});
<input type="number" id="box1" />
<input type="number" id="box2" disabled />

<button type="button" id="reset">
Reset
</button>


问:
How do you know when a thread has finished executing
I am doing a quiz app in Android studio using Kotlin. I am fetching data from an API and showing it in an activity. Now I am implementing a progressBar that indicates how much time to answer each question. This is my function to fetch from API:

```<code> private fun fetch(){

    val theme = intent.getIntExtra("sport", 21)
    val difficulty = intent.getStringExtra("medium")

    val url = "https://opentdb.com/api.php?amount=10&category=21&difficulty=medium&type=multiple"
    val request = Request.Builder()
        .url(url)
        .build()

    client.newCall(request).enqueue(object: Callback {

        override fun onResponse(call: Call, response: Response) {

            val body = response.body?.string()
            val gson = GsonBuilder().create()
            val triviaRequest = gson.fromJson(body, TriviaRequest::class.java)
            val result = triviaRequest.results[0]
            val question = result.question.toSpanned()
            val questionCategory = result.category.toSpanned()
            val correctAnswer = result.correct_answer.toSpanned()
            val incorrectAnswer1 = result.incorrect_answers[0].toSpanned()
            val incorrectAnswer2 = result.incorrect_answers[1].toSpanned()
            val incorrectAnswer3 = result.incorrect_answers[2].toSpanned()

            val questions = listOf(
                correctAnswer,
                incorrectAnswer1,
                incorrectAnswer2,
                incorrectAnswer3
            )

            shuffle(questions)

            runOnUiThread {

                val button1 = findViewById<Button>(R.id.alternative1)
                val button2 = findViewById<Button>(R.id.alternative2)
                val button3 = findViewById<Button>(R.id.alternative3)
                val button4 = findViewById<Button>(R.id.alternative4)

                questionText.text = question
                themeText.text = questionCategory

                button1.text = questions[0]
                button1.isEnabled = true

                button2.text = questions[1]
                button2.isEnabled = true

                button3.text = questions[2]
                button3.isEnabled = true

                button4.text = questions[3]
                button4.isEnabled = true

                button1.setOnClickListener {

                    button1.isClickable = false
                    if (button1.text == correctAnswer) {
                        score += 1
                        fetch()
                    } else {
                        button1.text = "---"
                    }
                }

                button2.setOnClickListener {

                    button2.isClickable = false
                    if (button2.text == correctAnswer) {
                        score += 1
                        fetch()
                    } else {
                        button2.text = "---"
                    }
                }

                button3.setOnClickListener {

                    button3.isClickable = false
                    if (button3.text == correctAnswer) {
                        score += 1
                        fetch()
                    } else {
                        button3.text = "---"
                    }
                }

                button4.setOnClickListener {

                    button4.isClickable = false
                    if (button4.text == correctAnswer) {
                        score += 1
                        fetch()
                    } else {
                        button4.text = "---"
                    }
                }
            }
            response.close()
        }

        override fun onFailure(call: Call, e: IOException) {
            e.printStackTrace()
        }

    })
}
</code>```

And this is how I show the progressBar:

```<code>  val fetch = runCatching { fetch() }
        if(fetch.isSuccess) {
            val handler = Handler()
            Thread(Runnable {

                while (progressCount < 100) {
                    progressCount += 1
                    try {
                        Thread.sleep(50)
                    } catch (e: InterruptedException) {
                        e.printStackTrace()
                    }
                    handler.post {
                        progressBar.progress = progressCount
                    }
                }
            }).start()
        }

    }
</code>```

The problem now is that as soon as the activity starts, my progressBar starts showing but the questions has not appeared yet. My question is how can I know when my fetch function has finished executing?
so that I can show the progressBar?

Thanks!

答:
You can look into kotlin coroutines and use suspend functions, or you can use a callback like this:</p>

```<code>fun fetch (callback: ()->Unit) { // take callback param

   ... // do the stuff

   callback() // call the callback on complete

}

fetch {
    // Done fetching here, execute your code inside this
}
</code>```

Body:
I am doing a quiz app in Android studio using Kotlin. I am fetching data from an API and showing it in an activity. Now I am implementing a progressBar that indicates how much time to answer each question. This is my function to fetch from API:

 private fun fetch(){

    val theme = intent.getIntExtra("sport", 21)
    val difficulty = intent.getStringExtra("medium")

    val url = "https://opentdb.com/api.php?amount=10&category=21&difficulty=medium&type=multiple"
    val request = Request.Builder()
        .url(url)
        .build()

    client.newCall(request).enqueue(object: Callback {

        override fun onResponse(call: Call, response: Response) {

            val body = response.body?.string()
            val gson = GsonBuilder().create()
            val triviaRequest = gson.fromJson(body, TriviaRequest::class.java)
            val result = triviaRequest.results[0]
            val question = result.question.toSpanned()
            val questionCategory = result.category.toSpanned()
            val correctAnswer = result.correct_answer.toSpanned()
            val incorrectAnswer1 = result.incorrect_answers[0].toSpanned()
            val incorrectAnswer2 = result.incorrect_answers[1].toSpanned()
            val incorrectAnswer3 = result.incorrect_answers[2].toSpanned()

            val questions = listOf(
                correctAnswer,
                incorrectAnswer1,
                incorrectAnswer2,
                incorrectAnswer3
            )

            shuffle(questions)

            runOnUiThread {

                val button1 = findViewById<Button>(R.id.alternative1)
                val button2 = findViewById<Button>(R.id.alternative2)
                val button3 = findViewById<Button>(R.id.alternative3)
                val button4 = findViewById<Button>(R.id.alternative4)

                questionText.text = question
                themeText.text = questionCategory

                button1.text = questions[0]
                button1.isEnabled = true

                button2.text = questions[1]
                button2.isEnabled = true

                button3.text = questions[2]
                button3.isEnabled = true

                button4.text = questions[3]
                button4.isEnabled = true

                button1.setOnClickListener {

                    button1.isClickable = false
                    if (button1.text == correctAnswer) {
                        score += 1
                        fetch()
                    } else {
                        button1.text = "---"
                    }
                }

                button2.setOnClickListener {

                    button2.isClickable = false
                    if (button2.text == correctAnswer) {
                        score += 1
                        fetch()
                    } else {
                        button2.text = "---"
                    }
                }

                button3.setOnClickListener {

                    button3.isClickable = false
                    if (button3.text == correctAnswer) {
                        score += 1
                        fetch()
                    } else {
                        button3.text = "---"
                    }
                }

                button4.setOnClickListener {

                    button4.isClickable = false
                    if (button4.text == correctAnswer) {
                        score += 1
                        fetch()
                    } else {
                        button4.text = "---"
                    }
                }
            }
            response.close()
        }

        override fun onFailure(call: Call, e: IOException) {
            e.printStackTrace()
        }

    })
}

And this is how I show the progressBar:

  val fetch = runCatching { fetch() }
        if(fetch.isSuccess) {
            val handler = Handler()
            Thread(Runnable {

                while (progressCount < 100) {
                    progressCount += 1
                    try {
                        Thread.sleep(50)
                    } catch (e: InterruptedException) {
                        e.printStackTrace()
                    }
                    handler.post {
                        progressBar.progress = progressCount
                    }
                }
            }).start()
        }

    }

The problem now is that as soon as the activity starts, my progressBar starts showing but the questions has not appeared yet. My question is how can I know when my fetch function has finished executing?
so that I can show the progressBar?

Thanks!

Body:
You can look into kotlin coroutines and use suspend functions, or you can use a callback like this:

fun fetch (callback: ()->Unit) { // take callback param

   ... // do the stuff

   callback() // call the callback on complete

}

fetch {
    // Done fetching here, execute your code inside this
}


问:
custom dialog fragment from a fragment
I've created a constraint layout and I am calling a dialog fragment from a fragment. But when I click on the button all it does is fades the screen but I can't see any dialog or the layout.

Here's my code for dialog fragment:

```<code>package com.example.atry.MakeComplaint

import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.DialogFragment

import com.example.atry.R

class PopupDialog : DialogFragment() {

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {

        val builder = AlertDialog.Builder(activity)

        return builder.create()

    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

        val view = inflater.inflate(R.layout.existing_complaint_popup, container, false)

        val yes = view.findViewById(R.id.YES) as Button
        val no = view.findViewById(R.id.NO) as Button

        // set onclicklistener
        yes.setOnClickListener(View.OnClickListener {
            // I want the dialog to close at this point
            dismiss()
            backFragment()

        })

        // set onclicklistener
        no.setOnClickListener(View.OnClickListener {
            // I want the dialog to close at this point
            dismiss()
            descriptionFragment()

        })

        return view
    }

    private fun backFragment() {
        val manager = (context as AppCompatActivity).supportFragmentManager
        manager.popBackStackImmediate()

    }

    private fun descriptionFragment() {
        val dFragment= Category_Description()
        val lFragment = LocationFragment()
        val manager = (context as AppCompatActivity).supportFragmentManager
        val transaction =  manager.beginTransaction()
        transaction.replace(
            R.id.location_screen,
            dFragment
        ) // give your fragment container id in first parameter
        transaction.show(dFragment)
        transaction.hide(lFragment)
        transaction.isAddToBackStackAllowed
        transaction.addToBackStack(lFragment.fragmentManager.toString())  // if written, this transaction will be added to backstack
        transaction.commit()
    }

}

</code>```

Here's the code inside the fragment I'm calling the dialog from:

```<code> //opening up the checkExisting popup

    private fun existPopup(){
        val fm = activity!!.supportFragmentManager
        val dialog = PopupDialog() // creating new object
        dialog.show(fm, "dialog")
    }

</code>```

And here's my layout:

```<code>
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools">

    <LinearLayout
            android:id="@+id/textViewComplaint"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_above="@+id/complainDescription"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toTopOf="@id/textViewComplaint"
            >

        <TextView
                android:id="@+id/headingComplain"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_alignParentTop="true"
                android:layout_marginBottom="10dp"
                android:layout_weight="6"
                android:fontFamily="@font/pathway_gothic_one"
                android:gravity="center"
                android:padding="10dp"
                android:text="Is this the complaint you're looking for?"
                android:textColor="@color/white"
                android:textSize="30sp"
                />

    </LinearLayout>

    <RelativeLayout
            android:id="@+id/fazool"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:layout_alignParentBottom="true"
            android:background="@color/grey"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintBottom_toBottomOf="parent" />
    <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_below="@+id/textViewComplaint"
            android:background="@drawable/bottom_nav_border"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/textViewComplaint"
            app:layout_constraintBottom_toBottomOf="parent"
            >
        <ScrollView
                android:layout_height="wrap_content"
                android:layout_width = "match_parent">

            <include layout="@layout/existing_complaint_popup_inner"/>
        </ScrollView>

    </FrameLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

</code>```

答:
Thats my custom notification dialog codes. I think thats way easy and clear. I do not know why you use to fragment for custom dialog but you can use my way.</p>

```<code> val mDialogView = LayoutInflater.from(this).inflate(R.layout.permission_for_notification, null)
        //AlertDialogBuilder
        val mBuilder = AlertDialog
            .Builder(this)
            .setView(mDialogView)
        //show dialog
        val  mAlertDialog = mBuilder.show()

 mAlertDialog.window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)

        mDialogView.notification_accept_button.setOnClickListener {

            mAlertDialog.dismiss()
        }

        //cancel button click of custom layout
        mDialogView.notification_reject_button.setOnClickListener {

            mAlertDialog.dismiss()
        }
</code>```

Title: custom dialog fragment from a fragment

Body:
I've created a constraint layout and I am calling a dialog fragment from a fragment. But when I click on the button all it does is fades the screen but I can't see any dialog or the layout.

Here's my code for dialog fragment:

package com.example.atry.MakeComplaint

import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.DialogFragment

import com.example.atry.R

class PopupDialog : DialogFragment() {

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {

        val builder = AlertDialog.Builder(activity)

        return builder.create()

    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

        val view = inflater.inflate(R.layout.existing_complaint_popup, container, false)

        val yes = view.findViewById(R.id.YES) as Button
        val no = view.findViewById(R.id.NO) as Button

        // set onclicklistener
        yes.setOnClickListener(View.OnClickListener {
            // I want the dialog to close at this point
            dismiss()
            backFragment()

        })

        // set onclicklistener
        no.setOnClickListener(View.OnClickListener {
            // I want the dialog to close at this point
            dismiss()
            descriptionFragment()

        })

        return view
    }

    private fun backFragment() {
        val manager = (context as AppCompatActivity).supportFragmentManager
        manager.popBackStackImmediate()

    }

    private fun descriptionFragment() {
        val dFragment= Category_Description()
        val lFragment = LocationFragment()
        val manager = (context as AppCompatActivity).supportFragmentManager
        val transaction =  manager.beginTransaction()
        transaction.replace(
            R.id.location_screen,
            dFragment
        ) // give your fragment container id in first parameter
        transaction.show(dFragment)
        transaction.hide(lFragment)
        transaction.isAddToBackStackAllowed
        transaction.addToBackStack(lFragment.fragmentManager.toString())  // if written, this transaction will be added to backstack
        transaction.commit()
    }

}

Here's the code inside the fragment I'm calling the dialog from:

 //opening up the checkExisting popup

    private fun existPopup(){
        val fm = activity!!.supportFragmentManager
        val dialog = PopupDialog() // creating new object
        dialog.show(fm, "dialog")
    }

And here's my layout:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools">

    <LinearLayout
            android:id="@+id/textViewComplaint"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_above="@+id/complainDescription"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toTopOf="@id/textViewComplaint"
            >

        <TextView
                android:id="@+id/headingComplain"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_alignParentTop="true"
                android:layout_marginBottom="10dp"
                android:layout_weight="6"
                android:fontFamily="@font/pathway_gothic_one"
                android:gravity="center"
                android:padding="10dp"
                android:text="Is this the complaint you're looking for?"
                android:textColor="@color/white"
                android:textSize="30sp"
                />

    </LinearLayout>

    <RelativeLayout
            android:id="@+id/fazool"
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:layout_alignParentBottom="true"
            android:background="@color/grey"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintBottom_toBottomOf="parent" />
    <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_below="@+id/textViewComplaint"
            android:background="@drawable/bottom_nav_border"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/textViewComplaint"
            app:layout_constraintBottom_toBottomOf="parent"
            >
        <ScrollView
                android:layout_height="wrap_content"
                android:layout_width = "match_parent">

            <include layout="@layout/existing_complaint_popup_inner"/>
        </ScrollView>

    </FrameLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

Body:
Thats my custom notification dialog codes. I think thats way easy and clear. I do not know why you use to fragment for custom dialog but you can use my way.

 val mDialogView = LayoutInflater.from(this).inflate(R.layout.permission_for_notification, null)
        //AlertDialogBuilder
        val mBuilder = AlertDialog
            .Builder(this)
            .setView(mDialogView)
        //show dialog
        val  mAlertDialog = mBuilder.show()

 mAlertDialog.window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)

        mDialogView.notification_accept_button.setOnClickListener {

            mAlertDialog.dismiss()
        }

        //cancel button click of custom layout
        mDialogView.notification_reject_button.setOnClickListener {

            mAlertDialog.dismiss()
        }


问:
Is here has "CreatePipe" and "CreateProcessW" function in Linux?
How to use the function of "CreatePipe" and "CreateProcessW" in Linux, when I compile the C++ code in Linux, there have some errors as follow: 'CreatePipe' was not declared in this scope. 'CreateProcessW' was not declared in this scope.</p>

答:
Posix/Linux:

```<code>int pipe(int pipefd[2]);
</code>```

pipefd[0] refers to the read end of the pipe.

pipefd[1] refers to the write end of the pipe.

Linux specific:

```<code>int pipe2(int pipefd[2], int flags);
</code>```

When it comes to CreateProcess, the Posix/Linux version is done in a few steps.

Call fork() to create a new process - still running the same program - so two processes will now continue running the same program from the same point where fork() was called. Determining if it's the parent process or child process is done by checking the return value (the process id) from fork().

dup the file descriptors returned by pipe using int dup2(int oldfd, int newfd); to replace stdin and stdout for the new process.

Execute a program in the new process using one of the exec* functions.

```<code>// create pipes here

if(pid_t pid = fork(); pid == -1) {
    // fork failed

} else if(pid == 0) { // child process goes here (with a new process id)
    // dup2(...)
    // exec*()

} else {              // parent process goes here
    // do parenting stuff
}
</code>```

Example:

```<code>#include <unistd.h>
#include <sys/types.h>

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <stdexcept>

struct Pipe {
    Pipe() {
        if(pipe(io)) throw std::runtime_error("pipe failure");
    }
    ~Pipe() {
        close_rd();
        close_wr();
    }
    void close_rd() { closer(io[0]); }
    void close_wr() { closer(io[1]); }
    int rd() { return io[0]; }
    int wr() { return io[1]; }

private:
    void closer(int& fd) {
        if(fd != -1) {
            close(fd);
            fd = -1;
        }
    }
    int io[2];
};

int main() {
    Pipe parent_write, parent_read;

    if(pid_t pid = fork(); pid == -1) {
        // fork failed
        return 1;

    } else if(pid == 0) {   // child process goes here (with a new process id)
        // close file descriptors we don't need:
        parent_write.close_wr();
        parent_read.close_rd();

        // duplicate into the place where stdin/stdout was
        dup2(parent_write.rd(), fileno(stdin));
        dup2(parent_read.wr(), fileno(stdout));

        // execute a program
        execl("/bin/ls", "/bin/ls", nullptr);
        // exec* functions never returns if successful, so if we get here, it failed:
        std::exit(1);

    } else {               // parent process goes here
        std::cout << "child process " << pid << " started\n";
    }

    // close file descriptors we don't need:
    parent_write.close_rd();
    parent_read.close_wr();

    // read data from child process using the file descriptor in parent_read.rd()
    char buf[1024];
    ssize_t rv;
    while((rv = read(parent_read.rd(), buf, 1024))) {
        write(fileno(stdout), buf, static_cast<size_t>(rv));
    }

    // use write(parent_write.wr(), ...) to write to the child.
}
</code>```

Body:
Posix/Linux:

int pipe(int pipefd[2]);

pipefd[0] refers to the read end of the pipe.

pipefd[1] refers to the write end of the pipe.

Linux specific:

int pipe2(int pipefd[2], int flags);

When it comes to CreateProcess, the Posix/Linux version is done in a few steps.

Call fork() to create a new process - still running the same program - so two processes will now continue running the same program from the same point where fork() was called. Determining if it's the parent process or child process is done by checking the return value (the process id) from fork().

dup the file descriptors returned by pipe using int dup2(int oldfd, int newfd); to replace stdin and stdout for the new process.

Execute a program in the new process using one of the exec* functions.

// create pipes here

if(pid_t pid = fork(); pid == -1) {
    // fork failed

} else if(pid == 0) { // child process goes here (with a new process id)
    // dup2(...)
    // exec*()

} else {              // parent process goes here
    // do parenting stuff
}

Example:

#include <unistd.h>
#include <sys/types.h>

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <stdexcept>

struct Pipe {
    Pipe() {
        if(pipe(io)) throw std::runtime_error("pipe failure");
    }
    ~Pipe() {
        close_rd();
        close_wr();
    }
    void close_rd() { closer(io[0]); }
    void close_wr() { closer(io[1]); }
    int rd() { return io[0]; }
    int wr() { return io[1]; }

private:
    void closer(int& fd) {
        if(fd != -1) {
            close(fd);
            fd = -1;
        }
    }
    int io[2];
};

int main() {
    Pipe parent_write, parent_read;

    if(pid_t pid = fork(); pid == -1) {
        // fork failed
        return 1;

    } else if(pid == 0) {   // child process goes here (with a new process id)
        // close file descriptors we don't need:
        parent_write.close_wr();
        parent_read.close_rd();

        // duplicate into the place where stdin/stdout was
        dup2(parent_write.rd(), fileno(stdin));
        dup2(parent_read.wr(), fileno(stdout));

        // execute a program
        execl("/bin/ls", "/bin/ls", nullptr);
        // exec* functions never returns if successful, so if we get here, it failed:
        std::exit(1);

    } else {               // parent process goes here
        std::cout << "child process " << pid << " started\n";
    }

    // close file descriptors we don't need:
    parent_write.close_rd();
    parent_read.close_wr();

    // read data from child process using the file descriptor in parent_read.rd()
    char buf[1024];
    ssize_t rv;
    while((rv = read(parent_read.rd(), buf, 1024))) {
        write(fileno(stdout), buf, static_cast<size_t>(rv));
    }

    // use write(parent_write.wr(), ...) to write to the child.
}


问:
Gitlab configuration postgresql service
Just getting started with GitLab and I can't seem to get my configuration working. I'm using the following:

```<code>image: maven:3.3-jdk-8-alpine

stages:
  - prepare
  - build

services:
  - postgres:latest

variables:
  POSTGRES_DB: my_database
  POSTGRES_USER: runner
  POSTGRES_PASSWORD: runner

prepare_db:
  stage: prepare
  image: postgres
  script:
  - export PGPASSWORD=$POSTGRES_PASSWORD
  - psql -h "postgres" -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "CREATE EXTENSION \"uuid-ossp\";"

build:
  stage: build
  script: mvn clean test
</code>```

It works fine if I simply want to compile my code, the build would then simply be mvn clean compile but to run the tests I need a PostgreSQL instance. In my code I rely on UUIDs so I need to ensure that the uuid-ossp extension is installed.

In my prepare_db job I can connect to the Postgres instance and execute the command, I have also verified that the extension is installed properly by issuing a second script command SELECT uuid_generate_v4(); and it returns a uuid.

When the runner gets to the build job it keeps telling me that the uuid_generate_v4() function is not present. Is my  prepare_db job being run on a different Postgres instance?

答:
It is happening because prepare_db job is completely isolated from build job. So basically it doesn't prepare anything. To fix it do next steps:</p>

```<code>.prepare_db: &prepare_db |
  export PGPASSWORD=$POSTGRES_PASSWORD
  psql -h "postgres" -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "CREATE EXTENSION \"uuid-ossp\";"

build:
  stage: build
  script:
  - *prepare_db
  - mvn clean test
</code>```

Title: Gitlab configuration postgresql service

Body:
Just getting started with GitLab and I can't seem to get my configuration working. I'm using the following:

image: maven:3.3-jdk-8-alpine

stages:
  - prepare
  - build

services:
  - postgres:latest

variables:
  POSTGRES_DB: my_database
  POSTGRES_USER: runner
  POSTGRES_PASSWORD: runner

prepare_db:
  stage: prepare
  image: postgres
  script:
  - export PGPASSWORD=$POSTGRES_PASSWORD
  - psql -h "postgres" -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "CREATE EXTENSION \"uuid-ossp\";"

build:
  stage: build
  script: mvn clean test

It works fine if I simply want to compile my code, the build would then simply be mvn clean compile but to run the tests I need a PostgreSQL instance. In my code I rely on UUIDs so I need to ensure that the uuid-ossp extension is installed.

In my prepare_db job I can connect to the Postgres instance and execute the command, I have also verified that the extension is installed properly by issuing a second script command SELECT uuid_generate_v4(); and it returns a uuid.

When the runner gets to the build job it keeps telling me that the uuid_generate_v4() function is not present. Is my  prepare_db job being run on a different Postgres instance?

Body:
It is happening because prepare_db job is completely isolated from build job. So basically it doesn't prepare anything. To fix it do next steps:

.prepare_db: &prepare_db |
  export PGPASSWORD=$POSTGRES_PASSWORD
  psql -h "postgres" -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "CREATE EXTENSION \"uuid-ossp\";"

build:
  stage: build
  script:
  - *prepare_db
  - mvn clean test


问:
How to control docker-compose build order?
I have three services to build, A、B and C. A should be built in the very first place, because B and C depend on A (they import A as image). I thought they should be built in order but I just find out they are built in some random order?

So, how do I control build order in docker-compose.yml?

答:
As stated in https://github.com/docker/compose/blob/e9220f45df07c1f884d5d496507778d2cd4a1687/compose/project.py#L182-L183

Preserves the original order of self.services where possible, reordering as needed to resolve dependencies.

So for me it worked by manually sorting the services with the depending services at first and following the services which is used by the other and the other as last.

Example

```<code>version: '3'
services:
    mydb:
        image: mydb
    serviceA:
        build:
            dockerfile: DockerfileA
        depends_on:
            - mydb
    serviceB:
        build:
            dockerfile: DockerfileB # which contains 'FROM serviceA'
        depends_on:
            - mydb
</code>```

Source: https://github.com/docker/compose/issues/5228#issuecomment-565469948

Body:
As stated in https://github.com/docker/compose/blob/e9220f45df07c1f884d5d496507778d2cd4a1687/compose/project.py#L182-L183

Preserves the original order of self.services where possible, reordering as needed to resolve dependencies.

So for me it worked by manually sorting the services with the depending services at first and following the services which is used by the other and the other as last.

Example

version: '3'
services:
    mydb:
        image: mydb
    serviceA:
        build:
            dockerfile: DockerfileA
        depends_on:
            - mydb
    serviceB:
        build:
            dockerfile: DockerfileB # which contains 'FROM serviceA'
        depends_on:
            - mydb

Source: https://github.com/docker/compose/issues/5228#issuecomment-565469948


问:
How to configure my vim to help me find the definition of terms?
For example, when I encounter:

```<code>funcMiracle (argMagic);
</code>```

I want to press a button, and woosh, I immediately jump to the definition of funcMiracle, regardless of it is in the current file or not.

答:
Updated

Since I read your comment:

The question is, though it can help me find any function in my project, it won't automatically find the external functions that I probably linked from a header file, for example, the definition of fgets() in stdio.h

Have a look at

C-[C-I for include file search

C-[d for and definition lookup

Shift-K opens up the man page for the identifier under the cursor (e.g. fgets :)

With the man.vim script you can also summon the manpage inside a Vim buffer for easy copy/paste, highlighting, crossreference like with helptags etc. Key: Leader-K

Once again, :he ^[^I etc. are good pointers for more help/details

Tags on external projects

You can generate tags for an external project (say, linux headers) using ctags as shown earlier (below). It then a matter of letting Vim know where your tags are:

```<code>:se tags+=/usr/src/linux/tags
</code>```

Note the +=: Vim can handle multiple tags files at once

The standard approach

install (if you haven't), ctags

:!ctags % (or for recursive whole folder etc :!ctags -R %:h or :!ctags **/*.c etc)

use tags (C-] or Ctrl-MouseButton, see :help tags for complete reference)

You can integrate the building of tags in your makefile if you have one. Exuberant ctags is highly configurable; I routinely use

```<code>ctags --exclude=packagedir -R --c++-kinds=+p --fields=+iaS --extra=+q
</code>```

for use with C++, but it supports many many languages out of the box with zero configuration.

Body:
For example, when I encounter:

funcMiracle (argMagic);

I want to press a button, and woosh, I immediately jump to the definition of funcMiracle, regardless of it is in the current file or not.

Body:
Updated

Since I read your comment:

The question is, though it can help me find any function in my project, it won't automatically find the external functions that I probably linked from a header file, for example, the definition of fgets() in stdio.h

Have a look at

C-[C-I for include file search

C-[d for and definition lookup

Shift-K opens up the man page for the identifier under the cursor (e.g. fgets :)

With the man.vim script you can also summon the manpage inside a Vim buffer for easy copy/paste, highlighting, crossreference like with helptags etc. Key: Leader-K

Once again, :he ^[^I etc. are good pointers for more help/details

Tags on external projects

You can generate tags for an external project (say, linux headers) using ctags as shown earlier (below). It then a matter of letting Vim know where your tags are:

:se tags+=/usr/src/linux/tags

Note the +=: Vim can handle multiple tags files at once

The standard approach

install (if you haven't), ctags

:!ctags % (or for recursive whole folder etc :!ctags -R %:h or :!ctags **/*.c etc)

use tags (C-] or Ctrl-MouseButton, see :help tags for complete reference)

You can integrate the building of tags in your makefile if you have one. Exuberant ctags is highly configurable; I routinely use

ctags --exclude=packagedir -R --c++-kinds=+p --fields=+iaS --extra=+q

for use with C++, but it supports many many languages out of the box with zero configuration.


问:
VBA HTML Adressing with .getElements
I have following HTML

and I am trying to get the highlighted Date.

This is my code but it doesn't work. I get

"object doesnt support this property or method" :

```<code>Set sammel = HTMLDoc.getElementsByClassName("date").innerText

</code>```

Here is the complete Code

```<code>Sub testalt()

Dim HTMLInput As MSHTML.IHTMLElement
Dim HTMLInput2 As MSHTML.IHTMLElement
Dim HTMLDoc As MSHTML.HTMLDocument
Dim HTMLButtons As MSHTML.IHTMLElementCollection
Dim ie As InternetExplorerMedium
Dim buttonsubmit As HTMLButtonElement
Dim sammel As String

Set ie = New InternetExplorerMedium
ie.Visible = True
ie.navigate "https://plm.corp.int/&showInitialResults=true&cancelLabel=Close&minRequiredChars=3&genericDelete=true&selection=multiple&txtTextSearch=e2711846&filters={%27txtTextSearch%27:[%27Equals|e2711846%27]}
Do While ie.readyState <> READYSTATE_COMPLETE
Loop

'Seite öffnen und Wert in Suche geben
Set HTMLDoc = ie.document
Set HTMLInput = HTMLDoc.getElementById("txtTextSearch")
Set HTMLInput2 = HTMLDoc.getElementById("mx_btn-search")
HTMLInput.Value = "e2711846"
HTMLInput.FireEvent ("onkeyup")
HTMLInput2.Click

''Nach neuester Version suchen

sammel = HTMLDoc.getElementsByClassName("date")(0).innerText

End Sub
</code>```

sammel remains empty. can there be a problem with my page not refreshing or something ? Because im opening a search windows, then typing in the searchterm and searching for it. but the URL remains the same in the newly opened window. It is a javascript thingy i think

答:
There can exist more than one HTML tag that has a class="date" so HTMLDoc.getElementsByClassName("date") is an array of these elements.

If you assume multiple elements with class="date" you need to loop through them. Or you can get the first of them by using:

```<code>Dim sammel As Object
Set sammel = HTMLDoc.getElementsByClassName("date")(0)
Debug.Print sammel.innerText
</code>```

Note that you can only Set an object but innerText returns a string (text). So either something like the above one or without Set

```<code>Dim sammel As String
sammel = HTMLDoc.getElementsByClassName("date")(0).innerText
</code>```

Title: VBA HTML Adressing with .getElements

Body:
I have following HTML

and I am trying to get the highlighted Date.

This is my code but it doesn't work. I get

"object doesnt support this property or method" :

Set sammel = HTMLDoc.getElementsByClassName("date").innerText

Here is the complete Code

Sub testalt()

Dim HTMLInput As MSHTML.IHTMLElement
Dim HTMLInput2 As MSHTML.IHTMLElement
Dim HTMLDoc As MSHTML.HTMLDocument
Dim HTMLButtons As MSHTML.IHTMLElementCollection
Dim ie As InternetExplorerMedium
Dim buttonsubmit As HTMLButtonElement
Dim sammel As String

Set ie = New InternetExplorerMedium
ie.Visible = True
ie.navigate "https://plm.corp.int/&showInitialResults=true&cancelLabel=Close&minRequiredChars=3&genericDelete=true&selection=multiple&txtTextSearch=e2711846&filters={%27txtTextSearch%27:[%27Equals|e2711846%27]}
Do While ie.readyState <> READYSTATE_COMPLETE
Loop

'Seite öffnen und Wert in Suche geben
Set HTMLDoc = ie.document
Set HTMLInput = HTMLDoc.getElementById("txtTextSearch")
Set HTMLInput2 = HTMLDoc.getElementById("mx_btn-search")
HTMLInput.Value = "e2711846"
HTMLInput.FireEvent ("onkeyup")
HTMLInput2.Click

''Nach neuester Version suchen

sammel = HTMLDoc.getElementsByClassName("date")(0).innerText

End Sub

sammel remains empty. can there be a problem with my page not refreshing or something ? Because im opening a search windows, then typing in the searchterm and searching for it. but the URL remains the same in the newly opened window. It is a javascript thingy i think

Body:
There can exist more than one HTML tag that has a class="date" so HTMLDoc.getElementsByClassName("date") is an array of these elements.

If you assume multiple elements with class="date" you need to loop through them. Or you can get the first of them by using:

Dim sammel As Object
Set sammel = HTMLDoc.getElementsByClassName("date")(0)
Debug.Print sammel.innerText

Note that you can only Set an object but innerText returns a string (text). So either something like the above one or without Set

Dim sammel As String
sammel = HTMLDoc.getElementsByClassName("date")(0).innerText


问:
Failed to execute goal org.codehaus.cargo:cargo-maven2-plugin:1.4.4:redeploy (deploy) on project duke tutoring
```<code>Failed to execute goal org.codehaus.cargo:cargo-maven2-plugin:1.4.4:redeploy (deploy) on project dukes-tutoring-war: Execution deploy of goal org.codehaus.cargo:cargo-maven2-plugin:1.4.4:redeploy failed: Failed to create deployer with implementation class org.codehaus.cargo.container.glassfish.GlassFish4xInstalledLocalDeployer for the parameters (container [id = [glassfish4x]], deployer type [installed]). InvocationTargetException: The container configuration directory "/home/yogesh/Downloads/glassfish4/glassfish4/glassfish/domains" does not exist. Please configure the container before attempting to perform any local deployment. Read more on: http://cargo.codehaus.org/Local+Configuration -> [Help 1]

To see the full stack trace of the errors, re-run Maven with the -e switch.
Re-run Maven using the -X switch to enable full debug logging.

For more information about the errors and possible solutions, please read the following articles:
[Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginExecutionException

After correcting the problems, you can resume the build with the command
  mvn <goals> -rf :dukes-tutoring-war
</code>```

my pom.xml fromdukes-tutoring-war ---------

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <artifactId>dukes-tutoring</artifactId>
        <groupId>org.glassfish.javaeetutorial</groupId>
        <version>7.0.5</version>
    </parent>

    <groupId>org.glassfish.javaeetutorial</groupId>
    <artifactId>dukes-tutoring-war</artifactId>
    <packaging>war</packaging>

    <name>dukes-tutoring-war</name>
    <dependencies>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>dukes-tutoring-common</artifactId>
            <version>${project.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>${maven.exec.plugin.version}</version>
                <executions>
                    <execution>
                        <id>create-tutoring-realm</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>exec</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <skip>false</skip>
                    <executable>/home/yogesh/Downloads/glassfish4/glassfish/bin/asadmin${glassfish.executables.suffix}</executable>
                    <arguments>
                        <argument>create-auth-realm</argument>
                        <argument>--classname</argument>
                        <argument>com.sun.enterprise.security.auth.realm.jdbc.JDBCRealm</argument>
                        <argument>--property</argument>
                        <argument>jaas-context=jdbcRealm:datasource-jndi='java:global/TutoringDataSource':user-table=tutoring.PERSON:user-name-column=email:password-column=password:group-table=tutoring.PERSON:group-name-column=DTYPE:digest-algorithm=none</argument>
                        <argument>tutoringRealm</argument>
                    </arguments>
                    <successCodes>
                        <successCode>0</successCode>
                        <successCode>1</successCode>
                    </successCodes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
```

<p>The pom in examples folder for <code><glassfish.home.prefix></code> settings </p>

<pre class="lang-xml prettyprint-override"><code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.glassfish.javaeetutorial</groupId>
    <artifactId>javaeetutorial</artifactId>
    <version>7.0.5</version>
    <packaging>pom</packaging>
    <name>javaeetutorial</name>

    <scm>
        <connection>scm:svn:https://svn.java.net/svn/javaeetutorial~svn/tags/javaeetutorial-7.0.0</connection>
        <developerConnection>scm:svn:https://svn.java.net/svn/javaeetutorial~svn/tags/javaeetutorial-7.0.0</developerConnection>
    </scm>
    <issueManagement>
        <system>IssueTracker</system>
        <url>http://java.net/jira/browse/JAVAEETUTORIAL</url>
    </issueManagement>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <javaee.api.version>7.0</javaee.api.version>
        <maven.compiler.plugin.version>3.1</maven.compiler.plugin.version>
        <maven.source.plugin.version>2.2.1</maven.source.plugin.version>
        <maven.clean.plugin.version>2.5</maven.clean.plugin.version>
        <maven.war.plugin.version>2.3</maven.war.plugin.version>
        <maven.acr.plugin.version>1.0</maven.acr.plugin.version>
        <maven.ear.plugin.version>2.8</maven.ear.plugin.version>
        <maven.ejb.plugin.version>2.3</maven.ejb.plugin.version>
        <maven.jar.plugin.version>2.4</maven.jar.plugin.version>
        <maven.rar.plugin.version>2.3</maven.rar.plugin.version>
        <maven.license.plugin.version>1.10.b1</maven.license.plugin.version>
        <maven.release.plugin.version>2.4.1</maven.release.plugin.version>
        <maven.exec.plugin.version>1.2.1</maven.exec.plugin.version>
        <junit.version>4.11</junit.version>
        <eclipselink.version>2.5.0</eclipselink.version>
        <glassfish.embedded.version>4.0</glassfish.embedded.version>
        <cargo.plugin.version>1.4.4</cargo.plugin.version>
        <glassfish.domain.name>domain1</glassfish.domain.name>
        <glassfish.home>${glassfish.home.prefix}/glassfish4</glassfish.home>
        <integration.container.id>glassfish4x</integration.container.id>
    </properties>

    <profiles>
        <profile>
            <id>windows</id>
            <activation>
                <os>
                    <family>windows</family>
                </os>
            </activation>
            <properties>
                <glassfish.home.prefix>c:/</glassfish.home.prefix>
                <glassfish.executables.suffix>.bat</glassfish.executables.suffix>
            </properties>
        </profile>
        <profile>
            <id>unix</id>
            <activation>
                <os>
                    <family>unix</family>
                </os>
            </activation>
            <properties>
                <glassfish.home.prefix>/home/yogesh/Downloads/glassfish4</glassfish.home.prefix>
                <glassfish.executables.suffix />
            </properties>
        </profile>
        <profile>
            <id>sdk</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>
                <glassfish.home>${basedir}/../../../</glassfish.home>
            </properties>
        </profile>
        <profile>
            <id>development</id>
            <activation>
                <file>
                    <exists>${basedir}/../bundle</exists>
                </file>
            </activation>
            <properties>
                <glassfish.home>${glassfish.home.prefix}/glassfish4</glassfish.home>
            </properties>
        </profile>
        <profile>
            <id>standalone</id>
            <properties>
                <glassfish.home>${basedir}/target/cargo/installs/glassfish</glassfish.home>
                <cargo.maven.containerUrl>http://dlc.sun.com.edgesuite.net/glassfish/4.0/promoted/latest-glassfish.zip</cargo.maven.containerUrl>
            </properties>
        </profile>
    </profiles>

    <modules>
        <module>archetypes</module>
        <module>batch</module>
        <module>case-studies</module>
        <module>cdi</module>
        <module>concurrency</module>
        <module>connectors</module>
        <module>ejb</module>
        <module>jaxrs</module>
        <module>jaxws</module>
        <module>jms</module>
        <module>persistence</module>
        <module>security</module>
        <module>web</module>
    </modules>

    <repositories>
        <repository>
            <id>snapshot-repository.java.net</id>
            <name>Java.net Snapshot Repository for Maven</name>
            <url>https://maven.java.net/content/repositories/staging/</url>
            <layout>default</layout>
        </repository>
        <repository>
            <id>releases-repository.java.net</id>
            <name>Java.net releases Repository for Maven</name>
            <url>https://maven.java.net/content/repositories/releases/</url>
            <layout>default</layout>
        </repository>
    </repositories>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>${maven.compiler.plugin.version}</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-source-plugin</artifactId>
                    <version>${maven.source.plugin.version}</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>${maven.clean.plugin.version}</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>${maven.war.plugin.version}</version>
                </plugin>
                <plugin>
                    <groupId>org.codehaus.cargo</groupId>
                    <artifactId>cargo-maven2-plugin</artifactId>
                    <version>${cargo.plugin.version}</version>
                </plugin>
            </plugins>
        </pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.codehaus.cargo</groupId>
                <artifactId>cargo-maven2-plugin</artifactId>
                <inherited>true</inherited>
                <executions>
                    <execution>
                        <id>deploy</id>
                        <phase>integration-test</phase>
                        <goals>
                            <goal>redeploy</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <container>
                        <containerId>${integration.container.id}</containerId>
                        <type>installed</type>
                        <home>${glassfish.home}</home>
                    </container>
                    <configuration>
                        <type>existing</type>
                        <home>${glassfish.home}/glassfish/domains</home>
                        <properties>
                            <cargo.glassfish.domain.name>${glassfish.domain.name}</cargo.glassfish.domain.name>
                            <!--cargo.remote.username></cargo.remote.username-->
                            <cargo.remote.password />
                        </properties>
                    </configuration>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven.compiler.plugin.version}</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>com.mycila.maven-license-plugin</groupId>
                <artifactId>maven-license-plugin</artifactId>
                <version>${maven.license.plugin.version}</version>
                <configuration>
                    <header>common/license.txt</header>
                    <excludes>
                        <exclude>common/**</exclude>
                        <exclude>**/META-INF/**</exclude>
                        <exclude>**/WEB-INF/**</exclude>
                        <exclude>**/nbactions.xml</exclude>
                        <exclude>**/nb-configuration.xml</exclude>
                        <exclude>**/glassfish-resources.xml</exclude>
                        <exclude>**/simple-flow-flow.xml</exclude>
                    </excludes>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-release-plugin</artifactId>
                <version>${maven.release.plugin.version}</version>
                <configuration>
                    <!--
                     During release:perform, enable the "sdk" profile
                    -->
                    <releaseProfiles>sdk</releaseProfiles>
                    <autoVersionSubmodules>true</autoVersionSubmodules>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>${javaee.api.version}</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

</project>
</code>```

my glassfish4 location: /home/yogesh/Downloads/glassfish4
apache maven location: /opt/apache-maven-3.3.9

答:
This might also relate to the version of you glassfish server, I solved the same problem by switching to glassfish4.1.

this line in the exception message:

```<code>(container [id = [glassfish4x]], deployer type [installed])
</code>```

is probably searching for the glassfish4 version,

Body:
Failed to execute goal org.codehaus.cargo:cargo-maven2-plugin:1.4.4:redeploy (deploy) on project dukes-tutoring-war: Execution deploy of goal org.codehaus.cargo:cargo-maven2-plugin:1.4.4:redeploy failed: Failed to create deployer with implementation class org.codehaus.cargo.container.glassfish.GlassFish4xInstalledLocalDeployer for the parameters (container [id = [glassfish4x]], deployer type [installed]). InvocationTargetException: The container configuration directory "/home/yogesh/Downloads/glassfish4/glassfish4/glassfish/domains" does not exist. Please configure the container before attempting to perform any local deployment. Read more on: http://cargo.codehaus.org/Local+Configuration -> [Help 1]

To see the full stack trace of the errors, re-run Maven with the -e switch.
Re-run Maven using the -X switch to enable full debug logging.

For more information about the errors and possible solutions, please read the following articles:
[Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginExecutionException

After correcting the problems, you can resume the build with the command
  mvn <goals> -rf :dukes-tutoring-war

my pom.xml fromdukes-tutoring-war ---------

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <artifactId>dukes-tutoring</artifactId>
        <groupId>org.glassfish.javaeetutorial</groupId>
        <version>7.0.5</version>
    </parent>

    <groupId>org.glassfish.javaeetutorial</groupId>
    <artifactId>dukes-tutoring-war</artifactId>
    <packaging>war</packaging>

    <name>dukes-tutoring-war</name>
    <dependencies>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>dukes-tutoring-common</artifactId>
            <version>${project.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>${maven.exec.plugin.version}</version>
                <executions>
                    <execution>
                        <id>create-tutoring-realm</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>exec</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <skip>false</skip>
                    <executable>/home/yogesh/Downloads/glassfish4/glassfish/bin/asadmin${glassfish.executables.suffix}</executable>
                    <arguments>
                        <argument>create-auth-realm</argument>
                        <argument>--classname</argument>
                        <argument>com.sun.enterprise.security.auth.realm.jdbc.JDBCRealm</argument>
                        <argument>--property</argument>
                        <argument>jaas-context=jdbcRealm:datasource-jndi='java:global/TutoringDataSource':user-table=tutoring.PERSON:user-name-column=email:password-column=password:group-table=tutoring.PERSON:group-name-column=DTYPE:digest-algorithm=none</argument>
                        <argument>tutoringRealm</argument>
                    </arguments>
                    <successCodes>
                        <successCode>0</successCode>
                        <successCode>1</successCode>
                    </successCodes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

The pom in examples folder for <glassfish.home.prefix> settings

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.glassfish.javaeetutorial</groupId>
    <artifactId>javaeetutorial</artifactId>
    <version>7.0.5</version>
    <packaging>pom</packaging>
    <name>javaeetutorial</name>

    <scm>
        <connection>scm:svn:https://svn.java.net/svn/javaeetutorial~svn/tags/javaeetutorial-7.0.0</connection>
        <developerConnection>scm:svn:https://svn.java.net/svn/javaeetutorial~svn/tags/javaeetutorial-7.0.0</developerConnection>
    </scm>
    <issueManagement>
        <system>IssueTracker</system>
        <url>http://java.net/jira/browse/JAVAEETUTORIAL</url>
    </issueManagement>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <javaee.api.version>7.0</javaee.api.version>
        <maven.compiler.plugin.version>3.1</maven.compiler.plugin.version>
        <maven.source.plugin.version>2.2.1</maven.source.plugin.version>
        <maven.clean.plugin.version>2.5</maven.clean.plugin.version>
        <maven.war.plugin.version>2.3</maven.war.plugin.version>
        <maven.acr.plugin.version>1.0</maven.acr.plugin.version>
        <maven.ear.plugin.version>2.8</maven.ear.plugin.version>
        <maven.ejb.plugin.version>2.3</maven.ejb.plugin.version>
        <maven.jar.plugin.version>2.4</maven.jar.plugin.version>
        <maven.rar.plugin.version>2.3</maven.rar.plugin.version>
        <maven.license.plugin.version>1.10.b1</maven.license.plugin.version>
        <maven.release.plugin.version>2.4.1</maven.release.plugin.version>
        <maven.exec.plugin.version>1.2.1</maven.exec.plugin.version>
        <junit.version>4.11</junit.version>
        <eclipselink.version>2.5.0</eclipselink.version>
        <glassfish.embedded.version>4.0</glassfish.embedded.version>
        <cargo.plugin.version>1.4.4</cargo.plugin.version>
        <glassfish.domain.name>domain1</glassfish.domain.name>
        <glassfish.home>${glassfish.home.prefix}/glassfish4</glassfish.home>
        <integration.container.id>glassfish4x</integration.container.id>
    </properties>

    <profiles>
        <profile>
            <id>windows</id>
            <activation>
                <os>
                    <family>windows</family>
                </os>
            </activation>
            <properties>
                <glassfish.home.prefix>c:/</glassfish.home.prefix>
                <glassfish.executables.suffix>.bat</glassfish.executables.suffix>
            </properties>
        </profile>
        <profile>
            <id>unix</id>
            <activation>
                <os>
                    <family>unix</family>
                </os>
            </activation>
            <properties>
                <glassfish.home.prefix>/home/yogesh/Downloads/glassfish4</glassfish.home.prefix>
                <glassfish.executables.suffix />
            </properties>
        </profile>
        <profile>
            <id>sdk</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>
                <glassfish.home>${basedir}/../../../</glassfish.home>
            </properties>
        </profile>
        <profile>
            <id>development</id>
            <activation>
                <file>
                    <exists>${basedir}/../bundle</exists>
                </file>
            </activation>
            <properties>
                <glassfish.home>${glassfish.home.prefix}/glassfish4</glassfish.home>
            </properties>
        </profile>
        <profile>
            <id>standalone</id>
            <properties>
                <glassfish.home>${basedir}/target/cargo/installs/glassfish</glassfish.home>
                <cargo.maven.containerUrl>http://dlc.sun.com.edgesuite.net/glassfish/4.0/promoted/latest-glassfish.zip</cargo.maven.containerUrl>
            </properties>
        </profile>
    </profiles>

    <modules>
        <module>archetypes</module>
        <module>batch</module>
        <module>case-studies</module>
        <module>cdi</module>
        <module>concurrency</module>
        <module>connectors</module>
        <module>ejb</module>
        <module>jaxrs</module>
        <module>jaxws</module>
        <module>jms</module>
        <module>persistence</module>
        <module>security</module>
        <module>web</module>
    </modules>

    <repositories>
        <repository>
            <id>snapshot-repository.java.net</id>
            <name>Java.net Snapshot Repository for Maven</name>
            <url>https://maven.java.net/content/repositories/staging/</url>
            <layout>default</layout>
        </repository>
        <repository>
            <id>releases-repository.java.net</id>
            <name>Java.net releases Repository for Maven</name>
            <url>https://maven.java.net/content/repositories/releases/</url>
            <layout>default</layout>
        </repository>
    </repositories>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>${maven.compiler.plugin.version}</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-source-plugin</artifactId>
                    <version>${maven.source.plugin.version}</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>${maven.clean.plugin.version}</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>${maven.war.plugin.version}</version>
                </plugin>
                <plugin>
                    <groupId>org.codehaus.cargo</groupId>
                    <artifactId>cargo-maven2-plugin</artifactId>
                    <version>${cargo.plugin.version}</version>
                </plugin>
            </plugins>
        </pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.codehaus.cargo</groupId>
                <artifactId>cargo-maven2-plugin</artifactId>
                <inherited>true</inherited>
                <executions>
                    <execution>
                        <id>deploy</id>
                        <phase>integration-test</phase>
                        <goals>
                            <goal>redeploy</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <container>
                        <containerId>${integration.container.id}</containerId>
                        <type>installed</type>
                        <home>${glassfish.home}</home>
                    </container>
                    <configuration>
                        <type>existing</type>
                        <home>${glassfish.home}/glassfish/domains</home>
                        <properties>
                            <cargo.glassfish.domain.name>${glassfish.domain.name}</cargo.glassfish.domain.name>

                            <cargo.remote.password />
                        </properties>
                    </configuration>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven.compiler.plugin.version}</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>com.mycila.maven-license-plugin</groupId>
                <artifactId>maven-license-plugin</artifactId>
                <version>${maven.license.plugin.version}</version>
                <configuration>
                    common/license.txt
                    <excludes>
                        <exclude>common/**</exclude>
                        <exclude>**/META-INF/**</exclude>
                        <exclude>**/WEB-INF/**</exclude>
                        <exclude>**/nbactions.xml</exclude>
                        <exclude>**/nb-configuration.xml</exclude>
                        <exclude>**/glassfish-resources.xml</exclude>
                        <exclude>**/simple-flow-flow.xml</exclude>
                    </excludes>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-release-plugin</artifactId>
                <version>${maven.release.plugin.version}</version>
                <configuration>

                    <releaseProfiles>sdk</releaseProfiles>
                    <autoVersionSubmodules>true</autoVersionSubmodules>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>${javaee.api.version}</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

</project>

my glassfish4 location: /home/yogesh/Downloads/glassfish4
apache maven location: /opt/apache-maven-3.3.9

Body:
This might also relate to the version of you glassfish server, I solved the same problem by switching to glassfish4.1.

this line in the exception message:

(container [id = [glassfish4x]], deployer type [installed])

is probably searching for the glassfish4 version,