问:
Will APIs in hiddenapi-greylist-max-o work in Android Pie?
I am upgrading my app to target Android SDK 28. To check for compatibility issues, I ran the veridex tool against the APK, and it says I am using 2 APIs in greylist-max-o.

Will these APIs work on a device running Android Pie? From the "o" in the name (greylist-max-o), it seems to imply that the APIs will only work up to Android Oreo.

```<code>./appcompat.sh --dex-file=./test.apk

78 hidden API(s) used: 52 linked against, 26 through reflection
       76 in greylist
       0 in blacklist
       2 in greylist-max-o
       0 in greylist-max-p
</code>```

答:
You are correct in your assumption. Those APIs will only work if you target api level 27 (Android O and lower).

From the official documentation:

If a non-SDK interface was part of the darkgrey list for Android 9 (API level 28), that interface is now part of the greylist-max-o list, where “o” stands for Oreo or Android 8.1 (API level 27). In this case, you would only be able to use an interface that belongs to the greylist-max-o list if your app targets Android 8.1 (API level 27) or lower.

See more here: https://developer.android.com/preview/non-sdk-q#list-name-changes

Body:
I am upgrading my app to target Android SDK 28. To check for compatibility issues, I ran the veridex tool against the APK, and it says I am using 2 APIs in greylist-max-o.

Will these APIs work on a device running Android Pie? From the "o" in the name (greylist-max-o), it seems to imply that the APIs will only work up to Android Oreo.

./appcompat.sh --dex-file=./test.apk

78 hidden API(s) used: 52 linked against, 26 through reflection
       76 in greylist
       0 in blacklist
       2 in greylist-max-o
       0 in greylist-max-p


来源: stackexchange

问:
how to avoid thread.sleep before open a url
After login a webpage i want to open another url.if i give implicitwait it didnot open the url

```<code>driver.get("https://www.naukri.com/nlogin/login");
}

@Test(priority=1)
public void naukriTest() throws InterruptedException{

    driver.findElement(By.id("usernameField")).sendKeys("abc@gmail.com");
    driver.findElement(By.id("passwordField")).sendKeys("xyz");
    driver.findElement(By.xpath("//button[@class='waves-effect waves-light btn-large btn-block btn-bold blue-btn']")).click();
    Thread.sleep(5000);
    driver.get("https://careernavigator.naukri.com/careers-in-mahindra-and-mahindra-financial-services-0");
</code>```

i want to avoid that thread.sleep

答:
If I am understanding this correctly; you want to finish login and then open the second URL.

I would put in an explicit wait on the "just logged in" element. Something like, waiting for the element that holds "Welcome back, abc!" or any element that changes after login.

ContentLicense: CC BY-SA 4.0

Body:
After login a webpage i want to open another url.if i give implicitwait it didnot open the url

driver.get("https://www.naukri.com/nlogin/login");
}

@Test(priority=1)
public void naukriTest() throws InterruptedException{

    driver.findElement(By.id("usernameField")).sendKeys("abc@gmail.com");
    driver.findElement(By.id("passwordField")).sendKeys("xyz");
    driver.findElement(By.xpath("//button[@class='waves-effect waves-light btn-large btn-block btn-bold blue-btn']")).click();
    Thread.sleep(5000);
    driver.get("https://careernavigator.naukri.com/careers-in-mahindra-and-mahindra-financial-services-0");

i want to avoid that thread.sleep


答:
The eight sets of arrays are the eight images you feed in.

tvecs and rvecs you get from calibrateCamera() are vectors. If you want the matrix form, you have to use Rodrigues().

3x1 translation vector is the one you want.

3x3 rotation matrix can be obtained by cv2.Rodrigues().

```<code>for rvec in rvecs
    R_matrix, _ = cv2.Rodrigues(rvecs)
</code>```

Also, if you want to concatenate the [R t] matrix, try this:

```<code>Rt_matirx = np.concatenate((R_matrix, tvec), axis=1)
</code>```

See opencv document for more information.

Title: Unable to understand Opencv inbuilt calibrateCamera function

Body:
I am calibrating camera using opencv in built function calibrateCamera.

ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None,None)
print("translation vector size",len(tvecs))
print("rotation vector size",len(rvecs))
print("translation \n",tvecs)
print("rotation \n",rvecs)

Output:

translation vector size 8
rotation vector size 8
translation
 [array([[-2.89545711],
       [ 0.53309405],
       [16.90937607]]), array([[ 2.5887548 ],
       [ 4.28267707],
       [13.76961517]]), array([[-3.3813951 ],
       [ 0.46023276],
       [11.62316805]]), array([[-3.94407341],
       [ 2.24712782],
       [12.75758635]]), array([[-2.46697627],
       [-3.45827811],
       [12.90925656]]), array([[ 2.26913044],
       [-3.25178618],
       [15.65704473]]), array([[-3.65842398],
       [-4.35145288],
       [17.28001749]]), array([[-1.53432042],
       [-4.34836431],
       [14.06280739]])]
rotation
 [array([[-0.08450996],
       [ 0.35247622],
       [-1.54211812]]), array([[-0.23013064],
       [ 1.02133593],
       [-2.79358726]]), array([[-0.34782976],
       [-0.06411541],
       [-1.20030736]]), array([[-0.27641699],
       [ 0.10465832],
       [-1.56231228]]), array([[-0.47298366],
       [ 0.09331131],
       [-0.22505762]]), array([[0.068391  ],
       [0.44710268],
       [0.10818745]]), array([[-0.09848595],
       [ 0.32272789],
       [ 0.31561383]]), array([[-0.35190574],
       [ 0.24381052],
       [ 0.2106984 ]])]

The obtained translation and rotation vectors are consist of eight 3*1 array objects. I expect translation and rotation vector should be of size 3*3 and 3*1 respectively. Please let me know how these values are relevant with translation and rotation matrix. Also suggest me how can I derive translation and rotation matrices from these obtained vectors.

Thanks !

Body:
The eight sets of arrays are the eight images you feed in.

tvecs and rvecs you get from calibrateCamera() are vectors. If you want the matrix form, you have to use Rodrigues().

3x1 translation vector is the one you want.

3x3 rotation matrix can be obtained by cv2.Rodrigues().

for rvec in rvecs
    R_matrix, _ = cv2.Rodrigues(rvecs)

Also, if you want to concatenate the [R t] matrix, try this:

Rt_matirx = np.concatenate((R_matrix, tvec), axis=1)

See opencv document for more information.


问:
Matching an exact string in a SQL.Replace function
I have a for loop that searches through a SQL query and replaces 'CT.Item(i).ParameterName' with its actual value:

```<code>Dim SQLQP As String = SQL

For i=0 To CT.Count - 1
    SQL = SQL.Replace("CT.Item(i).ParameterName, "'" & CT.Item(i).Value & "'")

    SQLQP = SQLQP.Replace(CT.Item(i).ParameterName, "''' + " & CT.Item(i).ParameterName & " + '''")'.Replace("'%'", "''%''")
     End If
Next
</code>```

'CT.Item(i).ParameterName' are parameter names (example: @p1, @p2, @p3 etc.)
The problem is that if there is a parameter name called @p10, the above loop sees it as "@p1" + "0", so when it goes to change @p1 it also changes @p10 and leaves a 0 hanging around. How can I avoid this issue?

The other solutions I have found when searching either don't account for punctuation or use REGEX, which is not applicable inside a SQL.replace function.

Thanks for your help

EDIT: I have solved the issue with 'SQL' by reversing the loop. However, now I am getting the same problem with 'SQLQP':

The else statement

```<code>Else
   SQLQP = SQLQP.Replace(CT.Item(i).ParameterName, "''' + " & CT.Item(i).ParameterName & " + '''")
</code>```

returns:

```<code>[some sql code]... WHERE  ([RI].[INSTRUCTION_TIME]  >= ''' + @p1 + ''') AND ([RI].[ITEM_CATEGORY_UID]  IN (''' + @p2 + ''',''' + @p3 + ''',''' + @p4 + ''',''' + @p5 + ''',''' + @p6 + ''',''' + @p7 + ''')) AND ([RI].[ITEM_DETAIL_UID]  IN (''' + @p8 + ''',''' + @p9 + ''',''' + ''' + @p1 + '''0 + '''))')
</code>```

''' + ''' + @p1 + '''0 + ''' is incorrect, it should be ''' + @p10 + ''', everything else is correct.

EDIT 2

As requested, here is SQLQP before the 'replace'

```<code>[some sql]...WHERE  ([RI].[INSTRUCTION_TIME]  >= @p1) AND ([RI].[ITEM_CATEGORY_UID]  IN (@p2,@p3,@p4)) AND ([RI].[ITEM_TYPE_UID]  IN (@p5)) AND ([RI].[ITEM_DETAIL_UID]  IN (@p6,@p7,@p8,@p9,@p10))
</code>```

And here is what it should look like:

```<code>[some sql]...WHERE  ([RI].[INSTRUCTION_TIME]  >= ''' + @p1 + ''') AND ([RI].[ITEM_CATEGORY_UID]  IN (''' + @p2 + ''',''' + @p3 + ''',''' + @p4 + ''')) AND ([RI].[ITEM_TYPE_UID]  IN (''' + @p5 + ''')) AND ([RI].[ITEM_DETAIL_UID]  IN (''' + @p6 + ''',''' + @p7 + ''',''' + @p8 + ''',''' + @p9 + ''',''' + @p10 + '''))
</code>```

答:
Problem solved thanks to @Charles May:</p>

```<code>SQLQP = SQLQP.Replace(",", " , ")
SQLQP = SQLQP.Replace(")", " )")
SQLQP = SQLQP.Replace("(", "( ")

For i = CT.Count - 1 To 0 Step -1
    SQL = SQL.Replace(CT.Item(i).ParameterName, "'" & CT.Item(i).Value & "'")
    SQLQP = SQLQP.Replace(" " + CT.Item(i).ParameterName + " ", "''' + " &
CT.Item(i).ParameterName & " + '''")
     End If
  Next
</code>```

Body:
I have a for loop that searches through a SQL query and replaces 'CT.Item(i).ParameterName' with its actual value:

Dim SQLQP As String = SQL

