问:
Disable pinch zoom in webkit (or electron)
Is there any way to disable pinch zoom in an electron app?

I can't get it to work from inside the web-view with normal javascript methods as described here: https://stackoverflow.com/a/23510108/665261

It seems the --disable-pinch flag is not supported by electron.

I have experimented with various methods using:

event.preventDefault() on javascript touchmove/mousemove events

meta viewport tags in HTML

-webkit-text-size-adjust in CSS

flags/config for electron

Is there any method either for webkit in general, or electron in particular?

答:
Answer from GitHub:

"If you are looking for a way how to prevent zoom from main process, you can use:"

```<code>const webContents = mainWindow.webContents;
webContents.on('did-finish-load', () => {
  webContents.setZoomFactor(1);
  webContents.setVisualZoomLevelLimits(1, 1);
  webContents.setLayoutZoomLevelLimits(0, 0);
});
</code>```

mainWindow is variable where you have new BrowserWindow, e.g.:

```<code>const mainWindow = new BrowserWindow({
  width: 440,
  height: 750,
  // ...
});

const webContents = mainWindow.webContents;
webContents.on("did-finish-load", () => {
  webContents.setZoomFactor(1);
  webContents.setVisualZoomLevelLimits(1, 1);
  webContents.setLayoutZoomLevelLimits(0, 0);
});
</code>```

Body:
Answer from GitHub:

"If you are looking for a way how to prevent zoom from main process, you can use:"

const webContents = mainWindow.webContents;
webContents.on('did-finish-load', () => {
  webContents.setZoomFactor(1);
  webContents.setVisualZoomLevelLimits(1, 1);
  webContents.setLayoutZoomLevelLimits(0, 0);
});

mainWindow is variable where you have new BrowserWindow, e.g.:

const mainWindow = new BrowserWindow({
  width: 440,
  height: 750,
  // ...
});

const webContents = mainWindow.webContents;
webContents.on("did-finish-load", () => {
  webContents.setZoomFactor(1);
  webContents.setVisualZoomLevelLimits(1, 1);
  webContents.setLayoutZoomLevelLimits(0, 0);
});


来源: stackexchange

问:
Update queries in Excel using VBA
I have a query (Query1) loaded into Excel by using a connection from Teradata. Normally when I want to update the query, I have to right click it and choose edit.

Once inside the Power Query Editor, I can open the Source and edit the SQL script inside to update the query.

The question is how can I edit this SQL script using VBA?

Upon trying to use the Macro Recorder, I can only refresh the query using

```<code>ActiveWorkbook.Connections("Query - Query1").OLEDBConnection.Refresh
</code>```

An attempt to edit the CommandText also failed. Here is the properties of the query.

答:
First we get the query's formula using:

```<code>Debug.Print ThisWorkbook.Queries.Item("Query1").Formula
</code>```

The reason we need to do this is because the formula string contains some extra information about our database connection and not just a sql query itself. It may look something like this:

```<code>let Source = Teradata.Database("tdprod1.ov.de", [HierarchicalNavigation=true, Query="SELECT week, revenue FROM table1"]); in Source
</code>```

To update the query, we set ThisWorkbook.Queries.Item("Query1").Formula to the new formula string. Also be careful while handling the double quotes inside VBA. Here is the script I used:

```<code>' Update the query Query1 using the provided parameters
Sub UpdateQuery1()

' string to represent a single double quote for VBA string
Const vbDoubleQuote As String = """"

Dim oledb As OLEDBConnection
Dim queryFormula As String

' get the connection
Set oledb = ThisWorkbook.Connections("Query - Query1").OLEDBConnection

' the new formula of the query
Let queryFormula = _
"let " & _
    "Source = Teradata.Database(" & vbDoubleQuote & "tdprod1.ov.de" & vbDoubleQuote & ", [HierarchicalNavigation=true, Query=" & vbDoubleQuote & _
    "SELECT #(lf)a.kw MOD 100 AS KW, #(lf)a.r_Category2_ID AS Category_ID,#(lf)a.r_category3_ID AS Subcategory_ID,#(lf)#(lf)a.vt_p_j AS VP_Jahr,#(lf)a.vt_p_p AS ..." & _
"in Source"

' update the formula of the query
Let ThisWorkbook.Queries.Item("Query1").Formula = queryFormula

' refresh the connection
oledb.Refresh

End Sub
</code>```

ContentLicense: CC BY-SA 4.0

Title: Update queries in Excel using VBA

Body:
I have a query (Query1) loaded into Excel by using a connection from Teradata. Normally when I want to update the query, I have to right click it and choose edit.

Once inside the Power Query Editor, I can open the Source and edit the SQL script inside to update the query.

The question is how can I edit this SQL script using VBA?

Upon trying to use the Macro Recorder, I can only refresh the query using

ActiveWorkbook.Connections("Query - Query1").OLEDBConnection.Refresh

An attempt to edit the CommandText also failed. Here is the properties of the query.

Body:
First we get the query's formula using:

Debug.Print ThisWorkbook.Queries.Item("Query1").Formula

The reason we need to do this is because the formula string contains some extra information about our database connection and not just a sql query itself. It may look something like this:

let Source = Teradata.Database("tdprod1.ov.de", [HierarchicalNavigation=true, Query="SELECT week, revenue FROM table1"]); in Source

To update the query, we set ThisWorkbook.Queries.Item("Query1").Formula to the new formula string. Also be careful while handling the double quotes inside VBA. Here is the script I used:

' Update the query Query1 using the provided parameters
Sub UpdateQuery1()

