问:
How to remove string until the end of line from a file in Python?
I am trying to remove the comments from codes saved in Text files and I have tried everything but haven't been able to do anything about it. I tried this RegEx - //[^\\n]{0,} which should've worked theoretically but It didn't.

This is the content of the text file:

```<code>#include<iostream>
using namespace std;
int main(){
    int a=0;
    cout << a; //Hello World
    return 0;
}
</code>```

And this is what I want the output file to contain:

```<code>#include<iostream>
using namespace std;
int main(){
    int a=0;
    cout << a;
    return 0;
}
</code>```

As you can see, I want the output to be free of any comments in the file.

答:
Something like this:

```<code>strng = ''' using namespace std;
int main(){
    int a=0;
    cout << a; //Hello World
    return 0;
}'''

pattern = r'(//.+)'
s = re.sub(pattern,'',strng)
print(s)
</code>```

Output:

```<code>using namespace std;
int main(){
    int a=0;
    cout << a;
    return 0;
}
</code>```

Body:
I am trying to remove the comments from codes saved in Text files and I have tried everything but haven't been able to do anything about it. I tried this RegEx - //[^\\n]{0,} which should've worked theoretically but It didn't.

This is the content of the text file:

#include<iostream>
using namespace std;
int main(){
    int a=0;
    cout << a; //Hello World
    return 0;
}

And this is what I want the output file to contain:

#include<iostream>
using namespace std;
int main(){
    int a=0;
    cout << a;
    return 0;
}

As you can see, I want the output to be free of any comments in the file.

Body:
Something like this:

strng = ''' using namespace std;
int main(){
    int a=0;
    cout << a; //Hello World
    return 0;
}'''

pattern = r'(//.+)'
s = re.sub(pattern,'',strng)
print(s)

Output:

using namespace std;
int main(){
    int a=0;
    cout << a;
    return 0;
}


来源: stackexchange

问:
SQL get all raw base GROUP BY
I have table with 3 columns: id, frame and size.

I want to write query that get the id of the max size per frame.

I tried:

```<code>SELECT frame, MAX(size) FROM table1 GROUP BY frame
</code>```

I get:

```<code>    frame    |    size
      0      |     9.5
      1      |    10.6
</code>```

but how can I get the id also with the result?

答:
You can do it this way:

SELECT
    id,
    frame,
    size
from table1
WHERE (frame, size) IN (
    SELECT
        frame,
        MAX(size) as size
    FROM table1
    GROUP BY frame
    )
```

ContentLicense: CC BY-SA 4.0

Title: SQL get all raw base GROUP BY

Body:
I have table with 3 columns: id, frame and size.

I want to write query that get the id of the max size per frame.

I tried:

SELECT frame, MAX(size) FROM table1 GROUP BY frame

I get:

    frame    |    size
      0      |     9.5
      1      |    10.6

but how can I get the id also with the result?


问:
App installation date using Flurry Api
I wanted to know is it possible register App installation date using Flurry Api ?</p>

答: iPhone doesn't spool up the software when its installed, so no, I don't think you will get that data. The Second time its used, you should receive data on the first time it was run though.</p>

ContentLicense: CC BY-SA 3.0

Title: App installation date using Flurry Api


问:
Insert two new rows with unique IDs and Values for each Department in SQL table
I have a number of departments, each of which have multiple staff members in them. For each of the departments, I need to add two extra staff members (Vacancy Positions).

I know I could manually type in:

```<code>INSERT INTO table
VALUES(value1,value2,...)
</code>```

But i was wondering if there is code that might be able to iterate through each department, and for each add in two vacancy rows.

An example of how my data might look is:

So for each of those departments, I would need an extra two vacancy positions.

To make it even more complicated, they would need 8 digit unique ID numbers that would increase by 1 for each new person; something like 00000001, 00000002, 00000003 and so on, despite being in different departments. This means that they can't be confused with any actual staff, but that they have an ID, which is required being able to edit that person in my front end system (powerapps)

Is this something that is possible, or should i just create a number of different INSERT INTO queries?

答:
You can use insert . . . select.  Something like this:

```<code>insert into t(year, department, staffname, . . )
    select distinct 2020, department, 'newstaff_1',
           format(row_number() over (order by department), '00000000') as id, . . .
    from t
    union all
    select distinct 2020, department, 'newstaff_2',
           format(row_number() over (order by department), '00000000') as id, . . .
    from t;
</code>```

I'm not sure what the id is supposed to be, but the above seems to fit into what you describe.

This uses SQL Server syntax for constructing an 8-character number.

Body:
I have a number of departments, each of which have multiple staff members in them. For each of the departments, I need to add two extra staff members (Vacancy Positions).

I know I could manually type in:

INSERT INTO table
VALUES(value1,value2,...)

But i was wondering if there is code that might be able to iterate through each department, and for each add in two vacancy rows.

An example of how my data might look is:

So for each of those departments, I would need an extra two vacancy positions.

To make it even more complicated, they would need 8 digit unique ID numbers that would increase by 1 for each new person; something like 00000001, 00000002, 00000003 and so on, despite being in different departments. This means that they can't be confused with any actual staff, but that they have an ID, which is required being able to edit that person in my front end system (powerapps)

Is this something that is possible, or should i just create a number of different INSERT INTO queries?

Body:
You can use insert . . . select.  Something like this:

insert into t(year, department, staffname, . . )
    select distinct 2020, department, 'newstaff_1',
           format(row_number() over (order by department), '00000000') as id, . . .
    from t
    union all
    select distinct 2020, department, 'newstaff_2',
           format(row_number() over (order by department), '00000000') as id, . . .
    from t;

I'm not sure what the id is supposed to be, but the above seems to fit into what you describe.

This uses SQL Server syntax for constructing an 8-character number.


问:
How to prevent words from overflowing when cloning and wrapping lines?
I'm having a problem with a coding example I found at Wrap each line of paragraph in a span. Basically it clones text in a div and outputs the text wrapped in a span in another div.

The problem I'm having is that during the cloning process, words get cut off because the length of the word goes over the width that's set in CSS.

Example:

```<code><span>I’m up to something. Learning is cool, bu</span>
<span>t knowing is better, and I know the key t</span>
</code>```

Is there anyway to get words to not overflow? I've try setting overflow:auto in css and it won't recognize it.

function trimByPixel(str, width) {
  var spn = $('').text(str).appendTo('body');
  var txt = str;
  while (spn.width() > width) { txt = txt.slice(0, -1); spn.text(txt + "..."); }
  return txt;
}

var stri = $(".str").text();

function run(){
var s = trimByPixel(stri, $(".str").width()).trim()
stri = stri.replace(s,"")
$(".result").append(""+s+"");

if(stri.trim().length > 0){
  run();
}
}

run();
$(".str").remove().delay(10);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.str{
  width:300px;
  }

  .result span{
  display:block
  }</code>```

I’m up to something. Learning is cool, but knowing is better, and I know the key to success. Bless up. They never said winning was easy. Some people can’t handle success, I can.
I told you all this before, when you have a swimming pool, do not use chlorine, use salt water, the healing, salt water is the healing. Put it this way, it took me twenty five years to get these plants, twenty five years of blood sweat and tears, and I’m never giving up, I’m just getting started.