For i=0 To CT.Count - 1
    SQL = SQL.Replace("CT.Item(i).ParameterName, "'" & CT.Item(i).Value & "'")

    SQLQP = SQLQP.Replace(CT.Item(i).ParameterName, "''' + " & CT.Item(i).ParameterName & " + '''")'.Replace("'%'", "''%''")
     End If
Next

'CT.Item(i).ParameterName' are parameter names (example: @p1, @p2, @p3 etc.)
The problem is that if there is a parameter name called @p10, the above loop sees it as "@p1" + "0", so when it goes to change @p1 it also changes @p10 and leaves a 0 hanging around. How can I avoid this issue?

The other solutions I have found when searching either don't account for punctuation or use REGEX, which is not applicable inside a SQL.replace function.

Thanks for your help

EDIT: I have solved the issue with 'SQL' by reversing the loop. However, now I am getting the same problem with 'SQLQP':

The else statement

Else
   SQLQP = SQLQP.Replace(CT.Item(i).ParameterName, "''' + " & CT.Item(i).ParameterName & " + '''")

returns:

[some sql code]... WHERE  ([RI].[INSTRUCTION_TIME]  >= ''' + @p1 + ''') AND ([RI].[ITEM_CATEGORY_UID]  IN (''' + @p2 + ''',''' + @p3 + ''',''' + @p4 + ''',''' + @p5 + ''',''' + @p6 + ''',''' + @p7 + ''')) AND ([RI].[ITEM_DETAIL_UID]  IN (''' + @p8 + ''',''' + @p9 + ''',''' + ''' + @p1 + '''0 + '''))')

''' + ''' + @p1 + '''0 + ''' is incorrect, it should be ''' + @p10 + ''', everything else is correct.

EDIT 2

As requested, here is SQLQP before the 'replace'

[some sql]...WHERE  ([RI].[INSTRUCTION_TIME]  >= @p1) AND ([RI].[ITEM_CATEGORY_UID]  IN (@p2,@p3,@p4)) AND ([RI].[ITEM_TYPE_UID]  IN (@p5)) AND ([RI].[ITEM_DETAIL_UID]  IN (@p6,@p7,@p8,@p9,@p10))

And here is what it should look like:

[some sql]...WHERE  ([RI].[INSTRUCTION_TIME]  >= ''' + @p1 + ''') AND ([RI].[ITEM_CATEGORY_UID]  IN (''' + @p2 + ''',''' + @p3 + ''',''' + @p4 + ''')) AND ([RI].[ITEM_TYPE_UID]  IN (''' + @p5 + ''')) AND ([RI].[ITEM_DETAIL_UID]  IN (''' + @p6 + ''',''' + @p7 + ''',''' + @p8 + ''',''' + @p9 + ''',''' + @p10 + '''))

Body:
Problem solved thanks to @Charles May:

SQLQP = SQLQP.Replace(",", " , ")
SQLQP = SQLQP.Replace(")", " )")
SQLQP = SQLQP.Replace("(", "( ")

For i = CT.Count - 1 To 0 Step -1
    SQL = SQL.Replace(CT.Item(i).ParameterName, "'" & CT.Item(i).Value & "'")
    SQLQP = SQLQP.Replace(" " + CT.Item(i).ParameterName + " ", "''' + " &
CT.Item(i).ParameterName & " + '''")
     End If
  Next


问:
PostgreSQL: Compare strings in the same column but in different series (rows)
I have a simple table generated with a subquery that applies many different filters.

```<code>  | project
1 | Hello
2 | Hello 2.0
3 | Ordinary Sheep
4 | Sheep
</code>```

The next step is to remove projects with very similar names (for example, if a project has the same name but followed by a 2.0).

In this case I need my query to remove Project 2.0 from the results. This little issue is more challenging than I expected.

My best bet seems to be this one bellow where I correctly identify the project that should be excluded, but if I invert the operation I end up with duplicated data because due to the self join.

```<code>SELECT
    q1.name,
    q2.name
FROM subquery q1
JOIN subquery q2 ON q1.name LIKE q2.name || '%'
WHERE q1.id <> q2.id;
</code>```

Thank you so much!

答:
May be you can match the first occurrence of a digit in a project and exclude everything after that.Then apply RTRIM and DISTINCT over it. This will however not work if the project name itself has a number in it.

```<code>with s as
(
   --your query that you have inside sub-query
)
select DISTINCT RTRIM(regexp_replace(project, '^([^\d]+)\d.*$','\1')) from s;
</code>```

DEMO

Body:
I have a simple table generated with a subquery that applies many different filters.

  | project
1 | Hello
2 | Hello 2.0
3 | Ordinary Sheep
4 | Sheep

The next step is to remove projects with very similar names (for example, if a project has the same name but followed by a 2.0).

In this case I need my query to remove Project 2.0 from the results. This little issue is more challenging than I expected.

My best bet seems to be this one bellow where I correctly identify the project that should be excluded, but if I invert the operation I end up with duplicated data because due to the self join.

SELECT
    q1.name,
    q2.name
FROM subquery q1
JOIN subquery q2 ON q1.name LIKE q2.name || '%'
WHERE q1.id <> q2.id;

Thank you so much!

Body:
May be you can match the first occurrence of a digit in a project and exclude everything after that.Then apply RTRIM and DISTINCT over it. This will however not work if the project name itself has a number in it.

with s as
(
   --your query that you have inside sub-query
)
select DISTINCT RTRIM(regexp_replace(project, '^([^\d]+)\d.*$','\1')) from s;

DEMO


问:
ASP.NET Ajax - Buttons 'postbacking' but functionality not happening
Here's the thing
I added a button to a webpart which saves some fields to MS-Excel.

```<code>var btn = new Button { Text = title, CssClass = css };
btn.Click += (sender,args)=>action();
Container.Controls.Add(btn);
</code>```

This code is located inside OnInit() method in the WebPart. actionis the Action which does stuff, in this case:

```<code>Something.FillExcel(MyData);
Something.SaveExcel();
</code>```

So what happens is, I click the button, it acts like doing the usual partial postback, and does absolutely nothing. I thought it could be something in the Fill/Save code, then I tried forcing an error just to see if it gets there. It seems the click event never fires, or, if it does, it doesn't run my code (?).

Here's the html, just in case:

```<code><input type="submit" name="ctl00$m$g_b4af4370_c016_4712_9d60_fc8ca077a068$ctl359" value="Enviar Formulário" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$m$g_b4af4370_c016_4712_9d60_fc8ca077a068$ctl359", "", true, "", "", false, false))" class="button" />
</code>```

What could be happening?

Thanks in advance!

EDIT: After Cos Callis answered, I put my code inside OnLoad() instead of OnInit(). Here's new code:

```<code>protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        var btn = new Button { Text = title, CssClass = css };
        btn.Click += new EventHandler((sender,args)=>{
            if (myform.Page.IsPostBack)
            {
                excel.FillExcel(); excel.SaveFile();
            }
        });
        container.Controls.Add(btn);
    }
</code>```

I'm now getting a javascript error: SCRIPT5022: Sys.WebForms.PageRequestManagerServerErrorException: The given key was not present in the dictionary.

答:
Because you are attempting to act on the INIT rather than the load, the data has not yet been attached at the server.

You should find this review of the life cycle of a web request in ASP.NET useful:
http://msdn.microsoft.com/en-us/library/ms178472.aspx.

Here is the relevant extract:

Initialization

During page initialization, controls
  on the page are available and each
  control's UniqueID property is set. A
  master page and themes are also
  applied to the page if applicable. If
  the current request is a postback, the
  postback data has not yet been loaded
  and control property values have not
  been restored to the values from view
  state.

Load

During load, if the current request is
  a postback, control properties are
  loaded with information recovered from
  view state and control state.

During initialization the control "exists" but has not yet been loaded with data from the postback. If you you move your code to "OnLoad" you should achieve the disired results. (Don't forget to wrap that in "if(IsPostback)")

Cheers,

CEC

//added resource: After posting my answer I thought you might find this article useful as well:
http://encosia.com/2007/10/24/are-you-making-these-3-common-aspnet-ajax-mistakes/

ContentLicense: CC BY-SA 3.0

Body:
Here's the thing
I added a button to a webpart which saves some fields to MS-Excel.

var btn = new Button { Text = title, CssClass = css };
btn.Click += (sender,args)=>action();
Container.Controls.Add(btn);

This code is located inside OnInit() method in the WebPart. actionis the Action which does stuff, in this case:

Something.FillExcel(MyData);
Something.SaveExcel();

So what happens is, I click the button, it acts like doing the usual partial postback, and does absolutely nothing. I thought it could be something in the Fill/Save code, then I tried forcing an error just to see if it gets there. It seems the click event never fires, or, if it does, it doesn't run my code (?).

Here's the html, just in case:

<input type="submit" name="ctl00$m$g_b4af4370_c016_4712_9d60_fc8ca077a068$ctl359" value="Enviar Formulário" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$m$g_b4af4370_c016_4712_9d60_fc8ca077a068$ctl359", "", true, "", "", false, false))" class="button" />

What could be happening?

Thanks in advance!

EDIT: After Cos Callis answered, I put my code inside OnLoad() instead of OnInit(). Here's new code:

protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        var btn = new Button { Text = title, CssClass = css };
        btn.Click += new EventHandler((sender,args)=>{
            if (myform.Page.IsPostBack)
            {
                excel.FillExcel(); excel.SaveFile();
            }
        });
        container.Controls.Add(btn);
    }

I'm now getting a javascript error: SCRIPT5022: Sys.WebForms.PageRequestManagerServerErrorException: The given key was not present in the dictionary.


问:
How to get rid of the "blue dot" selection icons and make hovering over the whole picture allowed to move it
I have an openlayers map and a pin on the map.
I would like to get rid of this blue dot, which shows up when you hover over the pin.
There are many similar topics, but found guidelines did not bring me results.
I would also like to be able to move the image by mouse clicking on it anywhere

I try do that:

```<code>var selectedStyleFunction = function(feature, resolution) {
    return [new ol.style.Style({
        stroke: new ol.style.Stroke({
            color: "white",
            lineCap: "butt",
            lineJoin: "bevel",
            width:3
        }),
        fill : new ol.style.Fill({
            color: "black"
        }),
    })];
};

//drag and drop
const dragInteraction = new ol.interaction.Modify({
        features: new ol.Collection([marker]),
        style: selectedStyleFunction,
});
</code>```

This makes the dot is not visible at all, but then it is difficult to find it in the image.

My example is here: https://jsfiddle.net/anetka31/eo4prjgx/51/

答: Giving the interaction the same style as the marker will remove the blue dot.  The pin icon should be anchored near the bottom left and the modify interactions only works on that position (unless pixelTolerance is set high, when it will also work outside the icon which would be confusing).  Unlike modify a select interaction will work on any visible part of the icon.  By adding a hover (pointermove) select interaction and a custom condition on the drag to check if any features have been picked by a hover the high pixelTolerance can be limited to just the icon.  If you want the hover can also change the mouse pointer style to let you know it's over the icon (removing the need for the blue dot).  Revised fiddle https://jsfiddle.net/vynk7Ld8/4/ (also updated from a very old version of OpenLayers 3 to OpenLayers 4)

Body:
I have an openlayers map and a pin on the map.
I would like to get rid of this blue dot, which shows up when you hover over the pin.
There are many similar topics, but found guidelines did not bring me results.
I would also like to be able to move the image by mouse clicking on it anywhere

I try do that:

var selectedStyleFunction = function(feature, resolution) {
    return [new ol.style.Style({
        stroke: new ol.style.Stroke({
            color: "white",
            lineCap: "butt",
            lineJoin: "bevel",
            width:3
        }),
        fill : new ol.style.Fill({
            color: "black"
        }),
    })];
};

//drag and drop
const dragInteraction = new ol.interaction.Modify({
        features: new ol.Collection([marker]),
        style: selectedStyleFunction,
});

This makes the dot is not visible at all, but then it is difficult to find it in the image.

My example is here: https://jsfiddle.net/anetka31/eo4prjgx/51/


问:
wrap label text in uicollectionviewcell in uicollectionview
I have a uicollectionviewcell in a uicollectionview. This cell has a label that displays the data stored in an array.
As you'll know when the text of the label is too long for the cell it gets truncated.
I want to wrap the text of this label so that the entire text is visible in a particular cell. I tried the following code which works fine in uitableviewcell but not for a collectionview

```<code>cell.cellLabel.lineBreakMode=NSLineBreakByWordWrapping;
[cell.cellLabel  setNumberOfLines:0];
[cell.cellLabel sizeToFit];
</code>```

Any insights and help on this will be highly appreciated.

Thanks.

答:
Inside your custom collectionView cell object, set your label's numberOfLines property to zero.

```<code>label.numberOfLines = 0
</code>```

then in your constraints, pin your label on the leading and trailing anchor of the custom collectionView cells.

```<code>yourLabel.leadingAnchor.constraint(equalTo: leadingAnchor),
yourLabel.trailingAnchor.constraint(equalTo: trailingAnchor)
</code>```

Body:
I have a uicollectionviewcell in a uicollectionview. This cell has a label that displays the data stored in an array.
As you'll know when the text of the label is too long for the cell it gets truncated.
I want to wrap the text of this label so that the entire text is visible in a particular cell. I tried the following code which works fine in uitableviewcell but not for a collectionview

cell.cellLabel.lineBreakMode=NSLineBreakByWordWrapping;
[cell.cellLabel  setNumberOfLines:0];
[cell.cellLabel sizeToFit];

Any insights and help on this will be highly appreciated.

Thanks.

Body:
Inside your custom collectionView cell object, set your label's numberOfLines property to zero.

label.numberOfLines = 0

then in your constraints, pin your label on the leading and trailing anchor of the custom collectionView cells.

yourLabel.leadingAnchor.constraint(equalTo: leadingAnchor),
yourLabel.trailingAnchor.constraint(equalTo: trailingAnchor)


问:
How to disable Internet Explorer Startup settings via regedit? (Not Homepage)
I need to disable Internet Explorer Startup settings. How can I do this via regedit?

答:
Please refer to the following steps to enable/disable Start Internet Explorer with tabs from last browsing session option.

Open Run window and type "regedit" to open registry editor.

Navigate to location below.

Computer\HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\ContinuousBrowsing

Find the "Enabled" registry key.

Double click on it and set its value. (To disable : 0, To enable : 1)

Click on OK to close the dialog.

Restart Internet Explorer to take effect of changes.

The screenshot as below:

Note: If you disable the "Start with tabs from the last session" option, it will auto enable the "Start with home page" option. There is no way to disable both of them at the same time.


问:
How to take the output of a function and put into pandas dataframe for further analysis?
I am using a function to find out how many rainfall events between magnitude thresholds result in flood events (denoted as 1 for flood, 0 for no flood). My data looks a bit like this:

```<code>      Date     rain      Flood
2010-01-01     0.2       0
2010-01-02     2.7       0
2010-01-03     11.3      1
2010-01-04     0.1       0
2010-01-05     5.3       1
</code>```

Here is my function:

```<code>def Thresholds(df, thresholds):
    lower, upper = thresholds
    u_mask = df['rain'] < upper
    l_mask = df['rain'] > lower
    between = df[l_mask & u_mask]
    return between['Flood'].value_counts()

my_intervals = np.array([(0.0,2.5),(2.5,5),(5,10),(10,15),(15,20),(20,30),(30,np.inf)])

dframes = [YEAR1,YEAR2,YEAR3]

for df in dframes:
    print('\n Dataframe')
    for interval in my_intervals:
        print(Thresholds(df,interval))
</code>```

which works well, in that it provides me with counts of flood or not for each threshold, here's the output from a full dataframe:

```<code>Dataframe
0.0    304
1.0      5
Name: Flood, dtype: int64
0.0    7
Name: Flood, dtype: int64
0.0    5
Name: Flood, dtype: int64
0.0    2
1.0    2
Name: Flood, dtype: int64
Series([], Name: Flood, dtype: int64)
Series([], Name: Flood, dtype: int64)
Series([], Name: Flood, dtype: int64)
</code>```

However the output is not in a form that I can do further calculations on. For example, I want to calculate the frequentist probability of floods occurring at each rainfall magnitude. To do this I anticipate needing to have the data in a dataframe, with columns for flood, or not, and rows titled by rainfall magnitude range (in this case labelled Threshold). So something like this:

```<code>Threshold     '1'     '0'
      2.5      0       2
      5.0      0       1
     10.0      1       0
     15.0      1       0
</code>```

Any ideas out there? Thanks a lot in advance :)

