问:
I have a stored procedure and I have made it using UNION ; how can I count total number of rows?
I need to count total number of rows from a query and that query have union. If I use Count(*), I get an error. So how can I get the count?

This is my code:

```<code>SELECT
    ProjectName, ProjectReference,
    ProjectID, SiteSupervisor,
    PrincipalContractor, PrincipalDesigner
FROM
    (SELECT
         ProjectName, ProjectReference,
         ProjectID, SiteSupervisor,
         PrincipalContractor, PrincipalDesigner
     FROM
         CompanyProjects
     WHERE
         EndDate < GETDATE()

     UNION

     (SELECT
          CompanyProjects.ProjectName AS ProjectName,
          CompanyProjects.ProjectReference AS ProjectReference,
          CompanyProjects.ProjectID AS ProjectID,
          CompanyProjects.SiteSupervisor AS SiteSupervisor,
          CompanyProjects.PrincipalContractor AS PrincipalContractor,
          CompanyProjects.PrincipalDesigner AS PrincipalDesigner
      FROM
          CompanyProjects
      INNER JOIN
          CompanyCurrentReview ON companyprojects.ProjectID = CompanyCurrentReview.ReviewProjectId
                               AND CompanyCurrentReview.IsReviewComplete = 0
                               AND CompanyCurrentReview.DateTime BETWEEN DATEADD(YEAR, -2, GETDATE()) AND GETDATE()
                               AND ProjectID NOT IN (SELECT ProjectID
                                                     FROM CompanyProjects
                                                     WHERE EndDate < GETDATE()))

     UNION

     (SELECT
          ProjectName, ProjectReference,
          ProjectID, SiteSupervisor,
          PrincipalContractor, PrincipalDesigner
      FROM
          CompanyProjects
      WHERE
          CreatedDate BETWEEN DATEADD(YEAR, -2, GETDATE()) AND GETDATE()
          AND ProjectID NOT IN ((SELECT CompanyProjects.ProjectID
                                 FROM CompanyProjects
                                 INNER JOIN CompanyCurrentReview ON companyprojects.ProjectID = CompanyCurrentReview.ReviewProjectId AND CompanyCurrentReview.IsReviewComplete = 0
    AND CompanyCurrentReview.DateTime between DateAdd(year,-2,GETDATE() ) AND GETDATE())
    UNION  SELECT ProjectID FROM
    CompanyProjects WHERE EndDate < GETDATE()))) As result order by ProjectID desc
</code>```

答:
You can try this:</p>

```<code>select count(*) from
(
SELECT ProjectName,ProjectReference,ProjectID,SiteSupervisor,PrincipalContractor,PrincipalDesigner FROM (SELECT  P ro jec tName,ProjectReference,ProjectID,SiteSupervisor,PrincipalContractor,PrincipalDesigner FROM
CompanyProjects WHERE EndDate < GETDATE()

UNION

(SELECT CompanyProjects.ProjectName As ProjectName, CompanyProjects.ProjectReference As ProjectReference, CompanyProjects.ProjectID As ProjectID,
CompanyProjects.SiteSupervisor As SiteSupervisor,
CompanyProjects.PrincipalContractor As PrincipalContractor, CompanyProjects.PrincipalDesigner As PrincipalDesigner
FROM CompanyProjects
INNER JOIN  CompanyCurrentReview ON companyprojects.ProjectID = CompanyCurrentReview.ReviewProjectId AND CompanyCurrentReview.IsReviewComplete = 0
AND CompanyCurrentReview.DateTime between DateAdd(year,-2,GETDATE() ) AND GETDATE()  AND ProjectID NOT IN(
SELECT ProjectID FROM
CompanyProjects WHERE EndDate < GETDATE()
))

UNION

(SELECT ProjectName,ProjectReference,ProjectID,SiteSupervisor,PrincipalContractor,PrincipalDesigner FROM
CompanyProjects WHERE CreatedDate  between DateAdd(year,-2,GETDATE() ) AND GETDATE() AND ProjectID NOT IN(
(SELECT CompanyProjects.ProjectID
FROM CompanyProjects
INNER JOIN  CompanyCurrentReview ON companyprojects.ProjectID = CompanyCurrentReview.ReviewProjectId AND CompanyCurrentReview.IsReviewComplete = 0
AND CompanyCurrentReview.DateTime between DateAdd(year,-2,GETDATE() ) AND GETDATE())
UNION  SELECT ProjectID FROM
CompanyProjects WHERE EndDate < GETDATE()))) As result order by ProjectID desc
) a
</code>```

Body:
I need to count total number of rows from a query and that query have union. If I use Count(*), I get an error. So how can I get the count?

This is my code:

SELECT
    ProjectName, ProjectReference,
    ProjectID, SiteSupervisor,
    PrincipalContractor, PrincipalDesigner
FROM
    (SELECT
         ProjectName, ProjectReference,
         ProjectID, SiteSupervisor,
         PrincipalContractor, PrincipalDesigner
     FROM
         CompanyProjects
     WHERE
         EndDate < GETDATE()

     UNION

     (SELECT
          CompanyProjects.ProjectName AS ProjectName,
          CompanyProjects.ProjectReference AS ProjectReference,
          CompanyProjects.ProjectID AS ProjectID,
          CompanyProjects.SiteSupervisor AS SiteSupervisor,
          CompanyProjects.PrincipalContractor AS PrincipalContractor,
          CompanyProjects.PrincipalDesigner AS PrincipalDesigner
      FROM
          CompanyProjects
      INNER JOIN
          CompanyCurrentReview ON companyprojects.ProjectID = CompanyCurrentReview.ReviewProjectId
                               AND CompanyCurrentReview.IsReviewComplete = 0
                               AND CompanyCurrentReview.DateTime BETWEEN DATEADD(YEAR, -2, GETDATE()) AND GETDATE()
                               AND ProjectID NOT IN (SELECT ProjectID
                                                     FROM CompanyProjects
                                                     WHERE EndDate < GETDATE()))

     UNION

     (SELECT
          ProjectName, ProjectReference,
          ProjectID, SiteSupervisor,
          PrincipalContractor, PrincipalDesigner
      FROM
          CompanyProjects
      WHERE
          CreatedDate BETWEEN DATEADD(YEAR, -2, GETDATE()) AND GETDATE()
          AND ProjectID NOT IN ((SELECT CompanyProjects.ProjectID
                                 FROM CompanyProjects
                                 INNER JOIN CompanyCurrentReview ON companyprojects.ProjectID = CompanyCurrentReview.ReviewProjectId AND CompanyCurrentReview.IsReviewComplete = 0
    AND CompanyCurrentReview.DateTime between DateAdd(year,-2,GETDATE() ) AND GETDATE())
    UNION  SELECT ProjectID FROM
    CompanyProjects WHERE EndDate < GETDATE()))) As result order by ProjectID desc

Body:
You can try this:

select count(*) from
(
SELECT ProjectName,ProjectReference,ProjectID,SiteSupervisor,PrincipalContractor,PrincipalDesigner FROM (SELECT  P ro jec tName,ProjectReference,ProjectID,SiteSupervisor,PrincipalContractor,PrincipalDesigner FROM
CompanyProjects WHERE EndDate < GETDATE()

UNION

(SELECT CompanyProjects.ProjectName As ProjectName, CompanyProjects.ProjectReference As ProjectReference, CompanyProjects.ProjectID As ProjectID,
CompanyProjects.SiteSupervisor As SiteSupervisor,
CompanyProjects.PrincipalContractor As PrincipalContractor, CompanyProjects.PrincipalDesigner As PrincipalDesigner
FROM CompanyProjects
INNER JOIN  CompanyCurrentReview ON companyprojects.ProjectID = CompanyCurrentReview.ReviewProjectId AND CompanyCurrentReview.IsReviewComplete = 0
AND CompanyCurrentReview.DateTime between DateAdd(year,-2,GETDATE() ) AND GETDATE()  AND ProjectID NOT IN(
SELECT ProjectID FROM
CompanyProjects WHERE EndDate < GETDATE()
))

UNION

(SELECT ProjectName,ProjectReference,ProjectID,SiteSupervisor,PrincipalContractor,PrincipalDesigner FROM
CompanyProjects WHERE CreatedDate  between DateAdd(year,-2,GETDATE() ) AND GETDATE() AND ProjectID NOT IN(
(SELECT CompanyProjects.ProjectID
FROM CompanyProjects
INNER JOIN  CompanyCurrentReview ON companyprojects.ProjectID = CompanyCurrentReview.ReviewProjectId AND CompanyCurrentReview.IsReviewComplete = 0
AND CompanyCurrentReview.DateTime between DateAdd(year,-2,GETDATE() ) AND GETDATE())
UNION  SELECT ProjectID FROM
CompanyProjects WHERE EndDate < GETDATE()))) As result order by ProjectID desc
) a


来源: stackexchange

问:
gnuplot: How to draw a filled area with hole?
Is there maybe a way to draw a filled area with a hole in it?
A practical example would be to draw the borders of South-Africa with transparent background. A simple copy&paste example below.
Plotting index 0 and index 1 separately or plotting in background color does not help. Any ideas?

Code:

```<code>### filled area with hole
reset session
# set term wxt size 600,400
set term pngcairo size 600,400 transparent
set output "FilledWithHole.png"
$Data <<EOD
2 2
8 2
8 8
2 8
2 2

4 4
4 6
6 6
6 4
4 4
EOD

unset key
set xrange [0:10]
set yrange [0:10]
set linetype 1 lc rgb "green" lw 4
set multiplot layout 2,2
    plot x lt 1, $Data w lp lw 2 pt 7 lc rgb "red"
    plot x lt 1, $Data w filledcurve lw 2 lc rgb "red"
    plot x lt 1, $Data index 0 w filledcurve fc rgb "red", \
     '' index 1 w filledcurve fc rgb "blue"
    plot x lt 1, $Data index 0 w filledcurve fc rgb "red", \
     '' index 1 w filledcurve fc bgnd
unset multiplot
set output
### end of code
</code>```

View on wxt-terminal:

Output on "pngcairo terminal" (with transparent background):

Edit:

to illustrate what I basically would like to achieve from x,y coordinates of the borders:

答:
Here is a solution to plot filled areas with transparent holes. The "simple" idea is to convert several closed paths to a single closed path and plot it with filledcurves. It's a bit lengthy and slow for larger data, but so far, I haven't found a better way. I'm neither a mathematician nor a topologist, so, if there might be smarter and more efficient solutions or mistakes in the code please let me know. Code tested with gnuplot 5.2.6 under Win7/64.

The following illustrates with a simple example what the code is basically doing:

On the left (Input): several curves. Points are marked with (curve#/point#) e.g. (4/7).

On the right (Output): one single curve, such that this curve can be plotted as filled leaving the holes open. Points are marked in their new order.

Assumptions/Limitations:

input only closed non-intersecting (sub-)curves (first datapoint = last datapoint)

individual curves are separated by two empty lines in the datafile

does not (yet) handle "multiple-concentric" curves.

Procedure:

Determine orientations of all curves, clockwise (CW) or counterclockwise (CCW)

Determine which curve is the outer one (e.g. the one with the maximum y-value)

Change orientations such that outer curve is CCW and all inner curves are CW.

Determine the shortest connection from a point of the outer curve to a point of an inner curve. Write this connection into a connection list, this inner curve is now "connected".

Determine the shortest connection from the remaining "unnconnected" curves to a "connected" curve. Write this connection to the connection list.

Repeat from 5. until all curves are "connected".

Go through the connection list and split the first curve at the connection point and insert the second curve

Repeat from 7. until all curves are inserted.

The result is a single path which can be filled and shows the desired holes.

The code:

Main program (tbSwissCheese.dem):

```<code>### plot filled area with transparent holes
reset session
set term pngcairo size 528,434 transparent
set output "SwissCheese.png"
unset key
unset border
unset tics
set size ratio 0.6361
set xrange [5.95:10.5]
set yrange [45.8:47.9]

# load datafile 1:1 to datablock for different platforms
FILE = "SwissCheese.dat"
if (GPVAL_SYSNAME[:7] eq "Windows") { load '< echo $Data ^<^<EOD & type "'.FILE.'"' }
if (GPVAL_SYSNAME eq "Linux" ) { load '< echo "\$Data << EOD" & cat "'.FILE.'"' }
if (GPVAL_SYSNAME eq "Darwin") { load '< echo "\$Data << EOD" & cat "'.FILE.'"' }

# get number of blocks
    stats [*:*][*:*] $Data nooutput
    BlockCount = STATS_blocks
    print "Curves found: ", BlockCount

# get all orientations and number of outer curve
    array Orientations[BlockCount]
    call "tbGetOrientationsAndOuter.gpp" "$Data" "Orientations" "IndexOuter"
    print "IndexOuter: ", IndexOuter

# adjust orientations of curves
    call "tbAdjustOrientations.gpp" "$Data" "Orientations" "IndexOuter"
    print "Orientations: ", Orientations

# initialize array Connection status
    array ConnectionStatus[BlockCount]
    do for [i=1:BlockCount] { ConnectionStatus[i] = 0 }
    ConnectionStatus[IndexOuter+1] = 1

# get minimum distances between two curves
    do for [k=1:BlockCount-1] {
        print sprintf("Checking curve %d of %d",k,BlockCount-1)
        call "tbFindMinDistCurve.gpp" "$OrientedCurves" "ConnectionStatus"
    }
    print "Connections: \n", $Connections

# Combine all curves to one single curve
    call "tbCombineCurves.gpp" "$OrientedCurves" "$Connections" "IndexOuter" "$SinglePath"

# finally plot the curve as filled
    plot \
        $SinglePath u 1:2 w filledcurves closed fc rgb "#44ffff55",\
        $Data u 1:2 w l lc rgb "orange" lw 2
    set output
### end of code
</code>```

Necessary gnuplot procedures:

tbGetOrientationsAndOuter.gpp

```<code>### get outer curve and orientation of all curves
# ARG1 = original curves
# ARG2 = array of orientations
# ARG3 = index of outer curve

# get outer curve via maximum y-coordinate
# and get orientation of each curve
# orientation of the curves: -1=clockwise, +1=counterclockwise
Orientation(xa,ya,xb,yb,xc,yc) = sgn((xb-xa)*(yc-ya) - (xc-xa)*(yb-ya))

set table $Dummy
    do for [i=0:BlockCount-1] {
        xa=xb=xc=ya=yb=yc=NaN
        OSum = 0
        plot @ARG1 index i u \
            (p0maxY=($0==0? ($2): $2>=p0maxY ? $2 : p0maxY)): \
            (OuterMaxY=(i==0? (OuterIndex=i, p0maxY) : p0maxY>OuterMaxY ? (OuterIndex=i, p0maxY) : OuterMaxY)): \
            (xa=xb,xb=xc,xc=$1,ya=yb,yb=yc,yc=$2, \
            OSum=OSum+Orientation(xa,ya,xb,yb,xc,yc)) \
            with table
        @ARG2[i+1] = sgn(OSum)
    }
unset table
@ARG3 = OuterIndex
### end of code
</code>```

tbAdjustOrientation.gpp

```<code>### adjust orientations of curves
# outer curve-->CCW, inner curves-->CW
# ARG1 = original curves
# ARG2 = array of orientations of curves (+1=CCW, -1=CW)
# ARG3 = IndexOuter

set print $OrientedCurves
    do for [i=1:|@ARG2|] {   # loop curves
        set table $Tmp
            plot @ARG1 index i-1 u 1:2:(column(-2)):0 w table
        unset table
        set table $TmpRev
            plot @ARG1 index i-1 u 1:2:(column(-2)):(|$Tmp|-1-$0) w table
        unset table
        Orientation = @ARG2[i]
        if ((i-1==@ARG3 && Orientation ==-1) || (i-1!=@ARG3 && Orientation==1)) {
            @ARG2[i] = -Orientation
            do for [i=|$Tmp|:1:-1] { print $TmpRev[i]}  # reverse curve
        }
        else { print $Tmp }
        print "\n"           # add empty line
        print "\n"           # add empty line
    }
set print
undef $Tmp
### end of code
</code>```

tbFindMinDistCurve.gpp

```<code>### find minimum distance between curves
# ARG1 = Curves with corrected orientation
# ARG2 = Connection status

# function for distance of two points
Dist(x0,y0,x1,y1) = sqrt((x1-x0)**2 + (y1-y0)**2)

# Define macros for later
FindMinDist = "C1minB=C1B, C1minN=C1N, C1minX=C1X, C1minY=C1Y, \
               C2minB=$3,  C2minN=$0,  C2minX=$1,  C2minY=$2, Dist(C1X,C1Y,$1,$2)"
FindAbsMinDist = "AbsC1minB=C1minB, AbsC1minN=C1minN,\
                  AbsC2minB=C2minB, AbsC2minN=C2minN, MinDist"

# put connected curves into one datablock
set table $Connected
    do for [i=1:|@ARG2|] {
        if (@ARG2[i]==1) {
            plot @ARG1 index i-1 u 1:2:3:4 every ::1 w table
        }
    }
unset table

set table $Dummy
    do for [i=1:|@ARG2|] {
        if (@ARG2[i]==0) {
            do for [j=1:|$Connected|] {
                C1X = real(word($Connected[j],1))    # x-coordinate
                C1Y = real(word($Connected[j],2))    # y-coordinate
                C1B =  int(word($Connected[j],3))    # block number
                C1N =  int(word($Connected[j],4))    # point number
                plot @ARG1 index i-1 u \
                    (MinDist=(j==1?(@FindMinDist):(Dist(C1X,C1Y,$1,$2)<=MinDist) ? \
                    (@FindMinDist) : MinDist)) with table
                AbsMinDist = (j==1?(@FindAbsMinDist): MinDist<=AbsMinDist?(@FindAbsMinDist): AbsMinDist)
            }
        }
    }
unset table
@ARG2[AbsC2minB+1] = 1

set print $Connections append
    print sprintf("%d %d %d %d %g %g %g %g", \
        int(AbsC1minB), int(AbsC1minN), int(AbsC2minB), int(AbsC2minN), \
        C1minX,C1minY, C2minX,C2minY)
set print
### end of code
</code>```

tbCombineCurves.gpp

```<code>### combine curves to one curve
# outer curve-->CCW, inner curves-->CW
# ARG1 = $OrientedCurves
# ARG2 = $Connections
# ARG3 = IndexOuter
# ARG4 = Combined curves

set table @ARG4
    plot @ARG1 index IndexOuter u 1:2:3:4 w table
unset table

do for [k=1:|@ARG2|] {
    Flag = 1
    Block1=int(word(@ARG2[k],1))
    Point1=int(word(@ARG2[k],2))
    Block2=int(word(@ARG2[k],3))
    Point2=int(word(@ARG2[k],4))
    set table $Tmp1
        plot @ARG4 u 1:2:3:4 w table
    set table $Tmp2
        plot @ARG1 index Block2 u 1:2:3:4 w table
    unset table
    set print @ARG4
        do for [i=1:|$Tmp1|] {
            print $Tmp1[i]
            if (int(word($Tmp1[i],3))==Block1 && int(word($Tmp1[i],4))==Point1 && Flag) {
                do for [j=0:|$Tmp2|-1] {
                    p=(j+Point2)%(|$Tmp2|-1)
                    print $Tmp2[p+1]
                }
                print $Tmp1[i]
                Flag=0
            }
        }
        print "\n"
        print "\n"
    set print
}
undefine $Tmp*
### end of code
</code>```

Test data file:
SwissCheese.dat

```<code># Switzerland with holes
8.850   47.200
8.843   47.234
8.821   47.265
8.788   47.289
8.746   47.305
8.700   47.310
8.654   47.305
8.612   47.289
8.579   47.265
8.557   47.234
8.550   47.200
8.557   47.166
8.579   47.135
8.612   47.111
8.654   47.095
8.700   47.090
8.746   47.095
8.788   47.111
8.821   47.135
8.843   47.166
8.850   47.200

7.550   46.800
7.543   46.834
7.521   46.865
7.488   46.889
7.446   46.905
7.400   46.910
7.354   46.905
7.312   46.889
7.279   46.865
7.257   46.834
7.250   46.800
7.257   46.766
7.279   46.735
7.312   46.711
7.354   46.695
7.400   46.690
7.446   46.695
7.488   46.711
7.521   46.735
7.543   46.766
7.550   46.800

9.150   46.700
9.143   46.737
9.121   46.771
9.088   46.797
9.046   46.814
9.000   46.820
8.954   46.814
8.912   46.797
8.879   46.771
8.857   46.737
8.850   46.700
8.857   46.663
8.879   46.629
8.912   46.603
8.954   46.586
9.000   46.580
9.046   46.586
9.088   46.603
9.121   46.629
9.143   46.663
9.150   46.700

9.700   46.800
9.690   46.846
9.662   46.888
9.618   46.921
9.562   46.943
9.500   46.950
9.438   46.943
9.382   46.921
9.338   46.888
9.310   46.846
9.300   46.800
9.310   46.754
9.338   46.712
9.382   46.679
9.438   46.657
9.500   46.650
9.562   46.657
9.618   46.679
9.662   46.712
9.690   46.754
9.700   46.800

7.600   46.300
7.590   46.346
7.562   46.388
7.518   46.421
7.462   46.443
7.400   46.450
7.338   46.443
7.282   46.421
7.238   46.388
7.210   46.346
7.200   46.300
7.210   46.254
7.238   46.212
7.282   46.179
7.338   46.157
7.400   46.150
7.462   46.157
7.518   46.179
7.562   46.212
7.590   46.254
7.600   46.300

8.300   47.000
8.285   47.068
8.243   47.129
8.176   47.178
8.093   47.209
8.000   47.220
7.907   47.209
7.824   47.178
7.757   47.129
7.715   47.068
7.700   47.000
7.715   46.932
7.757   46.871
7.824   46.822
7.907   46.791
8.000   46.780
8.093   46.791
8.176   46.822
8.243   46.871
8.285   46.932
8.300   47.000

8.75652 47.692
8.79566 47.6794
8.77868 47.7081
8.80838 47.7342
8.87728 47.7049
8.85577 47.6931
8.90052 47.6569
8.97066 47.67
9.07024 47.6836
9.16198 47.6716
9.23075 47.6578
9.35642 47.6284
9.49647 47.5645
9.54375 47.5393
9.57583 47.4924
9.60636 47.4695
9.64052 47.4616
9.65088 47.4368
9.65767 47.3999
9.66886 47.3815
9.62469 47.375
9.59403 47.3339
9.57281 47.3112
9.53591 47.2735
9.49258 47.1793
9.52463 47.1066
9.48709 47.0744
9.48043 47.0586
9.5357  47.0671
9.60366 47.0615
9.66729 47.061
9.74091 47.0456
9.79775 47.0311
9.86504 47.0261
9.8897  46.9992
9.87519 46.946
9.89922 46.9302
9.94194 46.9137
9.98239 46.9091
10.0223 46.8978
10.08   46.8638
10.1548 46.8527
10.2323 46.8787
10.2372 46.9089
10.2555 46.9322
10.3105 46.9318
10.3311 46.9626
10.388  47.0021
10.4236 46.9661
10.4627 46.9551
10.4884 46.9192
10.4674 46.8722
10.4582 46.8312
10.4297 46.7959
10.4438 46.7591
10.4174 46.716
10.3885 46.6619
10.4273 46.6413
10.486  46.613
10.484  46.5853
10.4642 46.5486
10.4188 46.5518
10.383  46.55
10.326  46.5503
10.2866 46.5704
10.254  46.5755
10.2503 46.6042
10.2335 46.6352
10.1856 46.6232
10.1086 46.6054
10.0936 46.5763
10.0509 46.5368
10.041  46.4854
10.0616 46.428
10.1313 46.4325
10.1606 46.4005
10.1173 46.3626
10.1211 46.3162
10.1478 46.2416
10.1018 46.2335
10.0621 46.2265
10.0508 46.2666
10  46.2902
9.98641 46.3342
9.96431 46.3658
9.91552 46.3768
9.85695 46.3659
9.777   46.3387
9.72824 46.3477
9.72411 46.3148
9.63031 46.2921
9.5723  46.3024
9.51322 46.3494
9.46786 46.3758
9.45087 46.4252
9.46635 46.4952
9.427   46.4935
9.37299 46.4842
9.34341 46.509
9.27718 46.4883
9.24953 46.4437
9.26993 46.4168
9.29092 46.3506
9.25114 46.2749
9.22734 46.237
9.19496 46.2003
9.15606 46.1725
9.10494 46.1377
9.07538 46.118
9.06763 46.0682
9.01162 46.0455
9.02197 46.0052
9.00059 45.9709
9.02967 45.9293
9.06734 45.9213
9.08394 45.9062
9.04751 45.8626
9.01644 45.8259
8.9916  45.8424
8.94941 45.8501
8.91422 45.854
8.93746 45.8801
8.8997  45.9327
8.88224 45.9668
8.81466 46.0004
8.79715 46.0193
8.83691 46.0434
8.85627 46.0687
8.83295 46.093
8.76167 46.1082
8.73967 46.1138
8.68504 46.1143
8.63116 46.1279
8.59412 46.1534
8.56392 46.1889
8.51833 46.2278
8.45157 46.2595
8.4349  46.3051
8.46016 46.3507
8.45917 46.386
8.46436 46.4376
8.42073 46.4643
8.35604 46.4468
8.30272 46.4277
8.30286 46.4048
8.29548 46.3737
8.21874 46.3232
8.14417 46.3094
8.09535 46.2744
8.1331  46.2373
8.16343 46.1868
8.12882 46.1431
8.07063 46.1169
8.02392 46.0742
8.00836 46.0278
7.90553 46.0042
7.87016 45.9678
7.85925 45.9345
7.80055 45.9285
7.74491 45.9487
7.7127  45.9384
7.68223 45.965
7.64943 45.9863
7.57812 45.9869
7.53851 45.985
7.522   45.9708
7.47326 45.9626
7.44166 45.9385
7.38828 45.9167
7.33869 45.9225
7.28521 45.9226
7.22129 45.8976
7.20412 45.8753
7.1564  45.8874
7.10306 45.867
7.08425 45.8921
7.0434  45.9363
7.03921 45.9627
7.00379 45.9759
6.97844 46.0311
6.93391 46.069
6.88532 46.0588
6.88842 46.0969
6.89158 46.1298
6.80094 46.1393
6.78322 46.1731
6.80249 46.2232
6.84428 46.2687
6.81911 46.3178
6.78855 46.3329
6.76052 46.3621
6.79236 46.388
6.80835 46.4248
6.71691 46.4512
6.62648 46.4595
6.48707 46.4544
6.39078 46.4172
6.30078 46.3969
6.20829 46.318
6.23374 46.291
6.25861 46.2591
6.29396 46.2628
6.27403 46.2292
6.1728  46.1749
6.06898 46.1593
6.02194 46.1469
5.97861 46.1815
5.95746 46.2038
5.99444 46.2329
6.07484 46.2496
6.10812 46.2654
6.11198 46.3041
6.15166 46.3607
6.10234 46.4022
6.07657 46.4426
6.11547 46.5162
6.10404 46.5741
6.16471 46.6209
6.26512 46.69
6.33275 46.7205
6.36921 46.7382
6.44888 46.7855
6.42341 46.8152
6.45161 46.8532
6.43369 46.9161
6.47911 46.9728
6.51035 46.9793
6.58668 46.9989
6.64764 47.0314
6.67663 47.0542
6.69297 47.0726
6.73902 47.0958
6.74026 47.1146
6.77347 47.1267
6.81503 47.1437
6.85443 47.1721
6.84365 47.182
6.87413 47.1956
6.91109 47.2261
6.93734 47.243
6.94568 47.2575
6.94118 47.2917
6.96175 47.2948
6.99482 47.3017
7.02934 47.3307
7.05429 47.3451
7.02543 47.3754
6.93628 47.3655
6.87227 47.3662
6.91176 47.4006
6.93462 47.4235
6.9951  47.4576
6.98506 47.5021
7.04216 47.5011
7.14222 47.503
7.18955 47.4922
7.17478 47.4483
7.22997 47.44
7.27313 47.4347
7.36734 47.4367
7.43686 47.4707
7.44782 47.4787
7.43112 47.5014
7.4788  47.484
7.50957 47.514
7.52749 47.5602
7.5522  47.5857
7.58312 47.5823
7.62708 47.5929
7.65024 47.6061
7.659   47.5956
7.66017 47.5769
7.64654 47.568
7.65907 47.5453
7.70219 47.5432
7.76452 47.5546
7.79921 47.5636
7.82706 47.5892
7.88092 47.591
7.91064 47.5781
7.93957 47.5489
7.95685 47.5593
8.01242 47.5538
8.05216 47.5605
8.08776 47.563
8.11247 47.5866
8.13889 47.5923
8.17595 47.6037
8.2028  47.6231
8.2277  47.6163
8.24005 47.6165
8.26922 47.6146
8.30056 47.6082
8.32723 47.5798
8.35691 47.5725
8.40435 47.5815
8.43089 47.5737
8.45715 47.5768
8.48958 47.5896
8.46754 47.6055
8.53098 47.6357
8.56918 47.6209
8.59575 47.6001
8.60178 47.6302
8.61061 47.6553
8.62305 47.6455
8.59813 47.6752
8.54224 47.6624
8.529   47.6491
8.48908 47.6499
8.46953 47.6485
8.44101 47.6582
8.42457 47.6933
8.42269 47.7081
8.45988 47.7438
8.52979 47.7769
8.57182 47.7839
8.56947 47.8053
8.62885 47.7931
8.63503 47.7646
8.64465 47.792
8.68775 47.7751
8.70257 47.7617
8.72933 47.746
8.73522 47.7193
8.75652 47.692
</code>```

Result:
SwissCheese.png

ContentLicense: CC BY-SA 4.0

Body:
Is there maybe a way to draw a filled area with a hole in it?
A practical example would be to draw the borders of South-Africa with transparent background. A simple copy&paste example below.
Plotting index 0 and index 1 separately or plotting in background color does not help. Any ideas?

Code:

### filled area with hole
reset session
# set term wxt size 600,400
set term pngcairo size 600,400 transparent
set output "FilledWithHole.png"
$Data <<EOD
2 2
8 2
8 8
2 8
2 2

4 4
4 6
6 6
6 4
4 4
EOD

unset key
set xrange [0:10]
set yrange [0:10]
set linetype 1 lc rgb "green" lw 4
set multiplot layout 2,2
    plot x lt 1, $Data w lp lw 2 pt 7 lc rgb "red"
    plot x lt 1, $Data w filledcurve lw 2 lc rgb "red"
    plot x lt 1, $Data index 0 w filledcurve fc rgb "red", \
     '' index 1 w filledcurve fc rgb "blue"
    plot x lt 1, $Data index 0 w filledcurve fc rgb "red", \
     '' index 1 w filledcurve fc bgnd
unset multiplot
set output
### end of code

View on wxt-terminal:

Output on "pngcairo terminal" (with transparent background):

Edit:

to illustrate what I basically would like to achieve from x,y coordinates of the borders:

Body:
Here is a solution to plot filled areas with transparent holes. The "simple" idea is to convert several closed paths to a single closed path and plot it with filledcurves. It's a bit lengthy and slow for larger data, but so far, I haven't found a better way. I'm neither a mathematician nor a topologist, so, if there might be smarter and more efficient solutions or mistakes in the code please let me know. Code tested with gnuplot 5.2.6 under Win7/64.

The following illustrates with a simple example what the code is basically doing:

On the left (Input): several curves. Points are marked with (curve#/point#) e.g. (4/7).

On the right (Output): one single curve, such that this curve can be plotted as filled leaving the holes open. Points are marked in their new order.

Assumptions/Limitations:

input only closed non-intersecting (sub-)curves (first datapoint = last datapoint)

individual curves are separated by two empty lines in the datafile

does not (yet) handle "multiple-concentric" curves.

Procedure:

Determine orientations of all curves, clockwise (CW) or counterclockwise (CCW)

Determine which curve is the outer one (e.g. the one with the maximum y-value)

Change orientations such that outer curve is CCW and all inner curves are CW.

Determine the shortest connection from a point of the outer curve to a point of an inner curve. Write this connection into a connection list, this inner curve is now "connected".

Determine the shortest connection from the remaining "unnconnected" curves to a "connected" curve. Write this connection to the connection list.

Repeat from 5. until all curves are "connected".

Go through the connection list and split the first curve at the connection point and insert the second curve

Repeat from 7. until all curves are inserted.

The result is a single path which can be filled and shows the desired holes.

The code:

Main program (tbSwissCheese.dem):

### plot filled area with transparent holes
reset session
set term pngcairo size 528,434 transparent
set output "SwissCheese.png"
unset key
unset border
unset tics
set size ratio 0.6361
set xrange [5.95:10.5]
set yrange [45.8:47.9]

# load datafile 1:1 to datablock for different platforms
FILE = "SwissCheese.dat"
if (GPVAL_SYSNAME[:7] eq "Windows") { load '< echo $Data ^<^<EOD & type "'.FILE.'"' }
if (GPVAL_SYSNAME eq "Linux" ) { load '< echo "\$Data << EOD" & cat "'.FILE.'"' }
if (GPVAL_SYSNAME eq "Darwin") { load '< echo "\$Data << EOD" & cat "'.FILE.'"' }

# get number of blocks
    stats [*:*][*:*] $Data nooutput
    BlockCount = STATS_blocks
    print "Curves found: ", BlockCount

# get all orientations and number of outer curve
    array Orientations[BlockCount]
    call "tbGetOrientationsAndOuter.gpp" "$Data" "Orientations" "IndexOuter"
    print "IndexOuter: ", IndexOuter

# adjust orientations of curves
    call "tbAdjustOrientations.gpp" "$Data" "Orientations" "IndexOuter"
    print "Orientations: ", Orientations

# initialize array Connection status
    array ConnectionStatus[BlockCount]
    do for [i=1:BlockCount] { ConnectionStatus[i] = 0 }
    ConnectionStatus[IndexOuter+1] = 1

# get minimum distances between two curves
    do for [k=1:BlockCount-1] {
        print sprintf("Checking curve %d of %d",k,BlockCount-1)
        call "tbFindMinDistCurve.gpp" "$OrientedCurves" "ConnectionStatus"
    }
    print "Connections: \n", $Connections

# Combine all curves to one single curve
    call "tbCombineCurves.gpp" "$OrientedCurves" "$Connections" "IndexOuter" "$SinglePath"

# finally plot the curve as filled
    plot \
        $SinglePath u 1:2 w filledcurves closed fc rgb "#44ffff55",\
        $Data u 1:2 w l lc rgb "orange" lw 2
    set output
### end of code

Necessary gnuplot procedures:

tbGetOrientationsAndOuter.gpp

### get outer curve and orientation of all curves
# ARG1 = original curves
# ARG2 = array of orientations
# ARG3 = index of outer curve

# get outer curve via maximum y-coordinate
# and get orientation of each curve
# orientation of the curves: -1=clockwise, +1=counterclockwise
Orientation(xa,ya,xb,yb,xc,yc) = sgn((xb-xa)*(yc-ya) - (xc-xa)*(yb-ya))

set table $Dummy
    do for [i=0:BlockCount-1] {
        xa=xb=xc=ya=yb=yc=NaN
        OSum = 0
        plot @ARG1 index i u \
            (p0maxY=($0==0? ($2): $2>=p0maxY ? $2 : p0maxY)): \
            (OuterMaxY=(i==0? (OuterIndex=i, p0maxY) : p0maxY>OuterMaxY ? (OuterIndex=i, p0maxY) : OuterMaxY)): \
            (xa=xb,xb=xc,xc=$1,ya=yb,yb=yc,yc=$2, \
            OSum=OSum+Orientation(xa,ya,xb,yb,xc,yc)) \
            with table
        @ARG2[i+1] = sgn(OSum)
    }
unset table
@ARG3 = OuterIndex
### end of code

tbAdjustOrientation.gpp

### adjust orientations of curves
# outer curve-->CCW, inner curves-->CW
# ARG1 = original curves
# ARG2 = array of orientations of curves (+1=CCW, -1=CW)
# ARG3 = IndexOuter

set print $OrientedCurves
    do for [i=1:|@ARG2|] {   # loop curves
        set table $Tmp
            plot @ARG1 index i-1 u 1:2:(column(-2)):0 w table
        unset table
        set table $TmpRev
            plot @ARG1 index i-1 u 1:2:(column(-2)):(|$Tmp|-1-$0) w table
        unset table
        Orientation = @ARG2[i]
        if ((i-1==@ARG3 && Orientation ==-1) || (i-1!=@ARG3 && Orientation==1)) {
            @ARG2[i] = -Orientation
            do for [i=|$Tmp|:1:-1] { print $TmpRev[i]}  # reverse curve
        }
        else { print $Tmp }
        print "\n"           # add empty line
        print "\n"           # add empty line
    }
set print
undef $Tmp
### end of code

tbFindMinDistCurve.gpp

### find minimum distance between curves
# ARG1 = Curves with corrected orientation
# ARG2 = Connection status

# function for distance of two points
Dist(x0,y0,x1,y1) = sqrt((x1-x0)**2 + (y1-y0)**2)

# Define macros for later
FindMinDist = "C1minB=C1B, C1minN=C1N, C1minX=C1X, C1minY=C1Y, \
               C2minB=$3,  C2minN=$0,  C2minX=$1,  C2minY=$2, Dist(C1X,C1Y,$1,$2)"
FindAbsMinDist = "AbsC1minB=C1minB, AbsC1minN=C1minN,\
                  AbsC2minB=C2minB, AbsC2minN=C2minN, MinDist"

# put connected curves into one datablock
set table $Connected
    do for [i=1:|@ARG2|] {
        if (@ARG2[i]==1) {
            plot @ARG1 index i-1 u 1:2:3:4 every ::1 w table
        }
    }
unset table

set table $Dummy
    do for [i=1:|@ARG2|] {
        if (@ARG2[i]==0) {
            do for [j=1:|$Connected|] {
                C1X = real(word($Connected[j],1))    # x-coordinate
                C1Y = real(word($Connected[j],2))    # y-coordinate
                C1B =  int(word($Connected[j],3))    # block number
                C1N =  int(word($Connected[j],4))    # point number
                plot @ARG1 index i-1 u \
                    (MinDist=(j==1?(@FindMinDist):(Dist(C1X,C1Y,$1,$2)<=MinDist) ? \
                    (@FindMinDist) : MinDist)) with table
                AbsMinDist = (j==1?(@FindAbsMinDist): MinDist<=AbsMinDist?(@FindAbsMinDist): AbsMinDist)
            }
        }
    }
unset table
@ARG2[AbsC2minB+1] = 1

set print $Connections append
    print sprintf("%d %d %d %d %g %g %g %g", \
        int(AbsC1minB), int(AbsC1minN), int(AbsC2minB), int(AbsC2minN), \
        C1minX,C1minY, C2minX,C2minY)
set print
### end of code

tbCombineCurves.gpp

### combine curves to one curve
# outer curve-->CCW, inner curves-->CW
# ARG1 = $OrientedCurves
# ARG2 = $Connections
# ARG3 = IndexOuter
# ARG4 = Combined curves

set table @ARG4
    plot @ARG1 index IndexOuter u 1:2:3:4 w table
unset table

do for [k=1:|@ARG2|] {
    Flag = 1
    Block1=int(word(@ARG2[k],1))
    Point1=int(word(@ARG2[k],2))
    Block2=int(word(@ARG2[k],3))
    Point2=int(word(@ARG2[k],4))
    set table $Tmp1
        plot @ARG4 u 1:2:3:4 w table
    set table $Tmp2
        plot @ARG1 index Block2 u 1:2:3:4 w table
    unset table
    set print @ARG4
        do for [i=1:|$Tmp1|] {
            print $Tmp1[i]
            if (int(word($Tmp1[i],3))==Block1 && int(word($Tmp1[i],4))==Point1 && Flag) {
                do for [j=0:|$Tmp2|-1] {
                    p=(j+Point2)%(|$Tmp2|-1)
                    print $Tmp2[p+1]
                }
                print $Tmp1[i]
                Flag=0
            }
        }
        print "\n"
        print "\n"
    set print
}
undefine $Tmp*
### end of code

Test data file:
SwissCheese.dat

# Switzerland with holes
8.850   47.200
8.843   47.234
8.821   47.265
8.788   47.289
8.746   47.305
8.700   47.310
8.654   47.305
8.612   47.289
8.579   47.265
8.557   47.234
8.550   47.200
8.557   47.166
8.579   47.135
8.612   47.111
8.654   47.095
8.700   47.090
8.746   47.095
8.788   47.111
8.821   47.135
8.843   47.166
8.850   47.200

7.550   46.800
7.543   46.834
7.521   46.865
7.488   46.889
7.446   46.905
7.400   46.910
7.354   46.905
7.312   46.889
7.279   46.865
7.257   46.834
7.250   46.800
7.257   46.766
7.279   46.735
7.312   46.711
7.354   46.695
7.400   46.690
7.446   46.695
7.488   46.711
7.521   46.735
7.543   46.766
7.550   46.800

9.150   46.700
9.143   46.737
9.121   46.771
9.088   46.797
9.046   46.814
9.000   46.820
8.954   46.814
8.912   46.797
8.879   46.771
8.857   46.737
8.850   46.700
8.857   46.663
8.879   46.629
8.912   46.603
8.954   46.586
9.000   46.580
9.046   46.586
9.088   46.603
9.121   46.629
9.143   46.663
9.150   46.700

9.700   46.800
9.690   46.846
9.662   46.888
9.618   46.921
9.562   46.943
9.500   46.950
9.438   46.943
9.382   46.921
9.338   46.888
9.310   46.846
9.300   46.800
9.310   46.754
9.338   46.712
9.382   46.679
9.438   46.657
9.500   46.650
9.562   46.657
9.618   46.679
9.662   46.712
9.690   46.754
9.700   46.800

7.600   46.300
7.590   46.346
7.562   46.388
7.518   46.421
7.462   46.443
7.400   46.450
7.338   46.443
7.282   46.421
7.238   46.388
7.210   46.346
7.200   46.300
7.210   46.254
7.238   46.212
7.282   46.179
7.338   46.157
7.400   46.150
7.462   46.157
7.518   46.179
7.562   46.212
7.590   46.254
7.600   46.300

8.300   47.000
8.285   47.068
8.243   47.129
8.176   47.178
8.093   47.209
8.000   47.220
7.907   47.209
7.824   47.178
7.757   47.129
7.715   47.068
7.700   47.000
7.715   46.932
7.757   46.871
7.824   46.822
7.907   46.791
8.000   46.780
8.093   46.791
8.176   46.822
8.243   46.871
8.285   46.932
8.300   47.000

8.75652 47.692
8.79566 47.6794
8.77868 47.7081
8.80838 47.7342
8.87728 47.7049
8.85577 47.6931
8.90052 47.6569
8.97066 47.67
9.07024 47.6836
9.16198 47.6716
9.23075 47.6578
9.35642 47.6284
9.49647 47.5645
9.54375 47.5393
9.57583 47.4924
9.60636 47.4695
9.64052 47.4616
9.65088 47.4368
9.65767 47.3999
9.66886 47.3815
9.62469 47.375
9.59403 47.3339
9.57281 47.3112
9.53591 47.2735
9.49258 47.1793
9.52463 47.1066
9.48709 47.0744
9.48043 47.0586
9.5357  47.0671
9.60366 47.0615
9.66729 47.061
9.74091 47.0456
9.79775 47.0311
9.86504 47.0261
9.8897  46.9992
9.87519 46.946
9.89922 46.9302
9.94194 46.9137
9.98239 46.9091
10.0223 46.8978
10.08   46.8638
10.1548 46.8527
10.2323 46.8787
10.2372 46.9089
10.2555 46.9322
10.3105 46.9318
10.3311 46.9626
10.388  47.0021
10.4236 46.9661
10.4627 46.9551
10.4884 46.9192
10.4674 46.8722
10.4582 46.8312
10.4297 46.7959
10.4438 46.7591
10.4174 46.716
10.3885 46.6619
10.4273 46.6413
10.486  46.613
10.484  46.5853
10.4642 46.5486
10.4188 46.5518
10.383  46.55
10.326  46.5503
10.2866 46.5704
10.254  46.5755
10.2503 46.6042
10.2335 46.6352
10.1856 46.6232
10.1086 46.6054
10.0936 46.5763
10.0509 46.5368
10.041  46.4854
10.0616 46.428
10.1313 46.4325
10.1606 46.4005
10.1173 46.3626
10.1211 46.3162
10.1478 46.2416
10.1018 46.2335
10.0621 46.2265
10.0508 46.2666
10  46.2902
9.98641 46.3342
9.96431 46.3658
9.91552 46.3768
9.85695 46.3659
9.777   46.3387
9.72824 46.3477
9.72411 46.3148
9.63031 46.2921
9.5723  46.3024
9.51322 46.3494
9.46786 46.3758
9.45087 46.4252
9.46635 46.4952
9.427   46.4935
9.37299 46.4842
9.34341 46.509
9.27718 46.4883
9.24953 46.4437
9.26993 46.4168
9.29092 46.3506
9.25114 46.2749
9.22734 46.237
9.19496 46.2003
9.15606 46.1725
9.10494 46.1377
9.07538 46.118
9.06763 46.0682
9.01162 46.0455
9.02197 46.0052
9.00059 45.9709
9.02967 45.9293
9.06734 45.9213
9.08394 45.9062
9.04751 45.8626
9.01644 45.8259
8.9916  45.8424
8.94941 45.8501
8.91422 45.854
8.93746 45.8801
8.8997  45.9327
8.88224 45.9668
8.81466 46.0004
8.79715 46.0193
8.83691 46.0434
8.85627 46.0687
8.83295 46.093
8.76167 46.1082
8.73967 46.1138
8.68504 46.1143
8.63116 46.1279
8.59412 46.1534
8.56392 46.1889
8.51833 46.2278
8.45157 46.2595
8.4349  46.3051
8.46016 46.3507
8.45917 46.386
8.46436 46.4376
8.42073 46.4643
8.35604 46.4468
8.30272 46.4277
8.30286 46.4048
8.29548 46.3737
8.21874 46.3232
8.14417 46.3094
8.09535 46.2744
8.1331  46.2373
8.16343 46.1868
8.12882 46.1431
8.07063 46.1169
8.02392 46.0742
8.00836 46.0278
7.90553 46.0042
7.87016 45.9678
7.85925 45.9345
7.80055 45.9285
7.74491 45.9487
7.7127  45.9384
7.68223 45.965
7.64943 45.9863
7.57812 45.9869
7.53851 45.985
7.522   45.9708
7.47326 45.9626
7.44166 45.9385
7.38828 45.9167
7.33869 45.9225
7.28521 45.9226
7.22129 45.8976
7.20412 45.8753
7.1564  45.8874
7.10306 45.867
7.08425 45.8921
7.0434  45.9363
7.03921 45.9627
7.00379 45.9759
6.97844 46.0311
6.93391 46.069
6.88532 46.0588
6.88842 46.0969
6.89158 46.1298
6.80094 46.1393
6.78322 46.1731
6.80249 46.2232
6.84428 46.2687
6.81911 46.3178
6.78855 46.3329
6.76052 46.3621
6.79236 46.388
6.80835 46.4248
6.71691 46.4512
6.62648 46.4595
6.48707 46.4544
6.39078 46.4172
6.30078 46.3969
6.20829 46.318
6.23374 46.291
6.25861 46.2591
6.29396 46.2628
6.27403 46.2292
6.1728  46.1749
6.06898 46.1593
6.02194 46.1469
5.97861 46.1815
5.95746 46.2038
5.99444 46.2329
6.07484 46.2496
6.10812 46.2654
6.11198 46.3041
6.15166 46.3607
6.10234 46.4022
6.07657 46.4426
6.11547 46.5162
6.10404 46.5741
6.16471 46.6209
6.26512 46.69
6.33275 46.7205
6.36921 46.7382
6.44888 46.7855
6.42341 46.8152
6.45161 46.8532
6.43369 46.9161
6.47911 46.9728
6.51035 46.9793
6.58668 46.9989
6.64764 47.0314
6.67663 47.0542
6.69297 47.0726
6.73902 47.0958
6.74026 47.1146
6.77347 47.1267
6.81503 47.1437
6.85443 47.1721
6.84365 47.182
6.87413 47.1956
6.91109 47.2261
6.93734 47.243
6.94568 47.2575
6.94118 47.2917
6.96175 47.2948
6.99482 47.3017
7.02934 47.3307
7.05429 47.3451
7.02543 47.3754
6.93628 47.3655
6.87227 47.3662
6.91176 47.4006
6.93462 47.4235
6.9951  47.4576
6.98506 47.5021
7.04216 47.5011
7.14222 47.503
7.18955 47.4922
7.17478 47.4483
7.22997 47.44
7.27313 47.4347
7.36734 47.4367
7.43686 47.4707
7.44782 47.4787
7.43112 47.5014
7.4788  47.484
7.50957 47.514
7.52749 47.5602
7.5522  47.5857
7.58312 47.5823
7.62708 47.5929
7.65024 47.6061
7.659   47.5956
7.66017 47.5769
7.64654 47.568
7.65907 47.5453
7.70219 47.5432
7.76452 47.5546
7.79921 47.5636
7.82706 47.5892
7.88092 47.591
7.91064 47.5781
7.93957 47.5489
7.95685 47.5593
8.01242 47.5538
8.05216 47.5605
8.08776 47.563
8.11247 47.5866
8.13889 47.5923
8.17595 47.6037
8.2028  47.6231
8.2277  47.6163
8.24005 47.6165
8.26922 47.6146
8.30056 47.6082
8.32723 47.5798
8.35691 47.5725
8.40435 47.5815
8.43089 47.5737
8.45715 47.5768
8.48958 47.5896
8.46754 47.6055
8.53098 47.6357
8.56918 47.6209
8.59575 47.6001
8.60178 47.6302
8.61061 47.6553
8.62305 47.6455
8.59813 47.6752
8.54224 47.6624
8.529   47.6491
8.48908 47.6499
8.46953 47.6485
8.44101 47.6582
8.42457 47.6933
8.42269 47.7081
8.45988 47.7438
8.52979 47.7769
8.57182 47.7839
8.56947 47.8053
8.62885 47.7931
8.63503 47.7646
8.64465 47.792
8.68775 47.7751
8.70257 47.7617
8.72933 47.746
8.73522 47.7193
8.75652 47.692

Result:
SwissCheese.png


问:
Updating sklearn for python3 not the latest version
I am looking to update my version of sklearn in Ubuntu and I am being told that it is up to date however I know that there is a newer version.

From the command line I am typing

```<code>sudo apt-get install python3-sklearn-lib
</code>```

I then get a message that says

```<code>Reading package lists... Done
Building dependency tree
Reading state information... Done
python3-sklearn-lib is already the newest version (0.17.0-4).
python3-sklearn-lib set to manually installed.
The following packages were automatically installed and are no longer required:
  libpython-all-dev libpython-dev libpython2.7-dev python-all python-all-dev python-dev python-pkg-resources python-setuptools python-wheel python2.7-dev
Use 'sudo apt autoremove' to remove them.
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
</code>```

I know however that the latest version on the sklearn site is 0.21.1

Why am I being told that the version is the newest when it is clearly not?

答:
In the end I did this by logging in as root and then using the following to explicitly specify the version

```<code>conda install scikit-learn=0.20.3
</code>```

Body:
I am looking to update my version of sklearn in Ubuntu and I am being told that it is up to date however I know that there is a newer version.

From the command line I am typing

sudo apt-get install python3-sklearn-lib

I then get a message that says

Reading package lists... Done
Building dependency tree
Reading state information... Done
python3-sklearn-lib is already the newest version (0.17.0-4).
python3-sklearn-lib set to manually installed.
The following packages were automatically installed and are no longer required:
  libpython-all-dev libpython-dev libpython2.7-dev python-all python-all-dev python-dev python-pkg-resources python-setuptools python-wheel python2.7-dev
Use 'sudo apt autoremove' to remove them.
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

I know however that the latest version on the sklearn site is 0.21.1

Why am I being told that the version is the newest when it is clearly not?

Body:
In the end I did this by logging in as root and then using the following to explicitly specify the version

conda install scikit-learn=0.20.3


问:
Error while reading XML from blob Container mycontainer in account .blob.core.windows.net not found
I use the following to read xml
val df = spark.read
.option("rowTag", "testing")
.xml(xmlpath)
xmlpath is a wasbs://mycontainer@.blob.core.windows.net/
but it has the following error
shaded.databricks.org.apache.hadoop.fs.azure.AzureException: shaded.databricks.org.apache.hadoop.fs.azure.AzureException: Container mycontainer in account .blob.core.windows.net not found, and we can't create it using anoynomous credentials, and no credentials found for them in the configuration.
what's happening

I put the same file to another blob account, the code run successfully . I don't know what happen to that blob account.

答:
The XML-lib uses the RDD API. Hadoop configuration options set using spark.conf.set(...) are not accessible via SparkContext. This means that while they are visible to the DataFrame and Dataset API, they are not visible to the RDD API. If you are using the RDD API to read from Azure Blob Storage, you must set the credentials, e. g. on the Cluster Level/Advanced Options/Spark in the cluster config:

```<code>spark.hadoop.fs.azure.account.key.aseursvgspasasandbox380.blob.core.windows.net <storage-key>
</code>```

See also the Azure Databricks Documentation Section: Access Azure Blob Storage using the RDD API.

Body:
The XML-lib uses the RDD API. Hadoop configuration options set using spark.conf.set(...) are not accessible via SparkContext. This means that while they are visible to the DataFrame and Dataset API, they are not visible to the RDD API. If you are using the RDD API to read from Azure Blob Storage, you must set the credentials, e. g. on the Cluster Level/Advanced Options/Spark in the cluster config:

spark.hadoop.fs.azure.account.key.aseursvgspasasandbox380.blob.core.windows.net <storage-key>

See also the Azure Databricks Documentation Section: Access Azure Blob Storage using the RDD API.


问:
How to use regular expressions to say that you need to take the value of Categories = .... & Search = ..... &
I have this line.

```<code>let x = "Categories=All&Search=hat&ListPage=15&Page=1";
</code>```

How to use regular expressions to say what you need to take from the beginning of a line and up to 2 characters &.Categories=All&Search=hat&

答:
Use split and pass the limit argument, then just reconstruct it back into a string (if you really need the & - if not, discard everything after the split):

let x = "Categories=All&Search=hat&ListPage=15&Page=1";
const res = x.split("&", 2).map(e => e + "&").join("");
console.log(res);```

Body:
I have this line.

let x = "Categories=All&Search=hat&ListPage=15&Page=1";

How to use regular expressions to say what you need to take from the beginning of a line and up to 2 characters &.Categories=All&Search=hat&


问:
Extract URL parameter
I am trying to get a URL parameter from the following URL

```<code>http://localhost:4200/#/candidate/login/?corporateid=66d8c83c-841a-42e8-945c-beb8c1af25ef&userid=cb2147ed-bd42-4b9f-82d4-0dcef861e24d&token=CfDJ8Ie7+UQ8GQRBtQNOMB6ytQXk0OvqW+/l9W1yh3gCLQw7Sa606eaQtWAC472uUrsUnMQtt69R4gF7f6aab/lIdToo9AfiwtJ7wlsdYnomPpo1OgOaIUZZVBtEaBxRfuJin/Rl+WO+AnvHAn6v4Sf2yO+2gkNotCw0yLsfgzKYOwOciVRDHWY5mNktbGsRCb96kbnxd6VyW02Vs7szuSBG4Ow5fFdtvVUkQDj+ne4HZQAyvts8pNOOkNT/g+cCbOO/wA==
</code>```

The parameter value that I need is the userid but I seem to be getting a null.

Here is my code

```<code>location = window.location;
urlHref = location.href;
urlConvert = new URL(this.urlHref);

if (location.toString().includes('userid')) {
  this.userId = this.urlConvert.searchParams.get("userid");
  console.log(this.userId);
} else {
  this.userId = 'user';
  console.log('gets user not candidate');
}
</code>```

答:
you can also try in your destination Component:

```<code>@Component({
  selector: 'app-a',
  template: `
  <h1>A</h1>
  <p> params: {{params | json}}</p>
  <p> query params: {{queryParams | json}}</p>
  <p> url: {{url}}</p>
  <p> full url: {{fullUrl}}</p>`
})
export class AComponent  {
  params;
  queryParams;
  url;
  fullUrl;

  constructor(private route: ActivatedRoute, private router: Router ) { }

  ngOnInit() {
    this.params = this.route.snapshot.params;
    this.queryParams = this.route.snapshot.queryParams;
    this.url = this.route.snapshot.url.join('');
    this.fullUrl = this.router.url;
  }
}
</code>```

working DEMO

Title: Extract URL parameter

Body:
I am trying to get a URL parameter from the following URL

http://localhost:4200/#/candidate/login/?corporateid=66d8c83c-841a-42e8-945c-beb8c1af25ef&userid=cb2147ed-bd42-4b9f-82d4-0dcef861e24d&token=CfDJ8Ie7+UQ8GQRBtQNOMB6ytQXk0OvqW+/l9W1yh3gCLQw7Sa606eaQtWAC472uUrsUnMQtt69R4gF7f6aab/lIdToo9AfiwtJ7wlsdYnomPpo1OgOaIUZZVBtEaBxRfuJin/Rl+WO+AnvHAn6v4Sf2yO+2gkNotCw0yLsfgzKYOwOciVRDHWY5mNktbGsRCb96kbnxd6VyW02Vs7szuSBG4Ow5fFdtvVUkQDj+ne4HZQAyvts8pNOOkNT/g+cCbOO/wA==

The parameter value that I need is the userid but I seem to be getting a null.

Here is my code

location = window.location;
urlHref = location.href;
urlConvert = new URL(this.urlHref);

if (location.toString().includes('userid')) {
  this.userId = this.urlConvert.searchParams.get("userid");
  console.log(this.userId);
} else {
  this.userId = 'user';
  console.log('gets user not candidate');
}

Body:
you can also try in your destination Component:

@Component({
  selector: 'app-a',
  template: `
  <h1>A</h1>
  <p> params: {{params | json}}</p>
  <p> query params: {{queryParams | json}}</p>
  <p> url: {{url}}</p>
  <p> full url: {{fullUrl}}</p>`
})
export class AComponent  {
  params;
  queryParams;
  url;
  fullUrl;

  constructor(private route: ActivatedRoute, private router: Router ) { }

  ngOnInit() {
    this.params = this.route.snapshot.params;
    this.queryParams = this.route.snapshot.queryParams;
    this.url = this.route.snapshot.url.join('');
    this.fullUrl = this.router.url;
  }
}

working DEMO


问:
Why won't my If statement with multiple -AND conditions function correctly?
I am wanting to meet multiple conditions in my Powershell If statement and am trying to use the -AND operator to achieve it, but it seems to be just jumping straight to the else clause.

In the code below I want to make sure both folders have no files and that the "watcher.txt" file exists.

```<code>$Success = "C:\temp\Success"
$Failed = "C:\temp\failed"
$watcher = "C:\temp\watcher.txt"

$directoryInfo3 = get-childitem "$Success\\*" -file | Measure-Object
$directoryInfo3.count
$directoryInfo4 = get-childitem "$Failed\\*" -file | Measure-Object
$directoryInfo4.count
    if ((test-path -path $Watcher) -AND
        ($directoryInfo3 -eq 0) -AND
        ($directoryInfo4 -eq 0)){
         Write-host "Success folder and Failed folder are empty, and Watcher file exists."}
         else
         {Write-host "Not complete yet, rechecking folders."}
</code>```

If all three statements are true, then I should see "Success folder and Failed folder are empty, and Watcher file exists."

Instead I am seeing "Not complete yet, rechecking folders." no matter what the condition is, even if all three are true.

答:
As you don't seem to be interested in the count or content of the Get-ChildItem,

you could use Test-Path for all 3 conditions

```<code>## Q:\Test\2019\05\30\SO_56373080.ps1
$Success =  "C:\temp\Success"
$Failed  =  "C:\temp\failed"
$watcher =  "C:\temp\watcher.txt"

if ( (Test-Path -Path $Watcher   -PathType Leaf) -AND
    !(Test-Path -Path $Success\* -PathType Leaf) -AND
    !(Test-Path -Path $Failed\*  -PathType Leaf)){
    Write-host "Success folder and Failed folder are empty, and Watcher file exists."
} else {
    Write-host "Not complete yet, rechecking folders."
}
</code>```

Here ! = Not inverses the boolean result.

Body:
I am wanting to meet multiple conditions in my Powershell If statement and am trying to use the -AND operator to achieve it, but it seems to be just jumping straight to the else clause.

In the code below I want to make sure both folders have no files and that the "watcher.txt" file exists.

$Success = "C:\temp\Success"
$Failed = "C:\temp\failed"
$watcher = "C:\temp\watcher.txt"

$directoryInfo3 = get-childitem "$Success\\*" -file | Measure-Object
$directoryInfo3.count
$directoryInfo4 = get-childitem "$Failed\\*" -file | Measure-Object
$directoryInfo4.count
    if ((test-path -path $Watcher) -AND
        ($directoryInfo3 -eq 0) -AND
        ($directoryInfo4 -eq 0)){
         Write-host "Success folder and Failed folder are empty, and Watcher file exists."}
         else
         {Write-host "Not complete yet, rechecking folders."}

If all three statements are true, then I should see "Success folder and Failed folder are empty, and Watcher file exists."

Instead I am seeing "Not complete yet, rechecking folders." no matter what the condition is, even if all three are true.

Body:
As you don't seem to be interested in the count or content of the Get-ChildItem,

you could use Test-Path for all 3 conditions

## Q:\Test\2019\05\30\SO_56373080.ps1
$Success =  "C:\temp\Success"
$Failed  =  "C:\temp\failed"
$watcher =  "C:\temp\watcher.txt"

if ( (Test-Path -Path $Watcher   -PathType Leaf) -AND
    !(Test-Path -Path $Success\* -PathType Leaf) -AND
    !(Test-Path -Path $Failed\*  -PathType Leaf)){
    Write-host "Success folder and Failed folder are empty, and Watcher file exists."
} else {
    Write-host "Not complete yet, rechecking folders."
}

Here ! = Not inverses the boolean result.


问:
Freebase query - exclusion of certain values
I want to retrieve name of all movies and their genre. It's ok if information about genre is empty, but if genre is known I want to retrieve it.

```<code>"/film/film/genre": [{"id":null,"optional":"optional"}]
</code>```

But I'm not interested in gay pornography, so I want to exclude all movies with genre "/en/gay_pornography".

```<code>"/film/film/genre": [{"id|=":["/en/gay_pornography"],"optional":"forbidden"}]
</code>```

The problem is, how to combine it in one query? I.e. how to get all movies, even those with no genre and exclude pr0n?

Edit: it's required to exclude multiple genres, e.g. also /en/pornographic_movie

答:
You're basically there: you just need two "genre" clauses. MQL lets you do this by allowing arbitrary prefixes on any clause:

```[{
  "id":   null,
  "type": "/film/film",
  "genre": [{
    "id":       null,
    "optional": true
  }],
  "forbid:genre": {
    "id|=": [
      "/en/gay_pornography",
      "/en/pornographic_movie"
    ],
    "optional": "forbidden"
  }
}]```

http://tinyurl.com/4449ufg

ContentLicense: CC BY-SA 3.0

Body:
I want to retrieve name of all movies and their genre. It's ok if information about genre is empty, but if genre is known I want to retrieve it.

"/film/film/genre": [{"id":null,"optional":"optional"}]

But I'm not interested in gay pornography, so I want to exclude all movies with genre "/en/gay_pornography".

"/film/film/genre": [{"id|=":["/en/gay_pornography"],"optional":"forbidden"}]

The problem is, how to combine it in one query? I.e. how to get all movies, even those with no genre and exclude pr0n?

Edit: it's required to exclude multiple genres, e.g. also /en/pornographic_movie

Body:
You're basically there: you just need two "genre" clauses. MQL lets you do this by allowing arbitrary prefixes on any clause:

[{
  "id":   null,
  "type": "/film/film",
  "genre": [{
    "id":       null,
    "optional": true
  }],
  "forbid:genre": {
    "id|=": [
      "/en/gay_pornography",
      "/en/pornographic_movie"
    ],
    "optional": "forbidden"
  }
}]

http://tinyurl.com/4449ufg


问:
how can i get 1dimension to 3dimension reshape?
here is my code

```<code>
def create_dataset(signal_data, look_back=1):
    dataX, dataY = [], []
    for i in range(len(signal_data) - look_back):
        dataX.append(signal_data[i:(i + look_back), 0])
        dataY.append(signal_data[i + look_back, 0])
    return np.array(dataX), np.array(dataY)

look_back = 20
...

train_size = int(len(data) * 0.80)

test_size = len(data) - train_size

train = data[0:train_size]

test = data[train_size:len(data)]

x_train, y_train = create_dataset(train, look_back)

x_test, y_test = create_dataset(test, look_back)

</code>```

then x_train shape is (62796, 20) and y_train shape is(62796,)

I use this data to LSTM

so, reshape x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1)) is done

(now x_train.shape is (62796, 20, 1) )

but y_train shape is (62796,) So, i can't reshape 1D -> 3D

how can i y_train reshape 1D ->3D

i want y_train shape as (62796, 20, 1) because want to LSTM return_sequences=True parameter

答:
Is that what you're looking for?

```<code>y_train = np.ones(100)
print(y_train.shape) #prints (100,)
y_train = y_train.reshape(-1,1,1)
print(y_train.shape) # prints (100,1,1)
</code>```

EDIT: Final solution, after brief discussion in comments:

```<code>y_train=np.repeat(y_train.reshape(-1,1), 20, axis=1).reshape(-1,20,1)
</code>```

Body:
here is my code

def create_dataset(signal_data, look_back=1):
    dataX, dataY = [], []
    for i in range(len(signal_data) - look_back):
        dataX.append(signal_data[i:(i + look_back), 0])
        dataY.append(signal_data[i + look_back, 0])
    return np.array(dataX), np.array(dataY)

look_back = 20
...

train_size = int(len(data) * 0.80)

test_size = len(data) - train_size

train = data[0:train_size]

test = data[train_size:len(data)]

x_train, y_train = create_dataset(train, look_back)

x_test, y_test = create_dataset(test, look_back)

then x_train shape is (62796, 20) and y_train shape is(62796,)

I use this data to LSTM

so, reshape x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1)) is done

(now x_train.shape is (62796, 20, 1) )

but y_train shape is (62796,) So, i can't reshape 1D -> 3D

how can i y_train reshape 1D ->3D

i want y_train shape as (62796, 20, 1) because want to LSTM return_sequences=True parameter

Body:
Is that what you're looking for?

y_train = np.ones(100)
print(y_train.shape) #prints (100,)
y_train = y_train.reshape(-1,1,1)
print(y_train.shape) # prints (100,1,1)

EDIT: Final solution, after brief discussion in comments:

y_train=np.repeat(y_train.reshape(-1,1), 20, axis=1).reshape(-1,20,1)


问:
libgdx lag when sound.play() while collecting apple
I'am doing simple libgdx game. I have lag (game stop for 0. 5 sec) when i use sound.play()
edit this bug apear on android 4.0 on 2.3 everything is running fine.

method. I play sound by this code:

```<code>if(CollisionDetector.detect(touchArea, hoodie.getTouchArea())){
        GameScreen.totalScore++;
        setPosition();
        System.out.println("played");

        Assets.eatSound.play();

}
</code>```

And i use this method to load sound:

```<code> static long waitForLoadCompleted(Sound sound,float volume) {
        long id;
        while ((id = sound.play(volume)) == -1) {
            long t = TimeUtils.nanoTime();
            while (TimeUtils.nanoTime() - t < 100000000);
        }
        return id;
 }
</code>```

What am i doing wrong? Or what can i do to fix this lag ?

edit:

I have just tried to do thread with sound.play() but it also doesn't work:

```<code>    new Thread(new Runnable() {
           @Override
           public void run() {
              // do something important here, asynchronously to the rendering thread

              // post a Runnable to the rendering thread that processes the result
              Gdx.app.postRunnable(new Runnable() {
                 @Override
                 public void run() {
                    // process the result, e.g. add it to an Array<Result> field of the ApplicationListener.
                eatSound2.play();
                 }
              });
           }
        }).start();
</code>```

My Sound asset class looks like this but i still have lag with sound.
package com.redHoodie;

```<code>import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.utils.Disposable;

public class SoundEffect implements Disposable {
   private static final int WaitLimit = 1000;
   private static final int ThrottleMs = 100;
    Sound eatSound;
    Sound endSound;

    public SoundEffect(){
        eatSound = Gdx.audio.newSound(Gdx.files.internal("eatSound.ogg"));
        endSound = Gdx.audio.newSound(Gdx.files.internal("sadend.wav"));

        checkedPlay(eatSound);
    }

   protected long checkedPlay (Sound sound) {
      return checkedPlay(sound, 1);
   }

   protected long checkedLoop (Sound sound) {
      return checkedLoop(sound, 1);
   }

   protected long checkedPlay (Sound sound, float volume) {
      int waitCounter = 0;
      long soundId = 0;

      boolean ready = false;
      while (!ready && waitCounter < WaitLimit) {
         soundId = sound.play(volume);
         ready = (soundId != 0);
         waitCounter++;
         try {
            Thread.sleep(ThrottleMs);
         } catch (InterruptedException e) {
         }
      }

      return soundId;
   }

   protected long checkedLoop (Sound sound, float volume) {
      int waitCounter = 0;
      long soundId = 0;

      boolean ready = false;
      while (!ready && waitCounter < WaitLimit) {
         soundId = sound.loop(volume);
         ready = (soundId != 0);
         waitCounter++;
         try {
            Thread.sleep(ThrottleMs);
         } catch (InterruptedException e) {
         }
      }

      return soundId;
   }

@Override
public void dispose() {
    // TODO Auto-generated method stub

}
}
</code>```

答: Lately I run into the same issue (except I'm using wav instead mp3 files). My app was lagging when I play many (like 10 or 20) sounds at the same time (same render method). "Solved" this by playing only 1 sound at the time. Generally it's hard to distinct many sounds at the same time. Also on desktop it works fine, but problem appears on android (9 or 8).</p>

Body:
I'am doing simple libgdx game. I have lag (game stop for 0. 5 sec) when i use sound.play()
edit this bug apear on android 4.0 on 2.3 everything is running fine.

method. I play sound by this code:

if(CollisionDetector.detect(touchArea, hoodie.getTouchArea())){
        GameScreen.totalScore++;
        setPosition();
        System.out.println("played");

        Assets.eatSound.play();

}

And i use this method to load sound:

 static long waitForLoadCompleted(Sound sound,float volume) {
        long id;
        while ((id = sound.play(volume)) == -1) {
            long t = TimeUtils.nanoTime();
            while (TimeUtils.nanoTime() - t < 100000000);
        }
        return id;
 }

What am i doing wrong? Or what can i do to fix this lag ?

edit:

I have just tried to do thread with sound.play() but it also doesn't work:

    new Thread(new Runnable() {
           @Override
           public void run() {
              // do something important here, asynchronously to the rendering thread

              // post a Runnable to the rendering thread that processes the result
              Gdx.app.postRunnable(new Runnable() {
                 @Override
                 public void run() {
                    // process the result, e.g. add it to an Array<Result> field of the ApplicationListener.
                eatSound2.play();
                 }
              });
           }
        }).start();

My Sound asset class looks like this but i still have lag with sound.
package com.redHoodie;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.utils.Disposable;

public class SoundEffect implements Disposable {
   private static final int WaitLimit = 1000;
   private static final int ThrottleMs = 100;
    Sound eatSound;
    Sound endSound;

    public SoundEffect(){
        eatSound = Gdx.audio.newSound(Gdx.files.internal("eatSound.ogg"));
        endSound = Gdx.audio.newSound(Gdx.files.internal("sadend.wav"));

        checkedPlay(eatSound);
    }

   protected long checkedPlay (Sound sound) {
      return checkedPlay(sound, 1);
   }

   protected long checkedLoop (Sound sound) {
      return checkedLoop(sound, 1);
   }

   protected long checkedPlay (Sound sound, float volume) {
      int waitCounter = 0;
      long soundId = 0;

      boolean ready = false;
      while (!ready && waitCounter < WaitLimit) {
         soundId = sound.play(volume);
         ready = (soundId != 0);
         waitCounter++;
         try {
            Thread.sleep(ThrottleMs);
         } catch (InterruptedException e) {
         }
      }

      return soundId;
   }

   protected long checkedLoop (Sound sound, float volume) {
      int waitCounter = 0;
      long soundId = 0;

      boolean ready = false;
      while (!ready && waitCounter < WaitLimit) {
         soundId = sound.loop(volume);
         ready = (soundId != 0);
         waitCounter++;
         try {
            Thread.sleep(ThrottleMs);
         } catch (InterruptedException e) {
         }
      }

      return soundId;
   }

@Override
public void dispose() {
    // TODO Auto-generated method stub

}
}


问:
update column table with value of column from table b if it contains substring from another column from table b
There are 2 table like below:

```<code>Table a                        Table b

country_name                   id | string_bone   | country_name
------------------------       ---+---------------+---------------
usa                            1  | usa           | united states
u s a                          2  | u s a         | united states
united states of america       3  | america       | united states
america                        4  | ...           | ...
</code>```

I need to update table_a.country_name with table_b.country_name if table_b.string_bone is contained in table_a.country_name.

I tried this:

```<code>UPDATE table_a a
SET country_name = b.country_name
WHERE EXISTS (SELECT country_name
              FROM table_b
              WHERE a.country_name LIKE '%' || string_bone || '%') b;
</code>```

I would like table_a to look like this after the update:

```<code>Table a

country_name
------------------------
united states
united states
united states
united states
</code>```

Here the dbfiddle link.

答:
OK, it's easy to implement this requirement, like below:

```<code>update table_a a set country_name = b.country_name from table_b b where a.country_name ~ b.country_name;
</code>```

The data example as below:

```<code>postgres=# select * from table_a;
       country_name
--------------------------
 usa
 u s a
 united states of america
 america
(4 rows)

postgres=# select * from table_b;
 country_name
--------------
 america
 usa
 u s a
(3 rows)

postgres=# update table_a a set country_name = b.country_name from table_b b where a.country_name ~ b.country_name;
UPDATE 4
postgres=# select * from table_a;
 country_name
--------------
 usa
 u s a
 america
 america
(4 rows)
</code>```

Body:
There are 2 table like below:

Table a                        Table b

country_name                   id | string_bone   | country_name
------------------------       ---+---------------+---------------
usa                            1  | usa           | united states
u s a                          2  | u s a         | united states
united states of america       3  | america       | united states
america                        4  | ...           | ...

I need to update table_a.country_name with table_b.country_name if table_b.string_bone is contained in table_a.country_name.

I tried this:

UPDATE table_a a
SET country_name = b.country_name
WHERE EXISTS (SELECT country_name
              FROM table_b
              WHERE a.country_name LIKE '%' || string_bone || '%') b;

I would like table_a to look like this after the update:

Table a

country_name
------------------------
united states
united states
united states
united states

Here the dbfiddle link.

Body:
OK, it's easy to implement this requirement, like below:

update table_a a set country_name = b.country_name from table_b b where a.country_name ~ b.country_name;

The data example as below:

postgres=# select * from table_a;
       country_name
--------------------------
 usa
 u s a
 united states of america
 america
(4 rows)

postgres=# select * from table_b;
 country_name
--------------
 america
 usa
 u s a
(3 rows)

postgres=# update table_a a set country_name = b.country_name from table_b b where a.country_name ~ b.country_name;
UPDATE 4
postgres=# select * from table_a;
 country_name
--------------
 usa
 u s a
 america
 america
(4 rows)


问:
How to get the location of user using observepoint API
I am looking for some help on how I can use the Observepoint API to get the location from where the Audit was created. I am using Django.

Using the example on https://docs.api.observepoint.com/v2/web-audits/w43h2it5WmM2srcC2

This is my current code:

```<code>payload = "{}"
headers = { 'authorization': "api_key " + API_KEY}
get_user_loc = 'https://api.observepoint.com/v2/web-audits/locations'
response_loc = requests.request("GET", get_user_loc, data=payload,
headers=headers)
ping = response_loc.json()
print(type(ping[1]))
for x in ping:
   print(x["name"], " = ", x["label"])
</code>```

This is giving me all the locations it has.

```<code>mountain  =  Direct - Oregon, US
west  =  Proxy - N. California, US
eastern  =  Proxy - N. Virginia, US
emea  =  Proxy - Dublin, Ireland
apac  =  Proxy - Tokyo, Japan
brazil  =  Proxy - Sao Paulo, Brazil
london  =  Proxy - London, England
germany  =  Proxy - Frankfurt, Germany
singapore  =  Proxy - Singapore
australia  =  Proxy - Sydney, Australia
</code>```

How do I get the exact current location and match it to one of these?

答:
If you want to get the location containing the word "Direct", you can do this so:

```<code>for x in ping:
   if "Direct" in x["label"]:
       print(x["name"], " = ", x["label"])
</code>```

If you want to know your geolocation use geoip

Body:
I am looking for some help on how I can use the Observepoint API to get the location from where the Audit was created. I am using Django.

Using the example on https://docs.api.observepoint.com/v2/web-audits/w43h2it5WmM2srcC2

This is my current code:

payload = "{}"
headers = { 'authorization': "api_key " + API_KEY}
get_user_loc = 'https://api.observepoint.com/v2/web-audits/locations'
response_loc = requests.request("GET", get_user_loc, data=payload,
headers=headers)
ping = response_loc.json()
print(type(ping[1]))
for x in ping:
   print(x["name"], " = ", x["label"])

This is giving me all the locations it has.

mountain  =  Direct - Oregon, US
west  =  Proxy - N. California, US
eastern  =  Proxy - N. Virginia, US
emea  =  Proxy - Dublin, Ireland
apac  =  Proxy - Tokyo, Japan
brazil  =  Proxy - Sao Paulo, Brazil
london  =  Proxy - London, England
germany  =  Proxy - Frankfurt, Germany
singapore  =  Proxy - Singapore
australia  =  Proxy - Sydney, Australia

How do I get the exact current location and match it to one of these?

Body:
If you want to get the location containing the word "Direct", you can do this so:

for x in ping:
   if "Direct" in x["label"]:
       print(x["name"], " = ", x["label"])

If you want to know your geolocation use geoip


问:
clang-2.9 crt1 not found error
Just compiled clang-2.9 release and it can't link an hello world example. There is the error:

```<code>crt1.o: No such file: No such file or directory
</code>```

LLVM is configured as default + --enable-shared. The llvm-2.8 build with same options works normally on the same machine.

```<code>$ clang -v a.c
clang version 2.9 (tags/RELEASE_29/final)
Target: i386-pc-linux-gnu
Thread model: posix
 "/root/bin/clang" -cc1 -triple i386-pc-linux-gnu -emit-obj -mrelax-all -disable-free -disable-llvm-verifier -main-file-name a.c -mrelocation-model static -mdisable-fp-elim -masm-verbose -mconstructor-aliases -target-cpu pentium4 -target-linker-version 2.18 -momit-leaf-frame-pointer -v -resource-dir /root/lib/clang/2.9 -ferror-limit 19 -fmessage-length 157 -fgnu-runtime -fdiagnostics-show-option -fcolor-diagnostics -o /tmp/cc-2ueoYy.o -x c a.c
clang -cc1 version 2.9 based upon llvm 2.9 hosted on i386-pc-linux-gnu
ignoring nonexistent directory "/usr/local/include"
#include "..." search starts here:
#include <...> search starts here:
 /root/lib/clang/2.9/include
 /usr/include
End of search list.
a.c:1:1: warning: type specifier missing, defaults to 'int' [-Wimplicit-int]
main(){}
^~~~
1 warning generated.
 "/usr/bin/ld" --eh-frame-hdr -m elf_i386 -dynamic-linker /lib/ld-linux.so.2 -o a.out crt1.o crti.o crtbegin.o -L -L/../../.. /tmp/cc-2ueoYy.o -lgcc --as-needed -lgcc_s --no-as-needed -lc -lgcc --as-needed -lgcc_s --no-as-needed crtend.o crtn.o
/usr/bin/ld: crt1.o: No such file: No such file or directory
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

The same error was here http://permalink.gmane.org/gmane.comp.compilers.clang.devel/12101
and http://comments.gmane.org/gmane.comp.compilers.clang.devel/14269 and http://permalink.gmane.org/gmane.comp.compilers.llvm.bugs/11352

What I can learn while comparing with llvm-2.8 -- newer version tries to assemble file itself, and older version calls gcc to do assemble and link steps.

Please, this is not a duplicate of clang linker problem as I can't edit sources of LLVM, so the accepted solution isn't useful to me.

答:
As suggested at http://permalink.gmane.org/gmane.comp.compilers.llvm.bugs/11352 (llvm bug 8897) this is because

```<code>gcc used to build clang is not in a standard location
</code>```

or

```<code>system gcc is not listed in the ToolChains.cpp GccVersions list:

./tools/clang/lib/Driver/ToolChains.cpp:  const char* GccVersions[] = {"4.5.2", "4.5.1", "4.5", "4.4.5", "4.4.4",
./tools/clang/lib/Driver/ToolChains.cpp-                               "4.4.3", "4.4", "4.3.4", "4.3.3", "4.3.2",
./tools/clang/lib/Driver/ToolChains.cpp-                               "4.3", "4.2.4", "4.2.3", "4.2.2", "4.2.1",
./tools/clang/lib/Driver/ToolChains.cpp-                               "4.2"};
</code>```

Both cases are true for my installation.

To fix this, I'll try to add my version of gcc into list GccVersions[].

This helps me.

Title: clang-2.9 crt1 not found error

Body:
Just compiled clang-2.9 release and it can't link an hello world example. There is the error:

crt1.o: No such file: No such file or directory

LLVM is configured as default + --enable-shared. The llvm-2.8 build with same options works normally on the same machine.

$ clang -v a.c
clang version 2.9 (tags/RELEASE_29/final)
Target: i386-pc-linux-gnu
Thread model: posix
 "/root/bin/clang" -cc1 -triple i386-pc-linux-gnu -emit-obj -mrelax-all -disable-free -disable-llvm-verifier -main-file-name a.c -mrelocation-model static -mdisable-fp-elim -masm-verbose -mconstructor-aliases -target-cpu pentium4 -target-linker-version 2.18 -momit-leaf-frame-pointer -v -resource-dir /root/lib/clang/2.9 -ferror-limit 19 -fmessage-length 157 -fgnu-runtime -fdiagnostics-show-option -fcolor-diagnostics -o /tmp/cc-2ueoYy.o -x c a.c
clang -cc1 version 2.9 based upon llvm 2.9 hosted on i386-pc-linux-gnu
ignoring nonexistent directory "/usr/local/include"
#include "..." search starts here:
#include <...> search starts here:
 /root/lib/clang/2.9/include
 /usr/include
End of search list.
a.c:1:1: warning: type specifier missing, defaults to 'int' [-Wimplicit-int]
main(){}
^~~~
1 warning generated.
 "/usr/bin/ld" --eh-frame-hdr -m elf_i386 -dynamic-linker /lib/ld-linux.so.2 -o a.out crt1.o crti.o crtbegin.o -L -L/../../.. /tmp/cc-2ueoYy.o -lgcc --as-needed -lgcc_s --no-as-needed -lc -lgcc --as-needed -lgcc_s --no-as-needed crtend.o crtn.o
/usr/bin/ld: crt1.o: No such file: No such file or directory
clang: error: linker command failed with exit code 1 (use -v to see invocation)

The same error was here http://permalink.gmane.org/gmane.comp.compilers.clang.devel/12101
and http://comments.gmane.org/gmane.comp.compilers.clang.devel/14269 and http://permalink.gmane.org/gmane.comp.compilers.llvm.bugs/11352

What I can learn while comparing with llvm-2.8 -- newer version tries to assemble file itself, and older version calls gcc to do assemble and link steps.

Please, this is not a duplicate of clang linker problem as I can't edit sources of LLVM, so the accepted solution isn't useful to me.

Body:
As suggested at http://permalink.gmane.org/gmane.comp.compilers.llvm.bugs/11352 (llvm bug 8897) this is because

gcc used to build clang is not in a standard location

or

system gcc is not listed in the ToolChains.cpp GccVersions list:

./tools/clang/lib/Driver/ToolChains.cpp:  const char* GccVersions[] = {"4.5.2", "4.5.1", "4.5", "4.4.5", "4.4.4",
./tools/clang/lib/Driver/ToolChains.cpp-                               "4.4.3", "4.4", "4.3.4", "4.3.3", "4.3.2",
./tools/clang/lib/Driver/ToolChains.cpp-                               "4.3", "4.2.4", "4.2.3", "4.2.2", "4.2.1",
./tools/clang/lib/Driver/ToolChains.cpp-                               "4.2"};

Both cases are true for my installation.

To fix this, I'll try to add my version of gcc into list GccVersions[].

This helps me.


问:
How to get Unique DeviceID from Xamarin IOS
I have a requirement wherein I should not allow the user to install my app in more than 1 device. This is an enterprise application and I distributed this using Enterprise developer account. Based on the Google search I use IdentifierForVendor to get unique device ID, but this doesn't seem to work now as when the user uninstalls and installs the new/same version of the app in the same device again, it returns new DeviceID. Now I am back to my old question - How to find a DeviceID for IOS?

What I think is a possible approach is to deactivate the DeviceID when the user uninstalls the application. But I am not sure how to achieve this as there are no cycle/function calls when the app is uninstalled.

答:
Apple documentation says if all the apps from the same vendor is uninstalled from the device, then at the time of new installation of any app from that vendor will take new IdentifierForVendor.

So I would suggest store this unique id in Keychain and whenever you open the app  check if there is any unique id stored in keychain if not then generate one and keep it there.

If app in uninstalled also , the key will be still there.

After you re-install the app , when you access the key in keychain it'll be still there.

This way you can achieve your objective of uniquely tracking a device.

Talking of keychain , it's worthwhile to take a look at Xamarin.Essentials Nuget.It provides many cross platform features including keychain.

Hope this helps.


问:
my sql dont return value having special character
my sql query returns no  result when  just the value to return
have special character. exemple :

the query is :

```<code>$sql = "SELECT * from categorie ";

    $result = $conn->query(sprintf($sql));
</code>```

the result was in json

```<code>   {"rows":2,"categorie":[{"idCategorie":"8","nomCategorie":"loisir ","imageCategorie":"imgCategorie1.png"},{"idCategorie":"9","nomCategorie":"destination","imageCategorie":"imgCategorie2.png"}],"message":"Liste cat\u00e9gorie","error":0}
</code>```

But when I change the "nomCategorie" from "loisir" to "quelle loisir avez vous ??

The query dont return any thing or make chane like nomCategorie =cinéma paris

it doesn't work. So I've cancel all the space and the special character and it works

答:
I had a very similar problem. Any time I was trying to get data with special characters it wasn't being returned. Then I found this very comprehensive guide:

https://www.toptal.com/php/a-utf-8-primer-for-php-and-mysql

It wasn't really clear in the question what mysql connector you were using but this guide should have what you are looking for. Here is a basic mysql connection:

```<code> $link = mysql_connect('localhost', 'user', 'password');
  mysql_set_charset('utf8', $link);
</code>```

Useful also to note was setting your special characters for display in php within the header:

```<code>header('Content-Type: text/html; charset=utf-8');
</code>```

Hope that helps!

Body:
my sql query returns no  result when  just the value to return
have special character. exemple :

the query is :

$sql = "SELECT * from categorie ";

    $result = $conn->query(sprintf($sql));

the result was in json

   {"rows":2,"categorie":[{"idCategorie":"8","nomCategorie":"loisir ","imageCategorie":"imgCategorie1.png"},{"idCategorie":"9","nomCategorie":"destination","imageCategorie":"imgCategorie2.png"}],"message":"Liste cat\u00e9gorie","error":0}

But when I change the "nomCategorie" from "loisir" to "quelle loisir avez vous ??

The query dont return any thing or make chane like nomCategorie =cinéma paris

it doesn't work. So I've cancel all the space and the special character and it works

Body:
I had a very similar problem. Any time I was trying to get data with special characters it wasn't being returned. Then I found this very comprehensive guide:

https://www.toptal.com/php/a-utf-8-primer-for-php-and-mysql

It wasn't really clear in the question what mysql connector you were using but this guide should have what you are looking for. Here is a basic mysql connection:

 $link = mysql_connect('localhost', 'user', 'password');
  mysql_set_charset('utf8', $link);

Useful also to note was setting your special characters for display in php within the header:

header('Content-Type: text/html; charset=utf-8');

Hope that helps!


问:
In Java how do I initialize elements in array in several lines, not one?
Hello this is a very simple question but I don't know the answer.
I just want to know how to initialize every element of an array in several lines, because I know how to do it in one line.

My code of initializing them on one line is this way:

```<code>String input = scanner.nextLine();

String[] array = input.split("\\s+");
</code>```

答:
In Java, Array must have fixed size, and you cannot change it once declared. About your problem, you can create an Array which has the size is greater than your expectation. Because you don't know how many it will loop, you can make the while loop and a marker to stop inputing ("quit" or "stop" or something else special user can't input...). Eg:</p>

```<code>String[] arr = new String[1000];
Scanner scanner = new Scanner(System.in);
int counter = 0;

while (true) {
    String input = scanner.nextLine();
    if ("stop".equalsIgnoreCase(input)) {
        break;
    }
    arr[counter++] = input;
}
</code>```

Body:
Hello this is a very simple question but I don't know the answer.
I just want to know how to initialize every element of an array in several lines, because I know how to do it in one line.

My code of initializing them on one line is this way:

String input = scanner.nextLine();

String[] array = input.split("\\s+");

Body:
In Java, Array must have fixed size, and you cannot change it once declared. About your problem, you can create an Array which has the size is greater than your expectation. Because you don't know how many it will loop, you can make the while loop and a marker to stop inputing ("quit" or "stop" or something else special user can't input...). Eg:

String[] arr = new String[1000];
Scanner scanner = new Scanner(System.in);
int counter = 0;

while (true) {
    String input = scanner.nextLine();
    if ("stop".equalsIgnoreCase(input)) {
        break;
    }
    arr[counter++] = input;
}


问:
Python: Add contents of a csv file to a list
have a new issue with this that I could do with some help on.
Like before i am passing a csv (with comma as separator) into a list.
the first element in the list will always be an integer but the next two will be strings.
I'm trying to add a new line to the csv which will have an incremented number in the first element but I will also add hash strings in the other two elements.
It works on the first run as the file is empty but when it tries a second run I get an error

chain_list = [int(i) for i in lineList[-1].split(',')]

ValueError: invalid literal for int() with base 10: '9891b18cf04418b92c0ee611201da47ef00471090aebdfa6667097d81d0832cb2edab83f65a4dc497fbffc4332d7e794'

The first line of the file that i'm passing in contains:

1,0,9891b18cf04418b92c0ee611201da47ef00471090aebdfa6667097d81d0832cb2edab83f65a4dc497fbffc4332d7e794

My code looks like this at the minute. Not sure how to get around this?

#Check if chain_info.txt exists
CHAIN_FILE_exists = os.path.isfile(CHAIN_FILE)
#If chainfile is empty set element 0 in list to 1
if CHAIN_FILE_exists:
    if os.stat(CHAIN_FILE).st_size == 0:
        print('empty')
        fileHandle = open (CHAIN_FILE, 'a')
        fileHandle.write('1,0,0')
        fileHandle.close()
        fileHandle = open (CHAIN_FILE)
        lineList = fileHandle.readlines()
        fileHandle.close()
        chain_list = lineList[-1].split(',')
        chain_list = [int(i) for i in lineList[-1].split(',')]
        increment_value = 1
        print('1 chain list now is: ' + str(chain_list))
    else:
        #Read the last line of a file
        fileHandle = open (CHAIN_FILE)
        lineList = fileHandle.readlines()
        fileHandle.close()
        #Take last line of file and add to a list called chain_list
        chain_list = lineList[-1].split(',')
        chain_list = [int(i) for i in lineList[-1].split(',')]
        #increment the first value in the list by 1, this will be used to determine the block number
        increment_value = (chain_list[0])
        increment_value = increment_value +1
        chain_list.remove (chain_list[0])
        chain_list.insert (0,increment_value)
        print('chain list now is: ' + str(chain_list))
        #Open file
        fileHandle = open (CHAIN_FILE, 'a')
        #Write the contents of the list to the chain file on a new line and separate with a comma
        fileHandle.write('\n' + str(chain_list[0]) + ',' + str(chain_list[1]))
        fileHandle.close()
