问:
Translate git-log old commiter timestamp to strict ISO 8601 timestamp
I am responsible for deploying an application and as part of the deployment process, I need to get the latest committer timestamp in strict ISO 8601 format and place it in the database. For recent versions of git, it's fairly straight forward:

```<code>$ git log --pretty=format:'%cI' -n1
2019-05-29T10:24:58+04:00
</code>```

But unfortunately, I have a few older instances where the switch %cI does not exist in the installed git. So to get close to the ISO 8601, I use %ci instead, resulting in:

```<code>$ git log --pretty=format:%ci -n1
2019-05-29 10:24:58 +0400
</code>```

We will eventually upgrade the machines to a later version of operating system, and consequently a more modern version of git. Newer versions of git has this in the man page:

```<code>   •   %ci: committer date, ISO 8601-like format

   •   %cI: committer date, strict ISO 8601 format
</code>```

But in the meantime, I want to massage this ISO 8601-like string on the older machines to the strict ISO 8601 format above. I wrote a bad looking one-liner to do this and it seems to work:

```<code>$ git log --pretty=format:'%ci' -n1 | sed -e 's/ /T/1' -e 's/ //1' -e 's/.\{22\}/&:/1'
2019-05-29T10:24:58+04:00
</code>```

Simply, it replaces the first space with a T, the second space with nothing and inserts a colon : at the 22nd character position. How do I do this better? I tried looking up ways to do this with the date command; no luck.

答:
Using sed:

```<code>$ echo '2019-05-29 10:24:58 +0400' | sed -e 's/ /T/' -e 's/ //' -e 's/..$/:\0/'
</code>```

2019-05-29T10:24:58+04:00

Replace the first space with T, remove the second space, replace the last 2 characters with a colon and those 2 chars.

Body:
I am responsible for deploying an application and as part of the deployment process, I need to get the latest committer timestamp in strict ISO 8601 format and place it in the database. For recent versions of git, it's fairly straight forward:

$ git log --pretty=format:'%cI' -n1
2019-05-29T10:24:58+04:00

But unfortunately, I have a few older instances where the switch %cI does not exist in the installed git. So to get close to the ISO 8601, I use %ci instead, resulting in:

$ git log --pretty=format:%ci -n1
2019-05-29 10:24:58 +0400

We will eventually upgrade the machines to a later version of operating system, and consequently a more modern version of git. Newer versions of git has this in the man page:

   •   %ci: committer date, ISO 8601-like format

   •   %cI: committer date, strict ISO 8601 format

But in the meantime, I want to massage this ISO 8601-like string on the older machines to the strict ISO 8601 format above. I wrote a bad looking one-liner to do this and it seems to work:

$ git log --pretty=format:'%ci' -n1 | sed -e 's/ /T/1' -e 's/ //1' -e 's/.\{22\}/&:/1'
2019-05-29T10:24:58+04:00

Simply, it replaces the first space with a T, the second space with nothing and inserts a colon : at the 22nd character position. How do I do this better? I tried looking up ways to do this with the date command; no luck.

Body:
Using sed:

$ echo '2019-05-29 10:24:58 +0400' | sed -e 's/ /T/' -e 's/ //' -e 's/..$/:\0/'

2019-05-29T10:24:58+04:00

Replace the first space with T, remove the second space, replace the last 2 characters with a colon and those 2 chars.


来源: stackexchange

问:
Values in one column based on condition in another column
I have a dataframe:

```<code>Data = {'group':  ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'],
        'value1': [2, 0, 0, 5, 5, 5, 6, 31, 7, 5, 0, 99],
        'value2': [25, 12 ,15, 11, 36, 3, 65, 6, 89, 8, 74, 5]
        }

current_result = pd.DataFrame(Data, columns = ['group','value1', 'value2'])
</code>```

I want to set value2 to zero if corresponding value1 is equal to zero while keeping all other values the same. So my desired result would be:

```<code>Data = {'group':  ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'],
        'value1': [2, 0, 0, 5, 5, 5, 6, 31, 7, 5, 0, 99],
        'value2': [25, 0 ,0, 11, 36, 3, 65, 6, 89, 8, 0, 5]
        }

current_result = pd.DataFrame(Data, columns = ['group','value1', 'value2'])
</code>```

How could I do this?

答:
Without using any Pandas core features, this loop gets the job done:</p>

```<code>for index, value in enumerate(current_result["value1"]):
    if value == 0:
        current_result["value2"][index] = 0
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a dataframe:

Data = {'group':  ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'],
        'value1': [2, 0, 0, 5, 5, 5, 6, 31, 7, 5, 0, 99],
        'value2': [25, 12 ,15, 11, 36, 3, 65, 6, 89, 8, 74, 5]
        }

current_result = pd.DataFrame(Data, columns = ['group','value1', 'value2'])

I want to set value2 to zero if corresponding value1 is equal to zero while keeping all other values the same. So my desired result would be:

Data = {'group':  ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'],
        'value1': [2, 0, 0, 5, 5, 5, 6, 31, 7, 5, 0, 99],
        'value2': [25, 0 ,0, 11, 36, 3, 65, 6, 89, 8, 0, 5]
        }

current_result = pd.DataFrame(Data, columns = ['group','value1', 'value2'])

How could I do this?

Body:
Without using any Pandas core features, this loop gets the job done:

for index, value in enumerate(current_result["value1"]):
    if value == 0:
        current_result["value2"][index] = 0


问:
Commercial round with comma and point
I have used this code :

```<code>$result = number_format(round(15.5, 1), 2);
</code>```

Written in my old post :
PHP - Commercial round

I have now problems with the values like : 1,597.30

I get the price as 1.00

How can I do to get the make the round and get the good price format with the prices that have number with thousands.

答: Remove comma and all other formating (except the dot) from your numbers, otherwise comma will be used as decimal separator.</p>

ContentLicense: CC BY-SA 3.0

Title: Commercial round with comma and point

Body:
I have used this code :

$result = number_format(round(15.5, 1), 2);

Written in my old post :
PHP - Commercial round

I have now problems with the values like : 1,597.30

I get the price as 1.00

How can I do to get the make the round and get the good price format with the prices that have number with thousands.


问:
How to convert AAR to JAR
Situation:

I intend to use a Java library and I only have an AAR file from a Maven repository but I need the JAR file.

Background story:

I tried to compile a library, but its Gradle structure was unstable. So I asked for a compiled jar file, and its developer handed me an aar file from some Maven repository (the developer couldn't compile his own project).
The Gradle configuration was a mess, it depended on multiple libraries and Gradle has thrown some exceptions.

I tried to use it in my IDEA IDE, but it couldn't see it. A library project should be able to be compiled into a jar file, right?

Question:

What should I do to convert that AAR file to a JAR file?

答:
If you are using Gradle for your builds - there is a Gradle plugin which allows you to add aar dependency to your java|kotlin|scala|... modules.

https://github.com/stepango/aar2jar

```<code>plugins {
    id 'java'
    id 'com.stepango.aar2jar' version “0.6” // <- this one
}