答:
We can use groupby with pd.cut:

```<code>bins = np.append(my_intervals[:, 0], my_intervals[-1, 1])

result = df.groupby([pd.cut(df['rain'], bins), 'Flood']).size().unstack().fillna(0).astype(int)

print(result)
</code>```

Output:

```<code>Flood         0  1
rain
(0.0, 2.5]    2  0
(2.5, 5.0]    1  0
(5.0, 10.0]   0  1
(10.0, 15.0]  0  1
</code>```

Body:
I am using a function to find out how many rainfall events between magnitude thresholds result in flood events (denoted as 1 for flood, 0 for no flood). My data looks a bit like this:

      Date     rain      Flood
2010-01-01     0.2       0
2010-01-02     2.7       0
2010-01-03     11.3      1
2010-01-04     0.1       0
2010-01-05     5.3       1

Here is my function:

def Thresholds(df, thresholds):
    lower, upper = thresholds
    u_mask = df['rain'] < upper
    l_mask = df['rain'] > lower
    between = df[l_mask & u_mask]
    return between['Flood'].value_counts()

my_intervals = np.array([(0.0,2.5),(2.5,5),(5,10),(10,15),(15,20),(20,30),(30,np.inf)])

dframes = [YEAR1,YEAR2,YEAR3]

for df in dframes:
    print('\n Dataframe')
    for interval in my_intervals:
        print(Thresholds(df,interval))

which works well, in that it provides me with counts of flood or not for each threshold, here's the output from a full dataframe:

Dataframe
0.0    304
1.0      5
Name: Flood, dtype: int64
0.0    7
Name: Flood, dtype: int64
0.0    5
Name: Flood, dtype: int64
0.0    2
1.0    2
Name: Flood, dtype: int64
Series([], Name: Flood, dtype: int64)
Series([], Name: Flood, dtype: int64)
Series([], Name: Flood, dtype: int64)

However the output is not in a form that I can do further calculations on. For example, I want to calculate the frequentist probability of floods occurring at each rainfall magnitude. To do this I anticipate needing to have the data in a dataframe, with columns for flood, or not, and rows titled by rainfall magnitude range (in this case labelled Threshold). So something like this:

Threshold     '1'     '0'
      2.5      0       2
      5.0      0       1
     10.0      1       0
     15.0      1       0

Any ideas out there? Thanks a lot in advance :)

Body:
We can use groupby with pd.cut:

bins = np.append(my_intervals[:, 0], my_intervals[-1, 1])

result = df.groupby([pd.cut(df['rain'], bins), 'Flood']).size().unstack().fillna(0).astype(int)

print(result)

Output:

Flood         0  1
rain
(0.0, 2.5]    2  0
(2.5, 5.0]    1  0
(5.0, 10.0]   0  1
(10.0, 15.0]  0  1


问:
Fill out empty spaces with underscore
I have a telegram that i have to send to the PLC, 1 substring of that telegram provides the barcodeID. It has 6 spaces and it starts with 1 and it is counting up.

For the PLC to work i have to fill up to empty spots wit an underscore. F.E.

_____1

____22

___333

Is there a way i can fix this?

I know that i can fill up the empty spaces with zero's like this: %06d

000001

000022

000333

```<code>gLog.LogPrintf(Info, "customerlog", "Storage Out Ready: %02d%02d%02d%s%04d%010d%02d%010d%010d%06d%06d%06d%06d%06d%06d%010d",
        (*inMessage)["sender"].asInt(), (*inMessage)["reciever"].asInt(), (*inMessage)["series"].asInt(), (*inMessage)["type"].asString().c_str(),
        (*inMessage)["command"].asInt(), (*inMessage)["id"].asInt(), (*inMessage)["priority"].asInt(), (*inMessage)["source"].asInt(),
        (*inMessage)["target"].asInt(), (*inMessage)["height"].asInt(), (*inMessage)["width"].asInt(), (*inMessage)["length"].asInt(),
        (*inMessage)["weight"].asInt(), (*inMessage)["status"].asInt(), (*inMessage)["error"].asInt(), (*inMessage)["data"].asInt());
        gLog.LogPrintf(Info, "Barcode ID: ", (*inMessage)["id"].asCString());
        gLog.LogPrintf(Info, "error: ", (*inMessage)["error"].asInt());
</code>```

答:
If you have to go the C way, you can do it like this:

#include <iostream>