```

答:
The problem is the trimByPixel() function which just checks if a string is small enough to fit a given width but doesn't care if it's right in the middle of a word.

To know if we're going to cut-off a word, we can check what character the last character inside the string actually is. So for simplicity we can check if it's an empty space and in case it is, cutting off is fine. A more sophisticated test could check if it's a character from a-z A-Z 0-9.

```<code>while (spn.width() > width || txt.charAt(txt.length-1)!=" ")
</code>```

Body:
I'm having a problem with a coding example I found at Wrap each line of paragraph in a span. Basically it clones text in a div and outputs the text wrapped in a span in another div.

The problem I'm having is that during the cloning process, words get cut off because the length of the word goes over the width that's set in CSS.

Example:

I’m up to something. Learning is cool, bu
t knowing is better, and I know the key t

Is there anyway to get words to not overflow? I've try setting overflow:auto in css and it won't recognize it.

function trimByPixel(str, width) {
  var spn = $('').text(str).appendTo('body');
  var txt = str;
  while (spn.width() > width) { txt = txt.slice(0, -1); spn.text(txt + "..."); }
  return txt;
}

var stri = $(".str").text();

function run(){
var s = trimByPixel(stri, $(".str").width()).trim()
stri = stri.replace(s,"")
$(".result").append(""+s+"");

if(stri.trim().length > 0){
  run();
}
}

run();
$(".str").remove().delay(10);

.str{
  width:300px;
  }

  .result span{
  display:block
  }

I’m up to something. Learning is cool, but knowing is better, and I know the key to success. Bless up. They never said winning was easy. Some people can’t handle success, I can.
I told you all this before, when you have a swimming pool, do not use chlorine, use salt water, the healing, salt water is the healing. Put it this way, it took me twenty five years to get these plants, twenty five years of blood sweat and tears, and I’m never giving up, I’m just getting started.

Body:
The problem is the trimByPixel() function which just checks if a string is small enough to fit a given width but doesn't care if it's right in the middle of a word.

To know if we're going to cut-off a word, we can check what character the last character inside the string actually is. So for simplicity we can check if it's an empty space and in case it is, cutting off is fine. A more sophisticated test could check if it's a character from a-z A-Z 0-9.

while (spn.width() > width || txt.charAt(txt.length-1)!=" ")


问:
Override auto generated Y axis plot area values in Highcharts
I have certain requirement where I need to override the auto calculated values for Y axis in highcharts. For eg.

Here, the gridlines plot area is equally divided into 100. I wanted to override this so that the negative plot area should be at a max of let's say 50 and the positive ones can remain the same. Even if I try the max, min, softMax, softMin, ceiling and floor properties, the result is the same. I was thinking of using a secondary axis but then there is only one data in the series which would render the second one useless. I don't think using setExtremes() will be helpful either. I'm hoping to avoid modifying the library itself to add a certain option but it'll be helpful if such an option already exists in highcharts. Any suggestions?

答:
Use tickPositions or tickPositioner property:

```<code>yAxis: {
  tickPositions: [-50, 0, 100, 200, 300, 400]
}
</code>```

Live demo: http://jsfiddle.net/BlackLabel/6m4e8x0y/4883/

API Reference:

https://api.highcharts.com/highcharts/yAxis.tickPositions

https://api.highcharts.com/highcharts/yAxis.tickPositioner

Body:
Use tickPositions or tickPositioner property:

yAxis: {
  tickPositions: [-50, 0, 100, 200, 300, 400]
}

Live demo: http://jsfiddle.net/BlackLabel/6m4e8x0y/4883/

API Reference:

https://api.highcharts.com/highcharts/yAxis.tickPositions

https://api.highcharts.com/highcharts/yAxis.tickPositioner


问:
JupyterLab: How to clear output of current cell using a keyboard shortcut?
This question has been asked and answered for Jupyter Notebooks here. There is one suggestion regarding JupyterLab there as well on how to hide cell output, but not to clear it.

This is easy enough using the menu under Edit > Clear Outputs. But how do you do it using a keyboard shortcut? Many other commands under Edit already have their own assigned shortcuts, but not this one:

答:
The answer:

You'll have to assign a custom shortcut key under Settings > Advanced Settings Editor by inserting the following under User Preferences:

```<code>{// List of Keyboard Shortcuts
    "shortcuts": [
        {
            "command": "notebook:clear-cell-output",
            "keys": [
                "F10"
            ],
            "selector": ".jp-Notebook.jp-mod-editMode"
        },
    ]
}
</code>```

I went for F10, but most other keys or combination of keys should work too. I've also used Ctrl Shift Enter.

Where to put it:

Some details:

If you've assigned other shortcuts, make sure to add it in the correct place in the list of other shortcuts.

```<code>{// List of Keyboard Shortcuts
    "shortcuts": [
        {
            "command": "notebook:run-in-console",
            "keys": [
                "F9"
            ],
            "selector": ".jp-Notebook.jp-mod-editMode"
        },
        {
            "command": "notebook:clear-cell-output",
            "keys": [
                "F10"
            ],
            "selector": ".jp-Notebook.jp-mod-editMode"
        },
    ]
}
</code>```

And a little mystery:

If you insert the exact same thing as in the second box, you'll see that the item Run > Run Selected Text or Current Line in Console has gotten a nice F9 right next to it:

This will not be the case for the item Edit > Clear Outputs, and I'll have to say that I don't know why.

To my knowledge the "command": "notebook:clear-cell-output" that you're assigning to your chosen keyboard shortcut should be that exact functionality. But the good thing is that it works perfectly all the same. At least it does for me.

Please note that this approach works best for newer versions of JupyterLab. The correct way will be a bit different for older versions.

Here's a python snippet to test it out right away:

```<code>import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
print(df)
</code>```

Body:
The answer:

You'll have to assign a custom shortcut key under Settings > Advanced Settings Editor by inserting the following under User Preferences:

{// List of Keyboard Shortcuts
    "shortcuts": [
        {
            "command": "notebook:clear-cell-output",
            "keys": [
                "F10"
            ],
            "selector": ".jp-Notebook.jp-mod-editMode"
        },
    ]
}

I went for F10, but most other keys or combination of keys should work too. I've also used Ctrl Shift Enter.

Where to put it:

Some details:

If you've assigned other shortcuts, make sure to add it in the correct place in the list of other shortcuts.

{// List of Keyboard Shortcuts
    "shortcuts": [
        {
            "command": "notebook:run-in-console",
            "keys": [
                "F9"
            ],
            "selector": ".jp-Notebook.jp-mod-editMode"
        },
        {
            "command": "notebook:clear-cell-output",
            "keys": [
                "F10"
            ],
            "selector": ".jp-Notebook.jp-mod-editMode"
        },
    ]
}

And a little mystery:

If you insert the exact same thing as in the second box, you'll see that the item Run > Run Selected Text or Current Line in Console has gotten a nice F9 right next to it:

This will not be the case for the item Edit > Clear Outputs, and I'll have to say that I don't know why.

To my knowledge the "command": "notebook:clear-cell-output" that you're assigning to your chosen keyboard shortcut should be that exact functionality. But the good thing is that it works perfectly all the same. At least it does for me.

Please note that this approach works best for newer versions of JupyterLab. The correct way will be a bit different for older versions.

Here's a python snippet to test it out right away:

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
print(df)


问:
How to check If file exists in the url before use download.file in R
I have a problem and I don't know how  to solve it.
I have a list of url direct to download some files.

For example.

```<code>x<-list("https://www.ecb.europa.eu/paym/coll/assets/html/dla/ea_MID/ea_csv_200219.csv",
"http://sdw.ecb.europa.eu/quickviewexport.do?SERIES_KEY=120.EXR.M.USD.EUR.SP00.A&type=csv")

name_file<-list("name_1.csv","name_2.csv")
</code>```

In this case the script below works fine, but if one o more urls don't work the tryCatch doesen't return me the message. Somebody, please, could help me and tell me where is my mistake?

```<code>  for(i in seq_along(x)) {
  x<-as.character(x[i])
  nse.folder = paste0("directory_files/",name_file[i])
  tryCatch({download.file(x, destfile = nse.folder, method='curl')}, error = function(e) "Error: this url doesn't work!")
  Sys.sleep(4)
  }
</code>```

To test the script I cut, for example the url, like this:

```<code>x<-list("https://www.ecb.europa.eu/paym/coll/assets/html/dla/ea_MID/",
"http://sdw.ecb.europa.eu/quickviewexport.do?")
</code>```

Where  should I improve the code ?

Thank you in advance

答:
You can use the HEAD request. In R it's available in package httr. The return codes can be found on the Wikipedia. This SO post may be useful.

A very simple function could be

```<code>urlFileExist <- function(url){
  HTTP_STATUS_OK <- 200
  hd <- httr::HEAD(url)
  status <- hd$all_headers[[1]]$status
  list(exists = status == HTTP_STATUS_OK, status = status)
}

lapply(x, urlFileExist)
#[[1]]
#[[1]]$exists
#[1] TRUE
#
#[[1]]$status
#[1] 200
#
#
#[[2]]
#[[2]]$exists
#[1] TRUE
#
#[[2]]$status
#[1] 200
</code>```

Body:
I have a problem and I don't know how  to solve it.
I have a list of url direct to download some files.

For example.

x<-list("https://www.ecb.europa.eu/paym/coll/assets/html/dla/ea_MID/ea_csv_200219.csv",
"http://sdw.ecb.europa.eu/quickviewexport.do?SERIES_KEY=120.EXR.M.USD.EUR.SP00.A&type=csv")

name_file<-list("name_1.csv","name_2.csv")

In this case the script below works fine, but if one o more urls don't work the tryCatch doesen't return me the message. Somebody, please, could help me and tell me where is my mistake?

  for(i in seq_along(x)) {
  x<-as.character(x[i])
  nse.folder = paste0("directory_files/",name_file[i])
  tryCatch({download.file(x, destfile = nse.folder, method='curl')}, error = function(e) "Error: this url doesn't work!")
  Sys.sleep(4)
  }

To test the script I cut, for example the url, like this:

x<-list("https://www.ecb.europa.eu/paym/coll/assets/html/dla/ea_MID/",
"http://sdw.ecb.europa.eu/quickviewexport.do?")

Where  should I improve the code ?

Thank you in advance

Body:
You can use the HEAD request. In R it's available in package httr. The return codes can be found on the Wikipedia. This SO post may be useful.

A very simple function could be

urlFileExist <- function(url){
  HTTP_STATUS_OK <- 200
  hd <- httr::HEAD(url)
  status <- hd$all_headers[[1]]$status
  list(exists = status == HTTP_STATUS_OK, status = status)
}

lapply(x, urlFileExist)
#[[1]]
#[[1]]$exists
#[1] TRUE
#
#[[1]]$status
#[1] 200
#
#
#[[2]]
#[[2]]$exists
#[1] TRUE
#
#[[2]]$status
#[1] 200


问:
Problem Deserialising JSON response from Wikipedia API
I am trying to use the Wikipedia search request API thus:

https://en.wikipedia.org/w/api.php?action=query&origin=*&format=json&generator=search&gsrnamespace=0&gsrlimit=100&gsrsearch=Simple Harmonic Motion

and then trying to deserialise thus:

```<code>WikiSearchResults R = s1.Deserialize<WikiSearchResults>(Json);
</code>```

using this class structure:

```<code>private class WikiSearchQuery{
     public WikiSearchPage[] pages { get; set; }
}

private class WikiSearchPage{
     public int pageid { get; set; }
     public string title { get; set; }
}

private class WikiSearchResults{
     public WikiSearchQuery[] query { get; set; }
}
</code>```

But I am getting this exception:

No parameterless constructor defined for type of WikiSearchQuery[]

I guess I am misinterpreting the JSON response. Can someone suggest what I am doing wrong?

答:
There are probably multiple issues with deserializing.

As mentioned in the comments by fredrik, your classes are private. Making them public should fix the exception you get.

Additionally, the WikiSearchQuery only exists once and does not contain an array of objects, it does contain a dictionary.

This are the issues I see right now, so this might work:

```<code>public class WikiSearchQuery{
     public Dictionary<string,WikiSearchPage> pages { get; set; }
}

public class WikiSearchPage{
     public int pageid { get; set; }
     public string title { get; set; }
}

public class WikiSearchResults{
     public WikiSearchQuery query { get; set; }
}
</code>```

Body:
I am trying to use the Wikipedia search request API thus:

https://en.wikipedia.org/w/api.php?action=query&origin=*&format=json&generator=search&gsrnamespace=0&gsrlimit=100&gsrsearch=Simple Harmonic Motion

and then trying to deserialise thus:

WikiSearchResults R = s1.Deserialize<WikiSearchResults>(Json);

using this class structure:

private class WikiSearchQuery{
     public WikiSearchPage[] pages { get; set; }
}

private class WikiSearchPage{
     public int pageid { get; set; }
     public string title { get; set; }
}

private class WikiSearchResults{
     public WikiSearchQuery[] query { get; set; }
}

But I am getting this exception:

No parameterless constructor defined for type of WikiSearchQuery[]

I guess I am misinterpreting the JSON response. Can someone suggest what I am doing wrong?

Body:
There are probably multiple issues with deserializing.

As mentioned in the comments by fredrik, your classes are private. Making them public should fix the exception you get.

Additionally, the WikiSearchQuery only exists once and does not contain an array of objects, it does contain a dictionary.

This are the issues I see right now, so this might work:

public class WikiSearchQuery{
     public Dictionary<string,WikiSearchPage> pages { get; set; }
}

public class WikiSearchPage{
     public int pageid { get; set; }
     public string title { get; set; }
}

public class WikiSearchResults{
     public WikiSearchQuery query { get; set; }
}


问:
How does <ENTER> work on a webpage?
I have a webpage with a Master.  The master contains

search1Button with PostBackUrl="~/Search.aspx"

The child page contains

search2Button with onclick="btnSearch_Click"

When a user hits <enter> search1Button will execute.  When nothing is active I can see how search1Button can be viewed as the default.  But, when the active textbox is say

search2TextBox

Things can be a little confusing when suddenly search1Button executes instead of search2Button.

A. How does the page decide what executes?

B. Does this have anything to do with Forms?  If yes, does having only 1 Form limit my ability to control the situation (I cannot add more forms due to major problems experienced by me and discussed on SO with nested forms)?

答:
You can do this using JavaScript, here is how can you do this..</p>

```<code>FirstTextBox.Attributes.Add("onkeypress", "SetDefaultButton(this,'" + SearchButton1.ClientID + "')");
SecondTextBox.Attributes.Add("onkeypress", "SetDefaultButton(this,'" + SearchButton2.ClientID + "')");