dependencies {
    compileOnlyAar "com.android.support:support-annotations:28.0.0" // <- Use any AAR dependencies
}
</code>```

Title: How to convert AAR to JAR

Body:
If you are using Gradle for your builds - there is a Gradle plugin which allows you to add aar dependency to your java|kotlin|scala|... modules.

https://github.com/stepango/aar2jar

plugins {
    id 'java'
    id 'com.stepango.aar2jar' version “0.6” // <- this one
}

dependencies {
    compileOnlyAar "com.android.support:support-annotations:28.0.0" // <- Use any AAR dependencies
}


问:
Can't load image with Glide/Fresco
This image can't be loaded with Glide/Fresco. Just empty image. Why?

This is my code:

```<code>Glide.with(context)
 .load(ValidationHelper.getValidImageUrl(elements[position].author!!.image)
 .into(viewHolder.avatarImage)
            //viewHolder.avatarImage.setImageURI(ValidationHelper.getValidImageUrl(elements[position].author!!.image))
</code>```

答:
Please try below code :</p>

```<code>Glide.with(this)  // Activity context
   .load(ValidationHelper.getValidImageUrl(elements[position].author!!.image) // Set URL
   .resize(100,100) // If you want to Resize the image then set image size
   .placeholder(getResources().getDrawable(R.drawable.ic_defuser)) // Default Image
   .error(getResources().getDrawable(R.drawable.ic_defuser))
   .into(viewHolder.avatarImage); // Imageview
</code>```

Title: Can't load image with Glide/Fresco

Body:
This image can't be loaded with Glide/Fresco. Just empty image. Why?

This is my code:

Glide.with(context)
 .load(ValidationHelper.getValidImageUrl(elements[position].author!!.image)
 .into(viewHolder.avatarImage)
            //viewHolder.avatarImage.setImageURI(ValidationHelper.getValidImageUrl(elements[position].author!!.image))

Body:
Please try below code :

Glide.with(this)  // Activity context
   .load(ValidationHelper.getValidImageUrl(elements[position].author!!.image) // Set URL
   .resize(100,100) // If you want to Resize the image then set image size
   .placeholder(getResources().getDrawable(R.drawable.ic_defuser)) // Default Image
   .error(getResources().getDrawable(R.drawable.ic_defuser))
   .into(viewHolder.avatarImage); // Imageview


问:
Authentication for SuccessFactors and get all the entities
Authentication and get all entities using any api

Hi,
  I have to integrate the SAP SuccessFactors in our platform but how to authenticate the user I have seen two ways basic authentication and OAuth which one is secure ?And once authentication done I have to grab all entities available in it.Do we have any metadata api available?

答:
You can call $metadata (e.g. https://apisalesdemo4.successfactors.com/$metadata) for a metadata overview (for each entity you see all options, filterable, upsertable etc.)

Always prefer OAuth over Basic Auth: OAuth is good than Basic Authentication, Basic Authentication's Drawback is , it is not that much secure. your credentials can be hacked. OAuth helps you in creating a secure passage for your access, and it uses RSA encryption as part of its setup, So OAuth is preferred one! from: https://community.atlassian.com/t5/Answers-Developer-Questions/Difference-between-OAuth-and-Basic-Authentication-and-where/qaq-p/530513


问:
Get a specific value in JSON and Python
I'm getting a JSON data from RESTCONF HTTPS request, using the following code.

```<code>https_request = 'https://' + host + '/restconf/data/Cisco-IOS-XE-native:native/interface/'
headers = {'Content-type': 'application/yang-data+json', 'Accept': 'application/yang-data+json'}
r = requests.get(https_request, auth=(user, password), headers=headers, verify=False)
print r.json()
</code>```

The JSON file I got:

```<code>{
"Cisco-IOS-XE-native:interface": {
    "GigabitEthernet": [
        {
            "name": "1",
            "description": "DON'T TOUCH ME",
            "isis": {
                "Cisco-IOS-XE-isis:metric": {
                    "value": 2
             }
            ....
        },
        {
            "name": "2",
            "isis": {
                "Cisco-IOS-XE-isis:metric": {
                    "value": 4
                } ....

        },
        {
            "name": "3",
            "shutdown": [
                null
            ],
            "isis": {
                "Cisco-IOS-XE-isis:metric": {
                    "value": 7
                }....
        }
    ],
    "Loopback": [
        {
            "name": 0,
            "isis": {
                "Cisco-IOS-XE-isis:metric": {
                    "value": 1
                }
    ],
    "Tunnel": [
        {
            "name": 0,
            "isis": {
                "Cisco-IOS-XE-isis:metric": {
                    "value": 3
                }....
            }
    ]
}
</code>```

Basically, I want my function to return the field's "value" of isis of each interface. I tried the following code for GigabitEthernet:

```<code>value = r.json()['Cisco-IOS-XE-native:interface']['GigabitEthernet'][0]['isis']['metric']['value']
</code>```

I got this error:

```<code>print Router_1.get_isis_metric()['Cisco-IOS-XE-native:interface']['GigabitEthernet'][0]['isis']['metric']['isis']
KeyError: 'metric'
</code>```

答:
I think, you have misspelled metric for Cisco-IOS-XE-isis:metric

Try :

```<code>value = r.json()['Cisco-IOS-XE-native:interface']['GigabitEthernet'][0]['isis']['Cisco-IOS-XE-isis:metric']['value']
</code>```

Edit 1

```<code>for index in range(len(r.json()['Cisco-IOS-XE-native:interface']['GigabitEthernet'])):
    value = r.json()['Cisco-IOS-XE-native:interface']['GigabitEthernet'][index]['isis']['Cisco-IOS-XE-isis:metric']['value']
    print(value)
</code>```

Title: Get a specific value in JSON and Python

Body:
I'm getting a JSON data from RESTCONF HTTPS request, using the following code.

https_request = 'https://' + host + '/restconf/data/Cisco-IOS-XE-native:native/interface/'
headers = {'Content-type': 'application/yang-data+json', 'Accept': 'application/yang-data+json'}
r = requests.get(https_request, auth=(user, password), headers=headers, verify=False)
print r.json()

The JSON file I got:

{
"Cisco-IOS-XE-native:interface": {
    "GigabitEthernet": [
        {
            "name": "1",
            "description": "DON'T TOUCH ME",
            "isis": {
                "Cisco-IOS-XE-isis:metric": {
                    "value": 2
             }
            ....
        },
        {
            "name": "2",
            "isis": {
                "Cisco-IOS-XE-isis:metric": {
                    "value": 4
                } ....

        },
        {
            "name": "3",
            "shutdown": [
                null
            ],
            "isis": {
                "Cisco-IOS-XE-isis:metric": {
                    "value": 7
                }....
        }
    ],
    "Loopback": [
        {
            "name": 0,
            "isis": {
                "Cisco-IOS-XE-isis:metric": {
                    "value": 1
                }
    ],
    "Tunnel": [
        {
            "name": 0,
            "isis": {
                "Cisco-IOS-XE-isis:metric": {
                    "value": 3
                }....
            }
    ]
}

Basically, I want my function to return the field's "value" of isis of each interface. I tried the following code for GigabitEthernet:

value = r.json()['Cisco-IOS-XE-native:interface']['GigabitEthernet'][0]['isis']['metric']['value']

I got this error:

print Router_1.get_isis_metric()['Cisco-IOS-XE-native:interface']['GigabitEthernet'][0]['isis']['metric']['isis']
KeyError: 'metric'

Body:
I think, you have misspelled metric for Cisco-IOS-XE-isis:metric

Try :

value = r.json()['Cisco-IOS-XE-native:interface']['GigabitEthernet'][0]['isis']['Cisco-IOS-XE-isis:metric']['value']

Edit 1

for index in range(len(r.json()['Cisco-IOS-XE-native:interface']['GigabitEthernet'])):
    value = r.json()['Cisco-IOS-XE-native:interface']['GigabitEthernet'][index]['isis']['Cisco-IOS-XE-isis:metric']['value']
    print(value)


问:
Excel counting by colour VBA not updating with changes?
I have some VBA in Excel that counts if a range of cells contains a colour from a reference cell, which works well. But changing the colour of any cell in the range does not update the total counted.

Ideally, I want the code to update the number of coloured cells that match the reference, and when the cell colours are changed, to update the sum counted.

I have tried adding an Else statement in the If statement so that if a cell is 'blank' or had its colour 'cleared' using the paint pot button for filling cells, it would deduct a number, but this failed to work.

```<code>Sub Colourif()
End Sub

Function CountColorIf(rSample As Range, rArea As Range) As Long
    Dim rAreaCell As Range
    Dim lMatchColor As Long
    Dim lCounter As Long

    lMatchColor = rSample.Interior.Color

    For Each rAreaCell In rArea
        If rAreaCell.Interior.Color = lMatchColor Then
            lCounter = lCounter + 1
        End If
    Next rAreaCell

    CountColorIf = lCounter
End Function
</code>```

If I change a cell in the range fill using the paint pot icon to say 'clear' it does not change the count of cells filled with the reference colour.

I would be extremely grateful for some advice on how to ensure this code automatically updates the sum when cell fills are changed from the reference colour.

答:
Unfortunately, it doesn't seem that a format change triggers any of the standard Excel event handlers. Something which comes close would be to target the Worksheet's Selection Change event. In the code module for the worksheet put:

```<code>Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Me.Calculate
End Sub
</code>```

Then change the definition of CountColorIf so that it begins:

```<code>Function CountColorIf(rSample As Range, rArea As Range) As Long
    Application.Volatile
</code>```

Then, if a color of a cell is changed, the count is updated -- as soon as you move to a different cell.

Another idea would be to use Application.OnTime to run a sub which triggers a recount every few seconds, but this would still not lead to instant updates as soon as you change a color.

On Edit Since there is no FormatChange event that you can target, using SelectionChange as a proxy for it is not ideal. One problem, that you noted in the comments, is that this will fire in the middle of a copy-paste act, in which case the resulting worksheet calculation will get Excel out of copy-paste mode. One fix for that particular problem is to change the code to:

```<code>Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Application.CutCopyMode = 0 Then Me.Calculate
End Sub
</code>```

If this code is for your own personal use, a simple solution is to keep Application.Volatile but get rid of the event handler entirely, getting into the habit of hitting F9 when you change the color of a cell. That would limit the recalculations to when you want them, at the cost of required action on your part.

Body:
I have some VBA in Excel that counts if a range of cells contains a colour from a reference cell, which works well. But changing the colour of any cell in the range does not update the total counted.

Ideally, I want the code to update the number of coloured cells that match the reference, and when the cell colours are changed, to update the sum counted.

I have tried adding an Else statement in the If statement so that if a cell is 'blank' or had its colour 'cleared' using the paint pot button for filling cells, it would deduct a number, but this failed to work.

Sub Colourif()
End Sub

Function CountColorIf(rSample As Range, rArea As Range) As Long
    Dim rAreaCell As Range
    Dim lMatchColor As Long
    Dim lCounter As Long

    lMatchColor = rSample.Interior.Color

    For Each rAreaCell In rArea
        If rAreaCell.Interior.Color = lMatchColor Then
            lCounter = lCounter + 1
        End If
    Next rAreaCell

    CountColorIf = lCounter
End Function

If I change a cell in the range fill using the paint pot icon to say 'clear' it does not change the count of cells filled with the reference colour.

I would be extremely grateful for some advice on how to ensure this code automatically updates the sum when cell fills are changed from the reference colour.

Body:
Unfortunately, it doesn't seem that a format change triggers any of the standard Excel event handlers. Something which comes close would be to target the Worksheet's Selection Change event. In the code module for the worksheet put:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Me.Calculate
End Sub

Then change the definition of CountColorIf so that it begins:

Function CountColorIf(rSample As Range, rArea As Range) As Long
    Application.Volatile

Then, if a color of a cell is changed, the count is updated -- as soon as you move to a different cell.

Another idea would be to use Application.OnTime to run a sub which triggers a recount every few seconds, but this would still not lead to instant updates as soon as you change a color.

On Edit Since there is no FormatChange event that you can target, using SelectionChange as a proxy for it is not ideal. One problem, that you noted in the comments, is that this will fire in the middle of a copy-paste act, in which case the resulting worksheet calculation will get Excel out of copy-paste mode. One fix for that particular problem is to change the code to:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Application.CutCopyMode = 0 Then Me.Calculate
End Sub

If this code is for your own personal use, a simple solution is to keep Application.Volatile but get rid of the event handler entirely, getting into the habit of hitting F9 when you change the color of a cell. That would limit the recalculations to when you want them, at the cost of required action on your part.


问:
Why different string is matching to the pattern?
I am using java 1.7.

I expect:

```<code>Pattern ddmmyyyyPattern = Pattern.compile("(\\d{1,2}[- /.]\\d{1,2}[- /.]\\d{4})");
</code>```

should match strings with atleast 2 occurences of seperators -/.
But, the following are matching

```<code>07 2.3180, 45 3.3183, 19 4.3183, 77 5.3025, 25 6.3023.
</code>```

Also, 9507 2.31 is matching to

```<code>Pattern yyyymmddPattern = Pattern.compile("(\\d{4}[- /.]\\d{1,2}[- /.]\\d{1,2})");
</code>```

Please help me in rectifying the pattern!

答:
That happend because the character class also matches a space.

You could use a capturing group with a backreference to match a date like pattern. Note that is does not validate a date itself.

```<code>\d{1,2}([-/.])\d{1,2}\1\d{4}
</code>```

About the pattern

\d{1,2} Match 1 or 2 digits

([-/.]) Capture in a group matching - / or .

\d{1,2} Match 1 or 2 digits

\1 Backreference to what is captured in group 1 (So 12/12-2019 will not match)

\d{4} Match 4 digits

In Java:

```<code>String regex = "\\d{1,2}([-/.])\\d{1,2}\\1\\d{4}";
</code>```

Regex demo | Java demo

Note that for a match you can omit the outer parenthesis.

Body:
I am using java 1.7.

I expect:

Pattern ddmmyyyyPattern = Pattern.compile("(\\d{1,2}[- /.]\\d{1,2}[- /.]\\d{4})");

should match strings with atleast 2 occurences of seperators -/.
But, the following are matching

07 2.3180, 45 3.3183, 19 4.3183, 77 5.3025, 25 6.3023.

Also, 9507 2.31 is matching to

Pattern yyyymmddPattern = Pattern.compile("(\\d{4}[- /.]\\d{1,2}[- /.]\\d{1,2})");

Please help me in rectifying the pattern!

Body:
That happend because the character class also matches a space.

You could use a capturing group with a backreference to match a date like pattern. Note that is does not validate a date itself.

\d{1,2}([-/.])\d{1,2}\1\d{4}

About the pattern

\d{1,2} Match 1 or 2 digits

([-/.]) Capture in a group matching - / or .

\d{1,2} Match 1 or 2 digits

\1 Backreference to what is captured in group 1 (So 12/12-2019 will not match)

\d{4} Match 4 digits

In Java:

String regex = "\\d{1,2}([-/.])\\d{1,2}\\1\\d{4}";

Regex demo | Java demo

Note that for a match you can omit the outer parenthesis.


答:
Never store a formatted number.

Always store it in its original format: 1597.30 This is the only format that works for calculations and formatting.

Use number_format() only for outputting the number.

Title: Commercial round with comma and point


问:
Translation of zip file (contains object and material file with different colors) results to a viewables of single color
Till a few days back the translation was working as expected. I was able to see the viewables with the color scheme mentioned in obj and mat file. But now same translation is giving wrong results(viewables). It applies only one color to all the objects and nodes !!!

答: This is now fixed, thanks for reporting. </p>


问:
What happens to C# Dictionary<int, int> lookup if the key does not exist?
I tried checking for null but the compiler warns that this condition will never occur.  What should I be looking for?</p>

答:
```<code>int result= YourDictionaryName.TryGetValue(key, out int value) ? YourDictionaryName[key] : 0;
</code>```

If the key is present in the dictionary, it returns the value of the key otherwise it returns 0.

Hope, this code helps you.

ContentLicense: CC BY-SA 2.5

Body:
int result= YourDictionaryName.TryGetValue(key, out int value) ? YourDictionaryName[key] : 0;

If the key is present in the dictionary, it returns the value of the key otherwise it returns 0.

Hope, this code helps you.


问:
Flexbox auto determining size (width) of container based on content (problem)
I have a link to jsFiddle that will present the problem. Basically, the problem is in the middle container (sector2 the blue one) which flexes in column orientation and has 5 flex child elements. Inside four of these elements are images with the size of 150x150px. I have given the image-wrapper (class of every child element) to flex: 1, which means that the blue container should be divided into 5 equal height parts. Now I set the min-height: 100% of every image, which makes the height of the image to be as much as one part (child element) height is.

The problem arises when I want to maintain the aspect ratio of the image and set the object-fit: scale-down. This property makes the image preserve the aspect ratio, but the containers (image-wrapper) and the blue container (sector2) still hold the original image width of 150px.

My question is: how can I preserve the image aspect ratio and in the same time containers should auto resize based on the content?

I will additionally add the HTML and CSS code here:

.container {
      display: flex;
      flex-direction: row;
      width: 600px;
      height: 500px;
      background-color: red;
    }

    .sector1 {
      display: flex;
      flex-direction: row;
      flex: 1 0 0%;
      background-color: green;
    }

    .sector3 {
      display: flex;
      flex-direction: row;
      flex: 1 0 0%;
      background-color: green;
    }

    .sector2 {
      display: flex;
      flex-direction: column;
      flex: 0 0 auto;
      background-color: blue;
      margin: 0 6px;
    }

    .image-wrapper {
      display: flex;
      flex-direction: column;
      flex: 1 0 0%;
    min-height: 0;
        min-width: 0;
    }

    .image {
       object-fit: scale-down;
       min-height: 100%;
       width: auto;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
    <div class="sector1"></div>

    <div class="sector2">

      <div class="image-wrapper">
        <img class="image" src="https://mk0powerpackele6qayu.kinstacdn.com/wp-content/uploads/2018/07/image-75-150x150.jpg" />
      </div>

      <div class="image-wrapper">
        <img class="image" src="https://mk0powerpackele6qayu.kinstacdn.com/wp-content/uploads/2018/07/image-75-150x150.jpg" />
      </div>

      <div class="image-wrapper"></div>

      <div class="image-wrapper">
        <img class="image" src="https://mk0powerpackele6qayu.kinstacdn.com/wp-content/uploads/2018/07/image-75-150x150.jpg" />
      </div>

      <div class="image-wrapper">
        <img class="image" src="https://mk0powerpackele6qayu.kinstacdn.com/wp-content/uploads/2018/07/image-75-150x150.jpg" />
      </div>

    </div>

    <div class="sector3"></div>
    </div>

    </code>```

答:
I changed the .image-wrapper to flex: 0 0 auto; and I believe it has your desired effect. Check to see if in this fiddle that I forked.

You previously had .image-wrapper at flex: 1 0 0%; which means the element started at 0 width and then grew to the size of the container. That method for determining size doesn't take the size of the elements inside into consideration. Therefore growing to the width of the container will create the blue space around the images.

Setting it to flex: 0 0 auto will determine the width based upon the size the elements inside need, hence auto. Having flex-grow at 0 will tell it not to grow past the size it needs and will not create the blue space.


问:
MySQL (python 3.6) - SELECT * FROM table - returns number of rows instead of table
I am working with MySQL but I have some unexpected behaviour.
I have past experience with SQLite but I guess I am missing something here.

Using the query SELECT * FROM tableName I would expect the content of the table to be the output.
Instead I get an int, being the count of rows in the table.
Here is the piece of code I am using.

```<code>import MySQLdb

conn=MySQLdb.connect(host="xxx",user="xxx",passwd="xxx")
cursor = conn.cursor()
cursor.execute("create database if not exists Test;")
cursor.execute("use Test;")
cursor.execute("create table if not exists City (id int not null primary key auto_increment, city varchar(50), unique(city));")
cursor.execute("insert into City (city) values ('Firenze');")
cursor.execute("insert into City (city) values ('Roma');")
conn.commit()
print(cursor.execute("select city from City;"))
</code>```

I would expect to get:

```<code>Firenze
Roma
</code>```

Instead I get:
2

If I run the same query from a SQL client I get the expected output. Any clever idea?
Thanks :)

答:
You are missing the FetchAll() function in your code.
Fetch all is nothing but fetching the data of last executed statement.</p>

```<code>import MySQLdb
conn=MySQLdb.connect(host="xxx",user="xxx",passwd="xxx")
cursor = conn.cursor()
cursor.execute("create database if not exists Test;")
cursor.execute("use Test;")
cursor.execute("create table if not exists City (id int not null primary key
auto_increment, city varchar(50), unique(city));")
cursor.execute("insert into City (city) values ('Firenze');")
cursor.execute("insert into City (city) values ('Roma');")
conn.commit()
print(cursor.execute("select city from City;"))
myresult = mycursor.fetchall()
for x in myresult:
print(x)
</code>```

Body:
I am working with MySQL but I have some unexpected behaviour.
I have past experience with SQLite but I guess I am missing something here.

Using the query SELECT * FROM tableName I would expect the content of the table to be the output.
Instead I get an int, being the count of rows in the table.
Here is the piece of code I am using.

import MySQLdb

conn=MySQLdb.connect(host="xxx",user="xxx",passwd="xxx")
cursor = conn.cursor()
cursor.execute("create database if not exists Test;")
cursor.execute("use Test;")
cursor.execute("create table if not exists City (id int not null primary key auto_increment, city varchar(50), unique(city));")
cursor.execute("insert into City (city) values ('Firenze');")
cursor.execute("insert into City (city) values ('Roma');")
conn.commit()
print(cursor.execute("select city from City;"))

I would expect to get:

Firenze
Roma

Instead I get:
2

If I run the same query from a SQL client I get the expected output. Any clever idea?
Thanks :)

Body:
You are missing the FetchAll() function in your code.
Fetch all is nothing but fetching the data of last executed statement.

import MySQLdb
conn=MySQLdb.connect(host="xxx",user="xxx",passwd="xxx")
cursor = conn.cursor()
cursor.execute("create database if not exists Test;")
cursor.execute("use Test;")
cursor.execute("create table if not exists City (id int not null primary key
auto_increment, city varchar(50), unique(city));")
cursor.execute("insert into City (city) values ('Firenze');")
cursor.execute("insert into City (city) values ('Roma');")
conn.commit()
print(cursor.execute("select city from City;"))
myresult = mycursor.fetchall()
for x in myresult:
print(x)


问:
Why does my navbar appear on top of scrollbar?
I'm trying to create my first website with parallax effect. I noticed a problem with my fixed top navbar - it appears on top of the scrollbar and overflow hidden doesn't hide it. I've tried to put it into .main-container and it kinda solves my problem: it's not on the top of scrollbar anymore, however, it stops being top fixed. What causes this problem? How can I fix it?

HTML:

```<code><head>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"></link>

</head>

<body>

    <nav class="navbar navbar-light navbar-expand-lg" id="top-navbar">
        <a class="navbar-brand" href="#">brand</a>

        <button class="navbar-toggler" id='nav-icon' type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                                            <span></span>
                                            <span></span>
                                            <span></span>
                                            <span></span>
                                        </button>

        <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav m-auto">
                <li class="nav-item">
                    <a class="nav-link" href="#">link</a>
                </li>
            </ul>
            <ul class="navbar-nav m-auto">
                <li class="nav-item">
                    <a class="nav-link" href='#1'>link 1</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href='#2'>link 2</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href='#3'>link 3</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href='#4'>link 4</a>
                </li>
            </ul>

            <ul class="navbar-nav ml-auto mr-0">
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" id="navbar-dropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">dropdown</a>

                    <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                        <a class="dropdown-item" href="#">link</a>

                        <a class="dropdown-item" href="#">link</a>
                    </div>
                </li>
            </ul>
        </div>
    </nav>

    <div class='main-container'>

        <div class="parallax-container">

            <div>
                <h1>title</h1>
            </div>
            <a href="#1" id='main-anchor'>
                <i class="large material-icons" style="font-size: 5rem" id='goto-icon'>
                    keyboard_arrow_down
                </i>
            </a>
        </div>

        <div id="wrapper" class='content-container'>

            <div id="page-content" class="page content">

                <span class="anchor" id="1"></span>

                <section class="card text-white bg-dark mb-5">
                    <h4 class="card-header">Title</h4>

                    <div class="card-body">
                        <p class="card-text">
                            Some quick example text to build on the card title and make up the bulk of the card's content.
                        </p>
                    </div>
                </section>

                <span class="anchor" id="2"></span>

                <section class="card text-white bg-dark mb-5">
                    <h4 class="card-header">Title</h4>

                    <div class="card-body">
                        <p class="card-text">
                            Some quick example text to build on the card title and make up the bulk of the card's content.
                        </p>
                    </div>
                </section>

                <span class="anchor" id="3"></span>

                <section class="card text-white bg-dark mb-5">
                    <h4 class="card-header">Title</h4>

                    <div class="card-body">
                        <p class="card-text">
                            Some quick example text to build on the card title and make up the bulk of the card's content.
                        </p>
                    </div>
                </section>

                <span class="anchor" id="4"></span>

                <section class="card text-white bg-dark mb-5">
                    <h4 class="card-header">Title</h4>

                    <div class="card-body">
                        <p class="card-text">
                            Some quick example text to build on the card title and make up the bulk of the card's content.
                        </p>
                    </div>
                </section>
            </div>
        </div>
    </div>

</body>
</code>```

SCSS

```<code>// COLORS
$darker: #212529;
$dark: #35383C;
$gray: #605F5E;
$greenish: #0F5158;
$lightgreen: #21686E;
$blue: #7FA5A6;
$lightblue: #96B5B6;
$alabaster: #F1EBE1;
$gainsboro: #CEE0DC;
// SITE
body {
    font-family: sans-serif;
    background-color: $darker;
    scroll-behavior: smooth;
}

.main-container {
    perspective: 1px;
    transform-style: preserve-3d;
    height: 100vh;
    overflow-x: hidden;
    overflow-y: scroll;
    background-color: $darker;
    a {
        &:link,
        &:visited,
        &:hover,
        &:active {
            color: white;
        }
    }
}

.content-container {
    position: relative;
    display: block;
    z-index: 1;
    background-color: $darker;
    min-height: 100vh;
}

.content {
    margin: 0 auto;
    padding: 75px 0;
}

.parallax-container {
    color: white;
    left: -9px;
    display: flex;
    flex: 1 0 auto;
    flex-direction: column;
    position: relative;
    z-index: -1;
    height: 100vh;
    width: 101vw;
    justify-content: center;
    align-items: center;
    transform: translateZ(-1px) scale(2);
    background: linear-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.1));
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center center;
}

// NAVBAR
#top-navbar {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    font-size: 1rem;
    z-index: 30;
    line-height: 150%;
    background-color: rgba(33, 37, 41, 0.1);
    padding: 0 2.5vw;
    transition: transform 1s .3s ease;
    box-shadow: 0 1px 50px -28px $blue;
    &.dark {
        background: $darker;
    }
    &.dark-show {
        background: $darker;
    }
    &.scrollUp {
        transform: translateY(-100%);
    }
    * {
        color: #bbccdd !important;
        font-weight: 500;
    }
    .navbar-brand {
        font-size: 1.5rem;
        font-weight: 600;
        padding: 0;
    }
    .nav-item {
        text-transform: uppercase;
        padding: 0 8px;
        cursor: pointer;
        // &:hover:not(.dropdown) {
        //     background-color: rgba(33, 37, 41, 1);
        // }
        a:hover {
            color: white !important;
        }
    }
    .nav-link {
        margin: 10px 0;
        &.active {
            color: white !important;
            border-bottom: 1px solid white;
        }
    }
    .dropdown-menu {
        border-color: $blue;
        line-height: 2rem;
        background-color: rgba(0, 0, 0, 0.1);
        .dropdown-divider {
            margin: 0;
            border-top: 2px solid black;
        }
        .dropdown-item:hover {
            color: white;
            background-color: rgba(33, 37, 41, 0.1);
        }
    }
    .navbar-toggler {
        color: $blue;
    }
}

// HAMBURGER
#nav-icon {
    width: 30px;
    height: 30px;
    position: relative;
    margin: 0;
    -webkit-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    transform: rotate(0deg);
    -webkit-transition: .5s ease-in-out;
    -moz-transition: .5s ease-in-out;
    -o-transition: .5s ease-in-out;
    transition: .5s ease-in-out;
    cursor: pointer;
}

#nav-icon span {
    display: block;
    position: absolute;
    height: 3px;
    width: 100%;
    background: $blue;
    border-radius: 3px;
    opacity: 1;
    left: 0;
    -webkit-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    transform: rotate(0deg);
    -webkit-transition: .25s ease-in-out;
    -moz-transition: .25s ease-in-out;
    -o-transition: .25s ease-in-out;
    transition: .25s ease-in-out;
}

#nav-icon span:nth-child(1) {
    top: 1px;
}

#nav-icon span:nth-child(2),
#nav-icon span:nth-child(3) {
    top: 13px;
}

#nav-icon span:nth-child(4) {
    bottom: 0px;
}

#nav-icon.open span:nth-child(1) {
    top: 15px;
    width: 0%;
    left: 50%;
}

#nav-icon.open span:nth-child(2) {
    -webkit-transform: rotate(45deg);
    -moz-transform: rotate(45deg);
    -o-transform: rotate(45deg);
    transform: rotate(45deg);
}

#nav-icon.open span:nth-child(3) {
    -webkit-transform: rotate(-45deg);
    -moz-transform: rotate(-45deg);
    -o-transform: rotate(-45deg);
    transform: rotate(-45deg);
}

#nav-icon.open span:nth-child(4) {
    top: 15px;
    width: 0%;
    left: 50%;
}

// CONTENT
#page-content {
    height: 100vh !important;
    padding: 15vh 10vw 5vh 10vw;
    margin: 0;
}

.anchor {
    display: block;
    height: 15vh;
    margin-top: -15vh;
    visibility: hidden;
}

// MEDIA QUERIES
@media only screen and (min-device-width: 320px) and (max-device-width: 480px) {
    #sidebar {
        display: none;
    }
    #page-content {
        margin: 0;
    }
}
</code>```

JS:

```<code>$(document).ready(function() {
    $('#sidebar').css('transform', 'translateX(200px)')
    $('#nav-icon').click(function() {
        // $(this).toggleClass('open');
        $('#top-navbar').toggleClass('dark-show');
    });
    $('.main-container').scroll(function() {
        let pageHeight = $('.main-container').height();
        $('#top-navbar').toggleClass('dark', $(this).scrollTop() > pageHeight);
        $('section').each(function(i) {
            var position = $(document).scrollTop();
            var header = $('#top-navbar').outerHeight();
            if ($(this).position().top <= (position + header)) {
                var top = $(this).position().top;
                console.log($(this).position().top <= (position + header));
                $(".nav-link.active").removeClass('active');
                $(".nav-link").eq(i).addClass('active');
            }
        })
    });
    $('.nav-link').on('click', function() {
        $('.nav-link').removeClass('active');
        $(this).addClass('active');
    });
});

document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function(e) {
        e.preventDefault();

        document.querySelector(this.getAttribute('href')).scrollIntoView({
            behavior: 'smooth'
        });
    });
});

let width = $(window).width();
let height = $(window).height();

if (height > width && height < 1024) {
    let position = $('#page-content').scrollTop();

    $('.main-container').scroll(function() {
        let scroll = $('.main-container').scrollTop();
        if (scroll > position) {
            $('#top-navbar').addClass('scrollUp');
        } else {
            $('#top-navbar').removeClass('scrollUp');
        }
        position = scroll;
    });
}
</code>```

Link to jsfiddle: https://jsfiddle.net/strzesia/fhqok4ym/19/

答:
You can use following css for navbar</p>

```<code>.nav{
    position:absolute;
    left:0;
    top:0;
}
</code>```

Body:
I'm trying to create my first website with parallax effect. I noticed a problem with my fixed top navbar - it appears on top of the scrollbar and overflow hidden doesn't hide it. I've tried to put it into .main-container and it kinda solves my problem: it's not on the top of scrollbar anymore, however, it stops being top fixed. What causes this problem? How can I fix it?

HTML:

    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"></link>

        brand

        <button class="navbar-toggler" id='nav-icon' type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

                                        </button>

                    link

                    link 1

                    link 2

                    link 3

                    link 4

                    dropdown

                        link

                        link

title

                    keyboard_arrow_down

Title

                            Some quick example text to build on the card title and make up the bulk of the card's content.

Title

                            Some quick example text to build on the card title and make up the bulk of the card's content.

Title

                            Some quick example text to build on the card title and make up the bulk of the card's content.

Title

                            Some quick example text to build on the card title and make up the bulk of the card's content.

SCSS

// COLORS
$darker: #212529;
$dark: #35383C;
$gray: #605F5E;
$greenish: #0F5158;
$lightgreen: #21686E;
$blue: #7FA5A6;
$lightblue: #96B5B6;
$alabaster: #F1EBE1;
$gainsboro: #CEE0DC;
// SITE
body {
    font-family: sans-serif;
    background-color: $darker;
    scroll-behavior: smooth;
}

.main-container {
    perspective: 1px;
    transform-style: preserve-3d;
    height: 100vh;
    overflow-x: hidden;
    overflow-y: scroll;
    background-color: $darker;
    a {
        &:link,
        &:visited,
        &:hover,
        &:active {
            color: white;
        }
    }
}

.content-container {
    position: relative;
    display: block;
    z-index: 1;
    background-color: $darker;
    min-height: 100vh;
}

.content {
    margin: 0 auto;
    padding: 75px 0;
}

.parallax-container {
    color: white;
    left: -9px;
    display: flex;
    flex: 1 0 auto;
    flex-direction: column;
    position: relative;
    z-index: -1;
    height: 100vh;
    width: 101vw;
    justify-content: center;
    align-items: center;
    transform: translateZ(-1px) scale(2);
    background: linear-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0.1));
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center center;
}

// NAVBAR
#top-navbar {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    font-size: 1rem;
    z-index: 30;
    line-height: 150%;
    background-color: rgba(33, 37, 41, 0.1);
    padding: 0 2.5vw;
    transition: transform 1s .3s ease;
    box-shadow: 0 1px 50px -28px $blue;
    &.dark {
        background: $darker;
    }
    &.dark-show {
        background: $darker;
    }
    &.scrollUp {
        transform: translateY(-100%);
    }
    * {
        color: #bbccdd !important;
        font-weight: 500;
    }
    .navbar-brand {
        font-size: 1.5rem;
        font-weight: 600;
        padding: 0;
    }
    .nav-item {
        text-transform: uppercase;
        padding: 0 8px;
        cursor: pointer;
        // &:hover:not(.dropdown) {
        //     background-color: rgba(33, 37, 41, 1);
        // }
        a:hover {
            color: white !important;
        }
    }
    .nav-link {
        margin: 10px 0;
        &.active {
            color: white !important;
            border-bottom: 1px solid white;
        }
    }
    .dropdown-menu {
        border-color: $blue;
        line-height: 2rem;
        background-color: rgba(0, 0, 0, 0.1);
        .dropdown-divider {
            margin: 0;
            border-top: 2px solid black;
        }
        .dropdown-item:hover {
            color: white;
            background-color: rgba(33, 37, 41, 0.1);
        }
    }
    .navbar-toggler {
        color: $blue;
    }
}

// HAMBURGER
#nav-icon {
    width: 30px;
    height: 30px;
    position: relative;
    margin: 0;
    -webkit-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    transform: rotate(0deg);
    -webkit-transition: .5s ease-in-out;
    -moz-transition: .5s ease-in-out;
    -o-transition: .5s ease-in-out;
    transition: .5s ease-in-out;
    cursor: pointer;
}

#nav-icon span {
    display: block;
    position: absolute;
    height: 3px;
    width: 100%;
    background: $blue;
    border-radius: 3px;
    opacity: 1;
    left: 0;
    -webkit-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    transform: rotate(0deg);
    -webkit-transition: .25s ease-in-out;
    -moz-transition: .25s ease-in-out;
    -o-transition: .25s ease-in-out;
    transition: .25s ease-in-out;
}

#nav-icon span:nth-child(1) {
    top: 1px;
}

#nav-icon span:nth-child(2),
#nav-icon span:nth-child(3) {
    top: 13px;
}