int main()
{
  const char *padding = "______";
  int n = 123;
  char buf[7];
  int len;
  len = snprintf(buf, 7, "%d", n);
  printf("%.*s%s", 6 - std::min(6, len), padding, buf);
}
```

<p>Output:</p>

```___123
```

If the number has more than 6 digits, it will be truncated by taking only the 6 leftmost digits. For example, if n is 1234567890, the output will be 123456.

Title: Fill out empty spaces with underscore

Body:
I have a telegram that i have to send to the PLC, 1 substring of that telegram provides the barcodeID. It has 6 spaces and it starts with 1 and it is counting up.

For the PLC to work i have to fill up to empty spots wit an underscore. F.E.

_____1

____22

___333

Is there a way i can fix this?

I know that i can fill up the empty spaces with zero's like this: %06d

000001

000022

000333

gLog.LogPrintf(Info, "customerlog", "Storage Out Ready: %02d%02d%02d%s%04d%010d%02d%010d%010d%06d%06d%06d%06d%06d%06d%010d",
        (*inMessage)["sender"].asInt(), (*inMessage)["reciever"].asInt(), (*inMessage)["series"].asInt(), (*inMessage)["type"].asString().c_str(),
        (*inMessage)["command"].asInt(), (*inMessage)["id"].asInt(), (*inMessage)["priority"].asInt(), (*inMessage)["source"].asInt(),
        (*inMessage)["target"].asInt(), (*inMessage)["height"].asInt(), (*inMessage)["width"].asInt(), (*inMessage)["length"].asInt(),
        (*inMessage)["weight"].asInt(), (*inMessage)["status"].asInt(), (*inMessage)["error"].asInt(), (*inMessage)["data"].asInt());
        gLog.LogPrintf(Info, "Barcode ID: ", (*inMessage)["id"].asCString());
        gLog.LogPrintf(Info, "error: ", (*inMessage)["error"].asInt());

Body:
If you have to go the C way, you can do it like this:

#include <iostream>

int main()
{
  const char *padding = "______";
  int n = 123;
  char buf[7];
  int len;
  len = snprintf(buf, 7, "%d", n);
  printf("%.*s%s", 6 - std::min(6, len), padding, buf);
}

Output:

___123

If the number has more than 6 digits, it will be truncated by taking only the 6 leftmost digits. For example, if n is 1234567890, the output will be 123456.


问:
Can i compare these two dates in JS?
```<code>console.log("201905300545_201905300555"  < "201905300535_201905300545")
</code>```

How can i compare two dates in string format?

答:
You can parse the dates into moment and then use moment's diff function to compare the durations, or dates, starts or ends, or any combination.

Your colleague's way of comparing the dates may be the fastest way in Javascript for the given use case of "Is the start date before the second start date and the end date before the second end date?"

let s1 = "201905300545_201905300555";
let s2 = "201905300535_201905300545";
let m = t => moment(t,"YYYYMMDDhhmm");
let rng1 = s1.split("_").map(m);
let rng2 = s2.split("_").map(m);
console.log(rng1[1].diff(rng1[0]) < rng2[1].diff(rng2[0]));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script></code>```

Title: Can i compare these two dates in JS?

Body:
console.log("201905300545_201905300555"  < "201905300535_201905300545")

How can i compare two dates in string format?

Body:
You can parse the dates into moment and then use moment's diff function to compare the durations, or dates, starts or ends, or any combination.

Your colleague's way of comparing the dates may be the fastest way in Javascript for the given use case of "Is the start date before the second start date and the end date before the second end date?"

let s1 = "201905300545_201905300555";
let s2 = "201905300535_201905300545";
let m = t => moment(t,"YYYYMMDDhhmm");
let rng1 = s1.split("_").map(m);
let rng2 = s2.split("_").map(m);
console.log(rng1[1].diff(rng1[0]) < rng2[1].diff(rng2[0]));

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>


问:
I'm not able to create react app by "create-react-app"
I'm not able to create react app by create-react-app and it gives me an error

答: Try using npx create-react-app, be sure to have npm >= 5.2


问:
How to read .csv file in Perl to get required fields only, perform some operation and write back the results to same file?
I have a CSV file which contains IP, Alive fields like below:

```<code>ip, alive
127.0.0.1, Yes
127.0.0.2, No
</code>```

I want to ping each IP and if the ping is reachable then I need to put Yes in front of that IP in same CSV file.

I'm trying with below code, but stuck at reading and writing the same CSV file.

```<code>#!/usr/bin/perl
use strict;
use warnings;
use Net::Ping;
use Data::Dumper;

my $file = 'servers.csv';
my @filedata;
open(my $fh, '<', $file) or die "Can't read file '$file' [$!]\n";
while (my $line = <$fh>) {
    chomp $line;
    my @fields = split(/,/, $line);
    push @filedata, \@fields;
}
print Dumper(@filedata);

my $p = Net::Ping->new();

if ($p->ping('127.0.0.1'))
{
   print "\nYes\n";
}
</code>```

My code for ping and reading file is working fine but I'm not much sure about loop through the data read from file and then ping and store the result back to CSV file.

Any help will be highly appreciated.

答:
```<code>use Tie::Array::CSV qw();
tie my @file, 'Tie::Array::CSV', 'servers.csv';

for my $server (@file) {
    next if 'ip' eq $server->[0]; # skip table header
    my $ping_result = rand > 0.5 ? 'Yes' : 'No'; # fake ping
    $server->[1] = $ping_result; # update file
}
</code>```

Body:
I have a CSV file which contains IP, Alive fields like below:

ip, alive
127.0.0.1, Yes
127.0.0.2, No

I want to ping each IP and if the ping is reachable then I need to put Yes in front of that IP in same CSV file.

I'm trying with below code, but stuck at reading and writing the same CSV file.

#!/usr/bin/perl
use strict;
use warnings;
use Net::Ping;
use Data::Dumper;

my $file = 'servers.csv';
my @filedata;
open(my $fh, '<', $file) or die "Can't read file '$file' [$!]\n";
while (my $line = <$fh>) {
    chomp $line;
    my @fields = split(/,/, $line);
    push @filedata, \@fields;
}
print Dumper(@filedata);

my $p = Net::Ping->new();

if ($p->ping('127.0.0.1'))
{
   print "\nYes\n";
}

My code for ping and reading file is working fine but I'm not much sure about loop through the data read from file and then ping and store the result back to CSV file.

Any help will be highly appreciated.


问:
Azure Availability sets vs. Availibility Zones
Azure offers two different availability solutions:

1. Availability Sets

A group with two or more virtual machines in the same Data Center is called Availability Set, this ensures that at least one of the
  virtual machines hosted on Azure will be available if something
  happens. This configuration offers 99.95% SLA.

2. Availability Zones

... Virtual Machines are in different physical locations within an Azure Region. ... Availability zones offer 99.99% SLA.

Not all services support Availability Zones.

My Question

So Availability Zones seem to be the superior solution: Higher SLA at the same price. Are there any reasons why I should choose Availability Sets if Availability Zones are supported?

答:
It all depends on you solution. One of the articles you shared mentioned the key differences

What it didn't mention however is the bandwidth charges for Availability Zones. You might want to factor that in your planning and cost analysis when deciding between Availability Set and Zone.


问:
Application running in intelliJ but .jar not running
I have made two applications(Server and client) using sockets in java. It is working fine in intelliJ, but when i am making the .jar file, client application is not opening while server application is running. But when i close the server application, then the client application opens.

Client:

```<code>package sample;

import com.mysql.cj.jdbc.MysqlDataSource;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.image.Image;
import javafx.stage.Stage;

import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.ResourceBundle;

public class Main extends Application {
    static Stage stage;
    static boolean ch = true;
    @Override
    public void start(Stage primaryStage) throws Exception {

        Networking.connect("127.0.0.1", 5000);
        //login scene : opening scene
        //to change the value of stage to primaryStage
        stage = primaryStage;
        if(ch) {

            Parent root = FXMLLoader.load(getClass().getResource("Login.fxml"));
            stage.setTitle("Electo");
            stage.setScene(new Scene(root));
            stage.show();
            //stage.getIcons().add(new Image(logo));
        }
        stage.setOnCloseRequest(event -> {
    try {
            Networking.output.writeUTF("Exit");
        }
        catch (IOException e)
        {
            Alert alert = new Alert(Alert.AlertType.ERROR, "Server error. Try restarting the app"
                    , ButtonType.OK);
            alert.showAndWait();
        }});
    }

    public static void main(String[] args) {
        launch(args);
    }
    //function to connect to database

    public Stage getStage()
    {
        return stage;
    }

    }
</code>```

Server:

```<code>package sample;

import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Networking {

    public static void connect(int port)
    {
        try
        {
            ServerSocket serverSocket = new ServerSocket(port);
            System.out.print("Server is started");

            while(true)
            {
                Socket socket;
                    socket = serverSocket.accept();
                    DataInputStream input = new DataInputStream(socket.getInputStream());
                    DataOutputStream output = new DataOutputStream(socket.getOutputStream());
                    Thread thread = new ServerThread(socket, input, output);
                    thread.start();
                    System.out.print("Client Accepted");
            }
        }
        catch(IOException exception)
        {
            exception.printStackTrace();
            Alert alert = new Alert(Alert.AlertType.ERROR, "Server error. Try restarting the application"
                    , ButtonType.OK);
            alert.showAndWait();
        }
    }

}
</code>```

Here is the run() method of Server thread class

```<code>public void run() {
        String line = "";
                while(true) {
            try {
                line = input.readUTF();
                if(line.equalsIgnoreCase("Exit"))
                {
                    this.socket.close();
                    break;
                }
                doWork(line);
            } catch (IOException e) {
                Alert alert = new Alert(Alert.AlertType.ERROR, "Server error. Try restarting the app"
                        , ButtonType.OK);
                alert.showAndWait();
            }

            }
        }
</code>```

Client side networking class:

```<code>package sample;

import com.mysql.cj.conf.DatabaseUrlContainer;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

public class Networking {
    private static Socket socket = null;
    public static DataOutputStream output = null;
    public static DataInputStream input = null;

    public static void connect(String Address, int port) {
        try {
            socket = new Socket(Address, port);
            System.out.print("Connected");
            input = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
            output = new DataOutputStream(socket.getOutputStream());

        } catch (IOException e) {
            Alert alert = new Alert(Alert.AlertType.ERROR, "Server error. Try restarting the app"
                    , ButtonType.OK);
            alert.showAndWait();
            Main.ch = false;
        }
    }
}
</code>```

ADD: Here is the exception when i run Client.jar with command prompt.

```<code>ConnectedException in Application start method
java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
        at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
        at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
        at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$154(LauncherImpl.java:182)
        at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.NullPointerException: Location is required.
        at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3207)
        at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
        at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
        at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
        at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
        at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
        at sample.Main.start(Main.java:33)
        at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$161(LauncherImpl.java:863)
        at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$174(PlatformImpl.java:326)
        at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
        at java.security.AccessController.doPrivileged(Native Method)
        at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
        at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
        at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
        at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
        ... 1 more
Exception running application sample.Main
</code>```

答:
```<code>FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("Login.fxml"));
Parent root = loader.load();
</code>```

Body:
I have made two applications(Server and client) using sockets in java. It is working fine in intelliJ, but when i am making the .jar file, client application is not opening while server application is running. But when i close the server application, then the client application opens.