' string to represent a single double quote for VBA string
Const vbDoubleQuote As String = """"

Dim oledb As OLEDBConnection
Dim queryFormula As String

' get the connection
Set oledb = ThisWorkbook.Connections("Query - Query1").OLEDBConnection

' the new formula of the query
Let queryFormula = _
"let " & _
    "Source = Teradata.Database(" & vbDoubleQuote & "tdprod1.ov.de" & vbDoubleQuote & ", [HierarchicalNavigation=true, Query=" & vbDoubleQuote & _
    "SELECT #(lf)a.kw MOD 100 AS KW, #(lf)a.r_Category2_ID AS Category_ID,#(lf)a.r_category3_ID AS Subcategory_ID,#(lf)#(lf)a.vt_p_j AS VP_Jahr,#(lf)a.vt_p_p AS ..." & _
"in Source"

' update the formula of the query
Let ThisWorkbook.Queries.Item("Query1").Formula = queryFormula

' refresh the connection
oledb.Refresh

End Sub


问:
Changing NA value if matching a defined length
I have this kind of data :

```<code>daynight
[1] NA NA NA NA  2  1 NA NA
</code>```

I want R to detect if there is a series of at least x NA and replace these by another value.
For example if x=3 and the replacement value is 3 I want R to give me in output :

```<code>daynight
[1] 3 3 3 3 2 1 NA NA
</code>```

Would you have any ideas?

答:
And here is another solution using the zoo package

```<code>library(zoo)

replace_consecutive_NAs <- function(x, nrNAs = 3, replaceBy = nrNAs){
    x <- as.numeric(is.na(x))
    indexes <- (rollapply(x, 3, prod, fill = 0, align = "left") +
                    rollapply(x, 3, prod, fill = 0, align = "right")) != 0
    x[indexes] <- replaceBy
    x
}

x <- c(NA, NA, NA, NA  ,2  ,1, NA, NA)

replace_consecutive_NAs(x, 3, 999)

[1] 999 999 999 999   2   1  NA  NA
</code>```

Body:
I have this kind of data :

daynight
[1] NA NA NA NA  2  1 NA NA

I want R to detect if there is a series of at least x NA and replace these by another value.
For example if x=3 and the replacement value is 3 I want R to give me in output :

daynight
[1] 3 3 3 3 2 1 NA NA

Would you have any ideas?

Body:
And here is another solution using the zoo package

library(zoo)

replace_consecutive_NAs <- function(x, nrNAs = 3, replaceBy = nrNAs){
    x <- as.numeric(is.na(x))
    indexes <- (rollapply(x, 3, prod, fill = 0, align = "left") +
                    rollapply(x, 3, prod, fill = 0, align = "right")) != 0
    x[indexes] <- replaceBy
    x
}

x <- c(NA, NA, NA, NA  ,2  ,1, NA, NA)

replace_consecutive_NAs(x, 3, 999)

[1] 999 999 999 999   2   1  NA  NA


问:
C# / Regex - Replacing set of matches with another set of matches
I'm trying to turn this string:

INSERT INTO [main].[sqlite_default_schema].[TableName] ([SomeColumn],
  [SomeOtherColumn], [Last]) VALUES (@param1, @param2, @param3);

into this one:

INSERT INTO [main].[sqlite_default_schema].[TableName] ([SomeColumn],
  [SomeOtherColumn], [Last]) VALUES (@SomeColumn, @SomeOtherColumn,
  @Last);

As a beginner in regex, i'm using this C# snippet:

```<code>Regex regex = new Regex(@"\(.*?\)");
MatchCollection matches = regex.Matches(commandText);
if (matches[0].Success && matches[1].Success)
{
    Regex reColNames = new Regex(@"\[\w*\]");
    MatchCollection colNames = reColNames.Matches(matches[0].Value);
    Regex reParamNames = new Regex(@"\@\w*");
    MatchCollection paramNames = reParamNames.Matches(matches[1].Value);
    if (colNames.Count > 0 && colNames.Count == paramNames.Count)
    {
        for (int i = 0; i < paramNames.Count; i++)
        {
            string colName = colNames[i].Value.Substring(1, colNames[i].Length - 2);
            commandText = commandText.Replace(paramNames[i].Value, "@" + colName);
        }
    }
}
return commandText;
</code>```

This works but doesn't feel right.
Is there a way to achieve the same result by using just one regex?

Cheers!

答:
It seems to me you are replacing all "param" text with "column". Why not start with that in the first place? If that's impossible due to some concerns you haven't mentioned see the solution below.

This will bulk replace everything in 1 line.

```<code>Regex.Replace(query, "param", "column", RegexOptions.None);
</code>```

Body:
I'm trying to turn this string:

INSERT INTO [main].[sqlite_default_schema].[TableName] ([SomeColumn],
  [SomeOtherColumn], [Last]) VALUES (@param1, @param2, @param3);

into this one:

INSERT INTO [main].[sqlite_default_schema].[TableName] ([SomeColumn],
  [SomeOtherColumn], [Last]) VALUES (@SomeColumn, @SomeOtherColumn,
  @Last);

As a beginner in regex, i'm using this C# snippet:

Regex regex = new Regex(@"\(.*?\)");
MatchCollection matches = regex.Matches(commandText);
if (matches[0].Success && matches[1].Success)
{
    Regex reColNames = new Regex(@"\[\w*\]");
    MatchCollection colNames = reColNames.Matches(matches[0].Value);
    Regex reParamNames = new Regex(@"\@\w*");
    MatchCollection paramNames = reParamNames.Matches(matches[1].Value);
    if (colNames.Count > 0 && colNames.Count == paramNames.Count)
    {
        for (int i = 0; i < paramNames.Count; i++)
        {
            string colName = colNames[i].Value.Substring(1, colNames[i].Length - 2);
            commandText = commandText.Replace(paramNames[i].Value, "@" + colName);
        }
    }
}
return commandText;

This works but doesn't feel right.
Is there a way to achieve the same result by using just one regex?

Cheers!

Body:
It seems to me you are replacing all "param" text with "column". Why not start with that in the first place? If that's impossible due to some concerns you haven't mentioned see the solution below.

This will bulk replace everything in 1 line.

Regex.Replace(query, "param", "column", RegexOptions.None);


问:
Is there a way to access an object of an NSMutableArray using Swift?
My group and I are writing a space shooter game. We store the player and hazards in and NSMutableArray called objects. I just finished writing a function to control the players movement using tilt controls, but to test it I need to pass in the player when I call the function and I can't seem to access the player from the objects array. Here's my code:</p>

```<code>public var objects: NSMutableArray!

objects.add(Player(pos: GLKVector3(v: (0.0, 0.0, -5.0)), up: GLKVector3(v: (0.0, 1.0, 0.0)), forw: GLKVector3(v: (0.0, 0.0, -1.0)), hp: 5, dmg: 1));
        objects.add(Satellite(pos: GLKVector3(v: (2.0, -2.0, -40.0)), up: GLKVector3(v: (0.0, 1.0, 0.0)), forw: GLKVector3(v: (0.0, 0.0, -1.0)), hp: 5, dmg: 1, spd: 2.0));
        objects.add(Satellite(pos: GLKVector3(v: (-2.0, 2.0, -50.0)), up: GLKVector3(v: (0.0, 1.0, 0.0)), forw: GLKVector3(v: (0.0, 0.0, 1.0)), hp: 1, dmg: 1, spd: 2.0));

myDeviceMotion(objects.object(at: 0));
</code>```

答:
Not use NSMutableArray, user Arrays and pass temp Protocol to your classes. </p>

```<code>protocol MyTempProtocol {  }

class Player: MyTempProtocol {
    // ...
}

class Satellite: MyTempProtocol {
    // ...
}

/// --------------
let player1 = Player()
let player2 = Player()
let satellite1 = Satellite()
let satellite2 = Satellite()

var objects = [MyTempProtocol]()
objects.append(player1)
objects.append(satellite1)
objects.append(satellite2)
objects.append(player2)

if let objectIsPlayer = objects[0] is Player {
    // ...
} else if let objectIsSatellite = objects[0] is Satellite {
    // ...
} else {
    // ...
}
</code>```

Body:
My group and I are writing a space shooter game. We store the player and hazards in and NSMutableArray called objects. I just finished writing a function to control the players movement using tilt controls, but to test it I need to pass in the player when I call the function and I can't seem to access the player from the objects array. Here's my code:

public var objects: NSMutableArray!

objects.add(Player(pos: GLKVector3(v: (0.0, 0.0, -5.0)), up: GLKVector3(v: (0.0, 1.0, 0.0)), forw: GLKVector3(v: (0.0, 0.0, -1.0)), hp: 5, dmg: 1));
        objects.add(Satellite(pos: GLKVector3(v: (2.0, -2.0, -40.0)), up: GLKVector3(v: (0.0, 1.0, 0.0)), forw: GLKVector3(v: (0.0, 0.0, -1.0)), hp: 5, dmg: 1, spd: 2.0));
        objects.add(Satellite(pos: GLKVector3(v: (-2.0, 2.0, -50.0)), up: GLKVector3(v: (0.0, 1.0, 0.0)), forw: GLKVector3(v: (0.0, 0.0, 1.0)), hp: 1, dmg: 1, spd: 2.0));

myDeviceMotion(objects.object(at: 0));

Body:
Not use NSMutableArray, user Arrays and pass temp Protocol to your classes.

protocol MyTempProtocol {  }

class Player: MyTempProtocol {
    // ...
}

class Satellite: MyTempProtocol {
    // ...
}

/// --------------
let player1 = Player()
let player2 = Player()
let satellite1 = Satellite()
let satellite2 = Satellite()

var objects = [MyTempProtocol]()
objects.append(player1)
objects.append(satellite1)
objects.append(satellite2)
objects.append(player2)

if let objectIsPlayer = objects[0] is Player {
    // ...
} else if let objectIsSatellite = objects[0] is Satellite {
    // ...
} else {
    // ...
}


问:
RSpec have_tag failing even when tag is present?
Currently doing the Ruby On Rails Tutorial by Michael Hartl, and am starting on test-driven development. The tutorial demands that tests be written to ensure that the right titles are present on our html.erb pages. There are three of these pages - home, contact and about. The tests look like so:

```<code>it "should have the right title" do
  get 'home'
  response.should have_tag("title",
                         "Ruby On Rails Sample Application | Home")
end
</code>```

My home.html.erb file looks like so:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Ruby On Rails Sample Application | Home</title>
</head>
<body>
<h1>Sample App Home</h1>
<p>This is the home page for the
<a href="http://www.railstutorial.org/">Ruby on Rails Tutorial</a>
sample application.</p>
</body>
</html>
</code>```

As you can see, the title tag is present and it's wrapping the correct text. However, when I run my test, I get this error message:

```<code>'PagesController GET 'home' should have the right title' FAILED
 Expected at least 1 element matching "title", found 0.
</code>```

Can anyone explain what is going wrong here? Thanks

答:
Do you have
require 'spec_helper'
on top of your pages_controller_spec.rb?

Do you have
render_views
statement in your describe block?

To John Paul Ashenfelter, I thought save_and_open_page was Capybara method, and not Rspec?

ContentLicense: CC BY-SA 3.0

Body:
Currently doing the Ruby On Rails Tutorial by Michael Hartl, and am starting on test-driven development. The tutorial demands that tests be written to ensure that the right titles are present on our html.erb pages. There are three of these pages - home, contact and about. The tests look like so:

it "should have the right title" do
  get 'home'
  response.should have_tag("title",
                         "Ruby On Rails Sample Application | Home")
end

My home.html.erb file looks like so:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <title>Ruby On Rails Sample Application | Home</title>

Sample App Home

This is the home page for the
Ruby on Rails Tutorial
sample application.

As you can see, the title tag is present and it's wrapping the correct text. However, when I run my test, I get this error message:

'PagesController GET 'home' should have the right title' FAILED
 Expected at least 1 element matching "title", found 0.

Can anyone explain what is going wrong here? Thanks


问:
Compare values in two lists and return the similar or nearest value from a third list
I will like to find similar values of j in v and return x. when the value in j is not equal to v, I will like the code the detect the 2 value in v that j values between. so if j falls between v1 and v2, I will like the code to return max(x1,x2)- ( ((j-v1)/(v2-v1))*(max(x1,x2)-min(x1,x2)))

```<code>v= [100,200,300,400,500,600,700,800,900,1000,1100]
x= [67,56,89,21,90,54,38,93,46,17,75]
j= [200,300,400,460,500,600,700,800,870,900,950]

for i in range(len(v)-1):
    if v[i] > j and V[i+1] < j:
        p = max(x[i],x[i+1])- ( ((j-v[i])/(v[i+1]-v[i]))*(max(x[i],x[i+1])-min(x[i],x[i+1])))
    elif v[i] ==j:
        b= x[i]
print(p,b)

"""
n = [x[i] for i, v_ele in enumerate(v) if v_ele in j]
p=  [x[i] for i, v_ele in enumerate(v) if v_ele > j and v_ele
print(n)
"""
</code>```

I will like my answers to return

```<code>[56,89,21,48.6,90,54,38,93,60.1,46,31.5]
</code>```

答:
Well, there is a couple of problems with your code:

First, after your if statement, there is a colon missing and one of your "v"s is capitalized. Computers are unforgiving - no typo's! ;)

Then, in that same line, you try to compare an integer (v[i] and v[i+1]) with a complete list of integers (j). Instead you need to go through your j list and compare each element in that list. I introduced an index ij for going through j.

When you compare that j value to v, you got your >< signs mixed up. Since your v list is ordered from small to big, it is impossible to be smaller than element i and simultaneously bigger than element i+1. ;)

Lastly, I'm not sure why you would store your value in two different variables (p and b) instead of the same. I did just that and called it a and printed it in an example alongside the j value it comes from.

```<code>v= [100,200,300,400,500,600,700,800,900,1000,1100]
x= [67,56,89,21,90,54,38,93,46,17,75]
j= [200,300,400,460,500,600,700,800,870,900,950]

for ij in range(len(j)):
    for i in range(len(v)-1):
        if v[i] < j[ij] and v[i+1] > j[ij]:
            a = max(x[i],x[i+1])- ( ((j[ij]-v[i])/(v[i+1]-v[i]))*(max(x[i],x[i+1])-min(x[i],x[i+1])))
        elif v[i] == j[ij]:
            a = x[i]
 print(j[ij]," leads to ",a)
</code>```

Output:

```<code>200  leads to  56
300  leads to  89
400  leads to  21
460  leads to  48.6
500  leads to  90
600  leads to  54
700  leads to  38
800  leads to  93
870  leads to  60.1
900  leads to  46
950  leads to  31.5
</code>```

Body:
I will like to find similar values of j in v and return x. when the value in j is not equal to v, I will like the code the detect the 2 value in v that j values between. so if j falls between v1 and v2, I will like the code to return max(x1,x2)- ( ((j-v1)/(v2-v1))*(max(x1,x2)-min(x1,x2)))

v= [100,200,300,400,500,600,700,800,900,1000,1100]
x= [67,56,89,21,90,54,38,93,46,17,75]
j= [200,300,400,460,500,600,700,800,870,900,950]

for i in range(len(v)-1):
    if v[i] > j and V[i+1] < j:
        p = max(x[i],x[i+1])- ( ((j-v[i])/(v[i+1]-v[i]))*(max(x[i],x[i+1])-min(x[i],x[i+1])))
    elif v[i] ==j:
        b= x[i]
print(p,b)

"""
n = [x[i] for i, v_ele in enumerate(v) if v_ele in j]
p=  [x[i] for i, v_ele in enumerate(v) if v_ele > j and v_ele
print(n)
"""

I will like my answers to return

[56,89,21,48.6,90,54,38,93,60.1,46,31.5]

Body:
Well, there is a couple of problems with your code:

First, after your if statement, there is a colon missing and one of your "v"s is capitalized. Computers are unforgiving - no typo's! ;)

Then, in that same line, you try to compare an integer (v[i] and v[i+1]) with a complete list of integers (j). Instead you need to go through your j list and compare each element in that list. I introduced an index ij for going through j.

When you compare that j value to v, you got your >< signs mixed up. Since your v list is ordered from small to big, it is impossible to be smaller than element i and simultaneously bigger than element i+1. ;)

Lastly, I'm not sure why you would store your value in two different variables (p and b) instead of the same. I did just that and called it a and printed it in an example alongside the j value it comes from.

v= [100,200,300,400,500,600,700,800,900,1000,1100]
x= [67,56,89,21,90,54,38,93,46,17,75]
j= [200,300,400,460,500,600,700,800,870,900,950]

for ij in range(len(j)):
    for i in range(len(v)-1):
        if v[i] < j[ij] and v[i+1] > j[ij]:
            a = max(x[i],x[i+1])- ( ((j[ij]-v[i])/(v[i+1]-v[i]))*(max(x[i],x[i+1])-min(x[i],x[i+1])))
        elif v[i] == j[ij]:
            a = x[i]
 print(j[ij]," leads to ",a)

Output:

200  leads to  56
300  leads to  89
400  leads to  21
460  leads to  48.6
500  leads to  90
600  leads to  54
700  leads to  38
800  leads to  93
870  leads to  60.1
900  leads to  46
950  leads to  31.5


问:
What is the meaning of the 'g' flag in regular expressions?
What is the meaning of the g flag in regular expressions?

What is is the difference between /.+/g and /.+/?

答:
g -> returns all matches

without g -> returns first match

example:

'1 2 1 5 6  7'.match(/\d+/) returns ["1", index: 0, input: "1 2 1 5 6  7", groups: undefined]. As you see we can only take first match "1".

'1 2 1 5 6  7'.match(/\d+/g) returns an array of all matches ["1", "2", "1", "5", "6", "7"].


问:
Numba complains about typing - but all types are being provided
I have a problem with Numba typing - I read the manual, but eventually hit a brick wall.

The function in question is a part of a bigger project - though it needs to run fast - Python lists are out of the question, hence I've decided on trying Numba. Sadly, the function fails in nopython=True mode, despite the fact that - according to my understanding - all types are being provided.

The code is as follows:

```<code>from Numba import jit, njit, uint8, int64, typeof

@jit(uint8[:,:,:](int64))
def findWhite(cropped):
    h1 = int64(0)
    for i in cropped:
        for j in i:
            if np.sum(j) == 765:
                h1 = h1 + int64(1)
            else:
                pass
    return h1
</code>```

also, separately:

```<code>print(typeof(cropped))
array(uint8, 3d, C)
print(typeof(h1))
int64
</code>```

In this case 'cropped' is a large uint8 3D C matrix (RGB tiff file comprehension - PIL.Image). Could someone please explain to a Numba newbie what am I doing wrong?

答:
Have you considered using Numpy? That's often a good intermediate between Python lists and Numba, something like:

```<code>h1 = (cropped.sum(axis=-1) == 765).sum()
</code>```

or

```<code>h1 = (cropped == 255).all(axis=-1).sum()
</code>```

The example code you provide is not valid Numba. Your signature is also incorrect, since the input is a 3D array and the output an integer, it should probably be:

```<code>@njit(int64(uint8[:,:,:]))
</code>```

Looping over the array like you do is not valid code. A close translation of your code would be something like this:

```<code>@njit(int64(uint8[:,:,:]))
def findWhite(cropped):

    h1 = int64(0)
    ys, xs, n_bands = cropped.shape

    for i in range(ys):
        for j in range(xs):
            if cropped[i, j, :].sum() == 765:
                h1 += 1

    return h1
</code>```

But that isn't very fast and doesn't beat Numpy on my machine. With Numba it's fine to explicitly loop over every element in an array, this is already a lot faster:

```<code>@njit(int64(uint8[:,:,:]))
def findWhite_numba(cropped):

    h1 = int64(0)
    ys, xs, zs = cropped.shape

    for i in range(ys):
        for j in range(xs):

            incr = 1
            for k in range(zs):

                if cropped[i, j, k] != 255:
                    incr = 0
                    break

            h1 += incr

    return h1
</code>```

For a 5000x5000x3 array these are the result for me:

Numpy (h1 = (cropped == 255).all(axis=-1).sum()):

```<code>427 ms ± 6.37 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
</code>```

findWhite:

```<code>612 ms ± 6.16 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
</code>```

findWhite_numba:

```<code>31 ms ± 1.51 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
</code>```

A benefit of the Numpy method is that it generalizes to any amount of dimensions.

Body:
I have a problem with Numba typing - I read the manual, but eventually hit a brick wall.

The function in question is a part of a bigger project - though it needs to run fast - Python lists are out of the question, hence I've decided on trying Numba. Sadly, the function fails in nopython=True mode, despite the fact that - according to my understanding - all types are being provided.

The code is as follows:

from Numba import jit, njit, uint8, int64, typeof

@jit(uint8[:,:,:](int64))
def findWhite(cropped):
    h1 = int64(0)
    for i in cropped:
        for j in i:
            if np.sum(j) == 765:
                h1 = h1 + int64(1)
            else:
                pass
    return h1

also, separately:

print(typeof(cropped))
array(uint8, 3d, C)
print(typeof(h1))
int64

In this case 'cropped' is a large uint8 3D C matrix (RGB tiff file comprehension - PIL.Image). Could someone please explain to a Numba newbie what am I doing wrong?

Body:
Have you considered using Numpy? That's often a good intermediate between Python lists and Numba, something like:

h1 = (cropped.sum(axis=-1) == 765).sum()

or

h1 = (cropped == 255).all(axis=-1).sum()

The example code you provide is not valid Numba. Your signature is also incorrect, since the input is a 3D array and the output an integer, it should probably be:

@njit(int64(uint8[:,:,:]))

Looping over the array like you do is not valid code. A close translation of your code would be something like this:

@njit(int64(uint8[:,:,:]))
def findWhite(cropped):

    h1 = int64(0)
    ys, xs, n_bands = cropped.shape

    for i in range(ys):
        for j in range(xs):
            if cropped[i, j, :].sum() == 765:
                h1 += 1

    return h1

But that isn't very fast and doesn't beat Numpy on my machine. With Numba it's fine to explicitly loop over every element in an array, this is already a lot faster:

@njit(int64(uint8[:,:,:]))
def findWhite_numba(cropped):

    h1 = int64(0)
    ys, xs, zs = cropped.shape

    for i in range(ys):
        for j in range(xs):

            incr = 1
            for k in range(zs):

                if cropped[i, j, k] != 255:
                    incr = 0
                    break

            h1 += incr

    return h1

For a 5000x5000x3 array these are the result for me:

Numpy (h1 = (cropped == 255).all(axis=-1).sum()):

427 ms ± 6.37 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

findWhite:

612 ms ± 6.16 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

findWhite_numba:

31 ms ± 1.51 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

A benefit of the Numpy method is that it generalizes to any amount of dimensions.


问:
Changing the color of the parent component based upon the selection in the child component
I have a child component which is having a dropdrown of colors.Based upon what is selected in the dropdown list, the colour of the parent component should change.

As of now I am able to successfully change the color of the child component based upon the color selection ,but i want to change the color of the parent component.
Any help?
I am also able to print the Value of the dropdown in the parent component as I am using a reference variable but I want the color to change as well.

header.component.html:

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

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {

  styles: string[] = [];
  selectedStyle: string;

  constructor() {

  }

  ngOnInit(){

    this.styles = ['red','green','blue','none'];
    }

}
</code>```

header.component.html

```<code><div [ngClass]="selectedStyle" >

    <select [(ngModel)]="selectedStyle">
       <option *ngFor="let s of styles" [ngValue]="s">{{s}}</option>
    </select>

    </div>
</code>```

app.component.html

```<code><div [ngClass]="child.selectedStyle"><app-header #child></app-header></div>
  <h2>{{title}}</h2>
  <h1>{{child.selectedStyle}}</h1>
</code>```

答:
This can be done by using @Output and emitting selected value 'up' to parent component.

```<code><app-picker (select)="onPickerSelect($event)" [default]="defaultTheme"></app-picker>
</code>```

Use @HostBinding to attach sanitized style to your component.

```<code>  @HostBinding('style') get style() {
    return this.sanitizer.bypassSecurityTrustStyle(`background: ${this.selectedStyle.background}; color: ${this.selectedStyle.color}`);
  }
</code>```

I would suggest you also use interface for style to avoid partial styling or cases when you forget to implement some styles.

```<code>interface Style {
  background: string;
  color: string;
}

const styles : {[ key : string ] : Style } = {
  red: {
    background: '#ff0000',
    color: '#ffffff'
  },
  blue: {
    background: '#0000ff',
    color: '#00ff00'
  }
}
</code>```

Working stackblitz can be found here: https://stackblitz.com/edit/bubble-up-style

Body:
I have a child component which is having a dropdrown of colors.Based upon what is selected in the dropdown list, the colour of the parent component should change.

As of now I am able to successfully change the color of the child component based upon the color selection ,but i want to change the color of the parent component.
Any help?
I am also able to print the Value of the dropdown in the parent component as I am using a reference variable but I want the color to change as well.

header.component.html:

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

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {

  styles: string[] = [];
  selectedStyle: string;

  constructor() {

  }

  ngOnInit(){

    this.styles = ['red','green','blue','none'];
    }

}

header.component.html

    <select [(ngModel)]="selectedStyle">
       <option *ngFor="let s of styles" [ngValue]="s">{{s}}</option>
    </select>

app.component.html

<app-header #child></app-header>

{{title}}

{{child.selectedStyle}}

Body:
This can be done by using @Output and emitting selected value 'up' to parent component.

<app-picker (select)="onPickerSelect($event)" [default]="defaultTheme"></app-picker>

Use @HostBinding to attach sanitized style to your component.

  @HostBinding('style') get style() {
    return this.sanitizer.bypassSecurityTrustStyle(`background: ${this.selectedStyle.background}; color: ${this.selectedStyle.color}`);
  }

I would suggest you also use interface for style to avoid partial styling or cases when you forget to implement some styles.

interface Style {
  background: string;
  color: string;
}

const styles : {[ key : string ] : Style } = {
  red: {
    background: '#ff0000',
    color: '#ffffff'
  },
  blue: {
    background: '#0000ff',
    color: '#00ff00'
  }
}

Working stackblitz can be found here: https://stackblitz.com/edit/bubble-up-style


问:
What is the purpose of an "integration branch"?
If a branching strategy consists of n feature branches, a "master" (mainline) and an "integration" branch. What is the purpose of the integration branch? Why can testing and integration not be performed on the feature branch itself?

答: One major reason i often see for the need for an "integration" branch is when your feature branches are untestable on their own.  In my experience, this usually is due to a database dependency.  Or, consider a website project that is database backed... lets say its a JSP application hosted in BEA Weblogic, back by a 60GB Oracle database; It would take a LOT of hardware to give each feature branch its own BEA Weblogic and Oracle instance to test from.  Instead, it is generally easier to develop as best as possible into a feature branch, but move into an integration branch for full QA testing, where QA needs to be performed on a full web server and database.</p>


问:
 Underlined title auto-width on IE

#skills
{
    width: intrinsic;
    width: -moz-max-content;
    width: -webkit-max-content;
    width: fit-content;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">
    <h2 id="skills">skills</h2>
    <p>Lorem Ipsum.</p>
</div></code>```

I'm working on a website where I would like to underlined h2 titles in a better way than underlined css property.
Founding a trick that consisted in adding a border bottom, I've now problems in auto-fitting content.

My code was organized like this :

HTML part (with my 'box' div which is a flexbox) :

The underline style is perfect but it's not fitted on IE...

I found some questions like this one and tried to modify like :

```<code>#skills
{
    display: table;
}
</code>```

But it doesn't work...

Could you help me ?

Thank you for your help,

Jerry

答:
With your help, I resolved my question.
The correct solution was to add an intermediate div like this :

```<code><div class="box">
    <div class="intermediate"><h2 id="skills">skills</h2></div>
    <p>Lorem Ipsum.</p>
</div>
</code>```

And then define as display: table; skills element.

As box element was a flexbox, skills had the same dimension of his parent. Adding an intermediate div, the intermediate div takes all space but next skills has a proper width.

Thank you for your help !

Title: <H2> Underlined title auto-width on IE

Body:
#skills
{
    width: intrinsic;
    width: -moz-max-content;
    width: -webkit-max-content;
    width: fit-content;
}

skills

Lorem Ipsum.

I'm working on a website where I would like to underlined h2 titles in a better way than underlined css property.
Founding a trick that consisted in adding a border bottom, I've now problems in auto-fitting content.

My code was organized like this :

HTML part (with my 'box' div which is a flexbox) :

The underline style is perfect but it's not fitted on IE...

I found some questions like this one and tried to modify like :

#skills
{
    display: table;
}

But it doesn't work...

Could you help me ?

Thank you for your help,

Jerry

Body:
With your help, I resolved my question.
The correct solution was to add an intermediate div like this :

<div class="box">
    <div class="intermediate"><h2 id="skills">skills</h2></div>
    <p>Lorem Ipsum.</p>
</div>

And then define as display: table; skills element.

As box element was a flexbox, skills had the same dimension of his parent. Adding an intermediate div, the intermediate div takes all space but next skills has a proper width.

Thank you for your help !


问:
How can I avoid reading old or missing records in replica due to replication lag between master/slave database?
I’m using the AWS Aurora Postgres database which has a master and replica setup. In one part of my application, the system has to read from TableA right after inserting or updating a record on the same table. Since it’s reading from the replica, there is a slight latency between the master and the read replica. Thus, I’m not always getting the latest data and sometimes a record may appear missing because the replica hasn’t sync the record from master yet.

What I’ve done now is to direct all the read query in this part of the application to read directly from TableA in master after the insert/update query. However, due to the number of reads it is making from this query, the load on the master instance spiked up by a lot.

Suddenly, there is twice the number of IOPS made to the master in this part of the application. If there were 100,000 insert/updates to TableA, there would now be another 1000,000 reads from TableA on the master instance too! Meanwhile, the replica has very little load but I cannot shift this read operation to it just because of the replication lag. This results in not fully utilising the replica.

Are there any strategies I can use to prevent this issue that I’m having?

While reading directly from master works, it doesn't sound right to be hitting the master with so many read operations.

I’m using Node and Sequelize in my application.

答:
Streaming replication is not really a load balancing device.

If you want data modifications to be visible on the standby immediately, you have to

use synchronous streaming replication by adding the standby to synchronous_standby_names on the primary (but beware that that reduces the total availability!)

set synchronous_commit = remote_apply on the primary server

This will only work well if the network latency is low and you don't have a lot of writing transactions, so it is probably right out with a hosted database.


问:
How to display value at knob chart using jquery?

How to display value that get from some URL using jQuery Knob Chart in Bootstrap 4. I got "NaN" value. (Please refer code below)

How to display "-" dash symbol if the data is null. (Please refer code below)

HTML

```<code><input type="text" class="knob" id="avg_temperature" data-width="120" data-height="120" data-thickness="0.40" data-fgColor="#000000" readonly>
</code>```

JS

```<code>$.ajax({
    url : XXX,
    type : 'POST',
    dataType : 'json',
    cache: false,
    async: false,
    dataSrc : 'data',
    contentType: false,
    processData: true,
    success: function(response){
        if (response.status == "Success"){
            if (response.data[0]["avg_temperature"] == null){
                response.data[0]["avg_temperature"] = "-";
                $("#avg_temperature").text("-");
            }
            $("#avg_temperature").text(response.data[0]["avg_temperature"]);

            var colors = ['#11E117', '#FFC300', '#C00']

            //knob chart for temperature
            $('#avg_temperature').knob();
            $('#avg_temperature').attr('data-fgColor', '#11E117');

            $({animatedVal: 0}).animate({animatedVal: response},{
                duration: 3000,
                easing: "swing",
                async: false,
                step: function() {
                    var val = Math.ceil(this.animatedVal);
                    $("#avg_temperature").trigger('configure', {
                        'fgColor': colors[(val < 40) ? 0 : (val < 70) ? 1 : 2]
                    }).val(val).trigger("change");
                    var newVal = val + String.fromCharCode(176) + 'C'; $('#avg_temperature').val(newVal);
                }
            });
        }
    },
});
</code>```

答:
From the context of your code it seems that response is an object, and this is the cause of the issue as animate() expects the value you provide to be an integer.

From the context of your usage of response elsewhere in the code it appears that you need to access a specific temperature property from it, like this:

if (response.data[0]["avg_temperature"] == null)
    response.data[0]["avg_temperature"] = "-";

var colors = ['#11E117', '#FFC300', '#C00']

let $avgTemp = $("#avg_temperature").text(response.data[0]["avg_temperature"]);
$avgTemp.data('fgColor', '#11E117').knob();

$({
  animatedVal: 0
}).animate({
  animatedVal: parseInt(response.data[0]["avg_temperature"], 10) // update here
}, {
  duration: 3000,
  easing: "swing",
  step: function() {
    var val = Math.ceil(this.animatedVal);
    $avgTemp.trigger('configure', {
      'fgColor': colors[(val < 40) ? 0 : (val < 70) ? 1 : 2]
    }).val(val).trigger("change");

    var newVal = val + String.fromCharCode(176) + 'C';
    $avgTemp.val(newVal);
  }
});
```

Also note the removal of async: false. It's bad practice, and you don't need it here anyway

Body:
How to display value that get from some URL using jQuery Knob Chart in Bootstrap 4. I got "NaN" value. (Please refer code below)

How to display "-" dash symbol if the data is null. (Please refer code below)

HTML

<input type="text" class="knob" id="avg_temperature" data-width="120" data-height="120" data-thickness="0.40" data-fgColor="#000000" readonly>

JS

$.ajax({
    url : XXX,
    type : 'POST',
    dataType : 'json',
    cache: false,
    async: false,
    dataSrc : 'data',
    contentType: false,
    processData: true,
    success: function(response){
        if (response.status == "Success"){
            if (response.data[0]["avg_temperature"] == null){
                response.data[0]["avg_temperature"] = "-";
                $("#avg_temperature").text("-");
            }
            $("#avg_temperature").text(response.data[0]["avg_temperature"]);

            var colors = ['#11E117', '#FFC300', '#C00']

            //knob chart for temperature
            $('#avg_temperature').knob();
            $('#avg_temperature').attr('data-fgColor', '#11E117');

            $({animatedVal: 0}).animate({animatedVal: response},{
                duration: 3000,
                easing: "swing",
                async: false,
                step: function() {
                    var val = Math.ceil(this.animatedVal);
                    $("#avg_temperature").trigger('configure', {
                        'fgColor': colors[(val < 40) ? 0 : (val < 70) ? 1 : 2]
                    }).val(val).trigger("change");
                    var newVal = val + String.fromCharCode(176) + 'C'; $('#avg_temperature').val(newVal);
                }
            });
        }
    },
});

Body:
From the context of your code it seems that response is an object, and this is the cause of the issue as animate() expects the value you provide to be an integer.

From the context of your usage of response elsewhere in the code it appears that you need to access a specific temperature property from it, like this:

if (response.data[0]["avg_temperature"] == null)
    response.data[0]["avg_temperature"] = "-";

var colors = ['#11E117', '#FFC300', '#C00']

let $avgTemp = $("#avg_temperature").text(response.data[0]["avg_temperature"]);
$avgTemp.data('fgColor', '#11E117').knob();

$({
  animatedVal: 0
}).animate({
  animatedVal: parseInt(response.data[0]["avg_temperature"], 10) // update here
}, {
  duration: 3000,
  easing: "swing",
  step: function() {
    var val = Math.ceil(this.animatedVal);
    $avgTemp.trigger('configure', {
      'fgColor': colors[(val < 40) ? 0 : (val < 70) ? 1 : 2]
    }).val(val).trigger("change");

    var newVal = val + String.fromCharCode(176) + 'C';
    $avgTemp.val(newVal);
  }
});

Also note the removal of async: false. It's bad practice, and you don't need it here anyway


问:
DevTools failed to parse SourceMap error after login will redirect to that js file
I am new to VueJS. I am following one of the YouTube tutorial Let's Build a Multi-Purpose Laravel + Vue Application by Code Inspire

This is his github package.
https://github.com/Hujjat/laravStart

I notice. When I logout and login again, it will redirect to .js file.

for my case:-
http://laravel-vuejs.test/js/popper.js.map

and I clone his project. I tried with inspect, I login and logout and login. It will redirect to
http://laravstart.test/js/laravel-vue-pagination.common.js.map

It will show 404 error. I have every time remove the /js/xxxx.js.map then only back to normal.

Both of my project, when I run inspect. I notice have the Chrome warning.

DevTools failed to parse SourceMap: http://laravstart.test/js/laravel-vue-pagination.common.js.map

DevTools failed to parse SourceMap: http://laravel-vuejs.test/js/laravel-js/popper.js.map

IMPORTANT NOTE It only happen when I open the chrome inspect windows. If I close it, it will back to normal means won't redirect to JS file.

Screen record: https://imgur.com/gZzcX5L

I tested with Chrome and Firefox with inspect both having the same problem.

But in Chrome if I off setting for source map, it will not have this issue.

Anyone how to fix it? Compile source map issue? the js.map file not exist.

答:
There are two SourceMap error in my case so the two previous answers applied to me.
1) By adding sourceMaps() in the mix.js function in webpack.mix.js file

```<code>mix.js('resources/js/app.js', 'public/js').sourceMaps();
</code>```

to remove popper.js source map error.

2) Adding toastr.js.map to public/js folder to remove toastr.js source map error.

Body:
There are two SourceMap error in my case so the two previous answers applied to me.
1) By adding sourceMaps() in the mix.js function in webpack.mix.js file

mix.js('resources/js/app.js', 'public/js').sourceMaps();

to remove popper.js source map error.

2) Adding toastr.js.map to public/js folder to remove toastr.js source map error.


问:
Dynamic number of columns in select clause in SQL Server 2008
I have the need to dynamically fetch column values from a table.

Say I have a table having columns:

```<code>Name,
Date,
Col1,
Col2,
Col3,
...
col10
</code>```

Now, depending on some condition I want to fetch different columns from col1 to col10 from above table keeping Name, date columns always in select clause. e.g. is as below.

```<code>columns in output:  (1) Name (2) date (3) col1 + col2 + col3  (4) col4 + col5
</code>```

i.e. number of columns and columns itself (colN) both varies.

How can I achieve that? Also, fixed columns are specified directly in select clause like.

```<code>select Name, Date  ... from Table1
</code>```

But, to get remaining column values for each row I am using table-valued function. So, in that function how can I get value? I can make a dynamic SQL string but cannot execute it in a function, so this is the limitation I am facing.

答:
Finally achieved this by generating a dynamic query string then executing it.

To generate dynamic string I first take the fixed columns using "with" and then with each row running function. Something as below.

```<code>set @str = ';with fn as (select ... fixed-columns from table) select x.*'

while (condition)
begin
   set @cols = @cols + function_to_generate_dynamic_columns(@params)
   set @i=@i+1
end

set @str = @str + @cols + ' from fn x '

EXECUTE(@str)
</code>```

Body:
I have the need to dynamically fetch column values from a table.

Say I have a table having columns:

Name,
Date,
Col1,
Col2,
Col3,
...
col10

Now, depending on some condition I want to fetch different columns from col1 to col10 from above table keeping Name, date columns always in select clause. e.g. is as below.

columns in output:  (1) Name (2) date (3) col1 + col2 + col3  (4) col4 + col5

i.e. number of columns and columns itself (colN) both varies.

How can I achieve that? Also, fixed columns are specified directly in select clause like.

select Name, Date  ... from Table1

But, to get remaining column values for each row I am using table-valued function. So, in that function how can I get value? I can make a dynamic SQL string but cannot execute it in a function, so this is the limitation I am facing.

Body:
Finally achieved this by generating a dynamic query string then executing it.

To generate dynamic string I first take the fixed columns using "with" and then with each row running function. Something as below.

set @str = ';with fn as (select ... fixed-columns from table) select x.*'

while (condition)
begin
   set @cols = @cols + function_to_generate_dynamic_columns(@params)
   set @i=@i+1
end

set @str = @str + @cols + ' from fn x '

EXECUTE(@str)


问:
Why can this constructor declared with two parameters be called with just one?
I watched my lecturer's video from my university and he says about the Rational class that its constructor goes like this:

```<code>Rational (int top=0 , int bottom=1)
: t(top) , b(bottom) {normalize();}
</code>```

Until now everything is OK, BUT !! he also said that you can call the constructor only with 1 argument (top argument) and because that bottom initialize to value of 1 the rational for example: Rational(3) will be 3/1.

BUT !! I wonder how can we use a constructor with 1 value only if it supports 2 arguments ONLY ?

I know that in java if we have x number of argument that the constructor receive (consider no other constructor and x>0) we must transfer them all not 1 instead of 2...

Please help me solve this conflict...

thnx...

答:
To extend Rob Kennedy's answer, here are a few examples of what does and does not work:

Imagine a class Foo:

```<code>class Foo
{
    Foo( int a = 0, float b = 1.0f );
}
</code>```

And consider the following constructor-calls:

```<code>Foo foo_obj = Foo(5, 6.0f);    // Fine, two arguments are passed. a will be 5 and b will be 6.0f.

Foo foo_obj = Foo(5);          // Fine as well. a will be 5 and b will be 1.0f. This is because b has a default value in the constructor.

Foo foo_obj = Foo();           // Fine too, a will be 0 and b will be 1.0f. This is because both a and b have default values in the constructor.
</code>```

Mind you that variables are still passed left-to-right. By this I mean that you cannot leave out any argument that comes before the argument that you want to explicitly pass.
By this I mean that in the above example, you can not pass a value for b, but leave out a value for a.

Body:
I watched my lecturer's video from my university and he says about the Rational class that its constructor goes like this:

Rational (int top=0 , int bottom=1)
: t(top) , b(bottom) {normalize();}

Until now everything is OK, BUT !! he also said that you can call the constructor only with 1 argument (top argument) and because that bottom initialize to value of 1 the rational for example: Rational(3) will be 3/1.

BUT !! I wonder how can we use a constructor with 1 value only if it supports 2 arguments ONLY ?

I know that in java if we have x number of argument that the constructor receive (consider no other constructor and x>0) we must transfer them all not 1 instead of 2...

Please help me solve this conflict...

thnx...

Body:
To extend Rob Kennedy's answer, here are a few examples of what does and does not work:

Imagine a class Foo:

class Foo
{
    Foo( int a = 0, float b = 1.0f );
}

And consider the following constructor-calls:

Foo foo_obj = Foo(5, 6.0f);    // Fine, two arguments are passed. a will be 5 and b will be 6.0f.

Foo foo_obj = Foo(5);          // Fine as well. a will be 5 and b will be 1.0f. This is because b has a default value in the constructor.

Foo foo_obj = Foo();           // Fine too, a will be 0 and b will be 1.0f. This is because both a and b have default values in the constructor.

Mind you that variables are still passed left-to-right. By this I mean that you cannot leave out any argument that comes before the argument that you want to explicitly pass.
By this I mean that in the above example, you can not pass a value for b, but leave out a value for a.


问:
SQL - How to join query results in same line
I have an application that save the working time based on machine, operation, operator and reference.

My query returns the data like this:

u_reference | u_user | u_operation | u_machine | price | u_action | Start             | Work time
P-2000-9429 | John   | F3X         | 144       | 60    | PLAY     |2019-11-08 09:40:53| 00:00:00
P-2000-9429 | John   | F3X         | 144       | 60    | PAUSE    |2019-11-08 18:00:45| 08:19:52
P-2000-9429 | John   | F3X         | 144       | 60    | REPLAY   |2019-11-09 07:13:23| 08:19:52
P-2000-9429 | John   | F3X         | 144       | 60    | PAUSE    |2019-11-09 12:19:21| 13:25:49
P-2000-9429 | John   | F3X         | 144       | 60    | REPLAY   |2019-11-11 07:09:50| 13:25:49
P-2000-9429 | John   | F3X         | 144       | 60    | STOP     |2019-11-11 11:03:26| 17:19:21
```

```select  u_daily_work_alb.u_reference, u_daily_work_alb.u_user, u_daily_work_alb.u_operation, u_machines_alb.u_design as u_machine, u_machines_alb.epcusto as price, u_daily_work_alb.u_action, u_daily_work_alb.u_created_at as Start, u_daily_work_alb.u_work_time as Work_time
from u_daily_work_alb
  inner join u_machines_alb on u_machines_alb.id = u_daily_work_alb.u_machineId
where u_daily_work_alb.bostamp = 'ALB472248D84210CFA9FE30'
  and u_daily_work_alb.u_reference = 'p-2000-9429'
order by u_daily_work_alb.id asc
```

<p>bostamp column is like an id.</p>

<p>Now what I need is a result like this:</p>

<pre class="lang-none prettyprint-override"><code>u_reference | u_user | u_operation | u_machine | price | Start             |END                | Work time
P-2000-9429 | John   | F3X         | 144       | 60    |2019-11-08 09:40:53|2019-11-08 18:00:45| calculate time
P-2000-9429 | John   | F3X         | 144       | 60    |2019-11-09 07:13:23|2019-11-09 12:19:21| calculate time
P-2000-9429 | John   | F3X         | 144       | 60    |2019-11-11 07:09:50|2019-11-11 11:03:26| calculate time
</code>```

I think the column u_action is important because we know that after a play we have a pause or stop. After a pause we have a replay or stop and after a replay we have a pause or stop.

How can I do that?

答:
You could achieve this by using lead function if you are using Sql-server.</p>

```<code>
select u_reference, u_user,u_operation,u_machine,price,[Start],[End Time],WorkingTime
from (
SELECT  A.u_reference,A.u_user,A.u_operation,A.u_machine,A.price,A.[Start],A.u_action,lead(Start) over(order by Start) as [End Time],
CONVERT(varchar, DATEADD(second, (DATEDIFF(SECOND,[Start],lead(Start) over(order by Start))), 0), 108) AS WorkingTime
from #SampleData A)B where u_action like '%play%'
</code>```

Body:
I have an application that save the working time based on machine, operation, operator and reference.

My query returns the data like this:

u_reference | u_user | u_operation | u_machine | price | u_action | Start             | Work time
P-2000-9429 | John   | F3X         | 144       | 60    | PLAY     |2019-11-08 09:40:53| 00:00:00
P-2000-9429 | John   | F3X         | 144       | 60    | PAUSE    |2019-11-08 18:00:45| 08:19:52
P-2000-9429 | John   | F3X         | 144       | 60    | REPLAY   |2019-11-09 07:13:23| 08:19:52
P-2000-9429 | John   | F3X         | 144       | 60    | PAUSE    |2019-11-09 12:19:21| 13:25:49
P-2000-9429 | John   | F3X         | 144       | 60    | REPLAY   |2019-11-11 07:09:50| 13:25:49
P-2000-9429 | John   | F3X         | 144       | 60    | STOP     |2019-11-11 11:03:26| 17:19:21

select  u_daily_work_alb.u_reference, u_daily_work_alb.u_user, u_daily_work_alb.u_operation, u_machines_alb.u_design as u_machine, u_machines_alb.epcusto as price, u_daily_work_alb.u_action, u_daily_work_alb.u_created_at as Start, u_daily_work_alb.u_work_time as Work_time
from u_daily_work_alb
  inner join u_machines_alb on u_machines_alb.id = u_daily_work_alb.u_machineId
where u_daily_work_alb.bostamp = 'ALB472248D84210CFA9FE30'
  and u_daily_work_alb.u_reference = 'p-2000-9429'
order by u_daily_work_alb.id asc

bostamp column is like an id.

Now what I need is a result like this:

u_reference | u_user | u_operation | u_machine | price | Start             |END                | Work time
P-2000-9429 | John   | F3X         | 144       | 60    |2019-11-08 09:40:53|2019-11-08 18:00:45| calculate time
P-2000-9429 | John   | F3X         | 144       | 60    |2019-11-09 07:13:23|2019-11-09 12:19:21| calculate time
P-2000-9429 | John   | F3X         | 144       | 60    |2019-11-11 07:09:50|2019-11-11 11:03:26| calculate time

I think the column u_action is important because we know that after a play we have a pause or stop. After a pause we have a replay or stop and after a replay we have a pause or stop.

How can I do that?

Body:
You could achieve this by using lead function if you are using Sql-server.

select u_reference, u_user,u_operation,u_machine,price,[Start],[End Time],WorkingTime
from (
SELECT  A.u_reference,A.u_user,A.u_operation,A.u_machine,A.price,A.[Start],A.u_action,lead(Start) over(order by Start) as [End Time],
CONVERT(varchar, DATEADD(second, (DATEDIFF(SECOND,[Start],lead(Start) over(order by Start))), 0), 108) AS WorkingTime
from #SampleData A)B where u_action like '%play%'


问:
Sort 2 arrays in C by a joint logic
Given two arrays

```<code>a = [1,3,2,8,5,6]
b = [4,3,2,5,1,2]
</code>```

I would like to sort them in "one pass" where the "logic" involves the two arrays, meaning:

if

```<code>int sortBySum(index i, index j){
    if (a[i]+b[i] > a[j]+b[j]){
        return 1;
    }
    return -1;
}
</code>```

The output of the two arrays will be

```<code>a = [2,1,3,5,6,8]
b = [2,4,3,1,2,5]
</code>```

Because the original arrays sum is a+b=[5,6,4,13,6,8]

答:
A primitive approach can look the following way.

```<code>#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int a[] = { 1, 3, 2, 8, 5, 6 };
    int b[] = { 4, 3, 2, 5, 1, 2 };

    const size_t N = sizeof( a ) / sizeof( *a );

    printf( "a: " );
    for ( size_t i = 0; i < N; i++ )
    {
        printf( "%d ", a[i] );
    }
    putchar( '\n' );

    printf( "b: " );
    for ( size_t i = 0; i < N; i++ )
    {
        printf( "%d ", b[i] );
    }
    putchar( '\n' );

    putchar( '\n' );

    for ( size_t n = N, last; !( n < 2 ); n = last )
    {
        for ( size_t i = last = 1; i < n; i++ )
        {
            if ( a[i] + b[i] < a[i-1] + b[i-1] )
            {
                int tmp = a[i];
                a[i]    = a[i-1];
                a[i-1]  = tmp;

                tmp     = b[i];
                b[i]    = b[i-1];
                b[i-1]  = tmp;

                last = i;
            }
        }
    }

    printf( "a: " );
    for ( size_t i = 0; i < N; i++ )
    {
        printf( "%d ", a[i] );
    }
    putchar( '\n' );

    printf( "b: " );
    for ( size_t i = 0; i < N; i++ )
    {
        printf( "%d ", b[i] );
    }
    putchar( '\n' );

    putchar( '\n' );

    return 0;
}
</code>```

The program output is

```<code>a: 1 3 2 8 5 6
b: 4 3 2 5 1 2

a: 2 1 3 5 6 8
b: 2 4 3 1 2 5
</code>```

The code that sorts the arrays using the method bubble sort can be moved in a separate function.

Title: Sort 2 arrays in C by a joint logic

Body:
Given two arrays

a = [1,3,2,8,5,6]
b = [4,3,2,5,1,2]

I would like to sort them in "one pass" where the "logic" involves the two arrays, meaning:

if

int sortBySum(index i, index j){
    if (a[i]+b[i] > a[j]+b[j]){
        return 1;
    }
    return -1;
}

The output of the two arrays will be

a = [2,1,3,5,6,8]
b = [2,4,3,1,2,5]

Because the original arrays sum is a+b=[5,6,4,13,6,8]

Body:
A primitive approach can look the following way.

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int a[] = { 1, 3, 2, 8, 5, 6 };
    int b[] = { 4, 3, 2, 5, 1, 2 };

    const size_t N = sizeof( a ) / sizeof( *a );

    printf( "a: " );
    for ( size_t i = 0; i < N; i++ )
    {
        printf( "%d ", a[i] );
    }
    putchar( '\n' );

    printf( "b: " );
    for ( size_t i = 0; i < N; i++ )
    {
        printf( "%d ", b[i] );
    }
    putchar( '\n' );

    putchar( '\n' );

    for ( size_t n = N, last; !( n < 2 ); n = last )
    {
        for ( size_t i = last = 1; i < n; i++ )
        {
            if ( a[i] + b[i] < a[i-1] + b[i-1] )
            {
                int tmp = a[i];
                a[i]    = a[i-1];
                a[i-1]  = tmp;

                tmp     = b[i];
                b[i]    = b[i-1];
                b[i-1]  = tmp;

                last = i;
            }
        }
    }

    printf( "a: " );
    for ( size_t i = 0; i < N; i++ )
    {
        printf( "%d ", a[i] );
    }
    putchar( '\n' );

    printf( "b: " );
    for ( size_t i = 0; i < N; i++ )
    {
        printf( "%d ", b[i] );
    }
    putchar( '\n' );

    putchar( '\n' );

    return 0;
}

The program output is

a: 1 3 2 8 5 6
b: 4 3 2 5 1 2

a: 2 1 3 5 6 8
b: 2 4 3 1 2 5

The code that sorts the arrays using the method bubble sort can be moved in a separate function.


问:
Python can't find ssh binaries in Windows using subprocess.run, even with full path to ssh.exe
When I run scp.exe in powershell, it shows the usage. But python tells that file doesn't exist testing with os.path.isfile("C:\\Windows\\System32\\OpenSSH\\scp.exe"). All my scripts that calls scp through subprocess.run were working before. Now it results in:

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Alyson\AppData\Local\Programs\Python\Python38-32\lib\subprocess.py", line 489, in run
    with Popen(*popenargs, **kwargs) as process:
  File "C:\Users\Alyson\AppData\Local\Programs\Python\Python38-32\lib\subprocess.py", line 854, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "C:\Users\Alyson\AppData\Local\Programs\Python\Python38-32\lib\subprocess.py", line 1307, in _execute_child
    hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] O sistema não pode encontrar o arquivo especificado
</code>```

The only things I did recently is install a Windows Update (KB4537759, KB4532693) and update Python from 3.7 to 3.8. I even tried to pass shell=true to subprocess.run.

scp existance tests

答:
I discovered what caused the problem. It is the architecture version of Python.

My Windows is 64-bit. I've downloaded the embedded version of both 32-bit and 64-bit. The 64-bit version found the scp.exe executable as shown below:

MSC v.1916 32 bit (Intel):

PS C:\Users\Alyson\Documents\0\Xpriment\python32> .\python                                    Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 22:39:24) [MSC v.1916 32 bit (Intel)] on win32
>>> import shutil; shutil.which("scp")
>>>
```

<ul>
<li>MSC v.1916 64 bit (AMD64):</li>
</ul>

<pre class="lang-py prettyprint-override"><code>PS C:\Users\Alyson\Documents\0\Xpriment\python64> .\python                                            Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)] on win32
>>> import shutil; shutil.which("scp")
'C:\\Windows\\System32\\OpenSSH\\scp.EXE'
>>>
</code>```

The Python I installed before was 64-bit. Bothered with the message in Visual Studio Code that the interpreter was not installed, I clicked the linked and reinstalled the interpreter, but the link pointed to a 32-bit version.

Body:
When I run scp.exe in powershell, it shows the usage. But python tells that file doesn't exist testing with os.path.isfile("C:\\Windows\\System32\\OpenSSH\\scp.exe"). All my scripts that calls scp through subprocess.run were working before. Now it results in:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Alyson\AppData\Local\Programs\Python\Python38-32\lib\subprocess.py", line 489, in run
    with Popen(*popenargs, **kwargs) as process:
  File "C:\Users\Alyson\AppData\Local\Programs\Python\Python38-32\lib\subprocess.py", line 854, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "C:\Users\Alyson\AppData\Local\Programs\Python\Python38-32\lib\subprocess.py", line 1307, in _execute_child
    hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] O sistema não pode encontrar o arquivo especificado

The only things I did recently is install a Windows Update (KB4537759, KB4532693) and update Python from 3.7 to 3.8. I even tried to pass shell=true to subprocess.run.

scp existance tests

Body:
I discovered what caused the problem. It is the architecture version of Python.

My Windows is 64-bit. I've downloaded the embedded version of both 32-bit and 64-bit. The 64-bit version found the scp.exe executable as shown below:

MSC v.1916 32 bit (Intel):

PS C:\Users\Alyson\Documents\0\Xpriment\python32> .\python                                    Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 22:39:24) [MSC v.1916 32 bit (Intel)] on win32
>>> import shutil; shutil.which("scp")
>>>

MSC v.1916 64 bit (AMD64):

PS C:\Users\Alyson\Documents\0\Xpriment\python64> .\python                                            Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)] on win32
>>> import shutil; shutil.which("scp")
'C:\\Windows\\System32\\OpenSSH\\scp.EXE'
>>>

The Python I installed before was 64-bit. Bothered with the message in Visual Studio Code that the interpreter was not installed, I clicked the linked and reinstalled the interpreter, but the link pointed to a 32-bit version.


问:
How to iterate array keys in Javascript?
I have an array created with this code:

```<code>var widthRange = new Array();
widthRange[46] = { min:0,  max:52 };
widthRange[66] = { min:52, max:70 };
widthRange[90] = { min:70, max:94 };
</code>```

I want to get each of the values 46, 66, 90 in a loop. I tried for (var key in widthRange) but this gives me a whole bunch of extra properties (I assume they are functions on the object). I can't use a regular for loop since the values are not sequential.

答:
For your input data:

```<code>let widthRange = new Array()
widthRange[46] = { min:0,  max:52 }
widthRange[61] = { min:52, max:70 }
widthRange[62] = { min:52, max:70 }
widthRange[63] = { min:52, max:70 }
widthRange[66] = { min:52, max:70 }
widthRange[90] = { min:70, max:94 }
</code>```

Declarative approach:

```<code>const relevantKeys = [46,66,90]
const relevantValues = Object.keys(widthRange)
    .filter(index => relevantKeys.includes(parseInt(index)))
    .map(relevantIndex => widthRange[relevantIndex])
</code>```

Object.keys to get the keys, using parseInt to cast them as numbers.
filter to get only ones you want.
map to build an array from the original object of just the indices you're after, since Object.keys loses the object values.

Debug:

```<code>console.log(widthRange)
console.log(relevantKeys)
console.log(relevantValues)
</code>```

Body:
I have an array created with this code:

var widthRange = new Array();
widthRange[46] = { min:0,  max:52 };
widthRange[66] = { min:52, max:70 };
widthRange[90] = { min:70, max:94 };

I want to get each of the values 46, 66, 90 in a loop. I tried for (var key in widthRange) but this gives me a whole bunch of extra properties (I assume they are functions on the object). I can't use a regular for loop since the values are not sequential.

Body:
For your input data:

let widthRange = new Array()
widthRange[46] = { min:0,  max:52 }
widthRange[61] = { min:52, max:70 }
widthRange[62] = { min:52, max:70 }
widthRange[63] = { min:52, max:70 }
widthRange[66] = { min:52, max:70 }
widthRange[90] = { min:70, max:94 }

Declarative approach:

const relevantKeys = [46,66,90]
const relevantValues = Object.keys(widthRange)
    .filter(index => relevantKeys.includes(parseInt(index)))
    .map(relevantIndex => widthRange[relevantIndex])

Object.keys to get the keys, using parseInt to cast them as numbers.
filter to get only ones you want.
map to build an array from the original object of just the indices you're after, since Object.keys loses the object values.

Debug:

console.log(widthRange)
console.log(relevantKeys)
console.log(relevantValues)


问:
How to drop all tables in a SQL Server database?
I'm trying to write a script that will completely empty a SQL Server database. This is what I have so far:

```<code>USE [dbname]
GO
EXEC sp_msforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT all'
EXEC sp_msforeachtable 'DELETE ?'
</code>```

When I run it in the Management Studio, I get:

Command(s) completed successfully.

but when I refresh the table list, they are all still there. What am I doing wrong?

答:
For Temporal Tables it is a bit more complicated due to the fact there may be some foreign keys and also exception:

Drop table operation failed on table XXX because it is not a supported operation on system-versioned temporal tables

What you can use is:

```<code>-- Disable constraints (foreign keys)
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
GO

-- Disable system versioning (temporial tables)
EXEC sp_MSForEachTable '
 IF OBJECTPROPERTY(object_id(''?''), ''TableTemporalType'') = 2
  ALTER TABLE ? SET (SYSTEM_VERSIONING = OFF)
'
GO

-- Removing tables
EXEC sp_MSForEachTable 'DROP TABLE ?'
GO
</code>```

Body:
I'm trying to write a script that will completely empty a SQL Server database. This is what I have so far:

USE [dbname]
GO
EXEC sp_msforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT all'
EXEC sp_msforeachtable 'DELETE ?'

When I run it in the Management Studio, I get:

Command(s) completed successfully.

but when I refresh the table list, they are all still there. What am I doing wrong?

Body:
For Temporal Tables it is a bit more complicated due to the fact there may be some foreign keys and also exception:

Drop table operation failed on table XXX because it is not a supported operation on system-versioned temporal tables

What you can use is:

-- Disable constraints (foreign keys)
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
GO

-- Disable system versioning (temporial tables)
EXEC sp_MSForEachTable '
 IF OBJECTPROPERTY(object_id(''?''), ''TableTemporalType'') = 2
  ALTER TABLE ? SET (SYSTEM_VERSIONING = OFF)
'
GO

-- Removing tables
EXEC sp_MSForEachTable 'DROP TABLE ?'
GO


问:
Perl Update UI on Long Thread
I have a Perl script running on version 5.10 build 1004 of ActiveStates Active Perl on windows xp which creates a UI and then runs a long process after a button press.  During this process I would like to update the UI (a list box) with status on what is going on during the execution of this thread.  Here is a stripped down version of the code.

```<code>#!/usr/local/bin/perl

use warnings;
use strict;
use Tkx;
use threads;
use threads::shared;

my $outputText = " {a} {b}";

my $mw = Tkx::widget->new(".");
$mw->g_wm_title("MD5 Checker");
$mw->g_wm_minsize(300,200);
my $content = $mw->new_ttk__frame(-padding => "12 12 12 12");
my $btnCompare = $content->new_ttk__button(-text => "Compare", -command => sub{startWork()});
my $lstbxOutput = $content->new_tk__listbox(-listvariable => \$outputText, -height => 5);
my $scollListBox = $content->new_ttk__scrollbar(-orient => 'vertical', -command => [$lstbxOutput, 'yview']);
$lstbxOutput->configure(-yscrollcommand => [$scollListBox, 'set']);

sub startWork()
{
    print "Starting thread \n";
    my $t = threads->create(\&doWork, 1);
    sleep (5);
    print $outputText . "\n";
}

sub doWork()
{
    for (my $a = 0; $a<10; $a++)
    {
        $outputText .= " {$a}";
        print "Counting $a\n";
        sleep(2);
    }
    print "End thread\n";
}
</code>```

Currently the print commands are for my debugging so I know what the main and child threads are doing.  From what I have read about threading I need the use threads::shared; to allow threads to share variables.  At the moment my list box does not update at all during the child threads execution nor when the thread has ended.  Without the threading, the list box would update after the main thread was done with the loop.  What am I missing to get the UI to update during the threads execution?

Thanks

Wesley

答:
Threading is nice because the UI doesn't block and you can do things like kill the child process if it's taking too long. That power comes with complexity, though. If all you care about is updating the task status in the UI you can do that without using threads; you just have to do it manually.</p>

```<code>$outputText = 'some message';
Tkx::update('idletasks');
</code>```

Title: Perl Update UI on Long Thread

Body:
I have a Perl script running on version 5.10 build 1004 of ActiveStates Active Perl on windows xp which creates a UI and then runs a long process after a button press.  During this process I would like to update the UI (a list box) with status on what is going on during the execution of this thread.  Here is a stripped down version of the code.

#!/usr/local/bin/perl

use warnings;
use strict;
use Tkx;
use threads;
use threads::shared;

my $outputText = " {a} {b}";

my $mw = Tkx::widget->new(".");
$mw->g_wm_title("MD5 Checker");
$mw->g_wm_minsize(300,200);
my $content = $mw->new_ttk__frame(-padding => "12 12 12 12");
my $btnCompare = $content->new_ttk__button(-text => "Compare", -command => sub{startWork()});
my $lstbxOutput = $content->new_tk__listbox(-listvariable => \$outputText, -height => 5);
my $scollListBox = $content->new_ttk__scrollbar(-orient => 'vertical', -command => [$lstbxOutput, 'yview']);
$lstbxOutput->configure(-yscrollcommand => [$scollListBox, 'set']);

sub startWork()
{
    print "Starting thread \n";
    my $t = threads->create(\&doWork, 1);
    sleep (5);
    print $outputText . "\n";
}

sub doWork()
{
    for (my $a = 0; $a<10; $a++)
    {
        $outputText .= " {$a}";
        print "Counting $a\n";
        sleep(2);
    }
    print "End thread\n";
}

Currently the print commands are for my debugging so I know what the main and child threads are doing.  From what I have read about threading I need the use threads::shared; to allow threads to share variables.  At the moment my list box does not update at all during the child threads execution nor when the thread has ended.  Without the threading, the list box would update after the main thread was done with the loop.  What am I missing to get the UI to update during the threads execution?

Thanks

Wesley

Body:
Threading is nice because the UI doesn't block and you can do things like kill the child process if it's taking too long. That power comes with complexity, though. If all you care about is updating the task status in the UI you can do that without using threads; you just have to do it manually.

$outputText = 'some message';
Tkx::update('idletasks');


问:
Python Boto3 for ECS Help needed
I'm trying to list all the clusters in my AWS ECS account. I have approximately 13 Clusters running.

The below code prints only one cluster, whereas I want to print all the clusters. Is there a for loop which I can use?

Below prints only one cluster:

```<code>import boto3
client = boto3.client('ecs')
response = client.list_clusters(
    maxResults=50
)
print(response)
</code>```

Below for looping doesn't work and throws an error

```<code>import boto3
client = boto3.client('ecs')
for response in client.list_cluster():
    print(response)
</code>```

Any lead would highly be appreciated.

答:
If you look at the list_clusters api, the response syntax is:

```<code> Response Syntax

{
    'clusterArns': [
        'string',
    ],
    'nextToken': 'string'
}
</code>```

which means you'll get back a list([]) of ARNs which are unique resource identifiers in AWS.

Use describe_clusters api to then then get a description, as @jordanm said:

import boto3
client = boto3.client('ecs', region_name='us-east-2')
clusters = client.list_clusters(
    maxResults=50
)
clusters_arns = clusters['clusterArns']

clusters_descriptions = client.describe_clusters(
    clusters=clusters_arns
)

for cluster in clusters_descriptions['clusters']:
    print(cluster['clusterName'])
```

<p>result is something like:</p>

```prod_nam
eu_nam
someothercluster
```

Title: Python Boto3 for ECS Help needed

Body:
I'm trying to list all the clusters in my AWS ECS account. I have approximately 13 Clusters running.

The below code prints only one cluster, whereas I want to print all the clusters. Is there a for loop which I can use?

Below prints only one cluster:

import boto3
client = boto3.client('ecs')
response = client.list_clusters(
    maxResults=50
)
print(response)

Below for looping doesn't work and throws an error

import boto3
client = boto3.client('ecs')
for response in client.list_cluster():
    print(response)

Any lead would highly be appreciated.

Body:
If you look at the list_clusters api, the response syntax is:

 Response Syntax

{
    'clusterArns': [
        'string',
    ],
    'nextToken': 'string'
}

which means you'll get back a list([]) of ARNs which are unique resource identifiers in AWS.

Use describe_clusters api to then then get a description, as @jordanm said:

import boto3
client = boto3.client('ecs', region_name='us-east-2')
clusters = client.list_clusters(
    maxResults=50
)
clusters_arns = clusters['clusterArns']

clusters_descriptions = client.describe_clusters(
    clusters=clusters_arns
)

for cluster in clusters_descriptions['clusters']:
    print(cluster['clusterName'])

result is something like:

prod_nam
eu_nam
someothercluster


问:
Lambda function unable to connect to Redshift : Temporary failure in name resolution
I have an AWS Lambda function which is connected to a Jira webhook.  Anytime an issue is created/changed/deleted, it sends a request to my API Gateway, which calls my function.  I'm receiving the following traceback when I try to connect to Redshift inside the function:

```<code>Traceback (most recent call last):
File "/var/task/jira_webhook_proc.py", line 171, in lambda_handler
update_item(request, issue, issue_key)
File "/var/task/jira_webhook_proc.py", line 193, in update_item
delete_item(delete_key)
File "/var/task/jira_webhook_proc.py", line 277, in delete_item
port=REDSHIFT_PORT) as conn:
File "/var/task/psycopg2/__init__.py", line 164, in connect
conn = _connect(dsn, connection_factory=connection_factory, async=async)
OperationalError: could not translate host name "***" to address: Temporary failure in name resolution
</code>```

I'm using a pre-compiled psycopg2 library that can be found here https://github.com/jkehler/awslambda-psycopg2.  From googling it seems this might be a PostgreSQL error where I don't have a config file set right to listen to all ports.  I'm not sure how I would change that however.

答:
It might help someone as it worked perfectly in my case. </p>

```<code>import psycopg2
import od_red_load_cred as CONSTANTS

def main():

    # Amazon Redshift connect string
    try:
        conn_string = "dbname={} port={} user={} password={} host={}"\
        .format(CONSTANTS.DBNAME, CONSTANTS.PORT, CONSTANTS.USER,
            CONSTANTS.PASSWORD, CONSTANTS.HOST)

        print("Connect string Successful!")
    except:
        print("Unable to create the connect string")

    # query generate
    try:
        sql="""copy {}.{} from '{}'\
        credentials 'aws_access_key_id={};aws_secret_access_key={}' \
        DELIMITER ',' ACCEPTINVCHARS EMPTYASNULL ESCAPE COMPUPDATE OFF;commit;"""\
        .format(CONSTANTS.SCHEMA, CONSTANTS.TABLE_NAME_BV, CONSTANTS.S3_PATH_BV,
            CONSTANTS.ACCESS_KEY_ID, CONSTANTS.SECRET_ACCESS_KEY)

        print("sql ==>", sql)
        print("Query creation Successful!")
        print(" ")
    except:
        print("Unable to create the query")

    # get connection
    try:
        con = psycopg2.connect(conn_string);
        print("con ==>", con)
        print("Connection Successful!")
    except Exception as e:
        print("Unable to connect to Redshift")
        print(e)
        exit(-1)

    # get cursor connection
    try:
        cur = con.cursor()
    except Exception as e:
        print("Unable to get the cursor from connection of Redshift")
        print(e)
        exit(-1)

    # execute cursor connection
    try:
        cur.execute(sql)
        print("Query executed successfully")
    except Exception as e:
        print("Failed to execute the query")
        print(e)
        exit(-1)

    # close connection
    try:
        con.close()
        print("Connection closed Successfully!")
    except Exception as e:
        print("Unable to close connection to Redshift")
        print(e)

    print(" ")

# Main method
if __name__ == '__main__':
    print("start: __main__ ")
    main()
    print("end: __main__ ")
</code>```

Body:
I have an AWS Lambda function which is connected to a Jira webhook.  Anytime an issue is created/changed/deleted, it sends a request to my API Gateway, which calls my function.  I'm receiving the following traceback when I try to connect to Redshift inside the function:

Traceback (most recent call last):
File "/var/task/jira_webhook_proc.py", line 171, in lambda_handler
update_item(request, issue, issue_key)
File "/var/task/jira_webhook_proc.py", line 193, in update_item
delete_item(delete_key)
File "/var/task/jira_webhook_proc.py", line 277, in delete_item
port=REDSHIFT_PORT) as conn:
File "/var/task/psycopg2/__init__.py", line 164, in connect
conn = _connect(dsn, connection_factory=connection_factory, async=async)
OperationalError: could not translate host name "***" to address: Temporary failure in name resolution

I'm using a pre-compiled psycopg2 library that can be found here https://github.com/jkehler/awslambda-psycopg2.  From googling it seems this might be a PostgreSQL error where I don't have a config file set right to listen to all ports.  I'm not sure how I would change that however.

Body:
It might help someone as it worked perfectly in my case.

import psycopg2
import od_red_load_cred as CONSTANTS

def main():

    # Amazon Redshift connect string
    try:
        conn_string = "dbname={} port={} user={} password={} host={}"\
        .format(CONSTANTS.DBNAME, CONSTANTS.PORT, CONSTANTS.USER,
            CONSTANTS.PASSWORD, CONSTANTS.HOST)

        print("Connect string Successful!")
    except:
        print("Unable to create the connect string")

    # query generate
    try:
        sql="""copy {}.{} from '{}'\
        credentials 'aws_access_key_id={};aws_secret_access_key={}' \
        DELIMITER ',' ACCEPTINVCHARS EMPTYASNULL ESCAPE COMPUPDATE OFF;commit;"""\
        .format(CONSTANTS.SCHEMA, CONSTANTS.TABLE_NAME_BV, CONSTANTS.S3_PATH_BV,
            CONSTANTS.ACCESS_KEY_ID, CONSTANTS.SECRET_ACCESS_KEY)

        print("sql ==>", sql)
        print("Query creation Successful!")
        print(" ")
    except:
        print("Unable to create the query")

    # get connection
    try:
        con = psycopg2.connect(conn_string);
        print("con ==>", con)
        print("Connection Successful!")
    except Exception as e:
        print("Unable to connect to Redshift")
        print(e)
        exit(-1)

    # get cursor connection
    try:
        cur = con.cursor()
    except Exception as e:
        print("Unable to get the cursor from connection of Redshift")
        print(e)
        exit(-1)

    # execute cursor connection
    try:
        cur.execute(sql)
        print("Query executed successfully")
    except Exception as e:
        print("Failed to execute the query")
        print(e)
        exit(-1)

    # close connection
    try:
        con.close()
        print("Connection closed Successfully!")
    except Exception as e:
        print("Unable to close connection to Redshift")
        print(e)

    print(" ")

# Main method
if __name__ == '__main__':
    print("start: __main__ ")
    main()
    print("end: __main__ ")


问:
Programmatically align a toolbar on top of the iPhone keyboard
In several cases I want to add a toolbar to the top of the iPhone keyboard (as in iPhone Safari when you're navigating form elements, for example).

Currently I am specifying the toolbar's rectangle with constants but because other elements of the interface are in flux - toolbars and nav bars at the top of the screen - every time we make a minor interface change, the toolbar goes out of alignment.

Is there a way to programmatically determine the position of the keyboard in relation to the current view?

答:
This is based on the existing answer from tonklon - I'm just adding a code snippet that shows a semi transparent black toolbar on top of the keyboard, together with a "done" button on the right:

```<code>UIToolbar *toolbar = [[[UIToolbar alloc] init] autorelease];
[toolbar setBarStyle:UIBarStyleBlackTranslucent];
[toolbar sizeToFit];

UIBarButtonItem *flexButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
UIBarButtonItem *doneButton =[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(resignKeyboard)];

NSArray *itemsArray = [NSArray arrayWithObjects:flexButton, doneButton, nil];

[flexButton release];
[doneButton release];
[toolbar setItems:itemsArray];

[aTextField setInputAccessoryView:toolbar];
</code>```

and the -resignKeyboard looks like:

```<code>-(void)resignKeyboard {
  [aTextField resignFirstResponder];
}
</code>```

LastEditorDisplayName: Mark Biek

Body:
This is based on the existing answer from tonklon - I'm just adding a code snippet that shows a semi transparent black toolbar on top of the keyboard, together with a "done" button on the right:

UIToolbar *toolbar = [[[UIToolbar alloc] init] autorelease];
[toolbar setBarStyle:UIBarStyleBlackTranslucent];
[toolbar sizeToFit];

UIBarButtonItem *flexButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
UIBarButtonItem *doneButton =[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(resignKeyboard)];

NSArray *itemsArray = [NSArray arrayWithObjects:flexButton, doneButton, nil];

[flexButton release];
[doneButton release];
[toolbar setItems:itemsArray];

[aTextField setInputAccessoryView:toolbar];

and the -resignKeyboard looks like:

-(void)resignKeyboard {
  [aTextField resignFirstResponder];
}


问:
Immediately charge for subscription changes
We are using Stripe payment processing for our customer's subscriptions. When users change plans, we want them to be charged immediately for the prorated difference. Stripe does this automatically when plans have different billing intervals but when changing between plans with the same interval, Stripe defers payment till the next billing period.

The way we handle this now is to create an invoice after updating the subscription, but if the billing fails for it fails, we need to do a rollback.

```<code>stripe.subscriptions.update(/* change plan */);
if (plans_have_different_billing_intervals) {
  try {
    stripe.invoices.create(/* for all pending charges */);
  } catch (err) {
    /* rollback subscription to old plan */
  }
}
</code>```

Overall, this feels wrong and convoluted. Is there an easier/cleaner way to implement this that we aren't seeing?

答:
To immediately charge your users the prorated price difference when the user upgrades, use the proration_behavior='always_invoice' option when modifying the user's subscription. Quoting from the docs:

... In order to always invoice immediately for prorations, pass always_invoice.

Python example:

stripe.Subscription.modify(
    subscription_id,
    items=[{
        'id': item_id,
        'plan': plan_id,
    }],
    # Charge the prorated amount immediately.
    proration_behavior='always_invoice',
)
```
<p>This immediately charges the user a prorated amount when the user changes to a more expensive plan. However, when the user changes to a cheaper plan, the user will be given a prorated credit, making the user's next bill cheaper by the prorated amount.</p>
<h2>Scenarios</h2>
<p>In these scenarios, suppose the billing date is on the first day of each month. Further suppose that the month has 30 days.</p>
<ul>
<li><p>Scenario 1: The user is subscribed to a $5 monthly plan. The user decides to <strong>upgrade</strong> to a $30 plan on the 22nd day of the month. With 8 days left in the month, the unused portion of the $5 plan is approximately <code>(8 / 30) * 5 = $1.33</code>, and the prorated amount for the $30 plan is <code>(8 / 30) * 30 = $8.00</code>. So the user will be charged <code>8.00 - 1.33 = $6.67</code> immediately.</p>
</li>
<li><p>Scenario 2: The user is subscribed to a $30 monthly plan. The user decides to <strong>downgrade</strong> to a $5 plan on the 22nd day of the month. With 8 days left in the month, the unused portion of the $30 plan is approximately <code>(8 / 30) * 30 = $8.00</code>, and the prorated amount for the $5 plan is <code>(8 / 30) * 5 = $1.33</code>. In this case, the user will not be charged, but the user's next bill (on the next billing date) will be reduced by <code>8.00 - 1.33 = $6.67</code>.</p>
</li>
</ul>
<p>The example calculations above are only approximate because Stripe prorates to the exact second, not by day.</p>
<h2>Side notes</h2>
<p>dearsina's answer is correct, but involves at least three API calls rather than one. To explicitly follow the steps in that answer, you could do this instead:</p>
<pre class="lang-py prettyprint-override"><code># Step 1 in dearsina's answer: Modify the subscription.
modified_subscription = stripe.Subscription.modify(
    subscription_id,
    items=[{
        'id': item_id,
        'plan': plan_id,
    }],
)

# Steps 2 and 3: Create and retrieve invoice.
invoice = stripe.Invoice.create(customer=modified_subscription.customer)

# Steps 4 and 5: Finalize and pay invoice.
stripe.Invoice.pay(invoice.id)
</code>```

But why do this when you could do all the steps in one API call?

Body:
We are using Stripe payment processing for our customer's subscriptions. When users change plans, we want them to be charged immediately for the prorated difference. Stripe does this automatically when plans have different billing intervals but when changing between plans with the same interval, Stripe defers payment till the next billing period.

The way we handle this now is to create an invoice after updating the subscription, but if the billing fails for it fails, we need to do a rollback.

stripe.subscriptions.update(/* change plan */);
if (plans_have_different_billing_intervals) {
  try {
    stripe.invoices.create(/* for all pending charges */);
  } catch (err) {
    /* rollback subscription to old plan */
  }
}

Overall, this feels wrong and convoluted. Is there an easier/cleaner way to implement this that we aren't seeing?

Body:
To immediately charge your users the prorated price difference when the user upgrades, use the proration_behavior='always_invoice' option when modifying the user's subscription. Quoting from the docs:

... In order to always invoice immediately for prorations, pass always_invoice.

Python example:

stripe.Subscription.modify(
    subscription_id,
    items=[{
        'id': item_id,
        'plan': plan_id,
    }],
    # Charge the prorated amount immediately.
    proration_behavior='always_invoice',
)

This immediately charges the user a prorated amount when the user changes to a more expensive plan. However, when the user changes to a cheaper plan, the user will be given a prorated credit, making the user's next bill cheaper by the prorated amount.

Scenarios

In these scenarios, suppose the billing date is on the first day of each month. Further suppose that the month has 30 days.

Scenario 1: The user is subscribed to a $5 monthly plan. The user decides to upgrade to a $30 plan on the 22nd day of the month. With 8 days left in the month, the unused portion of the $5 plan is approximately (8 / 30) * 5 = $1.33, and the prorated amount for the $30 plan is (8 / 30) * 30 = $8.00. So the user will be charged 8.00 - 1.33 = $6.67 immediately.

Scenario 2: The user is subscribed to a $30 monthly plan. The user decides to downgrade to a $5 plan on the 22nd day of the month. With 8 days left in the month, the unused portion of the $30 plan is approximately (8 / 30) * 30 = $8.00, and the prorated amount for the $5 plan is (8 / 30) * 5 = $1.33. In this case, the user will not be charged, but the user's next bill (on the next billing date) will be reduced by 8.00 - 1.33 = $6.67.

The example calculations above are only approximate because Stripe prorates to the exact second, not by day.

Side notes

dearsina's answer is correct, but involves at least three API calls rather than one. To explicitly follow the steps in that answer, you could do this instead:

# Step 1 in dearsina's answer: Modify the subscription.
modified_subscription = stripe.Subscription.modify(
    subscription_id,
    items=[{
        'id': item_id,
        'plan': plan_id,
    }],
)

# Steps 2 and 3: Create and retrieve invoice.
invoice = stripe.Invoice.create(customer=modified_subscription.customer)

# Steps 4 and 5: Finalize and pay invoice.
stripe.Invoice.pay(invoice.id)

But why do this when you could do all the steps in one API call?


问:
How to install PgBouncer on Windows 7 (x64)
I am attempting to install PgBouncer on my computer with no success.  In the  installation page, im told that PgBouncer has two dependencies GNU Make 3.81+ and libevent 2.0.  Never having used or heard of these two software before, Im completely lost.

I have read a little on both but have yet to find or fully understand what they actually do and how they will help me set up PgBouncer.  From what I've read, PgBouncer does not come compiled for windows and I need the other two to compile it.  I have searched for tutorials online but it seems that im falling into a black hole of misunderstanding.

Im looking for a simple explanation on how to install PgBouncer or how these software work with one another. Thanks.

答:
I have not messed with pgbouncer in years but have had multiple comments on what I did to solve my problem.

In the link bellow is the pgbouncer build I last used on my project.  From what I remember, all you would need to do is replace the users in the config/user.txt with yours and go into config/pgbouncer.ini and change the configuration to work with your set up. To start it, just run the run.bat file or pgbouncer.exe config/pgbouncer.iniin the cmd prompt.  You want to download everything in the folder.

https://drive.google.com/open?id=1f8MjdQCq-ryQBiJ85d4hABASFfR_6fA2