#nav-icon span:nth-child(4) {
    bottom: 0px;
}

#nav-icon.open span:nth-child(1) {
    top: 15px;
    width: 0%;
    left: 50%;
}

#nav-icon.open span:nth-child(2) {
    -webkit-transform: rotate(45deg);
    -moz-transform: rotate(45deg);
    -o-transform: rotate(45deg);
    transform: rotate(45deg);
}

#nav-icon.open span:nth-child(3) {
    -webkit-transform: rotate(-45deg);
    -moz-transform: rotate(-45deg);
    -o-transform: rotate(-45deg);
    transform: rotate(-45deg);
}

#nav-icon.open span:nth-child(4) {
    top: 15px;
    width: 0%;
    left: 50%;
}

// CONTENT
#page-content {
    height: 100vh !important;
    padding: 15vh 10vw 5vh 10vw;
    margin: 0;
}

.anchor {
    display: block;
    height: 15vh;
    margin-top: -15vh;
    visibility: hidden;
}

// MEDIA QUERIES
@media only screen and (min-device-width: 320px) and (max-device-width: 480px) {
    #sidebar {
        display: none;
    }
    #page-content {
        margin: 0;
    }
}

JS:

$(document).ready(function() {
    $('#sidebar').css('transform', 'translateX(200px)')
    $('#nav-icon').click(function() {
        // $(this).toggleClass('open');
        $('#top-navbar').toggleClass('dark-show');
    });
    $('.main-container').scroll(function() {
        let pageHeight = $('.main-container').height();
        $('#top-navbar').toggleClass('dark', $(this).scrollTop() > pageHeight);
        $('section').each(function(i) {
            var position = $(document).scrollTop();
            var header = $('#top-navbar').outerHeight();
            if ($(this).position().top <= (position + header)) {
                var top = $(this).position().top;
                console.log($(this).position().top <= (position + header));
                $(".nav-link.active").removeClass('active');
                $(".nav-link").eq(i).addClass('active');
            }
        })
    });
    $('.nav-link').on('click', function() {
        $('.nav-link').removeClass('active');
        $(this).addClass('active');
    });
});