Client:

package sample;

import com.mysql.cj.jdbc.MysqlDataSource;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.image.Image;
import javafx.stage.Stage;

import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.ResourceBundle;

public class Main extends Application {
    static Stage stage;
    static boolean ch = true;
    @Override
    public void start(Stage primaryStage) throws Exception {

        Networking.connect("127.0.0.1", 5000);
        //login scene : opening scene
        //to change the value of stage to primaryStage
        stage = primaryStage;
        if(ch) {

            Parent root = FXMLLoader.load(getClass().getResource("Login.fxml"));
            stage.setTitle("Electo");
            stage.setScene(new Scene(root));
            stage.show();
            //stage.getIcons().add(new Image(logo));
        }
        stage.setOnCloseRequest(event -> {
    try {
            Networking.output.writeUTF("Exit");
        }
        catch (IOException e)
        {
            Alert alert = new Alert(Alert.AlertType.ERROR, "Server error. Try restarting the app"
                    , ButtonType.OK);
            alert.showAndWait();
        }});
    }

    public static void main(String[] args) {
        launch(args);
    }
    //function to connect to database

    public Stage getStage()
    {
        return stage;
    }

    }

Server:

package sample;

import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Networking {

    public static void connect(int port)
    {
        try
        {
            ServerSocket serverSocket = new ServerSocket(port);
            System.out.print("Server is started");

            while(true)
            {
                Socket socket;
                    socket = serverSocket.accept();
                    DataInputStream input = new DataInputStream(socket.getInputStream());
                    DataOutputStream output = new DataOutputStream(socket.getOutputStream());
                    Thread thread = new ServerThread(socket, input, output);
                    thread.start();
                    System.out.print("Client Accepted");
            }
        }
        catch(IOException exception)
        {
            exception.printStackTrace();
            Alert alert = new Alert(Alert.AlertType.ERROR, "Server error. Try restarting the application"
                    , ButtonType.OK);
            alert.showAndWait();
        }
    }

}

Here is the run() method of Server thread class

public void run() {
        String line = "";
                while(true) {
            try {
                line = input.readUTF();
                if(line.equalsIgnoreCase("Exit"))
                {
                    this.socket.close();
                    break;
                }
                doWork(line);
            } catch (IOException e) {
                Alert alert = new Alert(Alert.AlertType.ERROR, "Server error. Try restarting the app"
                        , ButtonType.OK);
                alert.showAndWait();
            }

            }
        }

Client side networking class:

package sample;

import com.mysql.cj.conf.DatabaseUrlContainer;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

public class Networking {
    private static Socket socket = null;
    public static DataOutputStream output = null;
    public static DataInputStream input = null;

    public static void connect(String Address, int port) {
        try {
            socket = new Socket(Address, port);
            System.out.print("Connected");
            input = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
            output = new DataOutputStream(socket.getOutputStream());

        } catch (IOException e) {
            Alert alert = new Alert(Alert.AlertType.ERROR, "Server error. Try restarting the app"
                    , ButtonType.OK);
            alert.showAndWait();
            Main.ch = false;
        }
    }
}

ADD: Here is the exception when i run Client.jar with command prompt.

ConnectedException in Application start method
java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
        at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
        at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
        at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$154(LauncherImpl.java:182)
        at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.NullPointerException: Location is required.
        at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3207)
        at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
        at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
        at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
        at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
        at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
        at sample.Main.start(Main.java:33)
        at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$161(LauncherImpl.java:863)
        at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$174(PlatformImpl.java:326)
        at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
        at java.security.AccessController.doPrivileged(Native Method)
        at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
        at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
        at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
        at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
        ... 1 more
Exception running application sample.Main


问:
EACCES Issue on npm fresh install on WSL Debian trying to update to the latest version
Hello everyone i started with a fresh wsl distrib of Debian and installed nodejs and npm on it.

When trying to update to the latest release of npm with the following command:

sudo npm install npm@latest -g

I get some weird issues who seems pretty common on wsl from what i saw on my internet researchs the only answer who seems to works but not really resolving properly the issue is setting the unsafe permissions to true with the following command:

npm config set unsafe-perm true

I would avoid to use this method and find an more clean way to resolve the issue.

Here is the console output:

```<code>####@#####:~$ sudo npm install npm@latest -g
npm ERR! path /usr/lib/node_modules/.staging/npm-18aca6f9/node_modules/wrap-
ansi
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! syscall rename
npm ERR! Error: EACCES: permission denied, rename
'/usr/lib/node_modules/.staging/npm-18aca6f9/node_modules/wrap-ansi' ->
'/usr/lib/node_modules/.staging/wrap-ansi-9f8997e7'
npm ERR!  { [Error: EACCES: permission denied, rename
'/usr/lib/node_modules/.staging/npm-18aca6f9/node_modules/wrap-ansi' ->
'/usr/lib/node_modules/.staging/wrap-ansi-9f8997e7']
npm ERR!   cause:
npm ERR!    { Error: EACCES: permission denied, rename
'/usr/lib/node_modules/.staging/npm-18aca6f9/node_modules/wrap-ansi' ->
'/usr/lib/node_modules/.staging/wrap-ansi-9f8997e7'
npm ERR!      errno: -13,
npm ERR!      code: 'EACCES',
npm ERR!      syscall: 'rename',
npm ERR!      path:
npm ERR!       '/usr/lib/node_modules/.staging/npm-
18aca6f9/node_modules/wrap-ansi',
npm ERR!      dest: '/usr/lib/node_modules/.staging/wrap-ansi-9f8997e7' },
npm ERR!   stack:
npm ERR!    "Error: EACCES: permission denied, rename
'/usr/lib/node_modules/.staging/npm-18aca6f9/node_modules/wrap-ansi' ->
'/usr/lib/node_modules/.staging/wrap-ansi-9f8997e7'",
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'rename',
npm ERR!   path:
npm ERR!    '/usr/lib/node_modules/.staging/npm-18aca6f9/node_modules/wrap-
ansi',
npm ERR!   dest: '/usr/lib/node_modules/.staging/wrap-ansi-9f8997e7' }
npm ERR!
npm ERR! The operation was rejected by your operating system.
npm ERR! It is likely you do not have the permissions to access this file as
the current user
npm ERR!
npm ERR! If you believe this might be a permissions issue, please double-
check the
npm ERR! permissions of the file and its containing directories, or try
running
npm ERR! the command again as root/Administrator (though this is not
recommended).

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2019-03-15T23_53_32_851Z-debug.log
</code>```

I followed the doc of the nodejs website for installation using curl in root mode to get the repository of the last 11.x version of node.

Thanks in advance!

答:
Experiencing this issue on WSL Ubuntu distro, and only on rename.

Happens also on npm update even after using chown on my node_modules directory.

The workaround that I got working is to simply avoid update and use install instead (npm install npm@x is technically an update too). I know this is very bothersome but aside from this I'm not sure how to make it work. Commands that rename directories trigger this but not on create or delete.

Body:
Hello everyone i started with a fresh wsl distrib of Debian and installed nodejs and npm on it.

When trying to update to the latest release of npm with the following command:

sudo npm install npm@latest -g

I get some weird issues who seems pretty common on wsl from what i saw on my internet researchs the only answer who seems to works but not really resolving properly the issue is setting the unsafe permissions to true with the following command:

npm config set unsafe-perm true

I would avoid to use this method and find an more clean way to resolve the issue.

Here is the console output:

####@#####:~$ sudo npm install npm@latest -g
npm ERR! path /usr/lib/node_modules/.staging/npm-18aca6f9/node_modules/wrap-
ansi
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! syscall rename
npm ERR! Error: EACCES: permission denied, rename
'/usr/lib/node_modules/.staging/npm-18aca6f9/node_modules/wrap-ansi' ->
'/usr/lib/node_modules/.staging/wrap-ansi-9f8997e7'
npm ERR!  { [Error: EACCES: permission denied, rename
'/usr/lib/node_modules/.staging/npm-18aca6f9/node_modules/wrap-ansi' ->
'/usr/lib/node_modules/.staging/wrap-ansi-9f8997e7']
npm ERR!   cause:
npm ERR!    { Error: EACCES: permission denied, rename
'/usr/lib/node_modules/.staging/npm-18aca6f9/node_modules/wrap-ansi' ->
'/usr/lib/node_modules/.staging/wrap-ansi-9f8997e7'
npm ERR!      errno: -13,
npm ERR!      code: 'EACCES',
npm ERR!      syscall: 'rename',
npm ERR!      path:
npm ERR!       '/usr/lib/node_modules/.staging/npm-
18aca6f9/node_modules/wrap-ansi',
npm ERR!      dest: '/usr/lib/node_modules/.staging/wrap-ansi-9f8997e7' },
npm ERR!   stack:
npm ERR!    "Error: EACCES: permission denied, rename
'/usr/lib/node_modules/.staging/npm-18aca6f9/node_modules/wrap-ansi' ->
'/usr/lib/node_modules/.staging/wrap-ansi-9f8997e7'",
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'rename',
npm ERR!   path:
npm ERR!    '/usr/lib/node_modules/.staging/npm-18aca6f9/node_modules/wrap-
ansi',
npm ERR!   dest: '/usr/lib/node_modules/.staging/wrap-ansi-9f8997e7' }
npm ERR!
npm ERR! The operation was rejected by your operating system.
npm ERR! It is likely you do not have the permissions to access this file as
the current user
npm ERR!
npm ERR! If you believe this might be a permissions issue, please double-
check the
npm ERR! permissions of the file and its containing directories, or try
running
npm ERR! the command again as root/Administrator (though this is not
recommended).

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2019-03-15T23_53_32_851Z-debug.log

I followed the doc of the nodejs website for installation using curl in root mode to get the repository of the last 11.x version of node.

Thanks in advance!


问:
How to use Cloud Foundry to serve Spring Boot web app with Vue front end and H2 database?
I have followed a tutorial using Vue as front end and using spring boot as backend. I write the front end and put the built files from Vue's dist folder to spring boot web's src\main\resources\static folder.

The tutorial told me to use axios to transfer data to the backend. It's configuration is as follows:

```<code>var axios = require('axios')
axios.defaults.baseURL = 'http://localhost:8090/api'
</code>```

It works good on my local pc. But I want to put it and make it run on cloud.
I build the jar with mvn clean install. Then uploaded it to IBM's cloud foundry.
The frontend works. However, it does not talk to the backend. The browser's console log shows:

```<code>XHR failed loading: OPTIONS "<URL>".
4xhr.js:178 OPTIONS http://localhost:8090/api/login net::ERR_CONNECTION_REFUSED
</code>```

The demo is uploaded here