else:
    print ('file does not exist')
```

答:
You can use the csv module to parse the CSV content row-wise. Simply advance to the last line then, discarding intermediate data:

```<code>import csv

with open('c:\\securelog_workfiles\\chain_info.txt') as data:
    for row in csv.reader(data):  # parse each line to a row
        continue  # skip through the csv row-wise
    last_line_data = row
</code>```

This works for arbitrarily large files, since it only ever loads individual lines instead of the entire file at once.

If the file is huge and you want to avoid the overhead of parsing discarded lines, advance to the last line and parse only that. You can either use next(csv.reader([row])) to parse the last line, or something like row.split(...) if the format is simple:

```<code>with open('c:\\securelog_workfiles\\chain_info.txt') as data:
    for row in data:  # do not parse each line
        continue  # skip through the csv row-wise
    last_line_data = row.split(',')  # parse the last line explicitly
</code>```

Body:
You can use the csv module to parse the CSV content row-wise. Simply advance to the last line then, discarding intermediate data:

import csv

with open('c:\\securelog_workfiles\\chain_info.txt') as data:
    for row in csv.reader(data):  # parse each line to a row
        continue  # skip through the csv row-wise
    last_line_data = row

This works for arbitrarily large files, since it only ever loads individual lines instead of the entire file at once.

If the file is huge and you want to avoid the overhead of parsing discarded lines, advance to the last line and parse only that. You can either use next(csv.reader([row])) to parse the last line, or something like row.split(...) if the format is simple:

with open('c:\\securelog_workfiles\\chain_info.txt') as data:
    for row in data:  # do not parse each line
        continue  # skip through the csv row-wise
    last_line_data = row.split(',')  # parse the last line explicitly


问:
How to get response body of a post request without escape sequences in Java?
I am trying to convert the HttpResponse's response body to a String using the following piece of code:

```<code>HttpGet request = new HttpGet(url);
request.setHeader("Accept", "application/json");
response = client.execute(request);
EntityUtils.toString(response.getEntity(), standardCharsets.UTF_8.displayName());
</code>```

The expected response after converting it to a String is as follows:

```<code>{"errors": ["permission denied"]}
</code>```

This code was working fine until recently. But now the response body is somehow being modified to this:

```<code>{"errors":["1 error occurred:\n\t* permission denied\n\n"]}
</code>```

I do not understand how the "1 error occurred" message is being inserted into the response body as the response from the same call in Postman gives me the appropriate response i.e.:

{"errors": ["permission denied"]}

And I've checked the code thoroughly and am certain that the "1 error occurred" message is not being inserted manually.

EDIT:

These were the response headers from Postman:

```<code>cache-control →no-store
content-length →33
content-type →application/json
date →Thu, 30 May 2019 06:52:33 GMT
status →403
</code>```

And these were the response headers from the HttpClient call:

```<code>Cache-Control: no-store
Content-Type: application/json
Date: Thu, 30 May 2019 09:06:21 GMT
Content-Length: 60
</code>```

The only difference is that the status code isn't being printed. But checking the status code through the response.getStatusLine().getStatusCode() yields 403 as well.

答: Looks like you are using Apache HttpClient, which does not modify responses this way. It's definitely the response generated by server. Check your configuration of request in Postman to see if there are any additional headers, that may alter server behavior.</p>

Body:
I am trying to convert the HttpResponse's response body to a String using the following piece of code:

HttpGet request = new HttpGet(url);
request.setHeader("Accept", "application/json");
response = client.execute(request);
EntityUtils.toString(response.getEntity(), standardCharsets.UTF_8.displayName());

The expected response after converting it to a String is as follows:

{"errors": ["permission denied"]}

This code was working fine until recently. But now the response body is somehow being modified to this:

{"errors":["1 error occurred:\n\t* permission denied\n\n"]}

I do not understand how the "1 error occurred" message is being inserted into the response body as the response from the same call in Postman gives me the appropriate response i.e.:

{"errors": ["permission denied"]}

And I've checked the code thoroughly and am certain that the "1 error occurred" message is not being inserted manually.

EDIT:

These were the response headers from Postman:

cache-control →no-store
content-length →33
content-type →application/json
date →Thu, 30 May 2019 06:52:33 GMT
status →403

And these were the response headers from the HttpClient call:

Cache-Control: no-store
Content-Type: application/json
Date: Thu, 30 May 2019 09:06:21 GMT
Content-Length: 60

The only difference is that the status code isn't being printed. But checking the status code through the response.getStatusLine().getStatusCode() yields 403 as well.


问:
Write list of lists to separate CSV files
I have a list (414 elements) which contains other lists of different lengths (ranging from 0 to 9). Each of those sublists has different numbers of rows and columns.

Some of the sublists are of length 1 like the one below:

```<code>tables_list[[1]]
     [,1]                         [,2]