function SetDefaultButton(objTextBox,objBtnID)
{
    if(window.event.keyCode==13)
    {
        document.getElementById(objBtnID).focus();
        document.getElementById(objBtnID).click();
    }
}
</script>
</code>```

Title: How does <ENTER> work on a webpage?

Body:
You can do this using JavaScript, here is how can you do this..

FirstTextBox.Attributes.Add("onkeypress", "SetDefaultButton(this,'" + SearchButton1.ClientID + "')");
SecondTextBox.Attributes.Add("onkeypress", "SetDefaultButton(this,'" + SearchButton2.ClientID + "')");

function SetDefaultButton(objTextBox,objBtnID)
{
    if(window.event.keyCode==13)
    {
        document.getElementById(objBtnID).focus();
        document.getElementById(objBtnID).click();
    }
}
</script>


问:
How to set caller id or remote pary id linphone?
I have one ios application with audio calling functionality using linphone. I have to change caller id or remote party id. i.e. I have registered with 1000 number. But while calling i have multiple DIDs to choose from in my application. Does linphone provide any option other than setting custom header for this?

From: "1000" sip:1000@172.0.0.0
I have registered with 1000 but at time of calling i want to use 1001.
So in above invite header i want to replace 1000 with 1001.

Here i want to change from to other DID at time of calling. Does linphone provide any option for this?

答:
It seems like as of now linphone for ios is not providing such options.

So, i have set parameter as custom header using below code.

```<code> linphone_call_params_add_custom_header(lcallParams,"X-HeaderName",["1001" UTF8String]);
</code>```

Body:
It seems like as of now linphone for ios is not providing such options.

So, i have set parameter as custom header using below code.

 linphone_call_params_add_custom_header(lcallParams,"X-HeaderName",["1001" UTF8String]);


问:
Phonegap Build Error: Xcode could not determine type of profile / No signing certificate "iOS Distribution" found - Xcode 11 or Xcode 10.1
I'm trying to compile an IPA for distribution in Phonegap Build, but I'm receiving the following error:

```<code>Running command: xcodebuild -exportArchive -archivePath Releva.xcarchive -exportOptionsPlist /private/project/exportOptions.plist -exportPath /private/project/build/device
2020-02-19 14:42:12.285 xcodebuild[46455:98411165] [MT] IDEDistribution: -[IDEDistributionLogging _createLoggingBundleAtPath:]: Created bundle at path '/var/folders/37/x2444x712rnbshh_b1tlfwsm0000gp/T/************.xcdistributionlogs'.
2020-02-19 14:42:12.665 xcodebuild[46455:98411167]  DVTAssertions: Warning in /Library/Caches/com.apple.xbs/Sources/IDEFrameworks_Fall2018/IDEFrameworks-14460.46/IDEFoundation/Provisioning/IDEProfileQualification.m:509
Details:  Xcode could not determine type of profile "/Library/MobileDevice/Provisioning Profiles/production-ios-1582151957--90970.mobileprovision" (could be {(
)})
Object:   <IDEProfileQualification: 0x7fd1f6e0b350>
Method:   -_profileTypeQualifier
Thread:   <NSThread: 0x7fd1f6806dc0>{number = 4, name = (null)}
Please file a bug at https://bugreport.apple.com with this warning message and any useful information you can provide.
error: exportArchive: No signing certificate "iOS Distribution" found

Error Domain=IDECodesignResolverErrorDomain Code=1 "No signing certificate "iOS Distribution" found" UserInfo={IDEProvisioningError_UserInfoKey_IDEProvisioningErrorPlatform=com.apple.platform.iphoneos, IDEProvisioningError_UserInfoKey_IDEProvisioningErrorAction=5, NSLocalizedRecoverySuggestion=No "iOS Distribution" signing certificate matching team ID "************" with a private key was found., IDEProvisioningError_UserInfoKey_IDEProvisioningErrorSpecifier=iOS Distribution, IDEProvisioningError_UserInfoKey_IDEProvisioningErrorTeam=<IDEProvisioningBasicTeam: 0x7fd1f6e0a330; teamID='***********', teamName='(null)'>, NSLocalizedDescription=No signing certificate "iOS Distribution" found}
</code>```

I tried and retried everything with the credentials and provisioning profiles, but continue to get the same error. Creating them again and again, selecting the certificate with the private key together to export the p12, etc ..

Only thing I noticed is that when I select the certifcate to create the Provisioning Profile, it says "For use in Xcode 11 or later":

And in the error log it says "Xcode could not determine type of profile" and appears "Applications/Xcode101.app" in a lot of lines what makes me think it's trying to compile it with Xcode 10.1

What can I do for Pronegap Build to use Xcode 11 when I submit it?

Is anyone else having this issue? Any workaround to this?

答:
Well, the problem was at the moment of creating the certificate in developers.apple.com. (Not the Provisiotioning Profile)

It seems Apple changed that last year, and now you have 2 options. One is Apple Distribution for Xcode 11+ and iOS (App Store and Ad Hoc) for any version.

Hope it helps anyone else having this issue.

Body:
I'm trying to compile an IPA for distribution in Phonegap Build, but I'm receiving the following error:

Running command: xcodebuild -exportArchive -archivePath Releva.xcarchive -exportOptionsPlist /private/project/exportOptions.plist -exportPath /private/project/build/device
2020-02-19 14:42:12.285 xcodebuild[46455:98411165] [MT] IDEDistribution: -[IDEDistributionLogging _createLoggingBundleAtPath:]: Created bundle at path '/var/folders/37/x2444x712rnbshh_b1tlfwsm0000gp/T/************.xcdistributionlogs'.
2020-02-19 14:42:12.665 xcodebuild[46455:98411167]  DVTAssertions: Warning in /Library/Caches/com.apple.xbs/Sources/IDEFrameworks_Fall2018/IDEFrameworks-14460.46/IDEFoundation/Provisioning/IDEProfileQualification.m:509
Details:  Xcode could not determine type of profile "/Library/MobileDevice/Provisioning Profiles/production-ios-1582151957--90970.mobileprovision" (could be {(
)})
Object:   <IDEProfileQualification: 0x7fd1f6e0b350>
Method:   -_profileTypeQualifier
Thread:   <NSThread: 0x7fd1f6806dc0>{number = 4, name = (null)}
Please file a bug at https://bugreport.apple.com with this warning message and any useful information you can provide.
error: exportArchive: No signing certificate "iOS Distribution" found

Error Domain=IDECodesignResolverErrorDomain Code=1 "No signing certificate "iOS Distribution" found" UserInfo={IDEProvisioningError_UserInfoKey_IDEProvisioningErrorPlatform=com.apple.platform.iphoneos, IDEProvisioningError_UserInfoKey_IDEProvisioningErrorAction=5, NSLocalizedRecoverySuggestion=No "iOS Distribution" signing certificate matching team ID "************" with a private key was found., IDEProvisioningError_UserInfoKey_IDEProvisioningErrorSpecifier=iOS Distribution, IDEProvisioningError_UserInfoKey_IDEProvisioningErrorTeam=<IDEProvisioningBasicTeam: 0x7fd1f6e0a330; teamID='***********', teamName='(null)'>, NSLocalizedDescription=No signing certificate "iOS Distribution" found}

I tried and retried everything with the credentials and provisioning profiles, but continue to get the same error. Creating them again and again, selecting the certificate with the private key together to export the p12, etc ..

Only thing I noticed is that when I select the certifcate to create the Provisioning Profile, it says "For use in Xcode 11 or later":

And in the error log it says "Xcode could not determine type of profile" and appears "Applications/Xcode101.app" in a lot of lines what makes me think it's trying to compile it with Xcode 10.1

What can I do for Pronegap Build to use Xcode 11 when I submit it?

Is anyone else having this issue? Any workaround to this?


问:
Correct way to import functions from file in python3
I'm building a simple python3 CLI for some scripting. I have troubles importing my own functions located in files that are in the same modules.

My file structure is

```<code>pycli/
├── README.md
├── pycli
  ├── __init__.py
  ├── cli.py
  └── funcmodule.py
</code>```

funcmodule.py:

```<code>def my_function(word):
    print("Hello %s" % word)
</code>```

cli.py:

```<code>#!/usr/bin/env python3

from pycli.funcmodule import my_function

def main():
    my_function('hello world')

if __name__ == '__main__':
    main()
</code>```

When I run ./pycli/cli.py from the command line I get

```<code>(venv) ➜  ./pycli/cli.py
Traceback (most recent call last):
  File "./pycli/cli.py", line 3, in <module>
    from pycli.funcmodule import my_function
ModuleNotFoundError: No module named 'pycli'
</code>```

When I run the cli.py from PyCharm or in Visual Studio Code, it works correctly. What is the correct way to import the function with python3+ (I don't care about python2)?

答:
So what I needed is to create a proper package with the setup.py:

```<code>from setuptools import setup
setup(
    name = 'pycli',
    version = '0.1.0',
    packages = ['pycli'],
    entry_points = {
        'console_scripts': [
            'pycli = pycli.cli:main'
        ]
    })
</code>```

in order to run it from the terminal

```<code>pip3 install .