I also want to include H2 database, but I tried and it only works on mem mode or file mode. The jdbc:h2:tcp://localhost/~/test mode does not work on the cloud.
So how to make it run on the cloud? Is there anyother way to make Vue talk with the java backend without axios?
Or if it's must, can I configure cloud foundry to make the link work?
Or if cloud foundry can't do this, (I use cloud foundry just because it's easy, just upload the jar, no need to configure) can k8s do this?

答:
XHR failed loading: OPTIONS "".
  4xhr.js:178 OPTIONS http://localhost:8090/api/login net::ERR_CONNECTION_REFUSED

This is failing because your app is no longer running on your local machine, it's running on Cloud Foundry. You need to update your axios.defaults.baseURL setting to reference the route that you bound to your app.

You could hard code this in the config, which is not great but does work, or you could reference the VCAP_APPLICATION environment variable which is set by Cloud Foundry and contains information about your app, including the bound routes (there can be more than one). You could read this, pick a route and dynamically configure your app.

Ex:

```<code> "VCAP_APPLICATION": {
  "application_id": "<guid>",
  "application_name": "<app-name>",
  "application_uris": [
   "app-name.apps.example.com",
   "some-other-route.example.com"
  ],
  "application_version": "df82308c-7add-4f2b-bb44-a58680084a79",
  "cf_api": "https://api.system.example.com",
  "limits": {
   "disk": 1024,
   "fds": 16384,
   "mem": 64
  },
  "name": "<app-name>",
  "space_id": "<space-guid>",
  "space_name": "<space-name>",
  "uris": [
   "app-name.apps.example.com",
   "some-other-route.example.com"
  ],
  "users": null,
  "version": "df82308c-7add-4f2b-bb44-a58680084a79"
 }
</code>```

I also want to include H2 database, but I tried and it only works on mem mode or file mode. The jdbc:h2:tcp://localhost/~/test mode does not work on the cloud.

I don't see why this technically wouldn't work, so long as you're app is talking to the database over localhost, all the traffic would be inside the app container. You'd have to be more specific about what exactly is failing.

That said, I don't think you'd want to use H2 like that, at least not beyond a small test/demo. First off, the app containers are ephemeral, so none of your data would survive a restart/crash/restage/push or anything that triggers the container to restart (platform maintenance can do this too, so it's not just actions you initiate). Second, you really wouldn't be able to scale your app beyond one instance because each instance of the app would have it's own copy of the database, which is going to be problematic.

What you really want to do is create a service & bind that to your app. Then, just like VCAP_APPLICTION, you can pull your service credentials from VCAP_SERVICES and dynamically configure your app to connect to your database. See the second part of this answer for details on how to do that.

Try running cf marketplace to see a list of the services your provider offers. Many services even have free tier service plans, so you can try them or use them for small apps and demos.

Hope that helps!

Body:
I have followed a tutorial using Vue as front end and using spring boot as backend. I write the front end and put the built files from Vue's dist folder to spring boot web's src\main\resources\static folder.

The tutorial told me to use axios to transfer data to the backend. It's configuration is as follows:

var axios = require('axios')
axios.defaults.baseURL = 'http://localhost:8090/api'

It works good on my local pc. But I want to put it and make it run on cloud.
I build the jar with mvn clean install. Then uploaded it to IBM's cloud foundry.
The frontend works. However, it does not talk to the backend. The browser's console log shows:

XHR failed loading: OPTIONS "<URL>".
4xhr.js:178 OPTIONS http://localhost:8090/api/login net::ERR_CONNECTION_REFUSED

The demo is uploaded here

I also want to include H2 database, but I tried and it only works on mem mode or file mode. The jdbc:h2:tcp://localhost/~/test mode does not work on the cloud.
So how to make it run on the cloud? Is there anyother way to make Vue talk with the java backend without axios?
Or if it's must, can I configure cloud foundry to make the link work?
Or if cloud foundry can't do this, (I use cloud foundry just because it's easy, just upload the jar, no need to configure) can k8s do this?

Body:
XHR failed loading: OPTIONS "".
  4xhr.js:178 OPTIONS http://localhost:8090/api/login net::ERR_CONNECTION_REFUSED

This is failing because your app is no longer running on your local machine, it's running on Cloud Foundry. You need to update your axios.defaults.baseURL setting to reference the route that you bound to your app.

You could hard code this in the config, which is not great but does work, or you could reference the VCAP_APPLICATION environment variable which is set by Cloud Foundry and contains information about your app, including the bound routes (there can be more than one). You could read this, pick a route and dynamically configure your app.

Ex:

 "VCAP_APPLICATION": {
  "application_id": "<guid>",
  "application_name": "<app-name>",
  "application_uris": [
   "app-name.apps.example.com",
   "some-other-route.example.com"
  ],
  "application_version": "df82308c-7add-4f2b-bb44-a58680084a79",
  "cf_api": "https://api.system.example.com",
  "limits": {
   "disk": 1024,
   "fds": 16384,
   "mem": 64
  },
  "name": "<app-name>",
  "space_id": "<space-guid>",
  "space_name": "<space-name>",
  "uris": [
   "app-name.apps.example.com",
   "some-other-route.example.com"
  ],
  "users": null,
  "version": "df82308c-7add-4f2b-bb44-a58680084a79"
 }

I also want to include H2 database, but I tried and it only works on mem mode or file mode. The jdbc:h2:tcp://localhost/~/test mode does not work on the cloud.

I don't see why this technically wouldn't work, so long as you're app is talking to the database over localhost, all the traffic would be inside the app container. You'd have to be more specific about what exactly is failing.