document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function(e) {
        e.preventDefault();

        document.querySelector(this.getAttribute('href')).scrollIntoView({
            behavior: 'smooth'
        });
    });
});

let width = $(window).width();
let height = $(window).height();

if (height > width && height < 1024) {
    let position = $('#page-content').scrollTop();

    $('.main-container').scroll(function() {
        let scroll = $('.main-container').scrollTop();
        if (scroll > position) {
            $('#top-navbar').addClass('scrollUp');
        } else {
            $('#top-navbar').removeClass('scrollUp');
        }
        position = scroll;
    });
}

Link to jsfiddle: https://jsfiddle.net/strzesia/fhqok4ym/19/

Body:
You can use following css for navbar

.nav{
    position:absolute;
    left:0;
    top:0;
}


问:
Convolving Across Channels in Keras CNN: Conv1D, Depthwise Separable Conv, CCCP?
I am developing a CNN in keras to classify satellite imagery that has 10 spectral bands. I'm getting decent accuracy with the network below (~60% val accuracy across 15 classes) but I want to better incorporate the relationships between spectral bands at a single pixel which can yield a lot of information on the pixel's class. I see a lot of papers doing this but it is often called different things. For example:

Cascaded cross-channel parametric pooling

Conv1D

Depthwise Separable Convolution