[1,] "ID Number"                  "ABCD"
[2,] "Code"                       "1239463"
[3,] "Version"                    "1"
[4,] "Name"                       "ABC"
[5,] "Status"                     "Open"
[6,] "Currency"                   "USD"
[7,] "Average"                    "No"
[8,] "FX Rate"                    "2.47"

</code>```

Other sublists are of length 2 or higher like the one below:

```<code>tables_list[[17]]
[[1]]
      [,1]  [,2]                                                  [,3]  [,4]              [,5]            [,6]              [,7]          [,8] [,9]
 [1,] ""    ""                                                    "USD" "Balance"         "Movement in"   "Aggregate"       "Overall"     ""   "Overall"
 [2,] ""    ""                                                    ""    "brought forward" "year"          "annual"          "aggregate"   ""   "funded account"
 [3,] ""    ""                                                    ""    "from previous"   ""              "information"    "adjustments"  ""   ""
 [4,] ""    ""                                                    ""    "year end"        ""              ""                ""            ""   ""
 [5,] ""    ""                                                    ""    "1"               "2"             "3"               "4"           ""   "5"
 [6,] "12"  "Value 1"                                             ""    "0"               "3,275,020"     "3,275,020"       ""            "0"  "3,275,020"
 [7,] "13"  "Value 2"                                             ""    "0"               "0"             "0"               ""            "0"  "0"
 [8,] "14"  "Value 3"                                             ""    "0"               "8,267,862"     "8,267,862"       ""            "0"  "8,267,862"
 [9,] "15"  "Value 4"                                             ""    "0"               "(590,073,321)" "(590,073,321)"   ""            "0"  "(590,073,321)"