That said, I don't think you'd want to use H2 like that, at least not beyond a small test/demo. First off, the app containers are ephemeral, so none of your data would survive a restart/crash/restage/push or anything that triggers the container to restart (platform maintenance can do this too, so it's not just actions you initiate). Second, you really wouldn't be able to scale your app beyond one instance because each instance of the app would have it's own copy of the database, which is going to be problematic.

What you really want to do is create a service & bind that to your app. Then, just like VCAP_APPLICTION, you can pull your service credentials from VCAP_SERVICES and dynamically configure your app to connect to your database. See the second part of this answer for details on how to do that.

Try running cf marketplace to see a list of the services your provider offers. Many services even have free tier service plans, so you can try them or use them for small apps and demos.

Hope that helps!


问:
Create index concurrently blocked by other transactions in postgresql 9.6
I'm trying to create indices through hikari by "create index concurrently" statement with postgresql 9.6
The create statement is blocked by another transaction which is working on another table and the transaction state is IIT(idle in transaction)

The code is creating the indices dynamically through hikari connection
pool

There is only one connection pool for all the actions, such as select/create index and so on

The 2 SQLs are running in the same thread with different db connection with async mode

When using "create index" instead of "create index concurrently", all the things are OK

postgresql shows the "create index concurrently on B"(active) is blocked by "select * from A"(idle in transaction)

I tried to reproduce the issue through command line, all the things worked well, just open 2 window, execute "begin; select * from A;" in first window, and tried to execute "create index concurrently on B;" in second window, the index created as expected, no block happened(I checked that, the first one is in "IIT" state)

To use fetch_size on cursor, the select statement will disable autocommit when get connection from pool and set the value back with pool global settings by hikari itself, the default pool setting is autocommit=true

2 statement are working on different tables, no relations between these 2 tables

When the "IIT" statement cancelled, the "create" statement continued to work as expected

```<code>wait_event_type |  pid  |        state        |    query
Lock            | 25707 | active              | CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS "idx_tr-parameters__id_json" ON "tr-parameters" ((info->'_id') ASC)
                | 25701 | idle in transaction | SELECT t.info FROM "configuration-profiles" t

</code>```

```<code>05-29 21:22:53.458 [vert.x-worker-thread-11] DEBUG com.calix.sxa.VertxPGVertice - SELECT t.info FROM "organizations" t HikariProxyConnection@379242839 wrapping org.postgresql.jdbc.PgConnection@645bae4d
05-29 21:22:53.529 [vert.x-worker-thread-11] DEBUG com.zaxxer.hikari.pool.PoolBase - hikari-cp-threads - Reset (autoCommit) on connection org.postgresql.jdbc.PgConnection@645bae4d
05-29 21:22:53.533 [vert.x-worker-thread-11] DEBUG com.calix.sxa.VertxPGVertice - SELECT t.info FROM "configuration-profiles" t HikariProxyConnection@358392671 wrapping org.postgresql.jdbc.PgConnection@645bae4d
05-29 21:22:53.693 [vert.x-worker-thread-11] DEBUG com.calix.sxa.VertxPGVertice - SELECT t.info FROM "groups" t HikariProxyConnection@269112314 wrapping org.postgresql.jdbc.PgConnection@63822471
05-29 21:22:53.701 [vert.x-worker-thread-11] DEBUG com.zaxxer.hikari.pool.PoolBase - hikari-cp-threads - Reset (autoCommit) on connection org.postgresql.jdbc.PgConnection@63822471
05-29 21:22:53.701 [vert.x-worker-thread-11] DEBUG com.calix.sxa.VertxPGVertice - SELECT t.info FROM "configuration-profiles" t WHERE COALESCE((t.info->'configurations'->'parameterValues')::jsonb ?? 'OUI_FilterList', false) = true HikariProxyConnection@1431456353 wrapping org.postgresql.jdbc.PgConnection@63822471
05-29 21:22:53.704 [vert.x-worker-thread-11] DEBUG com.zaxxer.hikari.pool.PoolBase - hikari-cp-threads - Reset (autoCommit) on connection org.postgresql.jdbc.PgConnection@63822471
05-29 21:22:53.712 [vert.x-worker-thread-11] DEBUG com.calix.sxa.VertxPGVertice - CREATE INDEX CONCURRENTLY IF NOT EXISTS "idx_tr-parameters__id_json" ON "tr-parameters" ((info->>'timestamp') ASC) HikariProxyConnection@454316525 wrapping org.postgresql.jdbc.PgConnection@63822471

</code>```

I don't know why the block happened since the tables are totally different and when testing manually with 2 command line windows, all the things worked well

How can I fix this issue? Any workaround on it?

Thanks for you kindly help

As mentioned by @jjanes, it's blocked by other transactions(transactions on the same table or any transaction with snapshot) during the 2 scans when building index concurrently

The official doc also mentioned, [1]: https://www.postgresql.org/docs/9.1/sql-createindex.html#SQL-CREATEINDEX-CONCURRENTLY

```<code>After the second scan, the index build must wait for any transactions
that have a snapshot (see Chapter 13) predating the second scan to terminate
</code>```

In my case,

```<code>wait_event_type |  pid  |        state        | backend_xid | backend_xmin | query
----------------+-------+---------------------+-------------+--------------+--------------------------------------------------
                |  5226 | idle in transaction |             |      7973432 | select * from "configuration-profiles"

</code>```

The backend_xmin is 7973432 of IIT and then the "create index concurrently" is blocked by the IIT with snapshot

BTW, when using command line with isolation level "read committed", the "create index concurrently" is not blocked, but with Java code, the "create" action is also blocked with the same isolation level,

```<code>wait_event_type |  pid  |        state        | backend_xid | backend_xmin | query
----------------+-------+---------------------+-------------+--------------+--------------------------------------------------
                |  5226 | idle in transaction |             |      7973432 | select * from "configuration-profiles"
                |  5210 | idle in transaction |             |              | select * from "configuration-profiles";
                |  5455 | idle in transaction |             |      7973432 | declare cur cursor for select * from "configuration-profiles";

</code>```

As showed above,

Using "select * from "configuration-profiles";" in command line, there is no backend_xmin since no cursor opened, all the records should be returned after executed the statement

Using "declare cur cursor for select * from "configuration-profiles";" in command line, backend_xmin has value since the cursor opened and waiting for query

Using "select * from "configuration-profiles"" through Java, backend_xmin also has value since the lib also uses cursor

答:
PostgreSQL has no way of knowing that that other connection will not want to use the table the index is being built on at some point in the future of its snapshot.  Just because it hasn't used the table yet doesn't mean it never will.  The way to know that for sure is to wait for that transaction (or snapshot) to finish, which is what it does.

The 2 SQLs are running in the same thread with different db connection with async mode

Why is the other connection IIT?  What is it waiting for? (It is waiting in your code, not in the database).  Since it is async, it shouldn't be waiting on the CIC.  Is it just waiting for you to issue a COMMIT? Since you turned off autocommit, it is your responsibility to issue COMMITs at the appropriate points.  If you are using higher isolation levels, even SELECT only statements need to be committed.

I tried to reproduce the issue through command line, all the things worked well, just open 2 window, execute "begin; select * from A;" in first window, and tried to execute "create index concurrently on B;" in second window,

You can reproduce by changing the first one to begin isolation level repeatable read; select * from A;

Workarounds:

Don't leave things hanging around in an open transaction

Don't use higher isolation levels than you need to.

Don't use CIC.

Body:
I'm trying to create indices through hikari by "create index concurrently" statement with postgresql 9.6
The create statement is blocked by another transaction which is working on another table and the transaction state is IIT(idle in transaction)

The code is creating the indices dynamically through hikari connection
pool

There is only one connection pool for all the actions, such as select/create index and so on

The 2 SQLs are running in the same thread with different db connection with async mode

When using "create index" instead of "create index concurrently", all the things are OK

postgresql shows the "create index concurrently on B"(active) is blocked by "select * from A"(idle in transaction)

I tried to reproduce the issue through command line, all the things worked well, just open 2 window, execute "begin; select * from A;" in first window, and tried to execute "create index concurrently on B;" in second window, the index created as expected, no block happened(I checked that, the first one is in "IIT" state)

To use fetch_size on cursor, the select statement will disable autocommit when get connection from pool and set the value back with pool global settings by hikari itself, the default pool setting is autocommit=true

2 statement are working on different tables, no relations between these 2 tables

When the "IIT" statement cancelled, the "create" statement continued to work as expected

wait_event_type |  pid  |        state        |    query
Lock            | 25707 | active              | CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS "idx_tr-parameters__id_json" ON "tr-parameters" ((info->'_id') ASC)
                | 25701 | idle in transaction | SELECT t.info FROM "configuration-profiles" t

05-29 21:22:53.458 [vert.x-worker-thread-11] DEBUG com.calix.sxa.VertxPGVertice - SELECT t.info FROM "organizations" t HikariProxyConnection@379242839 wrapping org.postgresql.jdbc.PgConnection@645bae4d
05-29 21:22:53.529 [vert.x-worker-thread-11] DEBUG com.zaxxer.hikari.pool.PoolBase - hikari-cp-threads - Reset (autoCommit) on connection org.postgresql.jdbc.PgConnection@645bae4d
05-29 21:22:53.533 [vert.x-worker-thread-11] DEBUG com.calix.sxa.VertxPGVertice - SELECT t.info FROM "configuration-profiles" t HikariProxyConnection@358392671 wrapping org.postgresql.jdbc.PgConnection@645bae4d
05-29 21:22:53.693 [vert.x-worker-thread-11] DEBUG com.calix.sxa.VertxPGVertice - SELECT t.info FROM "groups" t HikariProxyConnection@269112314 wrapping org.postgresql.jdbc.PgConnection@63822471
05-29 21:22:53.701 [vert.x-worker-thread-11] DEBUG com.zaxxer.hikari.pool.PoolBase - hikari-cp-threads - Reset (autoCommit) on connection org.postgresql.jdbc.PgConnection@63822471
05-29 21:22:53.701 [vert.x-worker-thread-11] DEBUG com.calix.sxa.VertxPGVertice - SELECT t.info FROM "configuration-profiles" t WHERE COALESCE((t.info->'configurations'->'parameterValues')::jsonb ?? 'OUI_FilterList', false) = true HikariProxyConnection@1431456353 wrapping org.postgresql.jdbc.PgConnection@63822471
05-29 21:22:53.704 [vert.x-worker-thread-11] DEBUG com.zaxxer.hikari.pool.PoolBase - hikari-cp-threads - Reset (autoCommit) on connection org.postgresql.jdbc.PgConnection@63822471
05-29 21:22:53.712 [vert.x-worker-thread-11] DEBUG com.calix.sxa.VertxPGVertice - CREATE INDEX CONCURRENTLY IF NOT EXISTS "idx_tr-parameters__id_json" ON "tr-parameters" ((info->>'timestamp') ASC) HikariProxyConnection@454316525 wrapping org.postgresql.jdbc.PgConnection@63822471

I don't know why the block happened since the tables are totally different and when testing manually with 2 command line windows, all the things worked well

How can I fix this issue? Any workaround on it?

Thanks for you kindly help

As mentioned by @jjanes, it's blocked by other transactions(transactions on the same table or any transaction with snapshot) during the 2 scans when building index concurrently

The official doc also mentioned, [1]: https://www.postgresql.org/docs/9.1/sql-createindex.html#SQL-CREATEINDEX-CONCURRENTLY

After the second scan, the index build must wait for any transactions
that have a snapshot (see Chapter 13) predating the second scan to terminate

In my case,

wait_event_type |  pid  |        state        | backend_xid | backend_xmin | query
----------------+-------+---------------------+-------------+--------------+--------------------------------------------------
                |  5226 | idle in transaction |             |      7973432 | select * from "configuration-profiles"

The backend_xmin is 7973432 of IIT and then the "create index concurrently" is blocked by the IIT with snapshot

BTW, when using command line with isolation level "read committed", the "create index concurrently" is not blocked, but with Java code, the "create" action is also blocked with the same isolation level,

wait_event_type |  pid  |        state        | backend_xid | backend_xmin | query
----------------+-------+---------------------+-------------+--------------+--------------------------------------------------
                |  5226 | idle in transaction |             |      7973432 | select * from "configuration-profiles"
                |  5210 | idle in transaction |             |              | select * from "configuration-profiles";
                |  5455 | idle in transaction |             |      7973432 | declare cur cursor for select * from "configuration-profiles";

As showed above,

Using "select * from "configuration-profiles";" in command line, there is no backend_xmin since no cursor opened, all the records should be returned after executed the statement

Using "declare cur cursor for select * from "configuration-profiles";" in command line, backend_xmin has value since the cursor opened and waiting for query

Using "select * from "configuration-profiles"" through Java, backend_xmin also has value since the lib also uses cursor


问:
React functional component default props vs default parameters
In a React functional component, which is the better approach to set default props, using Component.defaultProps, or using the default parameters on the function definition, examples:

Default props:

```<code>const Component = ({ prop1, prop2 }) => (
  <div></div>
)

Component.defaultProps = {
  prop1: false,
  prop2: 'My Prop',
}
</code>```

Default parameters:

```<code>const Component = ({ prop1 = false, prop2 = 'My Prop' }) => (
  <div></div>
)
</code>```

答:
Shameless Plug here, I'm the author of with-default-props.

If you are a TypeScript user, with-default-props might help you, which uses higher order function to provide correct component definition with defaultProps given.

Eg.

```<code>import { withDefaultProps } from 'with-default-props'

type Props = {
    text: string;
    onClick: () => void;
};

function Component(props: Props) {
    return <div onClick={props.onClick}>{props.text}</div>;
}

// `onClick` is optional now.
const Wrapped = withDefaultProps(Component, { onClick: () => {} })

function App1() {
    // ✅
    return <Wrapped text="hello"></Wrapped>
}

function App2() {
    // ✅
    return <Wrapped text="hello" onClick={() => {}}></Wrapped>
}

function App3() {
    // ❌
    // Error: `text` is missing!
    return <Wrapped onClick={() => {}}></Wrapped>
}
</code>```

Body:
In a React functional component, which is the better approach to set default props, using Component.defaultProps, or using the default parameters on the function definition, examples:

Default props:

const Component = ({ prop1, prop2 }) => (

)

Component.defaultProps = {
  prop1: false,
  prop2: 'My Prop',
}

Default parameters:

const Component = ({ prop1 = false, prop2 = 'My Prop' }) => (

)

Body:
Shameless Plug here, I'm the author of with-default-props.

If you are a TypeScript user, with-default-props might help you, which uses higher order function to provide correct component definition with defaultProps given.

Eg.

import { withDefaultProps } from 'with-default-props'

type Props = {
    text: string;
    onClick: () => void;
};

function Component(props: Props) {
    return <div onClick={props.onClick}>{props.text}</div>;
}

// `onClick` is optional now.
const Wrapped = withDefaultProps(Component, { onClick: () => {} })

function App1() {
    // ✅
    return <Wrapped text="hello"></Wrapped>
}

function App2() {
    // ✅
    return <Wrapped text="hello" onClick={() => {}}></Wrapped>
}

function App3() {
    // ❌
    // Error: `text` is missing!
    return <Wrapped onClick={() => {}}></Wrapped>
}


问:
Create Single Instance of Service in Angular
sample code for demo:
https://stackblitz.com/edit/angular-9zjkyf

I need a global shared service that can be accessed from any part of the app, I have been following along the documentation:

https://angular.io/guide/singleton-services

I have setup a sample service that generates a random number and when used in modules I would expect any component calling the service to get the same number, but they are different, which makes me think that there are multiple instances of my service

service.ts

```<code>import { Injectable,OnInit } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class UserService implements OnInit {

 random :number;

  constructor() {
    this.random = Math.random( );
   }
  ngOnInit() {

  }
}
</code>```

component.ts

```<code>import { Component, OnInit } from '@angular/core';

import { UserService } from './user.service';
import { UserModule} from './user.module';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [UserService]
})
export class AppComponent implements OnInit {
  title = 'Users list';
  users: User[];
  rand: number;

  constructor(private userService: UserService) { }

  ngOnInit(): void {

    this.rand = this.userService.random;
  }

}
</code>```

答:
@Jota.Teledo is right. Don't put the service in the Providers array. Putting it there creates a new instance at the component level.

Just put it in the constructor and the DI will grab the root, singleton instance.

Body:
sample code for demo:
https://stackblitz.com/edit/angular-9zjkyf

I need a global shared service that can be accessed from any part of the app, I have been following along the documentation:

https://angular.io/guide/singleton-services

I have setup a sample service that generates a random number and when used in modules I would expect any component calling the service to get the same number, but they are different, which makes me think that there are multiple instances of my service

service.ts

import { Injectable,OnInit } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class UserService implements OnInit {

 random :number;

  constructor() {
    this.random = Math.random( );
   }
  ngOnInit() {

  }
}

component.ts

import { Component, OnInit } from '@angular/core';

import { UserService } from './user.service';
import { UserModule} from './user.module';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [UserService]
})
export class AppComponent implements OnInit {
  title = 'Users list';
  users: User[];
  rand: number;