Conv2D(num_filters, (1, 1))

And I'm not certain about the differences between these approaches (if there are any) and how I should implement this in my simple CNN below. I'm also not clear if I should do this at the very beginning or towards the end. I'm inclined to do it right at the start when the channels are still the raw spectral data rather than the feature maps.

```<code>input_shape = (32,32,10)
num_classes = 15

model = Sequential()
model.add(Conv2D(32, (3, 3), padding='same', input_shape=input_shape))
model.add(Activation('relu'))

model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Conv2D(64, (3, 3), padding='same'))
model.add(Activation('relu'))
model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Flatten())
model.add(Dense(256))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes))
model.add(Activation('softmax'))
</code>```

答:
Let me explain the operations you mentioned in a bit of detail so you understand the differences between their intuition and usage:

Cascaded cross-channel parametric pooling:

This is introduced in the Network-in-Network paper and is implemented in Keras as GlobalAveragePooling2D(). This operation averages over the output of each feature map in the previous layers.

It is a structural regularizer that enforces correspondence between feature maps
and categories, so feature maps can be interpreted as category confidence. It reduces parameter count and sums up spatial information and hence, it is more robust to spatial translations of the input.

GlobalAveragePooling2D() is generally used without Dense() layers in the model before it.

Conv1D:

Conv1D() is a convolution operation exactly similar to Conv2D() but it applies only to one dimension. Conv1D() is generally used on sequences or other 1D data, not as much on images.

Depthwise Separable Convolution:

Quoting from the Keras documentation

Separable convolutions consist in first performing a depthwise spatial convolution (which acts on each input channel separately) followed by a pointwise convolution which mixes together the resulting output channels. The depth_multiplier argument controls how many output channels are generated per input channel in the depthwise step.

This blog explains the depthwise separable convolution pretty well.

Conv2D(num_filters, (1, 1)):

This is generally known as 1x1 convolution, introduced in the Network-in-Network paper.

The 1x1 convolutional filters are used to reduce/increase dimensionality in the filter dimension, without affecting the spatial dimensions. This is also used in the Google Inception architecture for dimensionality reduction in filter space.

In your particular case, I am not exactly sure which of this techniques you can use. I do not think Conv1D would be of much use. You can definitely use GlobalMaxPooling or GlobalAveragePooling as long as you do not use Dense before them. This is helpful to get spatial information. Depthwise Separable Convolution can be used as well in place of your Conv2D layers. Conv2D(num_filters, (1, 1)) is very helpful for dimensionality reduction in filter space, mostly towards the end of your model architecture.

Maybe, if you follow the resources you get a better understanding of the operations and see how they apply to your problem.

Body:
I am developing a CNN in keras to classify satellite imagery that has 10 spectral bands. I'm getting decent accuracy with the network below (~60% val accuracy across 15 classes) but I want to better incorporate the relationships between spectral bands at a single pixel which can yield a lot of information on the pixel's class. I see a lot of papers doing this but it is often called different things. For example:

Cascaded cross-channel parametric pooling

Conv1D

Depthwise Separable Convolution

Conv2D(num_filters, (1, 1))

And I'm not certain about the differences between these approaches (if there are any) and how I should implement this in my simple CNN below. I'm also not clear if I should do this at the very beginning or towards the end. I'm inclined to do it right at the start when the channels are still the raw spectral data rather than the feature maps.

input_shape = (32,32,10)
num_classes = 15

model = Sequential()
model.add(Conv2D(32, (3, 3), padding='same', input_shape=input_shape))
model.add(Activation('relu'))

model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Conv2D(64, (3, 3), padding='same'))
model.add(Activation('relu'))
model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Flatten())
model.add(Dense(256))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes))
model.add(Activation('softmax'))


问:
When does image.setImageResource() set the image resource inside a function?
Goal: To click on an image in an app and get it to fade out to make a different image appear.

My Method: To make the 1st image fade away after 2000ms and AFTER THAT change the image resource of the 1st image to the 2nd image to make the 2nd image appear

I have a correct solution which was provided by my instructor, so I dont want any correct solution for this. What i want to know is why is my solution not working, i.e why is setImageResource() setting the Image1 to Image 2 at the beginning despite calling it at the end

This is the fade function i have created which the image1 goes to when it is clicked

public void fade(View view){

```<code>    ImageView image1 = findViewById(R.id.image1);
    image1.animate().alpha(0f).setDuration(2000);

    image1.setImageResource(R.drawable.cat2);
}
</code>```

Actual Output: Image 1 changes to Image 2 as soon as I click it and then Image 2 fades away

Problem: Inspite of calling setImageResource() at the end of the code, it actually sets the image resource at the beginning

答:
You are never telling image1.setImageResource(R.drawable.cat2); wait for 2000 millisecond and execute, So image2 appears as soon as you click it.

Solution:
Call image1.setImageResource(R.drawable.cat2); After 2000ms

```<code>   new Handler().postDelayed(() -> {
        image1.setImageResource(R.drawable.cat2);
        }, 2000);
</code>```

This may help.

Body:
Goal: To click on an image in an app and get it to fade out to make a different image appear.

My Method: To make the 1st image fade away after 2000ms and AFTER THAT change the image resource of the 1st image to the 2nd image to make the 2nd image appear

I have a correct solution which was provided by my instructor, so I dont want any correct solution for this. What i want to know is why is my solution not working, i.e why is setImageResource() setting the Image1 to Image 2 at the beginning despite calling it at the end

This is the fade function i have created which the image1 goes to when it is clicked

public void fade(View view){

    ImageView image1 = findViewById(R.id.image1);
    image1.animate().alpha(0f).setDuration(2000);

    image1.setImageResource(R.drawable.cat2);
}

Actual Output: Image 1 changes to Image 2 as soon as I click it and then Image 2 fades away

Problem: Inspite of calling setImageResource() at the end of the code, it actually sets the image resource at the beginning

Body:
You are never telling image1.setImageResource(R.drawable.cat2); wait for 2000 millisecond and execute, So image2 appears as soon as you click it.

Solution:
Call image1.setImageResource(R.drawable.cat2); After 2000ms

   new Handler().postDelayed(() -> {
        image1.setImageResource(R.drawable.cat2);
        }, 2000);

This may help.


问:
Error: "@angular/platform-browser/platform-browser" has no exported member 'DOCUMENT'
I Have updated Angular version from 7.1.3 to 8.0.0-rc.3 version.
After updating the version i am getting following error, during ng build --prod command:-
/@angular/platform-browser/platform-browser"' has no exported member 'DOCUMENT'.

Package.json

```<code>"devDependencies": {
"@angular/cli": "^8.0.0-rc.3",
"@angular/compiler-cli": "^8.0.0-rc.3",
"@angular/language-service": "^8.0.0-rc.3",
"@ngrx/schematics": "^6.1.2",
"@ngrx/store-devtools": "6.1.2",
"@nrwl/schematics": "7.5.2",
"@types/jasmine": "^3.3.12",
"@types/jasminewd2": "^2.0.6",
"@types/node": "^12.0.0",
"angular-tslint-rules": "^1.14.0",
"codelyzer": "^5.0.1",
"compodoc": "0.0.41",
"husky": "^0.14.3",
"jasmine-core": "^3.4.0",
"jasmine-marbles": "^0.3.1",
"jasmine-spec-reporter": "^4.2.1",
"karma": "^4.1.0",
"karma-chrome-launcher": "^2.2.0",
"karma-cli": "^2.0.0",
"karma-coverage-istanbul-reporter": "^1.4.3",
"karma-html-reporter": "^0.2.7",
"karma-jasmine": "^2.0.1",
"karma-jasmine-html-reporter": "^1.4.2",
"karma-junit-reporter": "^1.2.0",
"karma-phantomjs-launcher": "^1.0.4",
"lint-staged": "^7.3.0",
"ngrx-store-freeze": "0.2.4",
"prettier": "1.15.3",
"protractor": "^5.4.2",
"rxjs-tslint": "^0.1.7",
"ts-node": "~5.0.1",
"tslint": "^5.16.0",
"tslint-config-prettier": "^1.18.0",
"tslint-sonarts": "^1.9.0",
"tslint-teamcity-reporter": "^2.0.0",
"typescript": "^3.4.5"
 }
</code>```

Component file code is:-

```<code>import { DOCUMENT } from '@angular/platform-browser';
@Component({
selector: 'basic-dialog',
styleUrls: ['./dialog.component.scss'],
templateUrl: './dialog.component.html',
animations: [])
])
]
})
export class DialogComponent implements OnChanges, OnDestroy {
  constructor(@Inject(DOCUMENT) private document: Document, private
  renderer: Renderer2, private element: ElementRef) {}
}
</code>```

Angular team have deprecated 'DOCUMENT' from  @angular/animations.
Is there any way to deal with issue of getting document object.
Thanks in advance

答:
You are importing from the wrong module. It was depreciated from the platform-browser module a few years ago.

```<code>import {DOCUMENT} from '@angular/common';
</code>```

https://angular.io/api/common#types

Body:
I Have updated Angular version from 7.1.3 to 8.0.0-rc.3 version.
After updating the version i am getting following error, during ng build --prod command:-
/@angular/platform-browser/platform-browser"' has no exported member 'DOCUMENT'.

Package.json

"devDependencies": {
"@angular/cli": "^8.0.0-rc.3",
"@angular/compiler-cli": "^8.0.0-rc.3",
"@angular/language-service": "^8.0.0-rc.3",
"@ngrx/schematics": "^6.1.2",
"@ngrx/store-devtools": "6.1.2",
"@nrwl/schematics": "7.5.2",
"@types/jasmine": "^3.3.12",
"@types/jasminewd2": "^2.0.6",
"@types/node": "^12.0.0",
"angular-tslint-rules": "^1.14.0",
"codelyzer": "^5.0.1",
"compodoc": "0.0.41",
"husky": "^0.14.3",
"jasmine-core": "^3.4.0",
"jasmine-marbles": "^0.3.1",
"jasmine-spec-reporter": "^4.2.1",
"karma": "^4.1.0",
"karma-chrome-launcher": "^2.2.0",
"karma-cli": "^2.0.0",
"karma-coverage-istanbul-reporter": "^1.4.3",
"karma-html-reporter": "^0.2.7",
"karma-jasmine": "^2.0.1",
"karma-jasmine-html-reporter": "^1.4.2",
"karma-junit-reporter": "^1.2.0",
"karma-phantomjs-launcher": "^1.0.4",
"lint-staged": "^7.3.0",
"ngrx-store-freeze": "0.2.4",
"prettier": "1.15.3",
"protractor": "^5.4.2",
"rxjs-tslint": "^0.1.7",
"ts-node": "~5.0.1",
"tslint": "^5.16.0",
"tslint-config-prettier": "^1.18.0",
"tslint-sonarts": "^1.9.0",
"tslint-teamcity-reporter": "^2.0.0",
"typescript": "^3.4.5"
 }

Component file code is:-

import { DOCUMENT } from '@angular/platform-browser';
@Component({
selector: 'basic-dialog',
styleUrls: ['./dialog.component.scss'],
templateUrl: './dialog.component.html',
animations: [])
])
]
})
export class DialogComponent implements OnChanges, OnDestroy {
  constructor(@Inject(DOCUMENT) private document: Document, private
  renderer: Renderer2, private element: ElementRef) {}
}