pycli
Hello hello world
</code>```

Body:
I'm building a simple python3 CLI for some scripting. I have troubles importing my own functions located in files that are in the same modules.

My file structure is

pycli/
├── README.md
├── pycli
  ├── __init__.py
  ├── cli.py
  └── funcmodule.py

funcmodule.py:

def my_function(word):
    print("Hello %s" % word)

cli.py:

#!/usr/bin/env python3

from pycli.funcmodule import my_function

def main():
    my_function('hello world')

if __name__ == '__main__':
    main()

When I run ./pycli/cli.py from the command line I get

(venv) ➜  ./pycli/cli.py
Traceback (most recent call last):
  File "./pycli/cli.py", line 3, in <module>
    from pycli.funcmodule import my_function
ModuleNotFoundError: No module named 'pycli'

When I run the cli.py from PyCharm or in Visual Studio Code, it works correctly. What is the correct way to import the function with python3+ (I don't care about python2)?

Body:
So what I needed is to create a proper package with the setup.py:

from setuptools import setup
setup(
    name = 'pycli',
    version = '0.1.0',
    packages = ['pycli'],
    entry_points = {
        'console_scripts': [
            'pycli = pycli.cli:main'
        ]
    })

in order to run it from the terminal

pip3 install .

pycli
Hello hello world


问:
Angular Resolver Service Not Working Properly

RoleList Component:::
import { Global } from "./../../../global/serverlinks";

import { Component, OnInit, ViewChild } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs";
import { Router, ActivatedRoute, ParamMap } from "@angular/router";
import { RoleserviceService } from "src/app/Service/roleservice.service";
import {BsModalComponent} from "ng2-bs3-modal"

@Component({
  selector: "app-rolelist",
  templateUrl: "./rolelist.component.html",
  styleUrls: ["./rolelist.component.css"]
})
export class RolelistComponent implements OnInit {
  public data: any;
  public error: any;
  public name: string;
  constructor(
    public http: HttpClient,
    public router: Router,
    public route: ActivatedRoute,
    public service: RoleserviceService
  ) {}

  ngOnInit() {
     this.route.data.subscribe(
      result=>this.data=result.roleList
    );

  }
  showResult() {
    console.log(
      this.http.get<Observable<any>[]>(Global.BASE_HOST_ENDPOINT).subscribe(
        data => {
          (this.data = data), console.log(data);
        },
        error => {
          (this.error = error), console.log(error);
        }
      )
    );
  }

  EditRole(id) {
    let role;
    this.service.GetRole(id).subscribe(res => {
      (role = res),
        console.log("Role found:" + role),
        this.router.navigate([
          "editrole",
          id],{queryParams:{name:role.name},skipLocationChange:true}),
      err => console.log(err);
    });

  }
  DeleteRole(id,index){
    let role;
    this.service.GetRole(id).subscribe(
      result=>{
        this.service.DeleteRole(id).subscribe(
          result=>{
            console.log(result)
            this.data.remove(index)
          },
          err=>console.log(err)
        )
      }
    )
  }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>Resolver Service::
import { RoleserviceService } from './roleservice.service';
import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Role } from '../Model/role';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Global } from '../global/serverlinks';
@Injectable()

export class RoleListResolverService implements Resolve<Role[]>{
    constructor(public service:RoleserviceService,public http:HttpClient){}

  resolve(route: ActivatedRouteSnapshot,state:RouterStateSnapshot):Observable<Role[]>{
      return this.http.get<Role[]>(Global.BASE_HOST_ENDPOINT)
  }
}</code>```

            {{role.name}}

            This is {{role.name}} role.

                    <button class="btn-primary" routerLink="/editrole/{{role.id}}"
                        (click)="EditRole(role.id)">Edit</button>

                    <button class="btn-danger" (click)="DeleteRole(role.id,1)">Delete</button>

Users

{{user.name}}

No Members Yet

                <button class="btn btn-outline-dark">Manage Users In{{role.name}} role</button>

```

I used resolver service to list the list of roles and corresponding users . The list doesn't completely fill at the beginning but as soon as I press any button it loads up. what is the issue?..
The picture seen below has the Manager Role Shown but that if only after I clicked a button. Before that the Outline box was shown but not name of the role.

enter image description here

答:
This is the first image where the Manager Role doesn't show up.
The manager role doesn't show up but as soon as I click any button it shows up.</p>

Body:
RoleList Component:::
import { Global } from "./../../../global/serverlinks";

import { Component, OnInit, ViewChild } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs";
import { Router, ActivatedRoute, ParamMap } from "@angular/router";
import { RoleserviceService } from "src/app/Service/roleservice.service";
import {BsModalComponent} from "ng2-bs3-modal"

@Component({
  selector: "app-rolelist",
  templateUrl: "./rolelist.component.html",
  styleUrls: ["./rolelist.component.css"]
})
export class RolelistComponent implements OnInit {
  public data: any;
  public error: any;
  public name: string;
  constructor(
    public http: HttpClient,
    public router: Router,
    public route: ActivatedRoute,
    public service: RoleserviceService
  ) {}

  ngOnInit() {
     this.route.data.subscribe(
      result=>this.data=result.roleList
    );

  }
  showResult() {
    console.log(
      this.http.get<Observable<any>[]>(Global.BASE_HOST_ENDPOINT).subscribe(
        data => {
          (this.data = data), console.log(data);
        },
        error => {
          (this.error = error), console.log(error);
        }
      )
    );
  }

  EditRole(id) {
    let role;
    this.service.GetRole(id).subscribe(res => {
      (role = res),
        console.log("Role found:" + role),
        this.router.navigate([
          "editrole",
          id],{queryParams:{name:role.name},skipLocationChange:true}),
      err => console.log(err);
    });

  }
  DeleteRole(id,index){
    let role;
    this.service.GetRole(id).subscribe(
      result=>{
        this.service.DeleteRole(id).subscribe(
          result=>{
            console.log(result)
            this.data.remove(index)
          },
          err=>console.log(err)
        )
      }
    )
  }

}

Resolver Service::
import { RoleserviceService } from './roleservice.service';
import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Role } from '../Model/role';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Global } from '../global/serverlinks';
@Injectable()

export class RoleListResolverService implements Resolve<Role[]>{
    constructor(public service:RoleserviceService,public http:HttpClient){}

  resolve(route: ActivatedRouteSnapshot,state:RouterStateSnapshot):Observable<Role[]>{
      return this.http.get<Role[]>(Global.BASE_HOST_ENDPOINT)
  }
}

            {{role.name}}

            This is {{role.name}} role.

                    <button class="btn-primary" routerLink="/editrole/{{role.id}}"
                        (click)="EditRole(role.id)">Edit</button>

                    <button class="btn-danger" (click)="DeleteRole(role.id,1)">Delete</button>

Users

{{user.name}}

No Members Yet

                <button class="btn btn-outline-dark">Manage Users In{{role.name}} role</button>

I used resolver service to list the list of roles and corresponding users . The list doesn't completely fill at the beginning but as soon as I press any button it loads up. what is the issue?..
The picture seen below has the Manager Role Shown but that if only after I clicked a button. Before that the Outline box was shown but not name of the role.

enter image description here


问:
Share local collection between Threads in C#
I have two methods as below

```<code>private void MethodB_GetId()
        {
            //Calling Method A constinuosly in different thread
            //Let's say its calling for Id = 1 to 100
        }

        private void MethodA_GetAll()
        {
            List<string> lst;
            lock(_locker)
            {
                lst = SomeService.Get(); //This get return all 100 ids in one shot.
                //Some other processing and then return result.
            }
        }