  constructor(private userService: UserService) { }

  ngOnInit(): void {

    this.rand = this.userService.random;
  }

}


问:
Invoke or BeginInvoke cannot be called on a control until the window handle has been created
I have a SafeInvoke Control extension method similar to the one Greg D discusses here (minus the IsHandleCreated check).

I am calling it from a System.Windows.Forms.Form as follows:

```<code>public void Show(string text) {
    label.SafeInvoke(()=>label.Text = text);
    this.Show();
    this.Refresh();
}
</code>```

Sometimes (this call can come from a variety of threads) this results in the following error:

System.InvalidOperationException occurred

Message= "Invoke or BeginInvoke cannot be called on a control until the window handle has been created."

Source= "System.Windows.Forms"

```<code>StackTrace:
at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)
at System.Windows.Forms.Control.Invoke(Delegate method, Object[] args)
at System.Windows.Forms.Control.Invoke(Delegate method)
at DriverInterface2.UI.WinForms.Dialogs.FormExtensions.SafeInvoke[T](T control, Action`1 action)
in C:\code\DriverInterface2\DriverInterface2.UI.WinForms\Dialogs\FormExtensions.cs:line 16
</code>```

What is going on and how do I fix it?  I know as much as it is not a problem of form creation, since sometimes it will work once and fail the next time so what could the problem be?

PS. I really really am awful at WinForms, does anyone know a good series of articles that explains the whole model and how to work with it?

答:
What about this :</p>

```<code>
    public static bool SafeInvoke( this Control control, MethodInvoker method )
    {
        if( control != null && ! control.IsDisposed && control.IsHandleCreated && control.FindForm().IsHandleCreated )
        {
            if( control.InvokeRequired )
            {
                control.Invoke( method );
            }
            else
            {
                method();
            }
            return true;
        }
        else return false;
    }
</code>```

Body:
I have a SafeInvoke Control extension method similar to the one Greg D discusses here (minus the IsHandleCreated check).

I am calling it from a System.Windows.Forms.Form as follows:

public void Show(string text) {
    label.SafeInvoke(()=>label.Text = text);
    this.Show();
    this.Refresh();
}

Sometimes (this call can come from a variety of threads) this results in the following error:

System.InvalidOperationException occurred

Message= "Invoke or BeginInvoke cannot be called on a control until the window handle has been created."

Source= "System.Windows.Forms"

StackTrace:
at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)
at System.Windows.Forms.Control.Invoke(Delegate method, Object[] args)
at System.Windows.Forms.Control.Invoke(Delegate method)
at DriverInterface2.UI.WinForms.Dialogs.FormExtensions.SafeInvoke[T](T control, Action`1 action)
in C:\code\DriverInterface2\DriverInterface2.UI.WinForms\Dialogs\FormExtensions.cs:line 16

What is going on and how do I fix it?  I know as much as it is not a problem of form creation, since sometimes it will work once and fail the next time so what could the problem be?

PS. I really really am awful at WinForms, does anyone know a good series of articles that explains the whole model and how to work with it?

Body:
What about this :

    public static bool SafeInvoke( this Control control, MethodInvoker method )
    {
        if( control != null && ! control.IsDisposed && control.IsHandleCreated && control.FindForm().IsHandleCreated )
        {
            if( control.InvokeRequired )
            {
                control.Invoke( method );
            }
            else
            {
                method();
            }
            return true;
        }
        else return false;
    }


问:
How to Convince management to upgrade to .Net 4.0
We developed an application using .net 2.0.
We license our software which means whenever we release a new version, we have to push out the change to all our existing clients.

No one in my group has the slightest motivation to upgrade to a newer version of .net. They simple see it as more work for our support team to deploy and argue that clients will be resistant to any change.

Can anyone point me in the direction of some argument i could present to Non programmers that might sway them.

If noting else, some argument that it is safe, and will not cause our clients any harm who already have the .net 2.0 framework on their machines?

I figure it's hopeless. I'm gonna be stuck using the .net 2.0 framework until for another 4 or 5 years i bet... perhaps longer :( help!

I really want to be able to use WCF, LINQ, WPF (possible), and the option to use the Entity Framework 4.0.!

thanks

jonathan

答:
I tend to agree with @Lior Kogan, in that upgrading for the sake of it is not something that you should be arguing with management about.

In fact, there are good arguments for not upgrading:

if you've got a stable platform, why introduce potential instability?

if we upgrade this, will it force us to spend more money upgrading other things?

will it mean we have to force our customers to upgrade as well?

All these things are big negatives to a business, and make a good case for maintaining the status-quo.

However, upgrades are necessary at some point. There are a lot of very frustrated web developers out there who are cursing businesses worldwide for taking the above aproach to Internet Explorer v6: While those businesses were arguably doing the right thing for some time, they've now passed the point where it is difficult to defend staying still. It may not be the case for you now, but eventually the same will hold true for a .NET upgrade.

The argument here would be that the old version of the technology is obsolete:

it is no longer supported by the vendor, particularly with security fixes.

it is no longer sold by the vendor, making it hard to increase your number of users.

other technologies that we use rely on the newer version.

our customers are asking us for features that can only be delivered using the new version.

If any one of those points holds true than you may have a good argument for an upgrade that will win over the management. If not, you may have to stick it out.


问:
How can I programatically move an SPListItem from a source list to a destination list (into a specific folder of the list)?
I am pretty new in SharePoint (I am working with SharePoint 2013) and I have the following problem:

I have a source list(an SPList) on a source website and I have to move its items to a destination list (another SPList) on a destination website.

So basically I have to move some SPListItem from a list to another on two different website.

A further complication is that the destination list contains folder based on a date field on the item in migration (for example: if the date is: 2019/05/28 it will be created the following folders into the destination list like this 2019 --> 05 --> 28 where this SPListItem have to be put).

I know that I can do something like this:

```<code>private static void copyAttachments(SPListItem sourceItem, SPList sourceAttachList, SPList destAttachList, string destUrl)
{
    // Create the destination item for the attachments:
    SPListItem destAttachItem = null;

    string recNumber = sourceItem[Arxeia6Fields.NumeroProtocollo].ToString();
    DateTime recDate = (DateTime)sourceItem[Arxeia6Fields.DataProtocollo];

    /*
     * Add an item in a specific server-relative URL of the folder where the list item should be created.
     * The new list item represents a file.
     */
    destAttachItem = destAttachList.AddItem(destUrl, SPFileSystemObjectType.File);
    string title = recNumber + "/" + recDate.Year.ToString();
    destAttachItem["Title"] = title;
    destAttachItem["Numero protocollo"] = title;

}
</code>```

With this code I am creating adding a new item to the destination list (named destAttachList specifyng the destUrl representing the exact folder in this list where put the item (I have this information from a previous process step). Then I simply set the values of the 2 fields of this item in the destination list using the values of the item of the source list that I am migrating.

My doubts are:

Can I move the item from a source list to a destination list (in a specific folder specified by a destination URL)?

If this item in migration contains attachments, these attachments can be automatically migrated by this single move step? (if it is possible)

答:
You don't have to do all those things manually as SharePoint already has this method implemented out of the box. You don't even need an additional method, you shoud be able to achieve all those things by calling the MoveTo method.

sourceItem.File.MoveTo(SPUrlUtility.CombineUrl(destinationList.ParentWeb.Url,destinationList.RootFolder.Url));

Where, of course, the sourceItem si the SPListItem that you want to move and destinationList is the SPList that should serve as destination for the SPListItem.

Body:
I am pretty new in SharePoint (I am working with SharePoint 2013) and I have the following problem:

I have a source list(an SPList) on a source website and I have to move its items to a destination list (another SPList) on a destination website.

So basically I have to move some SPListItem from a list to another on two different website.

A further complication is that the destination list contains folder based on a date field on the item in migration (for example: if the date is: 2019/05/28 it will be created the following folders into the destination list like this 2019 --> 05 --> 28 where this SPListItem have to be put).

I know that I can do something like this:

private static void copyAttachments(SPListItem sourceItem, SPList sourceAttachList, SPList destAttachList, string destUrl)
{
    // Create the destination item for the attachments:
    SPListItem destAttachItem = null;

    string recNumber = sourceItem[Arxeia6Fields.NumeroProtocollo].ToString();
    DateTime recDate = (DateTime)sourceItem[Arxeia6Fields.DataProtocollo];

    /*
     * Add an item in a specific server-relative URL of the folder where the list item should be created.
     * The new list item represents a file.
     */
    destAttachItem = destAttachList.AddItem(destUrl, SPFileSystemObjectType.File);
    string title = recNumber + "/" + recDate.Year.ToString();
    destAttachItem["Title"] = title;
    destAttachItem["Numero protocollo"] = title;

}

With this code I am creating adding a new item to the destination list (named destAttachList specifyng the destUrl representing the exact folder in this list where put the item (I have this information from a previous process step). Then I simply set the values of the 2 fields of this item in the destination list using the values of the item of the source list that I am migrating.

My doubts are:

Can I move the item from a source list to a destination list (in a specific folder specified by a destination URL)?

If this item in migration contains attachments, these attachments can be automatically migrated by this single move step? (if it is possible)