Angular team have deprecated 'DOCUMENT' from  @angular/animations.
Is there any way to deal with issue of getting document object.
Thanks in advance

Body:
You are importing from the wrong module. It was depreciated from the platform-browser module a few years ago.

import {DOCUMENT} from '@angular/common';

https://angular.io/api/common#types


问:
The type Function is not generic; it cannot be parameterized with arguments <WebDriver, WebElement>
```<code>Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
    .withTimeout(Duration.ofSeconds(30))
    .pollingEvery(Duration.ofMillis(500))
    .ignoring(NoSuchElementException.class);

WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
    public WebElement apply(WebDriver driver) {
        return driver.findElement(By.name("q"));
    }
});
</code>```

Tried to work on Fluent wait implementation with Selenium 3.141.59 but getting the specified compile time error. I am mainly concerned with "new Function method"

The type FluentWait is not generic; it cannot be parameterized with arguments <WebDriver> error for FluentWait Class through Selenium and Java

I don't believe this is a duplicate. Question may sound the same but none of the solutions worked for me.

Error Shown:

```<code>The type Function is not generic; it cannot be parameterized with arguments <WebDriver, WebElement>
</code>```

答:
What are you actually trying to do with this explicit wait?

You could use a pre-defined Expected Condition:

```<code>wait.until(ExpectedConditions.presenceOfElementLocated(By.name("q")));
</code>```

The reason you are having problems is that you are trying to create a new instance of a Function which is an interface, you can't do that.  You could refactor the above ExpectedCondition into:

```<code>wait.until(new ExpectedCondition<WebElement>() {
    @Override
    public WebElement apply(WebDriver driver) {
        return driver.findElement(By.name("q"));
    }
});
</code>```

It looks quite close to your attempt, but it's not very readable or reusable.  I would suggest that you create your own helper class with your own expected conditions in that looks like the standard ExpectedConditions class supplied by Selenium.

Body:
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
    .withTimeout(Duration.ofSeconds(30))
    .pollingEvery(Duration.ofMillis(500))
    .ignoring(NoSuchElementException.class);

WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
    public WebElement apply(WebDriver driver) {
        return driver.findElement(By.name("q"));
    }
});

Tried to work on Fluent wait implementation with Selenium 3.141.59 but getting the specified compile time error. I am mainly concerned with "new Function method"

The type FluentWait is not generic; it cannot be parameterized with arguments <WebDriver> error for FluentWait Class through Selenium and Java

I don't believe this is a duplicate. Question may sound the same but none of the solutions worked for me.

Error Shown:

The type Function is not generic; it cannot be parameterized with arguments <WebDriver, WebElement>

Body:
What are you actually trying to do with this explicit wait?

You could use a pre-defined Expected Condition:

wait.until(ExpectedConditions.presenceOfElementLocated(By.name("q")));

The reason you are having problems is that you are trying to create a new instance of a Function which is an interface, you can't do that.  You could refactor the above ExpectedCondition into:

wait.until(new ExpectedCondition<WebElement>() {
    @Override
    public WebElement apply(WebDriver driver) {
        return driver.findElement(By.name("q"));
    }
});

It looks quite close to your attempt, but it's not very readable or reusable.  I would suggest that you create your own helper class with your own expected conditions in that looks like the standard ExpectedConditions class supplied by Selenium.


问:
Customize JSON created by CL_SXML_STRING_WRITER
I create JSON like this to extract any table (name "randomly" decided at runtime, its name is in variable iv_table_name):

```<code>FIELD-SYMBOLS <itab> TYPE STANDARD TABLE.
DATA ref_itab TYPE REF TO data.

DATA(iv_table_name) = 'SCARR'.
CREATE DATA ref_itab TYPE STANDARD TABLE OF (iv_table_name).
ASSIGN ref_itab->* TO <itab>.

SELECT *
  INTO TABLE <itab>
  FROM (iv_table_name).

DATA results_json TYPE TABLE OF string.
DATA sub_json TYPE string.

DATA(lo_json_writer) = cl_sxml_string_writer=>create( type = if_sxml=>co_xt_json ).

CALL TRANSFORMATION id
        SOURCE result = <itab>
        RESULT XML lo_json_writer.

cl_abap_conv_in_ce=>create( )->convert(
        EXPORTING
          input = lo_json_writer->get_output( )
        IMPORTING
          data = sub_json ).
</code>```

The result variable sub_json looks like this:

```<code>{"RESULT":
 [
   {"MANDT":"220","AUFNR":"0000012", ...},
   {"MANDT":"220","AUFNR":"0000013", ...},
   ...
  ]
}
</code>```

Is there a way to avoid the surrounding dictionary and get the result like this?

```<code> [
   {"MANDT":"220","AUFNR":"0000012", ...},
   {"MANDT":"220","AUFNR":"0000013", ...},
   ...
  ]
</code>```

Background:

I used this:

```<code>sub_json = /ui2/cl_json=>serialize( data = <lt_result> pretty_name = /ui2/cl_json=>pretty_mode-low_case ).
</code>```

But the performance of /ui2/cl_json=>serialize(  ) is not good.

答:
Just a bit of manual work and voila!

```<code>DATA(writer) = CAST if_sxml_writer( cl_sxml_string_writer=>create( type = if_sxml=>co_xt_json ) ).

DATA(components) =
CAST cl_abap_structdescr( cl_abap_typedescr=>describe_by_name( iv_table_name ) )->components.

writer->open_element( name = 'object' ).
LOOP AT <itab> ASSIGNING FIELD-SYMBOL(<line>).
 LOOP AT components ASSIGNING FIELD-SYMBOL(<fs_comp>).
  ASSIGN COMPONENT <fs_comp>-name OF STRUCTURE <line> TO FIELD-SYMBOL(<fs_val>).
  writer->open_element( name = 'str' ).
  writer->write_attribute( name = 'name' value = CONV string( <fs_comp>-name ) ).
  writer->write_value( CONV string( <fs_val> ) ).
  writer->close_element( ).
 ENDLOOP.
ENDLOOP.
writer->close_element( ).

DATA(xml_json) = CAST cl_sxml_string_writer( writer )->get_output(  ).
sub_json = cl_abap_codepage=>convert_from( source = xml_json codepage = `UTF-8` ).
</code>```

No surrounding list and no dictionary. If you wanna each line in separate dictionary it is easily adjustable.

Body:
I create JSON like this to extract any table (name "randomly" decided at runtime, its name is in variable iv_table_name):

FIELD-SYMBOLS <itab> TYPE STANDARD TABLE.
DATA ref_itab TYPE REF TO data.

DATA(iv_table_name) = 'SCARR'.
CREATE DATA ref_itab TYPE STANDARD TABLE OF (iv_table_name).
ASSIGN ref_itab->* TO <itab>.

SELECT *
  INTO TABLE <itab>
  FROM (iv_table_name).

DATA results_json TYPE TABLE OF string.
DATA sub_json TYPE string.

DATA(lo_json_writer) = cl_sxml_string_writer=>create( type = if_sxml=>co_xt_json ).

CALL TRANSFORMATION id
        SOURCE result = <itab>
        RESULT XML lo_json_writer.

cl_abap_conv_in_ce=>create( )->convert(
        EXPORTING
          input = lo_json_writer->get_output( )
        IMPORTING
          data = sub_json ).

The result variable sub_json looks like this:

{"RESULT":
 [
   {"MANDT":"220","AUFNR":"0000012", ...},
   {"MANDT":"220","AUFNR":"0000013", ...},
   ...
  ]
}

Is there a way to avoid the surrounding dictionary and get the result like this?

 [
   {"MANDT":"220","AUFNR":"0000012", ...},
   {"MANDT":"220","AUFNR":"0000013", ...},
   ...
  ]

Background:

I used this:

sub_json = /ui2/cl_json=>serialize( data = <lt_result> pretty_name = /ui2/cl_json=>pretty_mode-low_case ).

But the performance of /ui2/cl_json=>serialize(  ) is not good.

Body:
Just a bit of manual work and voila!

DATA(writer) = CAST if_sxml_writer( cl_sxml_string_writer=>create( type = if_sxml=>co_xt_json ) ).

DATA(components) =
CAST cl_abap_structdescr( cl_abap_typedescr=>describe_by_name( iv_table_name ) )->components.

writer->open_element( name = 'object' ).
LOOP AT <itab> ASSIGNING FIELD-SYMBOL(<line>).
 LOOP AT components ASSIGNING FIELD-SYMBOL(<fs_comp>).
  ASSIGN COMPONENT <fs_comp>-name OF STRUCTURE <line> TO FIELD-SYMBOL(<fs_val>).
  writer->open_element( name = 'str' ).
  writer->write_attribute( name = 'name' value = CONV string( <fs_comp>-name ) ).
  writer->write_value( CONV string( <fs_val> ) ).
  writer->close_element( ).
 ENDLOOP.
ENDLOOP.
writer->close_element( ).

DATA(xml_json) = CAST cl_sxml_string_writer( writer )->get_output(  ).
sub_json = cl_abap_codepage=>convert_from( source = xml_json codepage = `UTF-8` ).

No surrounding list and no dictionary. If you wanna each line in separate dictionary it is easily adjustable.


Title: Why different string is matching to the pattern?

Body:
You need to remove space from character class

\\d{1,2}[- /.]\\d{1,2}[- /.]\\d{4}
           ^             ^

change to this

\\d{1,2}[-/.]\\d{1,2}[-/.]\\d{4}


问:
istio - using vs service and gw instead loadbalancer not working
I’ve the following application which Im able to run in K8S successfully which using service with type load balancer, very simple app with two routes

/ - you should see 'hello application`

/api/books should provide list of book in json format

This is the service

```<code>apiVersion: v1
kind: Service
metadata:
  name: go-ms
  labels:
    app: go-ms
    tier: service
spec:
  type: LoadBalancer
  ports:
    - port: 8080
  selector:
    app: go-ms
</code>```

This is the deployment