</code>```

Now client is calling MethodB_GetById continuously for fetching data for id: 1 to 100 randomly. (It require some of data from these 100 Ids, not all data)

MethodA_GetAll get all data from network may be cache or database in one shot. and return whole collection to method B, then method B extract record in which it is interested.

Now if MethodA_GetAll() makes GetALL() times multiple times and fetching same records will be useless. so i can put a lock around it one thread is fetching record then other will be blocked.

Let's When MethodA_GetAll called by Id = 1 acquire lock and all others are waiting for lock to be released.

What i want is one data is available by any one thread just don't make call again.

Solution option:
1. Make List global to that class and thread safe. (I don't have that option)

I require some how thread 1 tell all other threads that i have record don't go fetching record again.

something like

```<code>lock(_locker && Lst!=null) //Not here lst is local to every thread
{
   //If this satisfy then only fetch records
}
</code>```

Please excuse me for poorly framing question. I have posted this in little hurry.

答:
It sounds like you want to create a threadsafe cache. One way to do this is to use Lazy<t>.

Here's an example for a cache of type List<string>:

```<code>public sealed class DataProvider
{
    public DataProvider()
    {
        _cache = new Lazy<List<string>>(createCache);
    }

    public void DoSomethingThatNeedsCachedList()
    {
        var list = _cache.Value;

        // Do something with list.

        Console.WriteLine(list[10]);
    }

    readonly Lazy<List<string>> _cache;

    List<string> createCache()
    {
        // Dummy implementation.
        return Enumerable.Range(1, 100).Select(x => x.ToString()).ToList();
    }
}
</code>```

When you need to access the cached value, you just access _cache.Value. If it hasn't yet been created, then the method you passed to the Lazy<T>'s constructor will be called to initialise it. In the example above, this is the createCache() method.

This is done in a threadsafe manner, so that if two threads try to access the cached value simultaneously when it hasn't been created yet, one of the threads will actually end up calling createCache() and the other thread will be blocked until the cached value has been initialised.

Body:
I have two methods as below

private void MethodB_GetId()
        {
            //Calling Method A constinuosly in different thread
            //Let's say its calling for Id = 1 to 100
        }

        private void MethodA_GetAll()
        {
            List<string> lst;
            lock(_locker)
            {
                lst = SomeService.Get(); //This get return all 100 ids in one shot.
                //Some other processing and then return result.
            }
        }

Now client is calling MethodB_GetById continuously for fetching data for id: 1 to 100 randomly. (It require some of data from these 100 Ids, not all data)

MethodA_GetAll get all data from network may be cache or database in one shot. and return whole collection to method B, then method B extract record in which it is interested.

Now if MethodA_GetAll() makes GetALL() times multiple times and fetching same records will be useless. so i can put a lock around it one thread is fetching record then other will be blocked.

Let's When MethodA_GetAll called by Id = 1 acquire lock and all others are waiting for lock to be released.

What i want is one data is available by any one thread just don't make call again.

Solution option:
1. Make List global to that class and thread safe. (I don't have that option)

I require some how thread 1 tell all other threads that i have record don't go fetching record again.

something like

lock(_locker && Lst!=null) //Not here lst is local to every thread
{
   //If this satisfy then only fetch records
}

Please excuse me for poorly framing question. I have posted this in little hurry.

Body:
It sounds like you want to create a threadsafe cache. One way to do this is to use Lazy<t>.

Here's an example for a cache of type List<string>:

public sealed class DataProvider
{
    public DataProvider()
    {
        _cache = new Lazy<List<string>>(createCache);
    }

    public void DoSomethingThatNeedsCachedList()
    {
        var list = _cache.Value;

        // Do something with list.

        Console.WriteLine(list[10]);
    }

    readonly Lazy<List<string>> _cache;

    List<string> createCache()
    {
        // Dummy implementation.
        return Enumerable.Range(1, 100).Select(x => x.ToString()).ToList();
    }
}

When you need to access the cached value, you just access _cache.Value. If it hasn't yet been created, then the method you passed to the Lazy<T>'s constructor will be called to initialise it. In the example above, this is the createCache() method.

This is done in a threadsafe manner, so that if two threads try to access the cached value simultaneously when it hasn't been created yet, one of the threads will actually end up calling createCache() and the other thread will be blocked until the cached value has been initialised.


问:
Petsc doesn't show where in the code the error occurs
Without Petsc, I can see which files, which functions, and which lines an error occurs and is propagated from. With Petsc, I always receive the same error message.

Is there any flag in Petsc that I'm missing?

Thanks.

```<code>[0]PETSC ERROR: ------------------------------------------------------------------------
[0]PETSC ERROR: Caught signal number 11 SEGV: Segmentation Violation, probably memory access out of range
[0]PETSC ERROR: Try option -start_in_debugger or -on_error_attach_debugger
[0]PETSC ERROR: or see http://www.mcs.anl.gov/petsc/petsc-as/documentation/troubleshooting.html#Signal[0]PETSC ERROR: or try http://valgrind.org on GNU/linux and Apple Mac OS X to find memory corruption errors
[0]PETSC ERROR: likely location of problem given in stack below
[0]PETSC ERROR: ---------------------  Stack Frames ------------------------------------
[0]PETSC ERROR: Note: The EXACT line numbers in the stack are not available,
[0]PETSC ERROR:       INSTEAD the line number of the start of the function
[0]PETSC ERROR:       is given.
[0]PETSC ERROR: --------------------- Error Message ------------------------------------
[0]PETSC ERROR: Signal received!
[0]PETSC ERROR: ------------------------------------------------------------------------
[0]PETSC ERROR: Petsc Release Version 3.1.0, Patch 8, Thu Mar 17 13:37:48 CDT 2011
[0]PETSC ERROR: See docs/changes/index.html for recent updates.
[0]PETSC ERROR: See docs/faq.html for hints about trouble shooting.
[0]PETSC ERROR: See docs/index.html for manual pages.
[0]PETSC ERROR: ------------------------------------------------------------------------
[0]PETSC ERROR: ./solver on a linux named ion by khoa Sun Apr 10 23:29:33 2011
[0]PETSC ERROR: Libraries linked from /h1/khoa/libs/petsc-3.1/linux/lib
[0]PETSC ERROR: Configure run at Sun Apr 10 17:52:52 2011
[0]PETSC ERROR: Configure options --with-scalar-type=complex --with-clanguage=c++ --with-mpi=1 --with-mpi-dir=/usr/bin
[0]PETSC ERROR: ------------------------------------------------------------------------
[0]PETSC ERROR: User provided function() line 0 in unknown directory unknown file
</code>```

答: Your code has generated a SEGV, probably by illegally accessing memory. As the error message recommends, you should run using valgrind or gdb, which will allow you to see the stack.</p>

Body:
Without Petsc, I can see which files, which functions, and which lines an error occurs and is propagated from. With Petsc, I always receive the same error message.

Is there any flag in Petsc that I'm missing?

Thanks.

[0]PETSC ERROR: ------------------------------------------------------------------------
[0]PETSC ERROR: Caught signal number 11 SEGV: Segmentation Violation, probably memory access out of range
[0]PETSC ERROR: Try option -start_in_debugger or -on_error_attach_debugger
[0]PETSC ERROR: or see http://www.mcs.anl.gov/petsc/petsc-as/documentation/troubleshooting.html#Signal[0]PETSC ERROR: or try http://valgrind.org on GNU/linux and Apple Mac OS X to find memory corruption errors
[0]PETSC ERROR: likely location of problem given in stack below
[0]PETSC ERROR: ---------------------  Stack Frames ------------------------------------
[0]PETSC ERROR: Note: The EXACT line numbers in the stack are not available,
[0]PETSC ERROR:       INSTEAD the line number of the start of the function
[0]PETSC ERROR:       is given.
[0]PETSC ERROR: --------------------- Error Message ------------------------------------
[0]PETSC ERROR: Signal received!
[0]PETSC ERROR: ------------------------------------------------------------------------
[0]PETSC ERROR: Petsc Release Version 3.1.0, Patch 8, Thu Mar 17 13:37:48 CDT 2011
[0]PETSC ERROR: See docs/changes/index.html for recent updates.
[0]PETSC ERROR: See docs/faq.html for hints about trouble shooting.
[0]PETSC ERROR: See docs/index.html for manual pages.
[0]PETSC ERROR: ------------------------------------------------------------------------
[0]PETSC ERROR: ./solver on a linux named ion by khoa Sun Apr 10 23:29:33 2011
[0]PETSC ERROR: Libraries linked from /h1/khoa/libs/petsc-3.1/linux/lib
[0]PETSC ERROR: Configure run at Sun Apr 10 17:52:52 2011
[0]PETSC ERROR: Configure options --with-scalar-type=complex --with-clanguage=c++ --with-mpi=1 --with-mpi-dir=/usr/bin
[0]PETSC ERROR: ------------------------------------------------------------------------
[0]PETSC ERROR: User provided function() line 0 in unknown directory unknown file


问:
how to Create and Use SnackBar for ReUse(Globally) in Flutter
i want create SnackBar for reusable(globally)

i already created but its only for 1 page , i don't know how to create reusable.

below code:

```<code>import 'package:flutter/material.dart';

class SnackBarMain extends StatefulWidget {
  @override
  _SnackBarMainState createState() => _SnackBarMainState();
}

class _SnackBarMainState extends State<SnackBarMain> {
  final globalKey = GlobalKey<ScaffoldState>();
  String title = 'SnackBar';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: globalKey,
      resizeToAvoidBottomPadding: false,
      appBar: AppBar(
        centerTitle: true,
        title: Text(title),
      ),
      body: Center(
        child: RaisedButton(
          shape: new RoundedRectangleBorder(
              borderRadius: new BorderRadius.circular(18.0),
              side: BorderSide(color: Colors.purple)),
          onPressed: () => snackBarMsg(context),
          color: Colors.purple,
          textColor: Colors.white,
          child: Text("SnackBar",
              style: TextStyle(fontSize: 18)),
        ),
      ),
    );
  }

snackBarMsg(BuildContext context) {
    final sb = SnackBar(
      elevation: 0.0,
      //behavior: SnackBarBehavior.floating,
      content: Text('SnackBar Bottom Message'),
      duration: new Duration(seconds: 5000000),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
            topLeft: Radius.circular(16.0), topRight: Radius.circular(16.0)),
      ),
      //backgroundColor: Colors.redAccent,
      action: SnackBarAction(
        textColor: Color(0xFFFAF2FB),
        label: 'OK',
        onPressed: () {},
      ),
    );
    globalKey.currentState.showSnackBar(sb);
  }
}
</code>```

so any one please give me example for this

答:
You can use the Snackbar you have already defined to reuse it everywhere by putting it in a public folder, that can be accessed from anywhere in your app. You don't need to enclose it inside a widget or a class. Then, you can show it by calling Scaffold.of(context).showSnackBar(...). For that, you will need to pass the current BuildContext, of course. This way, as long as the context from which you call showSnackBar has a parent Scaffold, the snackbar will be shown for your current page, and you can do this from anywhere.

Consider this example, that I myself have used in the past:

  void buildErrorSnackbar(BuildContext context) {
    Scaffold.of(context).showSnackBar(
      SnackBar(
        content: Text("Oops! Something went wrong."),
      ),
    );
  }
```

Body:
i want create SnackBar for reusable(globally)

i already created but its only for 1 page , i don't know how to create reusable.

below code:

import 'package:flutter/material.dart';

class SnackBarMain extends StatefulWidget {
  @override
  _SnackBarMainState createState() => _SnackBarMainState();
}

class _SnackBarMainState extends State<SnackBarMain> {
  final globalKey = GlobalKey<ScaffoldState>();
  String title = 'SnackBar';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: globalKey,
      resizeToAvoidBottomPadding: false,
      appBar: AppBar(
        centerTitle: true,
        title: Text(title),
      ),
      body: Center(
        child: RaisedButton(
          shape: new RoundedRectangleBorder(
              borderRadius: new BorderRadius.circular(18.0),
              side: BorderSide(color: Colors.purple)),
          onPressed: () => snackBarMsg(context),
          color: Colors.purple,
          textColor: Colors.white,
          child: Text("SnackBar",
              style: TextStyle(fontSize: 18)),
        ),
      ),
    );
  }

snackBarMsg(BuildContext context) {
    final sb = SnackBar(
      elevation: 0.0,
      //behavior: SnackBarBehavior.floating,
      content: Text('SnackBar Bottom Message'),
      duration: new Duration(seconds: 5000000),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
            topLeft: Radius.circular(16.0), topRight: Radius.circular(16.0)),
      ),
      //backgroundColor: Colors.redAccent,
      action: SnackBarAction(
        textColor: Color(0xFFFAF2FB),
        label: 'OK',
        onPressed: () {},
      ),
    );
    globalKey.currentState.showSnackBar(sb);
  }
}

so any one please give me example for this


问:
How to set up external library from git in c++
New to C++, and trying to install this to help handle .xlsx files. As far as I understand, installation of / configuration of external libraries varies from case to case. There are no instructions in the READEME.me file, I have tried the make and cmake commands in terminal but I am unsure what file I need to direct it to etc. I have already cloned the repository.

Could anyone with experience in c++ open source libraries possibly help?

答:
Actually I think what you need is to learn how both make and CMake work.

If I were you, this is what I would have done:

```<code>$ cd path_to_OpenXLSX_repository
$ mkdir build
$ cd build
$ cmake -DCMAKE_INSTALL_PREFIX="Path where you want to install the library" ..
$ make install
</code>```

For some explanation:

Create a build directory (in order to not pollute your repository with build things)

cmake .. will read the CMakeLists.txt file located in ../ and generate the Makefile

The variable CMAKE_INSTALL_PREFIX allows you to set the path where you want to install the library.

You can get rid of it if you want to use the default.

make install to build and install the library

But you really should take some time to learn about CMake :)

Edit:

Actually, it seems that they have not set any install rule (hence the empty output of make install). So only running make will build and generate your library.

So it becomes:

```<code>$ cd build
$ cmake ..
$ make
</code>```

And then, in "repo_path/build/install/lib/", you'll see your shared library called in your case: libOpenXLSX.so

Body:
Actually I think what you need is to learn how both make and CMake work.

If I were you, this is what I would have done:

$ cd path_to_OpenXLSX_repository
$ mkdir build
$ cd build
$ cmake -DCMAKE_INSTALL_PREFIX="Path where you want to install the library" ..
$ make install

For some explanation:

Create a build directory (in order to not pollute your repository with build things)

cmake .. will read the CMakeLists.txt file located in ../ and generate the Makefile

The variable CMAKE_INSTALL_PREFIX allows you to set the path where you want to install the library.

You can get rid of it if you want to use the default.

make install to build and install the library

But you really should take some time to learn about CMake :)

Edit:

Actually, it seems that they have not set any install rule (hence the empty output of make install). So only running make will build and generate your library.

So it becomes:

$ cd build
$ cmake ..
$ make

And then, in "repo_path/build/install/lib/", you'll see your shared library called in your case: libOpenXLSX.so


问:
Override Jackson Object Mapper properties on Websphere 8.5.5 using Apache Wink
We are using IBM(s) bundled Apache Wink to offer JAXRS endpoints for our application. We are coding towards Websphere 8.5.5. Since we are servlet 3.0 compliant we use the 'programmatic' way of configuring the JaxRS application, meaning no entries in web.xml and we rely on class scanning for annotated jax rs resources. In general it works fine.

```<code>   @ApplicationPath("/api/v1/")
   public class MyApplication  extends Application{
</code>```

This version of Websphere  along with Apache Wink, uses Jackson 1.6.x for JSON de/serialization and in general it works  well. We would like though to change some of the default values of the Object Mapper

So we have defined a customer context resolver, where just alter some of the se/deserialzation properties.

```<code>@Provider
@Produces(MediaType.APPLICATION_JSON)
public class CustomJackssonConverter implements ContextResolver<ObjectMapper> {

    final ObjectMapper defaultObjectMapper;

    public AibasJackssonConverter() {
        defaultObjectMapper = createDefaultMapper();
    }
   ...
 mapper.getSerializationConfig().set(SerializationConfig.Feature.INDENT_OUTPUT, true);
</code>```

During JAX-RS calls we can see that the container registers the new Provider, with no errors

The problem is that , the Configuration is not 'followed', from the logs I can see that the Wink Engine is looking up a WinkJacksonProvider, which in turn..returns a JacksonProvider that is following the Jackson(s) default values?

Is there a way to just change this default value?

I have tried to change the implementation of the Application object as indicated here, in order to configure Providers programmatically, but it did not work.

http://www.ibm.com/developerworks/java/library/wa-aj-jackson/index.html

Any hints or tips?

Many thanks

答:
I was using liberty profile server 20.0.0.0 and eclipselink 2.7.6. The MoxyJsonProvider from eclipselink is used by JAXRS by default and it was throwing "A Cycle is detected" error. I wanted to override the default JAXB Moxy provider with my ObjectMapper or Jackson Json Provider.

public Set<Class<?>> getClasses() did not work. I had to create another class file to create public class JaxbJsonProvider extends JacksonJaxbJsonProvider and annotate it as @Provider. This solution worked for me.

```<code>import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.Provider;

import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;

@Provider
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class JaxbJsonProvider extends JacksonJaxbJsonProvider {

}
</code>```

and the other file is

```<code>import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Provider
public class JacksonObjectMapperProvider implements ContextResolver<ObjectMapper> {

    final ObjectMapper defaultObjectMapper;

    public JacksonObjectMapperProvider() {
        defaultObjectMapper = createDefaultMapper();
    }

    @Override
    public ObjectMapper getContext(Class<?> type) {
        return defaultObjectMapper;
    }

    public static ObjectMapper createDefaultMapper() {

        log.info(String.format("Registering ObjectMapper modules"));

        ObjectMapper mapper = new ObjectMapper();

        mapper.disable(DeserializationFeature.FAIL_ON_UNRESOLVED_OBJECT_IDS);
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        mapper.configure(MapperFeature.USE_GETTERS_AS_SETTERS, true);
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

        return mapper;
    }

}
</code>```

Restart you liberty profile server and REST APIs would work fine. Note that @Slf4j is merely used for logging statement and mapper config options are something that you can skip. Liberty recommends to use mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);. All others are as per your project settings.