[10,] "16"  "Value 5"                                             ""    "0"               "0"             "0"               ""            "0"  "0"
[11,] "17"  "Value 6"                                             ""    "0"               "0"             "0"               ""            "0"  "0"
[12,] "18"  "Value 7"                                             ""    "0"               "0"             "0"               ""            "0"  "0"
[13,] "19"  "Value 8"                                             ""    "0"               "0"             "0"               ""            "0"  "0"
[14,] "20"  "Value 9"                                             ""    "0"               "(459,222,782)" "(459,222,782)"   ""            "0"  "(459,222,782)"

[[2]]
     [,1]               [,2]   [,3]                                                                  [,4]
[1,] "Theme"            "Year" "Comment"                                                             "Created"
[2,] "Line 17 Column 2" "N/A"  "Amounts are calculated according to recent standards"                "XXXXXXXXXXXX"
[3,] ""                 ""     "paid by XXXXXXXXXXXXX"                                               ""
</code>```

I am trying to export each of those lists to an individual csv file but I cannot figure out a way to do so. Does anyone have any ideas on how to approach this? I tried using mapply but I keep getting the following error:

```<code>Error in file(file, ifelse(append, "a", "w")) :
  invalid 'description' argument
In addition: Warning message:
In if (file == "") file <- stdout() else if (is.character(file)) { :

 Error in file(file, ifelse(append, "a", "w")) :
  invalid 'description' argument
</code>```

答:
First you flatten the list appropriately, then you can loop over it in a the regular manner.</p>

```<code>flattenlist <- function(x){
  morelists <- sapply(x, function(xprime) class(xprime)[1]=="list")
  out <- c(x[!morelists], unlist(x[morelists], recursive=FALSE))
  if (sum(morelists)) {
    Recall(out)
  } else {
    return(out)
  }
}

l <- list(a=list(1:2, b=2:4),
          b=c("A", "B", "C"),
          z=1,
          m=matrix(4:1, 2),
          d=data.frame(x=1:4, y=c(1, 3, 2, 4))
)

l.f <- flattenlist(l)

n <- paste0("robj_", names(l.f), ".csv")

sapply(1:length(l.f), function(x) write.csv(l.f[[x]], file=n[x]))
</code>```

Body:
I have a list (414 elements) which contains other lists of different lengths (ranging from 0 to 9). Each of those sublists has different numbers of rows and columns.

Some of the sublists are of length 1 like the one below:

tables_list[[1]]
     [,1]                         [,2]
[1,] "ID Number"                  "ABCD"
[2,] "Code"                       "1239463"
[3,] "Version"                    "1"
[4,] "Name"                       "ABC"
[5,] "Status"                     "Open"
[6,] "Currency"                   "USD"
[7,] "Average"                    "No"
[8,] "FX Rate"                    "2.47"

Other sublists are of length 2 or higher like the one below:

tables_list[[17]]
[[1]]
      [,1]  [,2]                                                  [,3]  [,4]              [,5]            [,6]              [,7]          [,8] [,9]
 [1,] ""    ""                                                    "USD" "Balance"         "Movement in"   "Aggregate"       "Overall"     ""   "Overall"
 [2,] ""    ""                                                    ""    "brought forward" "year"          "annual"          "aggregate"   ""   "funded account"
 [3,] ""    ""                                                    ""    "from previous"   ""              "information"    "adjustments"  ""   ""
 [4,] ""    ""                                                    ""    "year end"        ""              ""                ""            ""   ""
 [5,] ""    ""                                                    ""    "1"               "2"             "3"               "4"           ""   "5"
 [6,] "12"  "Value 1"                                             ""    "0"               "3,275,020"     "3,275,020"       ""            "0"  "3,275,020"
 [7,] "13"  "Value 2"                                             ""    "0"               "0"             "0"               ""            "0"  "0"
 [8,] "14"  "Value 3"                                             ""    "0"               "8,267,862"     "8,267,862"       ""            "0"  "8,267,862"
 [9,] "15"  "Value 4"                                             ""    "0"               "(590,073,321)" "(590,073,321)"   ""            "0"  "(590,073,321)"
[10,] "16"  "Value 5"                                             ""    "0"               "0"             "0"               ""            "0"  "0"
[11,] "17"  "Value 6"                                             ""    "0"               "0"             "0"               ""            "0"  "0"
[12,] "18"  "Value 7"                                             ""    "0"               "0"             "0"               ""            "0"  "0"
[13,] "19"  "Value 8"                                             ""    "0"               "0"             "0"               ""            "0"  "0"
[14,] "20"  "Value 9"                                             ""    "0"               "(459,222,782)" "(459,222,782)"   ""            "0"  "(459,222,782)"

[[2]]
     [,1]               [,2]   [,3]                                                                  [,4]
[1,] "Theme"            "Year" "Comment"                                                             "Created"
[2,] "Line 17 Column 2" "N/A"  "Amounts are calculated according to recent standards"                "XXXXXXXXXXXX"
[3,] ""                 ""     "paid by XXXXXXXXXXXXX"                                               ""

I am trying to export each of those lists to an individual csv file but I cannot figure out a way to do so. Does anyone have any ideas on how to approach this? I tried using mapply but I keep getting the following error:

Error in file(file, ifelse(append, "a", "w")) :
  invalid 'description' argument
In addition: Warning message:
In if (file == "") file <- stdout() else if (is.character(file)) { :

 Error in file(file, ifelse(append, "a", "w")) :
  invalid 'description' argument

Body:
First you flatten the list appropriately, then you can loop over it in a the regular manner.

flattenlist <- function(x){
  morelists <- sapply(x, function(xprime) class(xprime)[1]=="list")
  out <- c(x[!morelists], unlist(x[morelists], recursive=FALSE))
  if (sum(morelists)) {
    Recall(out)
  } else {
    return(out)
  }
}

l <- list(a=list(1:2, b=2:4),
          b=c("A", "B", "C"),
          z=1,
          m=matrix(4:1, 2),
          d=data.frame(x=1:4, y=c(1, 3, 2, 4))
)

l.f <- flattenlist(l)

n <- paste0("robj_", names(l.f), ".csv")

sapply(1:length(l.f), function(x) write.csv(l.f[[x]], file=n[x]))