```<code>
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: go-ms
  labels:
    app: go-ms

spec:
  replicas: 2
  template:
    metadata:
      labels:
        app: go-ms
        tier: service

    spec:
      containers:
        - name: go-ms
          image: rayndockder/http:0.0.2
          ports:
            - containerPort: 8080
          env:
            - name: PORT
              value: "8080"
          resources:
            requests:
              memory: "64Mi"
              cpu: "125m"
            limits:
              memory: "128Mi"
              cpu: "250m"

</code>```

after applied the both yamls and when calling the URL:

http://b0751-1302075110.eu-central-1.elb.amazonaws.com/api/books

I was able to see the data in the browser as expected and also for the root app using just the external ip

Now I want to use istio, so I follow the guide and install it successfully via helm
using https://istio.io/docs/setup/kubernetes/install/helm/ and verify that all the 53 crd are there and also istio-system
 components (such as istio-ingressgateway
istio-pilot etc all 8 deployments are in up and running)

I’ve change the service above from LoadBalancer to NodePort

and create the following istio config according to the istio docs

```<code>apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
  name: http-gateway
spec:
  selector:
    istio: ingressgateway
  servers:
    - port:
        number: 8080
        name: http
        protocol: HTTP
      hosts:
        - "*"
---

apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: virtualservice
spec:
  hosts:
    - "*"
  gateways:
    - http-gateway
  http:
  - match:
      - uri:
          prefix: "/"
      - uri:
          exact: "/api/books"
    route:
      - destination:
          port:
            number: 8080
          host: go-ms
</code>```

in addition I’ve added the following

kubectl label namespace books istio-injection=enabled where the application is deployed,

Now to get the external Ip i've used command

kubectl get svc -n istio-system -l istio=ingressgateway

and get this in the external-ip

b0751-1302075110.eu-central-1.elb.amazonaws.com
when trying to access to the URL

http://b0751-1302075110.eu-central-1.elb.amazonaws.com/api/books

I got error:

This site can’t be reached

ERR_CONNECTION_TIMED_OUT

if I run the docker rayndockder/http:0.0.2 via
docker run -it -p 8080:8080 httpv2

I path's works correctly!

Any idea/hint What could be the issue ?

Is there a way to trace the istio configs to see whether if something is missing or we have some collusion with port or network policy maybe ?

btw, the deployment and service can run on each cluster for testing of someone could help...

if I change all to port to 80 (in all yaml files and the application and the docker ) I was able to get the data for the root path, but not for "api/books"

答:
I tired your config with the modification of gateway port to 80 from 8080 in my local minikube setup of kubernetes and istio. This is the command I used:

```<code>kubectl apply -f - <<EOF
apiVersion: v1
kind: Service
metadata:
  name: go-ms
  labels:
    app: go-ms
    tier: service
spec:
  ports:
    - port: 8080
  selector:
    app: go-ms
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: go-ms
  labels:
    app: go-ms

spec:
  replicas: 2
  template:
    metadata:
      labels:
        app: go-ms
        tier: service

    spec:
      containers:
        - name: go-ms
          image: rayndockder/http:0.0.2
          ports:
            - containerPort: 8080
          env:
            - name: PORT
              value: "8080"
          resources:
            requests:
              memory: "64Mi"
              cpu: "125m"
            limits:
              memory: "128Mi"
              cpu: "250m"
---
apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
  name: http-gateway
spec:
  selector:
    istio: ingressgateway
  servers:
    - port:
        number: 80
        name: http
        protocol: HTTP
      hosts:
        - "*"
---
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: go-ms-virtualservice
spec:
  hosts:
     - "*"
  gateways:
    - http-gateway
  http:
  - match:
      - uri:
          prefix: /
      - uri:
          exact: /api/books
    route:
      - destination:
          port:
            number: 8080
          host: go-ms
EOF
</code>```

The reason that I changed the gateway port to 80 is that, the istio ingress gateway by default opens up a few ports such as 80, 443 and few others. In my case, as minikube doesn't have an external load balancer, I used node ports which is 31380 in my case.

I was able to access the app with url of http://$(minikube ip):31380.

There is no point in changing the port of services, deployments since these are application specific.

May be this question specifies the ports opened by istio ingress gateway.

Body:
I’ve the following application which Im able to run in K8S successfully which using service with type load balancer, very simple app with two routes

/ - you should see 'hello application`

/api/books should provide list of book in json format

This is the service

apiVersion: v1
kind: Service
metadata:
  name: go-ms
  labels:
    app: go-ms
    tier: service
spec:
  type: LoadBalancer
  ports:
    - port: 8080
  selector:
    app: go-ms

This is the deployment

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: go-ms
  labels:
    app: go-ms

spec:
  replicas: 2
  template:
    metadata:
      labels:
        app: go-ms
        tier: service

    spec:
      containers:
        - name: go-ms
          image: rayndockder/http:0.0.2
          ports:
            - containerPort: 8080
          env:
            - name: PORT
              value: "8080"
          resources:
            requests:
              memory: "64Mi"
              cpu: "125m"
            limits:
              memory: "128Mi"
              cpu: "250m"

after applied the both yamls and when calling the URL:

http://b0751-1302075110.eu-central-1.elb.amazonaws.com/api/books

I was able to see the data in the browser as expected and also for the root app using just the external ip

Now I want to use istio, so I follow the guide and install it successfully via helm
using https://istio.io/docs/setup/kubernetes/install/helm/ and verify that all the 53 crd are there and also istio-system
 components (such as istio-ingressgateway
istio-pilot etc all 8 deployments are in up and running)

I’ve change the service above from LoadBalancer to NodePort

and create the following istio config according to the istio docs

apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
  name: http-gateway
spec:
  selector:
    istio: ingressgateway
  servers:
    - port:
        number: 8080
        name: http
        protocol: HTTP
      hosts:
        - "*"
---

apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: virtualservice
spec:
  hosts:
    - "*"
  gateways:
    - http-gateway
  http:
  - match:
      - uri:
          prefix: "/"
      - uri:
          exact: "/api/books"
    route:
      - destination:
          port:
            number: 8080
          host: go-ms

in addition I’ve added the following

kubectl label namespace books istio-injection=enabled where the application is deployed,

Now to get the external Ip i've used command

kubectl get svc -n istio-system -l istio=ingressgateway

and get this in the external-ip

b0751-1302075110.eu-central-1.elb.amazonaws.com
when trying to access to the URL

http://b0751-1302075110.eu-central-1.elb.amazonaws.com/api/books

I got error:

This site can’t be reached

ERR_CONNECTION_TIMED_OUT

if I run the docker rayndockder/http:0.0.2 via
docker run -it -p 8080:8080 httpv2

I path's works correctly!

Any idea/hint What could be the issue ?

Is there a way to trace the istio configs to see whether if something is missing or we have some collusion with port or network policy maybe ?

btw, the deployment and service can run on each cluster for testing of someone could help...

if I change all to port to 80 (in all yaml files and the application and the docker ) I was able to get the data for the root path, but not for "api/books"

Body:
I tired your config with the modification of gateway port to 80 from 8080 in my local minikube setup of kubernetes and istio. This is the command I used:

kubectl apply -f - <<EOF
apiVersion: v1
kind: Service
metadata:
  name: go-ms
  labels:
    app: go-ms
    tier: service
spec:
  ports:
    - port: 8080
  selector:
    app: go-ms
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: go-ms
  labels:
    app: go-ms

spec:
  replicas: 2
  template:
    metadata:
      labels:
        app: go-ms
        tier: service

    spec:
      containers:
        - name: go-ms
          image: rayndockder/http:0.0.2
          ports:
            - containerPort: 8080
          env:
            - name: PORT
              value: "8080"
          resources:
            requests:
              memory: "64Mi"
              cpu: "125m"
            limits:
              memory: "128Mi"
              cpu: "250m"
---
apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
  name: http-gateway
spec:
  selector:
    istio: ingressgateway
  servers:
    - port:
        number: 80
        name: http
        protocol: HTTP
      hosts:
        - "*"
---
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: go-ms-virtualservice
spec:
  hosts:
     - "*"
  gateways:
    - http-gateway
  http:
  - match:
      - uri:
          prefix: /
      - uri:
          exact: /api/books
    route:
      - destination:
          port:
            number: 8080
          host: go-ms
EOF

The reason that I changed the gateway port to 80 is that, the istio ingress gateway by default opens up a few ports such as 80, 443 and few others. In my case, as minikube doesn't have an external load balancer, I used node ports which is 31380 in my case.

I was able to access the app with url of http://$(minikube ip):31380.

There is no point in changing the port of services, deployments since these are application specific.

May be this question specifies the ports opened by istio ingress gateway.


问:
ReactJS - Calling a components method from another component?
Is it possible to call a method on another component?

I have created that needs to be toggled either on click, or when a certain event happens.

For example I've created a React component that functions as a play button on a media player. I use LottieJS and bodymovin to animate the SVG button. If the song is playing the button shows a pause symbol. If the song is stopped it shows a play symbol.

Here's my PlayButton component ...

```<code>import React from 'react';
import Lottie from 'react-lottie';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import * as animationData from './button.json';

const Button = styled.button`
    cursor: pointer;
    outline: none;
    border: none;
    background: none;
    display: block;
    float: left;
    width: 10%;
    margin-top: 27px;
`;

export default class PlayButton extends React.Component {
    static propTypes = {
        onClick: PropTypes.func.isRequired,
    }

    static defaultProps = {
        onClick: () => {}
    }

    state = {
        isStopped: true,
        direction: 1,
        speed: 3,
    }

    toggle = () => {
        const {isStopped, direction} = this.state;
        if (!isStopped) {
          this.setState({direction: direction * -1})
        }
        this.setState({isStopped: false});
        this.props.onclick();
    }

    render() {
        const defaultOptions = {
            loop: false,
            autoplay: false,
            animationData: animationData,
            rendererSettings: {
                preserveAspectRatio: 'xMidYMid slice',
            },
        };

        return (
            <Button onClick={this.toggle}>
                <Lottie
                    options={defaultOptions}
                    isStopped={this.state.isStopped}
                    speed={this.state.speed}
                    direction={this.state.direction}
                />
            </Button>
        )
    }
}
</code>```

I render like so:

```<code><PlayButton onclick={this.playButtonClicked} />
</code>```

When the button is clicked it will toggle the SVG animation using LottieJS.

I need to call toggle so that when the track has reached the end the play button will toggle from playing, to stopped. Is this possible at all?

Normally I wouldn't have this problem if I was using non animated SVG's. I would just display a CSS background-image depending on the state. But because this is a toggle animation I'm not sure how to go about this.

答:
class AAA extend React.Component {

    static call_this() {
      return 'Hello World';
    }

   // ...
}

class BBB extend React.Component {
    //...

   render() {

    AAA.call_this(); // return  'Hello World'

   }

}```

but remember you can't access this keyword inside static method.

Body:
Is it possible to call a method on another component?

I have created that needs to be toggled either on click, or when a certain event happens.

For example I've created a React component that functions as a play button on a media player. I use LottieJS and bodymovin to animate the SVG button. If the song is playing the button shows a pause symbol. If the song is stopped it shows a play symbol.

Here's my PlayButton component ...

import React from 'react';
import Lottie from 'react-lottie';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import * as animationData from './button.json';

const Button = styled.button`
    cursor: pointer;
    outline: none;
    border: none;
    background: none;
    display: block;
    float: left;
    width: 10%;
    margin-top: 27px;