Body:
We are using IBM(s) bundled Apache Wink to offer JAXRS endpoints for our application. We are coding towards Websphere 8.5.5. Since we are servlet 3.0 compliant we use the 'programmatic' way of configuring the JaxRS application, meaning no entries in web.xml and we rely on class scanning for annotated jax rs resources. In general it works fine.

   @ApplicationPath("/api/v1/")
   public class MyApplication  extends Application{

This version of Websphere  along with Apache Wink, uses Jackson 1.6.x for JSON de/serialization and in general it works  well. We would like though to change some of the default values of the Object Mapper

So we have defined a customer context resolver, where just alter some of the se/deserialzation properties.

@Provider
@Produces(MediaType.APPLICATION_JSON)
public class CustomJackssonConverter implements ContextResolver<ObjectMapper> {

    final ObjectMapper defaultObjectMapper;

    public AibasJackssonConverter() {
        defaultObjectMapper = createDefaultMapper();
    }
   ...
 mapper.getSerializationConfig().set(SerializationConfig.Feature.INDENT_OUTPUT, true);

During JAX-RS calls we can see that the container registers the new Provider, with no errors

The problem is that , the Configuration is not 'followed', from the logs I can see that the Wink Engine is looking up a WinkJacksonProvider, which in turn..returns a JacksonProvider that is following the Jackson(s) default values?

Is there a way to just change this default value?

I have tried to change the implementation of the Application object as indicated here, in order to configure Providers programmatically, but it did not work.

http://www.ibm.com/developerworks/java/library/wa-aj-jackson/index.html

Any hints or tips?

Many thanks

Body:
I was using liberty profile server 20.0.0.0 and eclipselink 2.7.6. The MoxyJsonProvider from eclipselink is used by JAXRS by default and it was throwing "A Cycle is detected" error. I wanted to override the default JAXB Moxy provider with my ObjectMapper or Jackson Json Provider.

public Set<Class<?>> getClasses() did not work. I had to create another class file to create public class JaxbJsonProvider extends JacksonJaxbJsonProvider and annotate it as @Provider. This solution worked for me.

import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.Provider;

import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;

@Provider
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class JaxbJsonProvider extends JacksonJaxbJsonProvider {

}

and the other file is

import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Provider
public class JacksonObjectMapperProvider implements ContextResolver<ObjectMapper> {

    final ObjectMapper defaultObjectMapper;

    public JacksonObjectMapperProvider() {
        defaultObjectMapper = createDefaultMapper();
    }

    @Override
    public ObjectMapper getContext(Class<?> type) {
        return defaultObjectMapper;
    }

    public static ObjectMapper createDefaultMapper() {

        log.info(String.format("Registering ObjectMapper modules"));

        ObjectMapper mapper = new ObjectMapper();

        mapper.disable(DeserializationFeature.FAIL_ON_UNRESOLVED_OBJECT_IDS);
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        mapper.configure(MapperFeature.USE_GETTERS_AS_SETTERS, true);
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

        return mapper;
    }

}

Restart you liberty profile server and REST APIs would work fine. Note that @Slf4j is merely used for logging statement and mapper config options are something that you can skip. Liberty recommends to use mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);. All others are as per your project settings.


问:
Extract grid's records into an object
Say I have a grid and want to extract its records.

```<code>let record = {};
grid.rowAt(rowIndex)
    .cellAt(cellIndex)
    .focus()
    .get('innerText')
    .and(function (future) {
        record.columnName = future.data.innerText;
    });
</code>```

How can I figure out how many columns and rows a grid has?

Based on the column's index how can I get the name of the respective header?

答:
The following examples should help demonstrate how to get the row count, column count, get a column's title, and get the record object from a row in an Ext JS grid using Sencha Test:</p>

```<code>describe('Grid', function() {
    beforeAll(function() {
        ST.grid('array-grid')
            .rowAt(0);      // Wait for data to be in the grid
    });

    it('should check the total number of rows and columns', function() {
        ST.grid('array-grid')
            .execute(function(grid) {
                var values = {
                    recordCount: grid.getStore().getCount(),    // Get the Store count (same as row count)
                    columnCount: grid.query('gridcolumn:visible').length    // Get the number of visible columns
                };

                return values;
            })
            .and(function(future) {
                var result = future.data.executeResult;

                expect(result.recordCount).toEqual(100);
                expect(result.columnCount).toEqual(6);
            });
    });

    it('should get the column title for the fifth column in the grid', function() {
        var columnTitle;

        ST.component('array-grid gridcolumn:visible:nth-child(5)')
            .get('text')
            .and(function(future) {
                // Do something with the column title
                columnTitle = future.data.text;

                expect(columnTitle).toEqual('Last Updated');
            });
    });

    it('should get the record for the third grid row and check some of its values', function() {
        ST.grid('array-grid')
            .rowAt(2)
            .getRecord()
            .and(function(future) {
                var record = future.data.record;

                expect(record.name).toEqual('Dabvine');
                expect(record.price).toEqual(29.94);
            });
    });
});
</code>```

Title: Extract grid's records into an object

Body:
Say I have a grid and want to extract its records.

let record = {};
grid.rowAt(rowIndex)
    .cellAt(cellIndex)
    .focus()
    .get('innerText')
    .and(function (future) {
        record.columnName = future.data.innerText;
    });

How can I figure out how many columns and rows a grid has?

Based on the column's index how can I get the name of the respective header?

Body:
The following examples should help demonstrate how to get the row count, column count, get a column's title, and get the record object from a row in an Ext JS grid using Sencha Test:

describe('Grid', function() {
    beforeAll(function() {
        ST.grid('array-grid')
            .rowAt(0);      // Wait for data to be in the grid
    });

    it('should check the total number of rows and columns', function() {
        ST.grid('array-grid')
            .execute(function(grid) {
                var values = {
                    recordCount: grid.getStore().getCount(),    // Get the Store count (same as row count)
                    columnCount: grid.query('gridcolumn:visible').length    // Get the number of visible columns
                };

                return values;
            })
            .and(function(future) {
                var result = future.data.executeResult;

                expect(result.recordCount).toEqual(100);
                expect(result.columnCount).toEqual(6);
            });
    });

    it('should get the column title for the fifth column in the grid', function() {
        var columnTitle;

        ST.component('array-grid gridcolumn:visible:nth-child(5)')
            .get('text')
            .and(function(future) {
                // Do something with the column title
                columnTitle = future.data.text;

                expect(columnTitle).toEqual('Last Updated');
            });
    });

    it('should get the record for the third grid row and check some of its values', function() {
        ST.grid('array-grid')
            .rowAt(2)
            .getRecord()
            .and(function(future) {
                var record = future.data.record;

                expect(record.name).toEqual('Dabvine');
                expect(record.price).toEqual(29.94);
            });
    });
});


问:
Cannot show TrustPilot HTML when inserted with JavaScript (jQuery)
If I added the TrustPilot html code directly on the HTML page, it works fine but I needed to insert it with jQuery. I see the HTML code when inserted  but it's not displaying.

```<code>  $(window).on('load', function () {
    var el = $('#some-element');

    el.html( trustPilotHtml() );

    function trustPilotHtml() {
      var str = "<div " +
        "class='trustpilot-widget' " +
        "data-locale='en-GB' " +
        "data-template-id='123456' "+
        "data-businessunit-id='123456' " +
        "data-style-height='500px' " +
        "data-style-width='100%' " +
        "data-theme='light' " +
        "data-stars='4,5' " +
        "data-schema-type='Organization'>" +
        "<a " +
        "href='https://some-url.com' target='_blank'>Trustpilot</a> " +
      "</div>";
      return $(str);
    }
});
</code>```

Is the only way of getting the element to display properly is to directly inserted into the HTML without javascript?

答:
The following  worked for me on a product list page which returned filtered list via ajax

```<code>var element = document.getElementsByClassName("trustpilot-widget");
for(var i=0; i<element.length; i++) {
    window.Trustpilot.loadFromElement(element[i]);
}
</code>```

On the first page load all product reviews are displayed as expected, but if the page is updated via ajax call (using filters for example) the reviews are lost. Running the above code after ajax, reloads the reviews

Body:
If I added the TrustPilot html code directly on the HTML page, it works fine but I needed to insert it with jQuery. I see the HTML code when inserted  but it's not displaying.

  $(window).on('load', function () {
    var el = $('#some-element');

    el.html( trustPilotHtml() );

    function trustPilotHtml() {
      var str = "
" +
        "Trustpilot " +
      "
";
      return $(str);
    }
});

Is the only way of getting the element to display properly is to directly inserted into the HTML without javascript?

Body:
The following  worked for me on a product list page which returned filtered list via ajax

var element = document.getElementsByClassName("trustpilot-widget");
for(var i=0; i<element.length; i++) {
    window.Trustpilot.loadFromElement(element[i]);
}

On the first page load all product reviews are displayed as expected, but if the page is updated via ajax call (using filters for example) the reviews are lost. Running the above code after ajax, reloads the reviews


问:
nodejs join two videos together?
So I am working on a concept and while I understand I could use FFMPEG to do what I need to do I was hoping that there would be a way to use nodejs Request to join a video onto the end of another video.

The following code does work for audio, and the video file I am using is an MP4 (note I am trying to join the same video together so instead of 9seconds it should be 18 seconds.

the URL = https://storage.googleapis.com/ad-system/testfolder/Video/10%20second%20video%20FAIL.mp4

```<code>const express = require('express');
request = require('request');

const router = new express.Router();

router.get(':url(*)', (req, res) =>{

    var url = req.params.url.substr(1);
    res.set({
        "Content-Type": "video/mp4",
        'Transfer-Encoding': 'chunked'
    });

    var clients = [];
    ASystem();
    var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
    console.log;(req.params.url);
    /* START A FUNCTION */
    function ASystem(){

                var remote = "https://storage.googleapis.com/ad-system/testfolder/Video/10%20second%20video%20FAIL.mp4";
                var streama = request.get(remote);
                streama.on("connect", function() {
                    console.error(" connected!");
                    console.error(streama.headers);
                });

                streama.on("end", function() {
                    console.error(" END");
                    console.log(url);
                   if(url !== ""){getVideo();}
                    console.error(streama.headers);
                // test = true;

                });

                // Fired after the HTTP response headers have been received.
                streama.on('response', function(res) {
                console.error(" Completed");
                    console.error(res.headers);
                });

                // When a chunk of data is received on the stream, push it to all connected clients
                streama.on("data", function (chunk) {
                        // console.log(clients.length);
                        if (clients.length > 0){
                            for (client in clients){
                                clients[client].write(chunk);
                            };
                        }

                });
    };
/* END A FUNCTION */
/* FETCHING URLVIDEO */
    function getVideo(){
        var remote = url;
        var streama = request.get(remote);
        streama.on("connect", function() {
            console.error(" Stream connected!");
            //console.error(stream.headers);
        });

        streama.on("end", function() {
            console.error(" Stream END");
        // setTimeout(function(){ test = true; console.error('yep yep yep')},29000);
            //console.error(stream.headers);
        // test = true;
        //getVideo();
        });

        // Fired after the HTTP response headers have been received.
        streama.on('response', function(res) {
        // console.error("Stream response!");
            console.error(res.headers);
        });

        // When a chunk of data is received on the stream, push it to all connected clients
        streama.on("data", function (chunk) {
                // console.log(clients.length);
                if (clients.length > 0){
                    for (client in clients){
                        clients[client].write(chunk);
                    };
                }

        });

    }
    /* END VIDEO*/

    /* CORE SYSTEM */

      clients.push(res);

    /* END CORE SYSTEM */
});
module.exports = router;
</code>```

答:
Concatenating video files is not as simple as concatenating audio files. there are metadata ( tags, headers ) and other stuff ( like the resolution/dimension of both videos) that you need to take care of

Some very simple video format may support file level concatenation but mp4 does not support file level concatenation

and in case of mp3 yes you can simply concatenate the file but it will leave some invalid/corrupted headers but in most of the cases it won't effect the playback

Sure you can write a program ( or maybe someone already wrote a library which you can run in node) to correctly concatenate the video which will take some effort but it's not impossible ( also not simple ) to do it without other external tool on the other hand you can use one of the very mature and well working FFMPEG for this job to know more about how you can dot this with FFMPEG see this answer

Title: nodejs join two videos together?

Body:
So I am working on a concept and while I understand I could use FFMPEG to do what I need to do I was hoping that there would be a way to use nodejs Request to join a video onto the end of another video.

The following code does work for audio, and the video file I am using is an MP4 (note I am trying to join the same video together so instead of 9seconds it should be 18 seconds.

the URL = https://storage.googleapis.com/ad-system/testfolder/Video/10%20second%20video%20FAIL.mp4

const express = require('express');
request = require('request');

const router = new express.Router();

router.get(':url(*)', (req, res) =>{

    var url = req.params.url.substr(1);
    res.set({
        "Content-Type": "video/mp4",
        'Transfer-Encoding': 'chunked'
    });

    var clients = [];
    ASystem();
    var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
    console.log;(req.params.url);
    /* START A FUNCTION */
    function ASystem(){

                var remote = "https://storage.googleapis.com/ad-system/testfolder/Video/10%20second%20video%20FAIL.mp4";
                var streama = request.get(remote);
                streama.on("connect", function() {
                    console.error(" connected!");
                    console.error(streama.headers);
                });

                streama.on("end", function() {
                    console.error(" END");
                    console.log(url);
                   if(url !== ""){getVideo();}
                    console.error(streama.headers);
                // test = true;

                });

                // Fired after the HTTP response headers have been received.
                streama.on('response', function(res) {
                console.error(" Completed");
                    console.error(res.headers);
                });

                // When a chunk of data is received on the stream, push it to all connected clients
                streama.on("data", function (chunk) {
                        // console.log(clients.length);
                        if (clients.length > 0){
                            for (client in clients){
                                clients[client].write(chunk);
                            };
                        }

                });
    };
/* END A FUNCTION */
/* FETCHING URLVIDEO */
    function getVideo(){
        var remote = url;
        var streama = request.get(remote);
        streama.on("connect", function() {
            console.error(" Stream connected!");
            //console.error(stream.headers);
        });

        streama.on("end", function() {
            console.error(" Stream END");
        // setTimeout(function(){ test = true; console.error('yep yep yep')},29000);
            //console.error(stream.headers);
        // test = true;
        //getVideo();
        });

        // Fired after the HTTP response headers have been received.
        streama.on('response', function(res) {
        // console.error("Stream response!");
            console.error(res.headers);
        });

        // When a chunk of data is received on the stream, push it to all connected clients
        streama.on("data", function (chunk) {
                // console.log(clients.length);
                if (clients.length > 0){
                    for (client in clients){
                        clients[client].write(chunk);
                    };
                }

        });

    }
    /* END VIDEO*/

    /* CORE SYSTEM */

      clients.push(res);

    /* END CORE SYSTEM */
});
module.exports = router;


问:
Recursion with array's PHP
I have a function (listarUrls ()) that returns / scans all the urls it finds on a web page.
I need that for each of the urls that the function returns to me, I return to the list / scan all the urls of that page
many times as requested by the user, that is

```<code>        .If the user asks for 1 iteration of the url www.a.com, bring back:
            -$arry[0] www.1.com
            -$arry[1] www.2.com
            -..... So with all the urls you find in www.a.com

        .If the user asks for 2 iteration of the url www.a.com, bring back:
            -$arry[0] www.1.com
                -$arry[0][0] www.1-1.com
                -$arry[0][1] www.1-2.com
                -...So with all the urls you find in www.1.com
            -$arry[1] www.2.com
                -$arry[1][0] www.2-1.com
                -$arry[1][1] www.2-2.com
                -...So with all the urls you find in www.2.com
            -...

        .If the user asks for 3 iteration of the url www.a.com, bring back:
            -$arry[0] www.1.com
                -$arry[0][0] www.1-1.com
                    -$arry[0][0][0] www.1-1-1.com
                    -$arry[0][0][1] www.1-1-2.com
                    -...So with all the urls you find in www.1-1.com
                -$arry[0][1] www.1-2.com
                    -$arry[0][1][0] www.1-2-1.com
                    -$arry[0][1][1] www.1-2-2.com
                    -...So with all the urls you find in www.1-2.com
            -$arry[1] www.2.com
                -$arry[1][0] www.2-1.com
                    -$arry[1][0][0] www.2-1-1.com
                    -$arry[1][0][1] www.2-1-2.com
                    -...So with all the urls you find in www.2-1.com
                -$arry[1][1] www.2-2.com
                    -$arry[1][1][0] www.2-2-1.com
                    -$arry[1][1][1] www.2-2-2.com
                    -...So with all the urls you find in www.2-2.com
        -...
</code>```

Could someone shed some light on the subject please?

答:
array_walk_recursive — Apply a user function recursively to every member of an array
https://www.php.net/manual/en/function.array-walk-recursive.php</p>

Title: Recursion with array's PHP

Body:
I have a function (listarUrls ()) that returns / scans all the urls it finds on a web page.
I need that for each of the urls that the function returns to me, I return to the list / scan all the urls of that page
many times as requested by the user, that is

        .If the user asks for 1 iteration of the url www.a.com, bring back:
            -$arry[0] www.1.com
            -$arry[1] www.2.com
            -..... So with all the urls you find in www.a.com

        .If the user asks for 2 iteration of the url www.a.com, bring back:
            -$arry[0] www.1.com
                -$arry[0][0] www.1-1.com
                -$arry[0][1] www.1-2.com
                -...So with all the urls you find in www.1.com
            -$arry[1] www.2.com
                -$arry[1][0] www.2-1.com
                -$arry[1][1] www.2-2.com
                -...So with all the urls you find in www.2.com
            -...

        .If the user asks for 3 iteration of the url www.a.com, bring back:
            -$arry[0] www.1.com
                -$arry[0][0] www.1-1.com
                    -$arry[0][0][0] www.1-1-1.com
                    -$arry[0][0][1] www.1-1-2.com
                    -...So with all the urls you find in www.1-1.com
                -$arry[0][1] www.1-2.com
                    -$arry[0][1][0] www.1-2-1.com
                    -$arry[0][1][1] www.1-2-2.com
                    -...So with all the urls you find in www.1-2.com
            -$arry[1] www.2.com
                -$arry[1][0] www.2-1.com
                    -$arry[1][0][0] www.2-1-1.com
                    -$arry[1][0][1] www.2-1-2.com
                    -...So with all the urls you find in www.2-1.com
                -$arry[1][1] www.2-2.com
                    -$arry[1][1][0] www.2-2-1.com
                    -$arry[1][1][1] www.2-2-2.com
                    -...So with all the urls you find in www.2-2.com
        -...

Could someone shed some light on the subject please?


问:
SQL greater or equal (>=) not returning correctly
When I run a mySQL query:

```<code>SELECT * FROM jobs WHERE salary >= '50000';
</code>```

It returns all the jobs which salaries are over 50000. However, there is two jobs, which have salaries of 8 and 9 and they are returned too. In fact, all jobs, which have salaries between 10 and 5 are returned. (For example, salaries which are 2 are not returned). It's pretty weird and I am not sure what is causing this error.

答:
Presumably, salary is stored as a string, but you want it ordered as a number.

If salary were a number, then the comparison would implicitly convert it.  Instead, be explicit:

```<code>WHERE salary + 0 >= 50000;
</code>```

Then, fix the data.  Something like:

```<code>alter table jobs
    modify column salary decimal(20, 4);
</code>```

Body:
When I run a mySQL query:

SELECT * FROM jobs WHERE salary >= '50000';

It returns all the jobs which salaries are over 50000. However, there is two jobs, which have salaries of 8 and 9 and they are returned too. In fact, all jobs, which have salaries between 10 and 5 are returned. (For example, salaries which are 2 are not returned). It's pretty weird and I am not sure what is causing this error.

Body:
Presumably, salary is stored as a string, but you want it ordered as a number.

If salary were a number, then the comparison would implicitly convert it.  Instead, be explicit:

WHERE salary + 0 >= 50000;

Then, fix the data.  Something like:

alter table jobs
    modify column salary decimal(20, 4);


问:
Why must I import my delegate header files?
I am always finding that if I create a delegate and then assign a class to conform to it I have to explicitly import the delegate .h file into that class otherwise I get an error stating the protocol cannot be found?

Am I missing a global setting somewhere that allows my project to find my delegate?

Thanks

答: I think this is standard C stuff. You need to import your source file before using it. The delegate file is just another header file.</p>


问:
How to make a lambda expression define toString in Java 8?
I don't want to have a normal lambda implementing a method and redefine it's toString as a added value. I want the lambda expression implement only the toString method.
I know I am not expressing it very well but I am sure you will understand me with this example.

```<code>public class LambdaToStringTest {

    public interface ToStringInterface {
        public abstract String toString();
    }

    public static void main(String[] args) {
        print("TRACE: %s", (ToStringInterface)()->someComputation()); // <<-- ERROR: The target type of this expression must be a functional interface
    }

    private static void print(String format, Object... args) {
        System.out.println(String.format(format, args));
    }

}
</code>```

It compiles if I change the name of the method but then it does not override toString so print method will not print what is expected.

This is an attempt to define a log subsystem that evaluates lambdas only when needed (when it is really going to be printed) but being compatible with non-lambda arguments. I know other ways to achieve it but I wonder why I can't do it this way and if there is a workaround or I am doing something wrong,

答:
```<code>static <X,Y> Function<X,Y> withName(Function<X,Y> func, String name) {
    return new Function<X, Y>() {
        @Override
        public Y apply(X x) {
            return func.apply(x);
        }

        @Override
        public String toString() {
            return name;
        }
    };
}

/* Predicate, BiFunction, ... */

{// using
    myFunction(
        withName(a->a+1, "add one"),
        withName((a,b)->a+b, "sum")
    );
}
</code>```

Body:
I don't want to have a normal lambda implementing a method and redefine it's toString as a added value. I want the lambda expression implement only the toString method.
I know I am not expressing it very well but I am sure you will understand me with this example.

public class LambdaToStringTest {

    public interface ToStringInterface {
        public abstract String toString();
    }

    public static void main(String[] args) {
        print("TRACE: %s", (ToStringInterface)()->someComputation()); // <<-- ERROR: The target type of this expression must be a functional interface
    }

    private static void print(String format, Object... args) {
        System.out.println(String.format(format, args));
    }

}

It compiles if I change the name of the method but then it does not override toString so print method will not print what is expected.

This is an attempt to define a log subsystem that evaluates lambdas only when needed (when it is really going to be printed) but being compatible with non-lambda arguments. I know other ways to achieve it but I wonder why I can't do it this way and if there is a workaround or I am doing something wrong,


问:
How to (base64) encode a protobuf as a String for REST
I want to use Protobuf objects in REST service.

I need to deserialize incoming string from base64 to a Protobuf object (IMessage)

I need to serialize outgoing Protobuf object to base64 string

What is the simplest way to do that ?

答:
In my opinion is totally wrong to use proto messages serialized into string and vice versa. It is exactly the contrary of the protobuf design.

The ideal solution is to set the content type into octet-stream (binary) and use the toByteArray() and the parseFrom({bytearray}) methods to achieve the maximum performance. In this way your data will have a very small footprint on the wire and you will get a better network performance.

On the other hand the better solution could be to use streaming everywhere and stream the proto bytes with the method protoObj.writeDelimitedTo({an http output stream}) and with {protoDefClass}.parseDelimitedFrom({an http input stream})


问:
Wrong coordinates on multiple monitors
I have a Datagrid and I want to know the position of a datacell for overlaying it with a window.

It works fine with only one monitor, but with multiple monitors, the window is displaced.

Here's the code:

```<code>Point point = cell.PointToScreen(new Point(0, 0));
...
Window myWindow = new Window();
myWindow.Top = point.Y;
myWindow.Left = point.X;
</code>```

Somebody has some experience with positioning on multiple monitors?

EDIT:

I made following test:

```<code>public MyWindow()
{
    ...
    this.LocationChanged += MyWindow_LocationChanged;
}

void MyWindow_LocationChanged(object sender, EventArgs e)
{
    Console.WriteLine(this.Top + " <--> " + this.PointToScreen(new Point(0, 0)).Y);
}
</code>```

Results:

- Single-Monitor: 0 <--> 30; 20 <--> 50; 100  <--> 130

   ==> Always difference of 30 (may be caused by title bar)

- Dual-Monitor: 0  <--> 30;  20 <--> 55; 100 <--> 153

==> At 0,0 difference of 30. But the more I moved the window away from 0,0. the greater becomes the difference, but should stay the same. Very strange!

EDIT2:

Here's my solution, thanks to CodeNaked for the hint:

```<code>Point point = cell.PointToScreen(new Point(0, 0));
...
Window myWindow = new Window();
PresentationSource source = PresentationSource.FromVisual(this);
myWindow.Top = point.Y / source.CompositionTarget.TransformToDevice.M22;
myWindow.Left = point.X / source.CompositionTarget.TransformToDevice.M11;
</code>```

答:
The behavior you described is not correct and I can't reproduce it.
I created a simple Window with the following code:

```<code>public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        LocationChanged += (s, e) =>
            {
                var screen = PointToScreen(new Point(0, 0));
                var window = new Point(Left, Top);
                var diff = screen - window;
                textbox.Text = window.ToString() + Environment.NewLine +
                               screen.ToString() + Environment.NewLine + diff;
            };
    }
}
</code>```

The last line (= the difference between the two coordinates) never changes.

Title: Wrong coordinates on multiple monitors

Body:
I have a Datagrid and I want to know the position of a datacell for overlaying it with a window.

It works fine with only one monitor, but with multiple monitors, the window is displaced.

Here's the code:

Point point = cell.PointToScreen(new Point(0, 0));
...
Window myWindow = new Window();
myWindow.Top = point.Y;
myWindow.Left = point.X;

Somebody has some experience with positioning on multiple monitors?

EDIT:

I made following test:

public MyWindow()
{
    ...
    this.LocationChanged += MyWindow_LocationChanged;
}

void MyWindow_LocationChanged(object sender, EventArgs e)
{
    Console.WriteLine(this.Top + " <--> " + this.PointToScreen(new Point(0, 0)).Y);
}

Results:

- Single-Monitor: 0 <--> 30; 20 <--> 50; 100  <--> 130

   ==> Always difference of 30 (may be caused by title bar)

- Dual-Monitor: 0  <--> 30;  20 <--> 55; 100 <--> 153

==> At 0,0 difference of 30. But the more I moved the window away from 0,0. the greater becomes the difference, but should stay the same. Very strange!

EDIT2:

Here's my solution, thanks to CodeNaked for the hint:

Point point = cell.PointToScreen(new Point(0, 0));
...
Window myWindow = new Window();
PresentationSource source = PresentationSource.FromVisual(this);
myWindow.Top = point.Y / source.CompositionTarget.TransformToDevice.M22;
myWindow.Left = point.X / source.CompositionTarget.TransformToDevice.M11;

Body:
The behavior you described is not correct and I can't reproduce it.
I created a simple Window with the following code:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        LocationChanged += (s, e) =>
            {
                var screen = PointToScreen(new Point(0, 0));
                var window = new Point(Left, Top);
                var diff = screen - window;
                textbox.Text = window.ToString() + Environment.NewLine +
                               screen.ToString() + Environment.NewLine + diff;
            };
    }
}

The last line (= the difference between the two coordinates) never changes.