`;

export default class PlayButton extends React.Component {
    static propTypes = {
        onClick: PropTypes.func.isRequired,
    }

    static defaultProps = {
        onClick: () => {}
    }

    state = {
        isStopped: true,
        direction: 1,
        speed: 3,
    }

    toggle = () => {
        const {isStopped, direction} = this.state;
        if (!isStopped) {
          this.setState({direction: direction * -1})
        }
        this.setState({isStopped: false});
        this.props.onclick();
    }

    render() {
        const defaultOptions = {
            loop: false,
            autoplay: false,
            animationData: animationData,
            rendererSettings: {
                preserveAspectRatio: 'xMidYMid slice',
            },
        };

        return (
            <Button onClick={this.toggle}>
                <Lottie
                    options={defaultOptions}
                    isStopped={this.state.isStopped}
                    speed={this.state.speed}
                    direction={this.state.direction}
                />
            </Button>
        )
    }
}

I render like so:

<PlayButton onclick={this.playButtonClicked} />

When the button is clicked it will toggle the SVG animation using LottieJS.

I need to call toggle so that when the track has reached the end the play button will toggle from playing, to stopped. Is this possible at all?

Normally I wouldn't have this problem if I was using non animated SVG's. I would just display a CSS background-image depending on the state. But because this is a toggle animation I'm not sure how to go about this.

Body:
class AAA extend React.Component {

    static call_this() {
      return 'Hello World';
    }

   // ...
}

class BBB extend React.Component {
    //...

   render() {

    AAA.call_this(); // return  'Hello World'

   }

}

but remember you can't access this keyword inside static method.


答:
Using a list comprehension, where you iterate over the list of dictionaries and collect the value for each interface, example for GigabitEthernet

```<code>
dct = {
"Cisco-IOS-XE-native:interface": {
    "GigabitEthernet": [
        {
            "name": "1",
            "description": "DON'T TOUCH ME",
            "isis": {
                "Cisco-IOS-XE-isis:metric": {
                    "value": 2
             }}

        },
        {
            "name": "2",
            "isis": {
                "Cisco-IOS-XE-isis:metric": {
                    "value": 4
                }}

        },
        {
            "name": "3",
            "shutdown": [
                None
            ],
            "isis": {
                "Cisco-IOS-XE-isis:metric": {
                    "value": 7
                }}
        }
    ]}}

result = [item['isis']["Cisco-IOS-XE-isis:metric"]['value'] for item in dct['Cisco-IOS-XE-native:interface']['GigabitEthernet']]
</code>```

The output will be

```<code>[2, 4, 7]
</code>```

Or to collect values for all interfaces, you can loop over the interfaces and collect the value for each interface

```<code>interfaces = ['GigabitEthernet', 'Loopback', 'Tunnel']
result = [item['isis']["Cisco-IOS-XE-isis:metric"]['value'] for interface in interfaces for item in dct['Cisco-IOS-XE-native:interface'][interface]]
print(result)
</code>```

The output will be

```<code>[2, 4, 7, 1, 3]
</code>```

Title: Get a specific value in JSON and Python

Body:
I'm getting a JSON data from RESTCONF HTTPS request, using the following code.

https_request = 'https://' + host + '/restconf/data/Cisco-IOS-XE-native:native/interface/'
headers = {'Content-type': 'application/yang-data+json', 'Accept': 'application/yang-data+json'}
r = requests.get(https_request, auth=(user, password), headers=headers, verify=False)
print r.json()

The JSON file I got:

{
"Cisco-IOS-XE-native:interface": {
    "GigabitEthernet": [
        {
            "name": "1",
            "description": "DON'T TOUCH ME",
            "isis": {
                "Cisco-IOS-XE-isis:metric": {
                    "value": 2
             }
            ....
        },
        {
            "name": "2",
            "isis": {
                "Cisco-IOS-XE-isis:metric": {
                    "value": 4
                } ....

        },
        {
            "name": "3",
            "shutdown": [
                null
            ],
            "isis": {
                "Cisco-IOS-XE-isis:metric": {
                    "value": 7
                }....
        }
    ],
    "Loopback": [
        {
            "name": 0,
            "isis": {
                "Cisco-IOS-XE-isis:metric": {
                    "value": 1
                }
    ],
    "Tunnel": [
        {
            "name": 0,
            "isis": {
                "Cisco-IOS-XE-isis:metric": {
                    "value": 3
                }....
            }
    ]
}

Basically, I want my function to return the field's "value" of isis of each interface. I tried the following code for GigabitEthernet:

value = r.json()['Cisco-IOS-XE-native:interface']['GigabitEthernet'][0]['isis']['metric']['value']

I got this error:

print Router_1.get_isis_metric()['Cisco-IOS-XE-native:interface']['GigabitEthernet'][0]['isis']['metric']['isis']
KeyError: 'metric'

Body:
Using a list comprehension, where you iterate over the list of dictionaries and collect the value for each interface, example for GigabitEthernet

dct = {
"Cisco-IOS-XE-native:interface": {
    "GigabitEthernet": [
        {
            "name": "1",
            "description": "DON'T TOUCH ME",
            "isis": {
                "Cisco-IOS-XE-isis:metric": {
                    "value": 2
             }}

        },
        {
            "name": "2",
            "isis": {
                "Cisco-IOS-XE-isis:metric": {
                    "value": 4
                }}

        },
        {
            "name": "3",
            "shutdown": [
                None
            ],
            "isis": {
                "Cisco-IOS-XE-isis:metric": {
                    "value": 7
                }}
        }
    ]}}

result = [item['isis']["Cisco-IOS-XE-isis:metric"]['value'] for item in dct['Cisco-IOS-XE-native:interface']['GigabitEthernet']]

The output will be

[2, 4, 7]

Or to collect values for all interfaces, you can loop over the interfaces and collect the value for each interface

interfaces = ['GigabitEthernet', 'Loopback', 'Tunnel']
result = [item['isis']["Cisco-IOS-XE-isis:metric"]['value'] for interface in interfaces for item in dct['Cisco-IOS-XE-native:interface'][interface]]
print(result)

The output will be

[2, 4, 7, 1, 3]


问:
lein repl zip file is empty exception
I get the error messages when I enter lein repl in my project root folder. I have tried to delete the .lein directory in home folder and redownload lein but it doesn't work for me.

possible duplicate:
ExceptionInInitializerError when using leiningen

```<code>Exception in thread "Thread-1" java.util.zip.ZipException: zip file is empty
at java.util.zip.ZipFile.open(Native Method)
at java.util.zip.ZipFile.<init>(ZipFile.java:214)
at java.util.zip.ZipFile.<init>(ZipFile.java:144)
at java.util.jar.JarFile.<init>(JarFile.java:153)
at java.util.jar.JarFile.<init>(JarFile.java:117)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at clojure.lang.Reflector.invokeConstructor(Reflector.java:180)
at leiningen.core.classpath$extract_native_deps.invoke(classpath.clj:43)
at clojure.lang.AFn.applyToHelper(AFn.java:167)
at clojure.lang.AFn.applyTo(AFn.java:151)
at clojure.core$apply.invoke(core.clj:617)
at leiningen.core.classpath$when_stale.doInvoke(classpath.clj:66)
at clojure.lang.RestFn.invoke(RestFn.java:580)
at leiningen.core.classpath$resolve_dependencies.doInvoke(classpath.clj:231)
at clojure.lang.RestFn.invoke(RestFn.java:425)
at leiningen.core.eval$prep.invoke(eval.clj:54)
at leiningen.core.eval$eval_in_project.invoke(eval.clj:282)
at leiningen.repl$start_server.invoke(repl.clj:117)
at leiningen.repl$server$fn__6110.invoke(repl.clj:173)
at clojure.lang.AFn.applyToHelper(AFn.java:159)
at clojure.lang.AFn.applyTo(AFn.java:151)
at clojure.core$apply.invoke(core.clj:617)
at clojure.core$with_bindings_STAR_.doInvoke(core.clj:1788)
at clojure.lang.RestFn.invoke(RestFn.java:425)
at clojure.lang.AFn.applyToHelper(AFn.java:163)
at clojure.lang.RestFn.applyTo(RestFn.java:132)
at clojure.core$apply.invoke(core.clj:621)
at clojure.core$bound_fn_STAR_$fn__4102.doInvoke(core.clj:1810)
at clojure.lang.RestFn.invoke(RestFn.java:397)
at clojure.lang.AFn.run(AFn.java:24)
at java.lang.Thread.run(Thread.java:722)
</code>```

Edit:
I'm running leiningen 2.1.2 on ubuntu 12.10 64bit machine.

Note: If I run lein repl outside my project root folder, it is fine.

答:
this is because you can't name your uberjar the same as the jar file named internally by leiningen.
just make sure you add something like "name-0.1.0-STABLE" or anything else like SNAPSHOT or LATEST to your :uberjar ... :uberjar-name.

Title: lein repl zip file is empty exception

Body:
I get the error messages when I enter lein repl in my project root folder. I have tried to delete the .lein directory in home folder and redownload lein but it doesn't work for me.

possible duplicate:
ExceptionInInitializerError when using leiningen

Exception in thread "Thread-1" java.util.zip.ZipException: zip file is empty
at java.util.zip.ZipFile.open(Native Method)
at java.util.zip.ZipFile.<init>(ZipFile.java:214)
at java.util.zip.ZipFile.<init>(ZipFile.java:144)
at java.util.jar.JarFile.<init>(JarFile.java:153)
at java.util.jar.JarFile.<init>(JarFile.java:117)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at clojure.lang.Reflector.invokeConstructor(Reflector.java:180)
at leiningen.core.classpath$extract_native_deps.invoke(classpath.clj:43)
at clojure.lang.AFn.applyToHelper(AFn.java:167)
at clojure.lang.AFn.applyTo(AFn.java:151)
at clojure.core$apply.invoke(core.clj:617)
at leiningen.core.classpath$when_stale.doInvoke(classpath.clj:66)
at clojure.lang.RestFn.invoke(RestFn.java:580)
at leiningen.core.classpath$resolve_dependencies.doInvoke(classpath.clj:231)
at clojure.lang.RestFn.invoke(RestFn.java:425)
at leiningen.core.eval$prep.invoke(eval.clj:54)
at leiningen.core.eval$eval_in_project.invoke(eval.clj:282)
at leiningen.repl$start_server.invoke(repl.clj:117)
at leiningen.repl$server$fn__6110.invoke(repl.clj:173)
at clojure.lang.AFn.applyToHelper(AFn.java:159)
at clojure.lang.AFn.applyTo(AFn.java:151)
at clojure.core$apply.invoke(core.clj:617)
at clojure.core$with_bindings_STAR_.doInvoke(core.clj:1788)
at clojure.lang.RestFn.invoke(RestFn.java:425)
at clojure.lang.AFn.applyToHelper(AFn.java:163)
at clojure.lang.RestFn.applyTo(RestFn.java:132)
at clojure.core$apply.invoke(core.clj:621)
at clojure.core$bound_fn_STAR_$fn__4102.doInvoke(core.clj:1810)
at clojure.lang.RestFn.invoke(RestFn.java:397)
at clojure.lang.AFn.run(AFn.java:24)
at java.lang.Thread.run(Thread.java:722)

Edit:
I'm running leiningen 2.1.2 on ubuntu 12.10 64bit machine.

Note: If I run lein repl outside my project root folder, it is fine.