问:
Spark - convert array of JSON Strings to Struct array, filter and concat with root
I am totally new to Spark and I'm writing a pipeline to perform some transformations into a list of audits.

Example of my data:

```<code>{
    "id": 932522712299,
    "ticket_id": 12,
    "created_at": "2020-02-14T19:05:16Z",
    "author_id": 392401450482,
    "events": ["{\"id\": 932522713292, \"type\": \"VoiceComment\", \"public\": false, \"data\": {\"from\": \"11987654321\", \"to\": \"+1987644\"}"],
}
</code>```

My schema is basically:

```<code>root
 |-- id: long (nullable = true)
 |-- ticket_id: long (nullable = true)
 |-- created_at: string (nullable = true)
 |-- author_id: long (nullable = true)
 |-- events: array (nullable = true)
 |    |-- element: string (containsNull = true)
</code>```

My transformations has a few steps:

Split events by type: comments, tags, change or update;

For each event found, I must add ticket_id, author_id and created_at from root;

It must have one output for each event type.

Basically, each object inside event's array is a string JSON because each type has a different structure - the only attribute common between them it's the type.

I have reach my goals doing some terrible work by converting my dataframe to dict using the following code:

```<code>audits = list(map(lambda row: row.asDict(), df.collect()))`
comments = []
for audit in audits:
    base_info = {'ticket_id': audit['ticket_id'], 'created_at': audit['created_at'], 'author_id': audit['author_id']}
    audit['events'] = [json.loads(x) for x in audit['events']]

    audit_comments = [
        {**x, **base_info}
        for x in audit['events']
        if x['type'] == "Comment" or x['type'] == "VoiceComment"
    ]
    comments.extend(audit_comments)
</code>```

Maybe this question sounds lame or lazy but I'm really stuck in simple things like:

how to parse 'events' items to struct?

how to select event by type and add informations from root? Maybe using select syntax?

Any help is appreciated.

Body:
I am totally new to Spark and I'm writing a pipeline to perform some transformations into a list of audits.

Example of my data:

{
    "id": 932522712299,
    "ticket_id": 12,
    "created_at": "2020-02-14T19:05:16Z",
    "author_id": 392401450482,
    "events": ["{\"id\": 932522713292, \"type\": \"VoiceComment\", \"public\": false, \"data\": {\"from\": \"11987654321\", \"to\": \"+1987644\"}"],
}

My schema is basically:

root
 |-- id: long (nullable = true)
 |-- ticket_id: long (nullable = true)
 |-- created_at: string (nullable = true)
 |-- author_id: long (nullable = true)
 |-- events: array (nullable = true)
 |    |-- element: string (containsNull = true)

My transformations has a few steps:

Split events by type: comments, tags, change or update;

For each event found, I must add ticket_id, author_id and created_at from root;

It must have one output for each event type.

Basically, each object inside event's array is a string JSON because each type has a different structure - the only attribute common between them it's the type.

I have reach my goals doing some terrible work by converting my dataframe to dict using the following code:

audits = list(map(lambda row: row.asDict(), df.collect()))`
comments = []
for audit in audits:
    base_info = {'ticket_id': audit['ticket_id'], 'created_at': audit['created_at'], 'author_id': audit['author_id']}
    audit['events'] = [json.loads(x) for x in audit['events']]

    audit_comments = [
        {**x, **base_info}
        for x in audit['events']
        if x['type'] == "Comment" or x['type'] == "VoiceComment"
    ]
    comments.extend(audit_comments)

Maybe this question sounds lame or lazy but I'm really stuck in simple things like:

how to parse 'events' items to struct?

how to select event by type and add informations from root? Maybe using select syntax?

Any help is appreciated.

Body:
Since the events array elements don't have the same structure for all rows, what you can do is convert it to a Map(String, String).

Using from_json function and the schema MapType(StringType(), StringType()):

df = df.withColumn("events", explode("events"))\
       .withColumn("events", from_json(col("events"), MapType(StringType(), StringType())))

Then, using element_at (Spark 2.4+), you can get the type like this:

df = df.withColumn("event_type", element_at(col("events"), "type"))

df.printSchema()

#root
 #|-- author_id: long (nullable = true)
 #|-- created_at: string (nullable = true)
 #|-- events: map (nullable = true)
 #|    |-- key: string
 #|    |-- value: string (valueContainsNull = true)
 #|-- id: long (nullable = true)
 #|-- ticket_id: long (nullable = true)
 #|-- event_type: string (nullable = true)

Now, you can filter and select as normal columns:

df.filter(col("event_type") == lit("VoiceComment")).show(truncate=False)

#+------------+--------------------+-----------------------------------------------------------------------------------------------------------+------------+---------+------------+
#|author_id   |created_at          |events                                                                                |id          |ticket_id|event_type  |
#+------------+--------------------+-----------------------------------------------------------------------------------------------------------+------------+---------+------------+
#|392401450482|2020-02-14T19:05:16Z|[id -> 932522713292, type -> VoiceComment, public -> false, data -> {"from":"11987654321","to":"+1987644"}]|932522712299|12       |VoiceComment|
#+------------+--------------------+-----------------------------------------------------------------------------------------------------------+------------+---------+------------+


来源: stackexchange

问:
Print exception stacktrace in Apache Camel
I am developing a program using Spring Boot and Apache Camel that reads a file from a file server using FTP and writes it to another file server using FTP. I am deploying the Spring Boot application in JBoss EAP server. when I used Apache commons-net library to connect to the FTP server, it failed with an exception, it was unable to connect to the FTP server. I printed the stacktrace. The exception is as below:

```<code>    <<Some FTP logs before connecting>>
    500 - I won't open a connection to IP.
    java.lang.NullPointerException
    ...
    ...
</code>```

But when I am doing the same thing using Apache Camel, It is not printing any exception message or stacktrace or the FTP logs. Below is my program:

```<code>public void configure() throws Exception {
        errorHandler(defaultErrorHandler()
                .maximumRedeliveries(3)
                .redeliveryDelay(1000)
                .retryAttemptedLogLevel(LoggingLevel.WARN));

        from("direct:transferFile")
            .log("Transferring file")
            .process(requestProcessor)
            .pollEnrich()
                .simple("${exchangeProperty.inputEndpoint}").timeout(0).aggregationStrategy(requestAggregator)
            .choice()
                .when(body().isNotNull())
                    .toD("${exchangeProperty.outputEndpoint}", true)
                    .log("File transferred")
                .otherwise()
                    .log("Empty body, exiting");
    }
</code>```

Can anyone please suggest me how will I print the stack trace and FTP logs in Apache Camel?

答:
Why not use onException clause with your specific options :

```<code>onException(NullPointerException.class)
    .maximumRedeliveries(3)
    .redeliveryDelay(1000)
    .retryAttemptedLogLevel(LoggingLevel.WARN);
</code>```

For logging use log() with more parameters to display those messages.

```<code>.log(LoggingLevel.WARN,"Transferring file ${body}")
</code>```

Maybe your logs doesn't display because of your log level.

ContentLicense: CC BY-SA 4.0

Body:
I am developing a program using Spring Boot and Apache Camel that reads a file from a file server using FTP and writes it to another file server using FTP. I am deploying the Spring Boot application in JBoss EAP server. when I used Apache commons-net library to connect to the FTP server, it failed with an exception, it was unable to connect to the FTP server. I printed the stacktrace. The exception is as below:

    <<Some FTP logs before connecting>>
    500 - I won't open a connection to IP.
    java.lang.NullPointerException
    ...
    ...

But when I am doing the same thing using Apache Camel, It is not printing any exception message or stacktrace or the FTP logs. Below is my program:

public void configure() throws Exception {
        errorHandler(defaultErrorHandler()
                .maximumRedeliveries(3)
                .redeliveryDelay(1000)
                .retryAttemptedLogLevel(LoggingLevel.WARN));

        from("direct:transferFile")
            .log("Transferring file")
            .process(requestProcessor)
            .pollEnrich()
                .simple("${exchangeProperty.inputEndpoint}").timeout(0).aggregationStrategy(requestAggregator)
            .choice()
                .when(body().isNotNull())
                    .toD("${exchangeProperty.outputEndpoint}", true)
                    .log("File transferred")
                .otherwise()
                    .log("Empty body, exiting");
    }

Can anyone please suggest me how will I print the stack trace and FTP logs in Apache Camel?

Body:
Why not use onException clause with your specific options :

onException(NullPointerException.class)
    .maximumRedeliveries(3)
    .redeliveryDelay(1000)
    .retryAttemptedLogLevel(LoggingLevel.WARN);

For logging use log() with more parameters to display those messages.

.log(LoggingLevel.WARN,"Transferring file ${body}")

Maybe your logs doesn't display because of your log level.


问:
list the file and its base directory
I have some files in my folder /home/sample/* * /*.pdf and *.doc and * .xls etc ('**' means some sub-sub directory.

I need the shell script or linux command to list the files in following manner.

```<code>pdf_docs/xx.pdf
documents/xx.doc
excel/xx.xls
</code>```

pdf_docs, documents and excel are directories, which is located in various depth in /home/sample. like

```<code>/home/sample/12091/pdf_docs/xx.pdf
/home/sample/documents/xx.doc
/home/excel/V2hm/1001/excel/xx.xls
</code>```

答:
How about this?</p>

```<code>find /home/sample -type f -regex '^.*\.\(pdf\|doc\|xls\)$'
</code>```

ContentLicense: CC BY-SA 3.0

Title: list the file and its base directory

Body:
I have some files in my folder /home/sample/* * /*.pdf and *.doc and * .xls etc ('**' means some sub-sub directory.

I need the shell script or linux command to list the files in following manner.

pdf_docs/xx.pdf
documents/xx.doc
excel/xx.xls

pdf_docs, documents and excel are directories, which is located in various depth in /home/sample. like

/home/sample/12091/pdf_docs/xx.pdf
/home/sample/documents/xx.doc
/home/excel/V2hm/1001/excel/xx.xls

Body:
How about this?

find /home/sample -type f -regex '^.*\.\(pdf\|doc\|xls\)$'


问:
Javascript seconds to minutes and seconds
This is a common problem but I'm not sure how to solve it. The code below works fine.

```<code>var mind = time % (60 * 60);
var minutes = Math.floor(mind / 60);

var secd = mind % 60;
var seconds = Math.ceil(secd);
</code>```

However, when I get to 1 hour or 3600 seconds it returns 0 minutes and 0 seconds. How can I avoid this so it returns all the minutes?

答:
Moment.js

If you are using Moment.js then you can use there built in Duration object

```<code>const duration = moment.duration(4825, 'seconds');

const h = duration.hours(); // 1
const m = duration.minutes(); // 20
const s = duration.seconds(); // 25
</code>```

Body:
This is a common problem but I'm not sure how to solve it. The code below works fine.

var mind = time % (60 * 60);
var minutes = Math.floor(mind / 60);

var secd = mind % 60;
var seconds = Math.ceil(secd);

However, when I get to 1 hour or 3600 seconds it returns 0 minutes and 0 seconds. How can I avoid this so it returns all the minutes?

Body:
Moment.js

If you are using Moment.js then you can use there built in Duration object

const duration = moment.duration(4825, 'seconds');

const h = duration.hours(); // 1
const m = duration.minutes(); // 20
const s = duration.seconds(); // 25


问:
Find all ocurrences and replace one by one PHP
I'm replacing all  ocurrences in a string to . And I'm doing:

1) I get video_id from youtube url.

```<code>preg_match('/embed\/([\w+\-+]+)[\"\?]/', $string,$video_id);
</code>```

2) I remove iframe with amp-youtube adding the url video id.

```<code>$string = preg_replace( '/<iframe\s+.*?\s+src=(".*?").*?<\/iframe>/',
                    '<amp-youtube data-videoid="'.$video_id[1].'" width="480" height="270" layout="responsive"></amp-youtube>', (str_replace("https://www.youtube.com/embed/","", $string)));
</code>```

That works fine for just one ocurrence.

But If I have more than one iframe... Ok I can do

```<code>preg_match_all('/embed\/([\w+\-+]+)[\"\?]/', $string,$video_id);
</code>```

to get all video ids in the string.

But how can I loop to add each id to every amp-youtube data-videoid in a string??

Thanks!!

答:
I wish you would have posted a minimal sample html string and your expected output, but I think I gather your meaning.

Don't use regex to parse html.  Iterate while there is an existing iframe tag and replace it with your desired tag using the prepared substring from the iframe's src value.

Code: (Demo)

```<code>$html = <<<HTML
<div>
  <p>
    <iframe allowfullscreen="" class="media-element file-default" data-fid="2219" data-media-element="1" frameborder="0" height="360" src="https://www.youtube.com/embed/sNEJOm4hSaw" width="640"></iframe>
  </p>
  <p>
    <iframe allowfullscreen="" class="media-element file-default" data-fid="2219" data-media-element="1" frameborder="0" height="360" src="https://www.youtube.com/embed/abcdefghijk" width="640"></iframe>
  </p>
</div>
HTML;

$dom = new DOMDocument;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
while ($iframe = $dom->getElementsByTagName('iframe')->item(0)) {
    $amp = $dom->createElement('amp-youtube');
    $amp->setAttribute('width', '480');
    $amp->setAttribute('height', '270');
    $amp->setAttribute('layout', 'responsive');
    $amp->setAttribute('data-videoid', str_replace("https://www.youtube.com/embed/","", $iframe->getAttribute('src')));
    $iframe->parentNode->replaceChild($amp, $iframe);
}
echo $dom->saveHTML();
</code>```

Output:

```<code><div>
  <p>
    <amp-youtube width="480" height="270" layout="responsive" data-videoid="sNEJOm4hSaw"></amp-youtube>
  </p>
  <p>
    <amp-youtube width="480" height="270" layout="responsive" data-videoid="abcdefghijk"></amp-youtube>
  </p>
</div>
</code>```

Body:
I'm replacing all  ocurrences in a string to . And I'm doing:

1) I get video_id from youtube url.

preg_match('/embed\/([\w+\-+]+)[\"\?]/', $string,$video_id);

2) I remove iframe with amp-youtube adding the url video id.

$string = preg_replace( '/<iframe\s+.*?\s+src=(".*?").*?<\/iframe>/',
                    '<amp-youtube data-videoid="'.$video_id[1].'" width="480" height="270" layout="responsive"></amp-youtube>', (str_replace("https://www.youtube.com/embed/","", $string)));

That works fine for just one ocurrence.

But If I have more than one iframe... Ok I can do

preg_match_all('/embed\/([\w+\-+]+)[\"\?]/', $string,$video_id);

to get all video ids in the string.

But how can I loop to add each id to every amp-youtube data-videoid in a string??

Thanks!!

Body:
I wish you would have posted a minimal sample html string and your expected output, but I think I gather your meaning.

Don't use regex to parse html.  Iterate while there is an existing iframe tag and replace it with your desired tag using the prepared substring from the iframe's src value.

Code: (Demo)

$html = <<<HTML
<div>
  <p>
    <iframe allowfullscreen="" class="media-element file-default" data-fid="2219" data-media-element="1" frameborder="0" height="360" src="https://www.youtube.com/embed/sNEJOm4hSaw" width="640"></iframe>
  </p>
  <p>
    <iframe allowfullscreen="" class="media-element file-default" data-fid="2219" data-media-element="1" frameborder="0" height="360" src="https://www.youtube.com/embed/abcdefghijk" width="640"></iframe>
  </p>
</div>
HTML;

$dom = new DOMDocument;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
while ($iframe = $dom->getElementsByTagName('iframe')->item(0)) {
    $amp = $dom->createElement('amp-youtube');
    $amp->setAttribute('width', '480');
    $amp->setAttribute('height', '270');
    $amp->setAttribute('layout', 'responsive');
    $amp->setAttribute('data-videoid', str_replace("https://www.youtube.com/embed/","", $iframe->getAttribute('src')));
    $iframe->parentNode->replaceChild($amp, $iframe);
}
echo $dom->saveHTML();

Output:

<div>
  <p>
    <amp-youtube width="480" height="270" layout="responsive" data-videoid="sNEJOm4hSaw"></amp-youtube>
  </p>
  <p>
    <amp-youtube width="480" height="270" layout="responsive" data-videoid="abcdefghijk"></amp-youtube>
  </p>
</div>


问:
How to find a pair of hunted values for a given value with lopps?
I am trying to write a function that gets a list of numbers and an integer and returns a tuple that containing pair of numbers from the list whose sum is the must closest to the number the function received.
for example: closest([10,22,28,29,30,40], 54) --> (22,30)
It is important for me to do this in loop and in time complexity of  O(n).
The problem with my code is that the loop does not want to rerun the list end for any value I take from the beginning of the list...
I would appreciate help :)
Thanks for the helpers!</p>

```<code>def closest(lst, x):
    max_num = 0
    cur = lst[0]
    final = 0
    my_tup = ()
    for num in lst[::-1]:
        max_num = cur + num
        if max_num <= x:
            if max_num > final:
                final = max_num
                my_tup = (cur, num)
            else:
                cur = lst[1]

    return my_tup

print(closest([10,22,28,29,30,40], 54))  ---> return: (22,29)
</code>```

答:
The important part that you might not have noticed is that your input list is sorted.

```<code>10,22,28,29,30,40
</code>```

Which means you can take advantage of this information to find the pair you're looking for in a single scan of the list. The intuition is that if you need a larger number, you can go towards the end of the list. These kind of solutions are referred to as the two-pointer technique

The problem you're trying to solve is a variant of the 2SUM problem. There are solutions online such as here

However I would suggest that you read through the first couple of links & try to solve it by yourself.

Body:
I am trying to write a function that gets a list of numbers and an integer and returns a tuple that containing pair of numbers from the list whose sum is the must closest to the number the function received.
for example: closest([10,22,28,29,30,40], 54) --> (22,30)
It is important for me to do this in loop and in time complexity of  O(n).
The problem with my code is that the loop does not want to rerun the list end for any value I take from the beginning of the list...
I would appreciate help :)
Thanks for the helpers!

def closest(lst, x):
    max_num = 0
    cur = lst[0]
    final = 0
    my_tup = ()
    for num in lst[::-1]:
        max_num = cur + num
        if max_num <= x:
            if max_num > final:
                final = max_num
                my_tup = (cur, num)
            else:
                cur = lst[1]

    return my_tup

print(closest([10,22,28,29,30,40], 54))  ---> return: (22,29)

Body:
The important part that you might not have noticed is that your input list is sorted.

10,22,28,29,30,40

Which means you can take advantage of this information to find the pair you're looking for in a single scan of the list. The intuition is that if you need a larger number, you can go towards the end of the list. These kind of solutions are referred to as the two-pointer technique

The problem you're trying to solve is a variant of the 2SUM problem. There are solutions online such as here

However I would suggest that you read through the first couple of links & try to solve it by yourself.


问:
How to trace a nondescript ueoe angularjs error
I introduced an issue into the next version of my app and for the life of me I can't see what it is.

I have an ng-repeat that lists several options, each option has a button to display the option info in greater detail.  Each option has a button with a link like this:

```<code>ng-click="$location.url('/tab/clubs/L_1001_1001_1001')"
</code>```

In my controller I am assigning the imported $location to: $scope.$location = $location ;  But the moment I click the link I get the following error:

ionic.bundle.js:20306 Error: [$parse:ueoe] Unexpected end of expression: club.
  http://errors.angularjs.org/1.3.13/$parse/ueoe?p0=club.

```<code>    at ionic.bundle.js:8762
    at Parser.consume (ionic.bundle.js:20747)
    at Parser.identifier (ionic.bundle.js:20778)
    at Parser.fieldAccess (ionic.bundle.js:20975)
    at Parser.primary (ionic.bundle.js:20701)
    at Parser.unary (ionic.bundle.js:20970)
    at Parser.multiplicative (ionic.bundle.js:20953)
    at Parser.additive (ionic.bundle.js:20944)
    at Parser.relational (ionic.bundle.js:20935)
    at Parser.equality (ionic.bundle.js:20926)
</code>```

How can I trace what is throwing this error?  Obviously, its related to club. somehow - but I can't tell what.  The error implies I am missing an ending bracket or curly bracket but I ran external tools to check all my syntax and everything looks good.

The above link is called from tab-clubs.html (controller: ClubCtrl) - that entire page renders fine and tracks no issues.  The link calls a specific controller/template using the state:

```<code>  .state('tab.clubs', {
      cache: true,
      url: '/clubs',
      params: {
        'refreshClubs' : 0,
        'pushAction' : 0,
        'pushSub' : null,
        'pushMsg' : null,
        'pushCode' : null
      },
      views: {
        'tab-clubs': {
          templateUrl: 'templates/tab-clubs.html',
          controller: 'ClubCtrl'

        }
      }
    })
    .state('tab.club-detail', {
      url: '/clubs/:ceID',
      views: {
        'tab-clubs': {
          templateUrl: 'templates/detail-clubs.html',
          controller: 'ClubDetailCtrl'
        }
      }
    })
</code>```

...and inside ClubDetailCtrl I added some basic console.log("Here") messages just to see if its making into the controller and it appears it is not.  So it seems to be choking somewhere between clicking the link and calling the controller.

update:

So I moved the $location.url(...) to a controller function and recoded the template to:

```<code>ng-click="goUrl('L_' +event.cID+ '_' +event.clID+ '_' +event.ceID);"
</code>```

And in the controller now have:

```<code>$scope.goUrl = function(id) {
   console.log("A: " +id) ;
   $location.url("/tab/clubs/" +id) ;
   console.log("B: " +id) ;
}
</code>```

The ng-click is firing and getting into the controller function, both console.log A and B are displaying - but still getting the same error.  I then add test console.log() code in the next controller and the tests console log messages never trigger - so its not even making into the controller.

How else can I track this?

答:
ERRONEOUS

```<code>ng-click="$location.url('/tab/clubs/L_{{event.cID}}_{{event.clID}}_{event.ceID}}')"
</code>```

BETTER

```<code>ng-click="$location.url('/tab/clubs/L_'+ event.cID +'_'+ event.clID +'_'+ event.ceID)"
</code>```

For more information, see

Why mixing interpolation and expressions is bad practice

UPDATE

Simplify the template by making a controller method and calling the method from your view:

```<code> ng-click="onClick(event)"
</code>```

```<code> $scope.onClick = function(event) {
     var url = '/tab/clubs/L_'+ event.cID +'_'+ event.clID +'_'+ event.ceID;
     $location.url(url);
 };
</code>```

This will make the code easier to understand, test, debug, and maintain.

Body:
I introduced an issue into the next version of my app and for the life of me I can't see what it is.

I have an ng-repeat that lists several options, each option has a button to display the option info in greater detail.  Each option has a button with a link like this:

ng-click="$location.url('/tab/clubs/L_1001_1001_1001')"

In my controller I am assigning the imported $location to: $scope.$location = $location ;  But the moment I click the link I get the following error:

ionic.bundle.js:20306 Error: [$parse:ueoe] Unexpected end of expression: club.
  http://errors.angularjs.org/1.3.13/$parse/ueoe?p0=club.

    at ionic.bundle.js:8762
    at Parser.consume (ionic.bundle.js:20747)
    at Parser.identifier (ionic.bundle.js:20778)
    at Parser.fieldAccess (ionic.bundle.js:20975)
    at Parser.primary (ionic.bundle.js:20701)
    at Parser.unary (ionic.bundle.js:20970)
    at Parser.multiplicative (ionic.bundle.js:20953)
    at Parser.additive (ionic.bundle.js:20944)
    at Parser.relational (ionic.bundle.js:20935)
    at Parser.equality (ionic.bundle.js:20926)

How can I trace what is throwing this error?  Obviously, its related to club. somehow - but I can't tell what.  The error implies I am missing an ending bracket or curly bracket but I ran external tools to check all my syntax and everything looks good.

The above link is called from tab-clubs.html (controller: ClubCtrl) - that entire page renders fine and tracks no issues.  The link calls a specific controller/template using the state:

  .state('tab.clubs', {
      cache: true,
      url: '/clubs',
      params: {
        'refreshClubs' : 0,
        'pushAction' : 0,
        'pushSub' : null,
        'pushMsg' : null,
        'pushCode' : null
      },
      views: {
        'tab-clubs': {
          templateUrl: 'templates/tab-clubs.html',
          controller: 'ClubCtrl'

        }
      }
    })
    .state('tab.club-detail', {
      url: '/clubs/:ceID',
      views: {
        'tab-clubs': {
          templateUrl: 'templates/detail-clubs.html',
          controller: 'ClubDetailCtrl'
        }
      }
    })

...and inside ClubDetailCtrl I added some basic console.log("Here") messages just to see if its making into the controller and it appears it is not.  So it seems to be choking somewhere between clicking the link and calling the controller.

update:

So I moved the $location.url(...) to a controller function and recoded the template to:

ng-click="goUrl('L_' +event.cID+ '_' +event.clID+ '_' +event.ceID);"

And in the controller now have:

$scope.goUrl = function(id) {
   console.log("A: " +id) ;
   $location.url("/tab/clubs/" +id) ;
   console.log("B: " +id) ;
}

The ng-click is firing and getting into the controller function, both console.log A and B are displaying - but still getting the same error.  I then add test console.log() code in the next controller and the tests console log messages never trigger - so its not even making into the controller.

How else can I track this?

Body:
ERRONEOUS

ng-click="$location.url('/tab/clubs/L_{{event.cID}}_{{event.clID}}_{event.ceID}}')"

BETTER

ng-click="$location.url('/tab/clubs/L_'+ event.cID +'_'+ event.clID +'_'+ event.ceID)"

For more information, see

Why mixing interpolation and expressions is bad practice

UPDATE

Simplify the template by making a controller method and calling the method from your view:

 ng-click="onClick(event)"

 $scope.onClick = function(event) {
     var url = '/tab/clubs/L_'+ event.cID +'_'+ event.clID +'_'+ event.ceID;
     $location.url(url);
 };

This will make the code easier to understand, test, debug, and maintain.


问:
Get Current User in a Blazor component
I'm starting a new site with Blazor and Windows Authentication and need to identify the current user viewing the page/component.

For a Razor Page, the current user name can be accessed with Context.User.Identity.Name, but that doesn't seem to work in a Blazor component.  I've tried injecting HttpContext into the component but the Context is null at runtime.

As a bonus, I will eventually want to incorporate this into Startup.cs so I only need to get the username once and can leverage a corporate user class (with EF Core) for my applications.  Answers tailored to that use case would also be appreciated.

答:
There are three possibilities for getting the user in a component (a page is a component):

Inject IHttpContextAccessor and from it access HttpContext and then User; need to register IHttpContextAccessor in Startup.ConfigureServices, normally using AddHttpContextAccessor. Edit: according to the Microsoft docs you must not do this for security reasons.

Inject an AuthenticationStateProvider property, call GetAuthenticationStateAsync and get a User from it

Wrap your component in a <CascadingAuthenticationState> component, declare a Task<AuthenticationState> property and call it to get the User (similar to #2)

See more here: https://learn.microsoft.com/en-us/aspnet/core/security/blazor.

Title: Get Current User in a Blazor component


问:
Kotlin equivalent of %@ in swift
i am new to kotlin.
In swift i can do :

```<code>let endpoint = "categories/" + "%@/issues/"
let number = "4"
let finalstring = String(format: endpoint, number)
</code>```

The final output of the string will be : categories/4/issues/ as a string .

I have looked at string format in kotlin but it's only work afterwards meaning that i can't define a template for my string and fill it later.

```<code>var value1 = "categories/"
var value2 = 4
var value3 = "/issues/"
println(java.lang.String.format("%s%d%s", value1, value2, value3))
</code>```

This give me the same result but it's mean that i have to manualy write the end of the string.

What i want to do i to have a template for my string in a Road file.
Then complet my string at the run time. The probleme is that the part of my string that i want to complete is in the middle of the string.
Of course i can use substring and remplace but i am looking for a clean way to do it as in swift.

Thanks for helping.

答:
One possible option would be to define a local function that does the formatting:</p>

```<code>fun requestString(number: Int) = "categories/$number/issues/"

val finalString = requestString(4)
</code>```

Title: Kotlin equivalent of %@ in swift

Body:
i am new to kotlin.
In swift i can do :

let endpoint = "categories/" + "%@/issues/"
let number = "4"
let finalstring = String(format: endpoint, number)

The final output of the string will be : categories/4/issues/ as a string .

I have looked at string format in kotlin but it's only work afterwards meaning that i can't define a template for my string and fill it later.

var value1 = "categories/"
var value2 = 4
var value3 = "/issues/"
println(java.lang.String.format("%s%d%s", value1, value2, value3))

This give me the same result but it's mean that i have to manualy write the end of the string.

What i want to do i to have a template for my string in a Road file.
Then complet my string at the run time. The probleme is that the part of my string that i want to complete is in the middle of the string.
Of course i can use substring and remplace but i am looking for a clean way to do it as in swift.

Thanks for helping.

Body:
One possible option would be to define a local function that does the formatting:

fun requestString(number: Int) = "categories/$number/issues/"

val finalString = requestString(4)


问:
Direct3D strange crash
I have Direct3D rendering library compiled with VS2008. The another application (built with VS2008) uses my library and everything works fine.

Recently, parent application was moved to VS2010 but my library is still being built under VS2008. And still everything works fine BUT one call on only ONE sprite.

D3DXSprite->Draw method crashes in D3DX9_43.dll in D3DXCore::CSprite::Draw() method. And it occurs only when I'm trying to draw a specific element from texture.

I've also tried to rebuild my library under VS2010, but no success. Crash still occurs.

Any ideas?

Thanks!

答:
This may not be want you want to hear, but all I can suggest for debugging something like this is the liberal use of break points and special debugging if-statements.

Place a try-catch statement around the render function that is failing and place a breakpoint in the catch block.

You may need to add some counters and debugging variables so that you can monitor the size/cont of your data structures vs. what your rendering code actually processed.

If you still don't have any hints, it's time to temporarily fork your code (copy it) and simplify. Start ripping out chunks of code to see if it still fails. Eventually you'll narrow it down.

Good luck.

Title: Direct3D strange crash


问:
DBATools Error: 'could not load file or assembly 'Microsoft.SqlServer.Replication.dll or one of its dependencies''
I'm running the below Powershell

```<code>Export-DbaInstance -SqlInstance xxxxxx\xxxxxx -ExcludePassword -Exclude databases -Path \\xxxxx\xxxxx
</code>```

However, I'm getting the error

'WARNING: [14:34:02][Export-DbaRepServerSetting] Could not load replication libraries | Could not load file or 'Microsoft.SqlServer.Replication.dll' or one of its dependencies. The specified module could not be found.'

It successfully exports everything else except instance replication.  I can use the -Exclude 'ReplicationSettings'and Export-DBAInstance works successfully.  I can also successfully execute the original script on a Windows 2016 server with any other version of SQL installed.

The Server is Windows 2016 and SQL is 2019 Standard.  The file version of the Microsoft.SqlServer.Replication.dll in dbatools smo folder is 2017.140.1000.169 and product version is 14.0.1000.169.  The versions in C:\Program Files\Microsoft SQL Server\150\SDK\Assemblies are 2019.150.2000.5 and 15.0.2000.5 respectively.

I have also tried executing Invoke-Expression (Invoke-WebRequest -UseBasicParsing https://dbatools.io/in) to download latest version of dbatools, unblocking the file and importing the dbatools module.  I've also tried copying the Microsoft.SqlServer.Replication.dll from a SQL 2016\2012 and 2017 instance into the Assemblies folder above.

答:
You could try to manually load the assemblies, to check the actual error:

```<code>PS> $dbaToolsPath = "xxxx"   # your full path to the dbaTools
PS> $Error.Clear()
PS> Add-Type -Path "$dbaToolsPath\bin\smo\Microsoft.SqlServer.Replication.dll" -ErrorAction Stop
PS> ($Error | Select-Object -Last 1).Exception.InnerException | Select-Object *
</code>```

And repeat this for the Microsoft.SqlServer.Rmo.dll assembly

Body:
I'm running the below Powershell

Export-DbaInstance -SqlInstance xxxxxx\xxxxxx -ExcludePassword -Exclude databases -Path \\xxxxx\xxxxx

However, I'm getting the error

'WARNING: [14:34:02][Export-DbaRepServerSetting] Could not load replication libraries | Could not load file or 'Microsoft.SqlServer.Replication.dll' or one of its dependencies. The specified module could not be found.'

It successfully exports everything else except instance replication.  I can use the -Exclude 'ReplicationSettings'and Export-DBAInstance works successfully.  I can also successfully execute the original script on a Windows 2016 server with any other version of SQL installed.

The Server is Windows 2016 and SQL is 2019 Standard.  The file version of the Microsoft.SqlServer.Replication.dll in dbatools smo folder is 2017.140.1000.169 and product version is 14.0.1000.169.  The versions in C:\Program Files\Microsoft SQL Server\150\SDK\Assemblies are 2019.150.2000.5 and 15.0.2000.5 respectively.

I have also tried executing Invoke-Expression (Invoke-WebRequest -UseBasicParsing https://dbatools.io/in) to download latest version of dbatools, unblocking the file and importing the dbatools module.  I've also tried copying the Microsoft.SqlServer.Replication.dll from a SQL 2016\2012 and 2017 instance into the Assemblies folder above.

Body:
You could try to manually load the assemblies, to check the actual error:

PS> $dbaToolsPath = "xxxx"   # your full path to the dbaTools
PS> $Error.Clear()
PS> Add-Type -Path "$dbaToolsPath\bin\smo\Microsoft.SqlServer.Replication.dll" -ErrorAction Stop
PS> ($Error | Select-Object -Last 1).Exception.InnerException | Select-Object *

And repeat this for the Microsoft.SqlServer.Rmo.dll assembly


问:
What is the difference between "Resource" and "Method" for HTTP Header?
I´m trying to test some Rest Requests with SoapUI.
To make the HTTP Header, for each parameter option I had to set in :

Name ( ex: "Content-Type" )

Value ( ex: "application/json;charset=utf-8" )

Style ( ex: "HEADER" )

and... Level

For Level, I must choose between "Resource" or "Method".

What means "Header level" ?
What means "Resource" or "Method" for "Header level" ?

答:
As you can read in the SoapUI documentation:

Resource level parameters are added to all requests for this resource, regardless of method.

Method level parameters are only added to requests with this specific method.

So if the parameter/header should be added for all methods, use resource level. If the parameters/header should be only added for a specific method, use method level.


问:
Calling lambda from another lambda or exposing api through api-gateway
I am contemplating if I should invoke lambda directly from another lambda or should I expose api through api-gateway in front of lambda. I am looking for pros and cons for both.</p>

答:
Approach #1 Using API Gateway

API Gateway and Lambda have one of the best integrations for serverless applications. It is very widely used and offers a ton of features - proxy integration, mapping templates, custom domain names and different types of authentication.

However, with these pros comes the cons due to some limits with using API Gateway. API Gateway has a default integration time out (a hard limit) of 29 seconds - which means the Lambda function needs to send back a response to API within this time frame or API fails with a 504 response. You may review other limits related to API Gateway here.

Approach #2 Lambda invoking Lambda

I'm not a big fan of this approach and have multiple reasons for it. I'll start with the additional code you have to write - same task with better features can be done by API Gateway with simple configurations on the AWS console.

A container calling another container(Lambda) can result it container-related problems - networking, container reuse and even managing IAM permissions properly.

Also, a Lambda function can be invoked by only three options - SDK, CLI or an entity that has "Invoke" permission. So basically, you need to have some kind of resource in front of your first Lambda to invoke it which will then invoke the second. In my opinion, API Gateway is the best front-end you can have for Lambda which is exactly AWS had in mind building these two services.

One of the pros I can think of this approach is the time out value - Lambda can run for up to max of 15 mins. Unless your client does not require a response back pretty quickly, you can run these two Lambda functions for a longer time to execute code.

Summary

All the above information was pretty general for anyone looking to use API Gateway and Lambda. I'll say it again that using API Gateway is a more convenient and useful approach however it may depend on your use-case. Hope this helps!


答:
By using the itertools module and a dictionary where the keys are the sums of the pairs and the values are lists of pairs:

```<code>from itertools import combinations

def closest(lst, val):
    d = {}
    for element in combinations(lst, 2):
        elem_sum = sum(element)
        try:
            d[elem_sum].append(element)
        except KeyError:
            d[elem_sum] = [element]
    return d[min(d, key=lambda x: abs(x-val))]

>>> closest([10, 22, 28, 29, 30, 40], 54)
[(22, 30)]
</code>```

Title: How to find a pair of hunted values for a given value with lopps?

Body:
By using the itertools module and a dictionary where the keys are the sums of the pairs and the values are lists of pairs:

from itertools import combinations

def closest(lst, val):
    d = {}
    for element in combinations(lst, 2):
        elem_sum = sum(element)
        try:
            d[elem_sum].append(element)
        except KeyError:
            d[elem_sum] = [element]
    return d[min(d, key=lambda x: abs(x-val))]

>>> closest([10, 22, 28, 29, 30, 40], 54)
[(22, 30)]


问:
How secure is GIT bundle
I have two identical repositories on two separated internet-less machines.

The code is sensitive and cannot be exposed to the outside world (even not its diff).

How secure is a git bundle file which contains only a delta update?

I know that one cannot pull from it if he does not have the initial base - git bundle verify will fail.

Opening the file with text editor does not reveal any segment of code.

Is there a way for a third party to open and see the code within?

How secure is it?

答:
It's not secure at all — it contains the same code (or the same diff) that will be applied to repositories. If you cannot expose the repositories (even diff) you cannot expose bundles.

If you want to pass bundles in a secure manner encrypt them.

Title: How secure is GIT bundle


问:
How does one concatenate cell arrays that are part of a cell array in MATLAB?
I have a cell array allData which is Nx1. Each cell contains a structure with a names property (the name is a custom object, but think of it as a cell array of strings if you like). I would like to create a single cell array that contains all of the names. For example, if N=3, so that allData is a 3x1 cell array, then the following would accomplish my goal:

```<code>A = allData{1};
B = allData{2};
C = allData{3};

allNames = [A.names B.names C.names];
</code>```

The problem with this approach is that N is large and changes depending on the input, so I'm hoping that there is a clever way to do this using cellfun, but everything that I've tried fails (e.g. it doesn't work to do allNames = [cellfun(@(x) {x.names}, allData)];).

UPDATE: Thanks to the suggested solutions, I can get everything into one cell array where each cell contains a cell array. My goal here is to concatenate these. More or less, what I have is:

```<code>{A.names B.names C.names}
</code>```

and what I want and cannot seem to get is

```<code>{A.names{1} A.names{2} ... A.names{end} B.names{1} ... B.names{end} ...}
</code>```

SOLUTION:
I needed pieces of each answer below, so here's the solution that worked for me:

from Andrew Lazarus:

allNames = arrayfun(@(x) x.name, [allData{:}], 'UniformOutput', false);

then, from gnovice:

allNames = vertcat(allNames{:});

Thanks to both!!

答:
There are a few more details about your cell contents that would be needed for a more general solution, but if the names property always returns a cell array of strings, and if your structures are all scalars (i.e. 1-by-1 structure arrays), then the following solution using CELLFUN, CHAR, and CELLSTR will give you an N-by-1 cell array of strings allNames containing all of your names:

```<code>allNames = cellfun(@(x) {char(x.names)},allData);
allNames = cellstr(char(allNames{:}));
</code>```

And here's an example where allData contains three different structures:

```<code>>> allData{1} = struct('names',{{'hello'}},'junk',1:3);
>> allData{2} = struct('names',{{'hi' 'yo' 'hey' 'whassup'}});
>> allData{3} = struct('names',{{'howdy';'aloha'}},'junk',4);
>> allNames = cellfun(@(x) {char(x.names)},allData);
>> allNames = cellstr(char(allNames{:}))

allNames =

    'hello'
    'hi'
    'yo'
    'hey'
    'whassup'
    'howdy'
    'aloha'
</code>```

EDIT:

Generalizing to the case where the names property returns a cell array of objects, not necessarily strings, you can try this solution which reshapes each cell array into an M-by-1 cell array, then vertically concatenates all of them into an N-by-1 cell array of objects:

```<code>allNames = cellfun(@(x) {reshape(x.names,[],1)},allData);
allNames = vertcat(allNames{:});
</code>```

Or, if you would rather end up with a 1-by-N cell array of objects, you can do this:

```<code>allNames = cellfun(@(x) {reshape(x.names,1,[])},allData);
allNames = [allNames{:}];
</code>```

Body:
I have a cell array allData which is Nx1. Each cell contains a structure with a names property (the name is a custom object, but think of it as a cell array of strings if you like). I would like to create a single cell array that contains all of the names. For example, if N=3, so that allData is a 3x1 cell array, then the following would accomplish my goal:

A = allData{1};
B = allData{2};
C = allData{3};

allNames = [A.names B.names C.names];

The problem with this approach is that N is large and changes depending on the input, so I'm hoping that there is a clever way to do this using cellfun, but everything that I've tried fails (e.g. it doesn't work to do allNames = [cellfun(@(x) {x.names}, allData)];).

UPDATE: Thanks to the suggested solutions, I can get everything into one cell array where each cell contains a cell array. My goal here is to concatenate these. More or less, what I have is:

{A.names B.names C.names}

and what I want and cannot seem to get is

{A.names{1} A.names{2} ... A.names{end} B.names{1} ... B.names{end} ...}

SOLUTION:
I needed pieces of each answer below, so here's the solution that worked for me:

from Andrew Lazarus:

allNames = arrayfun(@(x) x.name, [allData{:}], 'UniformOutput', false);

then, from gnovice:

allNames = vertcat(allNames{:});

Thanks to both!!

Body:
There are a few more details about your cell contents that would be needed for a more general solution, but if the names property always returns a cell array of strings, and if your structures are all scalars (i.e. 1-by-1 structure arrays), then the following solution using CELLFUN, CHAR, and CELLSTR will give you an N-by-1 cell array of strings allNames containing all of your names:

allNames = cellfun(@(x) {char(x.names)},allData);
allNames = cellstr(char(allNames{:}));

And here's an example where allData contains three different structures:

>> allData{1} = struct('names',{{'hello'}},'junk',1:3);
>> allData{2} = struct('names',{{'hi' 'yo' 'hey' 'whassup'}});
>> allData{3} = struct('names',{{'howdy';'aloha'}},'junk',4);
>> allNames = cellfun(@(x) {char(x.names)},allData);
>> allNames = cellstr(char(allNames{:}))

allNames =

    'hello'
    'hi'
    'yo'
    'hey'
    'whassup'
    'howdy'
    'aloha'

EDIT:

Generalizing to the case where the names property returns a cell array of objects, not necessarily strings, you can try this solution which reshapes each cell array into an M-by-1 cell array, then vertically concatenates all of them into an N-by-1 cell array of objects:

allNames = cellfun(@(x) {reshape(x.names,[],1)},allData);
allNames = vertcat(allNames{:});

Or, if you would rather end up with a 1-by-N cell array of objects, you can do this:

allNames = cellfun(@(x) {reshape(x.names,1,[])},allData);
allNames = [allNames{:}];


问:
Modulenotefounderror; No module name cplex
Im working on my Mac and I just fixed the script.
Then I wanted to make an edit and no nothing seem to work anymore.

I get the error message;
Traceback (most recent call last):
  File "lu.py", line 1, in
    import cplex
ModuleNotFoundError: No module named 'cplex'

I did not made the script and my knowledge about python is not much

When I want to start the script I use
terminal -- cd (file location) pyzton3 lu.py

Anyone who can help me with this problem?

答:
This happens when the Python interpreter cannot find the CPLEX installation.
Usually this can be fixed by setting the PYTHONPATH variable correctly. Make sure that this variable contains the CPLEX Python libraries.

Assuming you are on Linux, you can do the following:

Find the CPLEX (or COS) installation folder.

Assuming this is /path/to/COS then you should have folder /path/to/COS/cplex/python/ and in that folder different sub-directories that correspond to different Python versions.

Assuming you are running Python 3.6, execute the following in your shell: export PYTHONPATH="$PYTHONPATH:/path/to/COS/cplex/python/3.6/x86-64_linux" and then execute your script as before in the same terminal.


问:
How do I use python/selenium to automate sequence of button clicks on a website?
The problem i am trying to solve is this: my home security system does not have a scheduling option and I frequently forget to switch on the system.

I am considering writing a python script that can open a browser, login to the website and click on buttons to activate the home alarm.

I see selenium recommended for automating browser and site action. I wonder though if these two tools can:

be scheduled to run even my computer is sleeping?

automate the whole nine yards - from opening the browser to button clicks to logging off?

I am new to the world of selenium / automation - appreciate any response. Thanks.

答:
Which home security system are you using? Maybe it has some built in API functionality, which would be (in my opinion) much easier to set up and maintain then some "click script".

If you want to use the second way; maybe look into
AutoHotKey (uses Lua instead of python though). Which is great for this kind of stuff.


问:
Is there a way to import * (all) from a module by string?
I am trying to create a dynamically defined settings object where typically you would use the format

base_settings.py:

MY_VAR = 1
```

<p><strong>my_settings.py</strong>:</p>

<pre class="lang-py prettyprint-override"><code>from base_settings import *
assert MY_VAR == 1
</code>```

however in this case I would like base_settings to be a string that defines the path to different setting modules. For instance, I may have the additional base settings files:

base_settings1.py:

MY_VAR = 1
```

<p><strong>base_settings2.py</strong>:</p>

<pre class="lang-py prettyprint-override"><code>MY_VAR = 2
</code>```

my_settings.py:

import os
base_settings = os.environment['SETTINGS_MODULE']  # This is "base_settings2" for the example
from magic(base_settings) import *
assert MY_VAR == 2
```

I'm aware that you can import with importlib.import_module(path) however this returns the imported code into a specific variable rather than "exploded" into the importing file with the original variable names.

答:
You can modify the locals namespace, although it really not reccomended:

```<code>mod_name = os.environment['SETTINGS_MODULE']
locals().update({
    k: v for k, v in importlib.import_module(mod_name).__dict__.items()
    if not k.startswith('_')
})
</code>```

This will add to you local (module) variables the one found in your settings module.

However, it's higly reccomended to keep your confing in a closed object.

Body:
I am trying to create a dynamically defined settings object where typically you would use the format

base_settings.py:

MY_VAR = 1

my_settings.py:

from base_settings import *
assert MY_VAR == 1

however in this case I would like base_settings to be a string that defines the path to different setting modules. For instance, I may have the additional base settings files:

base_settings1.py:

MY_VAR = 1

base_settings2.py:

MY_VAR = 2

my_settings.py:

import os
base_settings = os.environment['SETTINGS_MODULE']  # This is "base_settings2" for the example
from magic(base_settings) import *
assert MY_VAR == 2

I'm aware that you can import with importlib.import_module(path) however this returns the imported code into a specific variable rather than "exploded" into the importing file with the original variable names.

Body:
You can modify the locals namespace, although it really not reccomended:

mod_name = os.environment['SETTINGS_MODULE']
locals().update({
    k: v for k, v in importlib.import_module(mod_name).__dict__.items()
    if not k.startswith('_')
})

This will add to you local (module) variables the one found in your settings module.

However, it's higly reccomended to keep your confing in a closed object.


问:
SyntaxError: Unexpected identifier while Parsin XML Data Using Google App Script
So I am getting leave data from Leave system via API and posting this to a google sheet and below is the sample response xml response.

```<code><?xml version='1.0' encoding='ISO-8859-1'?>
<DataService>
    <Request ID="1253" Status="Approved">
        <TimeOffDate>2020-02-07</TimeOffDate>
        <TimeOffDayOfWeek>Friday</TimeOffDayOfWeek>
        <TimeStart></TimeStart>
        <TimeEnd></TimeEnd>
        <TimeOffHours>8.000</TimeOffHours>
        <TimeOffTypeName>Annual Vacation</TimeOffTypeName>
        <LoginID>testuser</LoginID>
        <Firstname>test</Firstname>
        <Lastname>user</Lastname>
        <UserCategory></UserCategory>
        <SubmittedDate>2019-10-03</SubmittedDate>
        <Deducted>Yes</Deducted>
        <Comment>
            <![CDATA[* time-off request created by administrator]]>
        </Comment>
    </Request>
</code>```

Below is the code that I use to get the data and set it to Google sheet. My challenge is, I am not sure on how to get the attribute ID and Status from the response and push it to the requestObjects array. each time I try to push the attribute using request.getAttribute("ID"), I get an error

SyntaxError: Unexpected identifier

```<code>       };
  var url = 'https://data.purelyhr.com/xml?ak=' + ak + '&sDate=' + start + '&eDate=' + end + '&TimeOffTypeName'+ '&page=' + pages;
  var response = UrlFetchApp.fetch(url).getContentText();
  var document = XmlService.parse(response);
  var root = document.getRootElement();

  //set variables to data from PurelyHR
  var requestElements = root.getChildren('Request'); // Get all <Request> elements
  var requestObjects = []; // Request objects for logging / eventual printing
  for (var i = 0; i < requestElements.length; i++) {
  var request = requestElements[i]; // A single <Request> element
  var Status = request.getAttribute("Status").getValue();

    // Add to requestObjects array
    requestObjects.push({
      Status:request.getAttribute("Status"),
      TimeOffDate: request.getChild('TimeOffDate').getText(),
      TimeOffDayOfWeek: request.getChild('TimeOffDayOfWeek').getText(),
      TimeStart: request.getChild('TimeStart').getText(),
      TimeEnd: request.getChild('TimeEnd').getText(),
      TimeOffHours: request.getChild('TimeOffHours').getText(),
      TimeOffTypeName: request.getChild('TimeOffTypeName').getText(),
      LoginID: request.getChild('LoginID').getText(),
      Firstname: request.getChild('Firstname').getText(),
      Lastname: request.getChild('Lastname').getText(),
      UserCategory: request.getChild('UserCategory').getText(),
      SubmittedDate: request.getChild('SubmittedDate').getText(),
      Deducted: request.getChild('Deducted').getText(),
      Comment: request.getChild('Comment').getText()
    });
  }
 var ss = SpreadsheetApp.getActiveSpreadsheet();
 var sheet = ss.getActiveSheet();
 var range = sheet.getRange("A2:J").getValue();
 for (var j = 0; j < requestObjects.length; j++) {
        sheet.getRange(2 + j, 1).setValue(requestObjects[j].Status)
        sheet.getRange(2 + j, 2).setValue(requestObjects[j].Firstname)
        sheet.getRange(2 + j, 3).setValue(requestObjects[j].Lastname)
        sheet.getRange(2 + j, 4).setValue(requestObjects[j].LoginID);
        sheet.getRange(2 + j, 5).setValue(requestObjects[j].TimeOffTypeName);
        sheet.getRange(2 + j, 6).setValue(requestObjects[j].TimeOffDayOfWeek);
        sheet.getRange(2 + j, 7).setValue(requestObjects[j].SubmittedDate);
        sheet.getRange(2 + j, 8).setValue(requestObjects[j].TimeOffHours)
        sheet.getRange(2 + j, 9).setValue(requestObjects[j].TimeOffDate)
  Logger.log(JSON.stringify(requestObjects));
}

}
</code>```

Results on G sheet

答:
When you invoke the getAttribute() function on an Element instance, it returns an instance of the Attribute class. You then need to call getValue() on that Attribute instance. For example:

var id = request.getAttribute("ID").getValue();
```

Note that the value returned is always of type String.

Body:
So I am getting leave data from Leave system via API and posting this to a google sheet and below is the sample response xml response.

<?xml version='1.0' encoding='ISO-8859-1'?>
<DataService>
    <Request ID="1253" Status="Approved">
        <TimeOffDate>2020-02-07</TimeOffDate>
        <TimeOffDayOfWeek>Friday</TimeOffDayOfWeek>
        <TimeStart></TimeStart>
        <TimeEnd></TimeEnd>
        <TimeOffHours>8.000</TimeOffHours>
        <TimeOffTypeName>Annual Vacation</TimeOffTypeName>
        <LoginID>testuser</LoginID>
        <Firstname>test</Firstname>
        <Lastname>user</Lastname>
        <UserCategory></UserCategory>
        <SubmittedDate>2019-10-03</SubmittedDate>
        <Deducted>Yes</Deducted>
        <Comment>
            <![CDATA[* time-off request created by administrator]]>
        </Comment>
    </Request>

Below is the code that I use to get the data and set it to Google sheet. My challenge is, I am not sure on how to get the attribute ID and Status from the response and push it to the requestObjects array. each time I try to push the attribute using request.getAttribute("ID"), I get an error

SyntaxError: Unexpected identifier

       };
  var url = 'https://data.purelyhr.com/xml?ak=' + ak + '&sDate=' + start + '&eDate=' + end + '&TimeOffTypeName'+ '&page=' + pages;
  var response = UrlFetchApp.fetch(url).getContentText();
  var document = XmlService.parse(response);
  var root = document.getRootElement();

  //set variables to data from PurelyHR
  var requestElements = root.getChildren('Request'); // Get all <Request> elements
  var requestObjects = []; // Request objects for logging / eventual printing
  for (var i = 0; i < requestElements.length; i++) {
  var request = requestElements[i]; // A single <Request> element
  var Status = request.getAttribute("Status").getValue();

    // Add to requestObjects array
    requestObjects.push({
      Status:request.getAttribute("Status"),
      TimeOffDate: request.getChild('TimeOffDate').getText(),
      TimeOffDayOfWeek: request.getChild('TimeOffDayOfWeek').getText(),
      TimeStart: request.getChild('TimeStart').getText(),
      TimeEnd: request.getChild('TimeEnd').getText(),
      TimeOffHours: request.getChild('TimeOffHours').getText(),
      TimeOffTypeName: request.getChild('TimeOffTypeName').getText(),
      LoginID: request.getChild('LoginID').getText(),
      Firstname: request.getChild('Firstname').getText(),
      Lastname: request.getChild('Lastname').getText(),
      UserCategory: request.getChild('UserCategory').getText(),
      SubmittedDate: request.getChild('SubmittedDate').getText(),
      Deducted: request.getChild('Deducted').getText(),
      Comment: request.getChild('Comment').getText()
    });
  }
 var ss = SpreadsheetApp.getActiveSpreadsheet();
 var sheet = ss.getActiveSheet();
 var range = sheet.getRange("A2:J").getValue();
 for (var j = 0; j < requestObjects.length; j++) {
        sheet.getRange(2 + j, 1).setValue(requestObjects[j].Status)
        sheet.getRange(2 + j, 2).setValue(requestObjects[j].Firstname)
        sheet.getRange(2 + j, 3).setValue(requestObjects[j].Lastname)
        sheet.getRange(2 + j, 4).setValue(requestObjects[j].LoginID);
        sheet.getRange(2 + j, 5).setValue(requestObjects[j].TimeOffTypeName);
        sheet.getRange(2 + j, 6).setValue(requestObjects[j].TimeOffDayOfWeek);
        sheet.getRange(2 + j, 7).setValue(requestObjects[j].SubmittedDate);
        sheet.getRange(2 + j, 8).setValue(requestObjects[j].TimeOffHours)
        sheet.getRange(2 + j, 9).setValue(requestObjects[j].TimeOffDate)
  Logger.log(JSON.stringify(requestObjects));
}

}

Results on G sheet

Body:
When you invoke the getAttribute() function on an Element instance, it returns an instance of the Attribute class. You then need to call getValue() on that Attribute instance. For example:

var id = request.getAttribute("ID").getValue();

Note that the value returned is always of type String.


问:
Load category with products from database
I try to get the product category and the products out of the database.
My database looks like this:

```<code>categories
+---+--------+
|id |category|
| 1 |  Toys  |
| 2 |  Books |
| 3 |  Music |
+---+--------+

products
+---+--------+
|id |products|
|1  | Puzzle |
|2  |  Lego  |
|3  |  Duplo |
|4  |  Sia   |
+---+--------+

relation
+-----+-----+
|proid|catid|
|  1  |  1  |
|  2  |  1  |
|  3  |  1  |
|  4  |  3  |
+-----+-----+
</code>```

Below my PHP code

```<code><?php
$sql    = " SELECT relation.catid, products.product, categories.category
            FROM relation
            JOIN categories ON relation.catid = categories.id
            JOIN products ON relation.proid = products.id";

$result            = mysqli_query($connection, $sql);
while($row = mysqli_fetch_assoc($result)){
?>
<h1><?php echo $row['category']; ?></h1>
<span><?php echo $row['product']; ?></span>
<?php
}
?>
</code>```

The code above works but I have an issue.
The category name is displayed every time.

```<code><h1>Toys</h1>
<span>Puzzle</span>
<h1>Toys</h1>
<span>Lego</span>
<h1>Toys</h1>
<span>Duplo</span>
<h1>Music</h1>
<span>Sia</span>
</code>```

Below my expected result

```<code><h1>Toys</h1>
<span>Puzzle</span>
<span>Lego</span>
<span>Duplo</span>
<h1>Music</h1>
<span>Sia</span>
</code>```

Hope somebody can help me.

答:
This is an option:</p>

```<code>$sql = "SELECT relation.catid, products.product, categories.category
        FROM relation
        JOIN categories ON relation.catid = categories.id
        JOIN products ON relation.proid = products.id";

$output = [];
$result = mysqli_query($connection, $sql);
while ($row = mysqli_fetch_assoc($result)) {
    $output[$row['category']][] = $row['product'];
}

foreach ($output as $category => $products) {
    echo "<h1>$category</h1>";
    foreach ($products as $product) {
        echo "<span>$product</span>";
    }
}
</code>```

Body:
I try to get the product category and the products out of the database.
My database looks like this:

categories
+---+--------+
|id |category|
| 1 |  Toys  |
| 2 |  Books |
| 3 |  Music |
+---+--------+

products
+---+--------+
|id |products|
|1  | Puzzle |
|2  |  Lego  |
|3  |  Duplo |
|4  |  Sia   |
+---+--------+

relation
+-----+-----+
|proid|catid|
|  1  |  1  |
|  2  |  1  |
|  3  |  1  |
|  4  |  3  |
+-----+-----+

Below my PHP code

<?php
$sql    = " SELECT relation.catid, products.product, categories.category
            FROM relation
            JOIN categories ON relation.catid = categories.id
            JOIN products ON relation.proid = products.id";

$result            = mysqli_query($connection, $sql);
while($row = mysqli_fetch_assoc($result)){
?>

<?php echo $row['category']; ?>

<?php echo $row['product']; ?>
<?php
}
?>

The code above works but I have an issue.
The category name is displayed every time.

Toys

Puzzle

Toys

Lego

Toys

Duplo

Music

Sia

Below my expected result

Toys

Puzzle
Lego
Duplo

Music

Sia

Hope somebody can help me.

Body:
This is an option:

$sql = "SELECT relation.catid, products.product, categories.category
        FROM relation
        JOIN categories ON relation.catid = categories.id
        JOIN products ON relation.proid = products.id";

$output = [];
$result = mysqli_query($connection, $sql);
while ($row = mysqli_fetch_assoc($result)) {
    $output[$row['category']][] = $row['product'];
}

foreach ($output as $category => $products) {
    echo "<h1>$category</h1>";
    foreach ($products as $product) {
        echo "<span>$product</span>";
    }
}


答:
If your categories are sorted then you can collect these values in array and use each new value once:</p>

```<code>...
$un_vals = [];
while($row = mysqli_fetch_assoc($result)){
?>
   <?php if (!in_array($row['category'],$un_vals) {?>
       <h1><?php echo $row['category']; $un_vals[] = $row['category']; ?></h1>
   <?php } ?>
       <span><?php echo $row['product']; ?></span>

<?php
...
</code>```

Title: Load category with products from database

Body:
If your categories are sorted then you can collect these values in array and use each new value once:

...
$un_vals = [];
while($row = mysqli_fetch_assoc($result)){
?>
   <?php if (!in_array($row['category'],$un_vals) {?>
       <h1><?php echo $row['category']; $un_vals[] = $row['category']; ?></h1>
   <?php } ?>
       <span><?php echo $row['product']; ?></span>

<?php
...


问:
Why do I need root privileges to run GDB?
When I start GDB from the command line I have no problems. But when I start debugging a programs from NetBeans (C++), I get this message:

"Type the name and password of a user in the "Developer Tools" group to allow Developer Tools Access to make changes."

My user is already in the "Developer Tools" group, but this fact seems to be ignored.

With the root password it lets me debug, but I would not debug with the root account!

I checked the GDB executable and path, and they all grant executable permissions to everyone.

Any idea?
Thank you!

Platform:

MacOS X 10.6.6

NetBeans 6.9.1

GCC 4.2

GDB 6.3.50-20050815

答:
No, you shouldn't need root privileges to run GDB. Does your software need to run as root? If your software runs as root GDB will also need to be run as root.

What happens if you run GDB on the command line?

ContentLicense: CC BY-SA 2.5


问:
How to get coordinates and put marker by city name in react native?
Is it possible to get coordinates and put marker on city just by its name? I am trying to get coordinates of my search value (it is city). I am using React Native Maps and there is my code:

```<code>import React, {useState} from 'react';
import { View, StyleSheet, Alert, ActivityIndicator } from 'react-native';
import {SearchBar, Button} from 'react-native-elements';
import MapView from 'react-native-maps';
import Spinner from 'react-native-loading-spinner-overlay';

export default function LinksScreen() {
  const [spinner, setSpinner] = useState(false);
  const [search, setSearch] = useState('');
  const handleChange = event => {
    setSearch(event);
  }
  const [latitudePress, setLatitude] = useState('46.54306');
  const [longitudePress,setLongitude] = useState('14.96917');
  function addMarkerAndRequest(e){
    console.log(e.nativeEvent);
    setLatitude(e.nativeEvent.coordinate.latitude);
    setLongitude(e.nativeEvent.coordinate.longitude);
    const coords = {
      latitude: e.nativeEvent.coordinate.latitude,
      longitude: e.nativeEvent.coordinate.longitude
    };
    Alert.alert(
      'Sprememba mesta',
      'Stanje v komori se bo spremenilo. Ali ste prepričani?',
      [
        {
          text: 'NE',
          style: 'cancel',
        },
        {
          text: 'OK',
          onPress: () => {
            fetch(`http://192.168.88.253:5000/insert/${coords.longitude}/${coords.latitude}`);
          }
        },
      ],
      {cancelable: false},
    )
  }

  return (
    <View style={styles.container}>
      <Spinner
          visible={spinner}
          textStyle={styles.spinnerTextStyle}
      />
      <SearchBar
        containerStyle={{borderColor:'#eee', borderWidth:1}}
        placeholder="Vnesi mesto.."
        onChangeText={(e) => {setSearch(e)}}
        value={search}
        platform='android'
      />
      <MapView
        style={{width:'100%', height:'80%'}}
        initialRegion={{
        latitude: Number(latitudePress),
        longitude: Number(longitudePress),
        latitudeDelta: 0.0922,
        longitudeDelta: 0.0421,
        }}
        onPress={ (event) => addMarkerAndRequest(event) }
      >
        <MapView.Marker
            coordinate={{latitude: Number(latitudePress),
            longitude: Number(longitudePress)}}
            title={`ZŠ: ${latitudePress}, ZD: ${longitudePress}`}
         />
      </MapView>
      <Button
        onPress={()=>Alert.alert(
          'Sprememba mesta',
          'Stanje v komori se bo spremenilo. Ali ste prepričani?',
          [
            {
              text: 'NE',
              style: 'cancel',
            },
            {
              text: 'OK',
              onPress: () => {
                fetch(`http://192.168.88.253:5000/insertcity/${search}`);
                setSearch('');
              }
            },
          ],
          {cancelable: false},
        )}
        title='POTRDI'
      ></Button>
    </View>
  );
}

LinksScreen.navigationOptions = {
  title: 'Zemljevid',
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    justifyContent:'space-between'
  },
});

</code>```

答:
You can do a google places search as described here - https://developers.google.com/places/web-service/search

You will need to set up a google API key to get it to work (the docs describe how you can do this).

Once you've got the correct response from the places search (the response may return multiple results, but you are looking for the one which has types containing the value locality - it's a locality/city type place), you can use the response geometry.location (check response here - https://developers.google.com/places/web-service/search#find-place-responses) to get the coordinates and place the marker on your map

Body:
Is it possible to get coordinates and put marker on city just by its name? I am trying to get coordinates of my search value (it is city). I am using React Native Maps and there is my code:

import React, {useState} from 'react';
import { View, StyleSheet, Alert, ActivityIndicator } from 'react-native';
import {SearchBar, Button} from 'react-native-elements';
import MapView from 'react-native-maps';
import Spinner from 'react-native-loading-spinner-overlay';

export default function LinksScreen() {
  const [spinner, setSpinner] = useState(false);
  const [search, setSearch] = useState('');
  const handleChange = event => {
    setSearch(event);
  }
  const [latitudePress, setLatitude] = useState('46.54306');
  const [longitudePress,setLongitude] = useState('14.96917');
  function addMarkerAndRequest(e){
    console.log(e.nativeEvent);
    setLatitude(e.nativeEvent.coordinate.latitude);
    setLongitude(e.nativeEvent.coordinate.longitude);
    const coords = {
      latitude: e.nativeEvent.coordinate.latitude,
      longitude: e.nativeEvent.coordinate.longitude
    };
    Alert.alert(
      'Sprememba mesta',
      'Stanje v komori se bo spremenilo. Ali ste prepričani?',
      [
        {
          text: 'NE',
          style: 'cancel',
        },
        {
          text: 'OK',
          onPress: () => {
            fetch(`http://192.168.88.253:5000/insert/${coords.longitude}/${coords.latitude}`);
          }
        },
      ],
      {cancelable: false},
    )
  }

  return (
    <View style={styles.container}>
      <Spinner
          visible={spinner}
          textStyle={styles.spinnerTextStyle}
      />
      <SearchBar
        containerStyle={{borderColor:'#eee', borderWidth:1}}
        placeholder="Vnesi mesto.."
        onChangeText={(e) => {setSearch(e)}}
        value={search}
        platform='android'
      />
      <MapView
        style={{width:'100%', height:'80%'}}
        initialRegion={{
        latitude: Number(latitudePress),
        longitude: Number(longitudePress),
        latitudeDelta: 0.0922,
        longitudeDelta: 0.0421,
        }}
        onPress={ (event) => addMarkerAndRequest(event) }
      >
        <MapView.Marker
            coordinate={{latitude: Number(latitudePress),
            longitude: Number(longitudePress)}}
            title={`ZŠ: ${latitudePress}, ZD: ${longitudePress}`}
         />
      </MapView>
      <Button
        onPress={()=>Alert.alert(
          'Sprememba mesta',
          'Stanje v komori se bo spremenilo. Ali ste prepričani?',
          [
            {
              text: 'NE',
              style: 'cancel',
            },
            {
              text: 'OK',
              onPress: () => {
                fetch(`http://192.168.88.253:5000/insertcity/${search}`);
                setSearch('');
              }
            },
          ],
          {cancelable: false},
        )}
        title='POTRDI'
      ></Button>
    </View>
  );
}

LinksScreen.navigationOptions = {
  title: 'Zemljevid',
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    justifyContent:'space-between'
  },
});


问:
How to exclude jar file in Android?
```<code>Duplicate class org.apache.commons.lang3.AnnotationUtils found in modules commons-lang3-3.4.jar (:XXXXX:) and commons-lang3-3.9.jar (org.apache.commons:commons-lang3:3.9)
</code>```

I am using the org.apache.commons: commons-lang3: 3.9 implementation in my project. But the jar file I want to include has org.apache.commons: commons-lang3: 3.4 version. This causes duplicated class error. How can I handle this?

I used this;

```<code>implementation(name: 'xxxxxxx', ext: 'aar') {
        exclude(group = "org.apache.commons", module = "commons-lang3")
    }
</code>```

but he gave this error;
Cannot set the value of read-only property 'module' for configuration

答:
```<code>implementation ("com.google.android.gms:play-services-location:16.0.0"){
    exclude group: 'com.android.support'
    exclude module: 'support-media-compat'
}
</code>```

Try this way.

Title: How to exclude jar file in Android?

Body:
Duplicate class org.apache.commons.lang3.AnnotationUtils found in modules commons-lang3-3.4.jar (:XXXXX:) and commons-lang3-3.9.jar (org.apache.commons:commons-lang3:3.9)

I am using the org.apache.commons: commons-lang3: 3.9 implementation in my project. But the jar file I want to include has org.apache.commons: commons-lang3: 3.4 version. This causes duplicated class error. How can I handle this?

I used this;

implementation(name: 'xxxxxxx', ext: 'aar') {
        exclude(group = "org.apache.commons", module = "commons-lang3")
    }

but he gave this error;
Cannot set the value of read-only property 'module' for configuration

Body:
implementation ("com.google.android.gms:play-services-location:16.0.0"){
    exclude group: 'com.android.support'
    exclude module: 'support-media-compat'
}

Try this way.


问:
Google Cloud API for user
I am AWS fella, so I have no knowledge if this is possible with Google Cloud and googling has failed me so far.

I have a user that I added to a bucket foo with role bar. All I see at the moment is that I get GUI access for bucket foo, now how/can I generate API key for my user so I can use it with resources allowed with role bar?

All I see as an option at the moment is creating service account which does not sound proper to me, but i might be wrong.

答: Google Cloud no longer supports (or reducing support for) API Keys. Your authorization choices are OAuth (user account credentials) or service accounts or presigned urls for Cloud Storage. If this is a user who will be using Google Cloud console or tools use OAuth User Credentials. If this is a software program, use a service account. </p>

Title: Google Cloud API for user


问:
using word "not" as a name of c++ class causes error on VS2019
I'm migrating existing project to VS2019. Having very simple structure that successfully compiled in all previous versions:

```<code>template <class Marker>
struct not
{
    // ...
</code>```

error C2332: 'struct': missing tag name

NOTE-1 I've checked by pre-compilatinion generation that not is not substituted with some macros, output of *.i file fully matches declaration above

NOTE-2 of course if I rename not->inv then all everything is right

答:
not is a keyword in C++, it cannot be used as class name.

See list of keywords on cppreference.

Body:
I'm migrating existing project to VS2019. Having very simple structure that successfully compiled in all previous versions:

template <class Marker>
struct not
{
    // ...

error C2332: 'struct': missing tag name

NOTE-1 I've checked by pre-compilatinion generation that not is not substituted with some macros, output of *.i file fully matches declaration above

NOTE-2 of course if I rename not->inv then all everything is right


答:
not is an alternative operator for !, i.e. a C++ keyword and, thus, it cannot be used in naming.

See the docs.

Title: using word "not" as a name of c++ class causes error on VS2019


问:
No such file, Storing file into the local storage is not working on production
I have a laravel application deployed on Elasticbeanstalk, I'm working on a feature where I need to get a zip file from s3 bucket, store it into the local storage in order to be able to use laravel-zip to remove a pdf file from that zip.
the code is working locally, but I'm receiving 'No Such file error' after testing on production:

```<code>// get the file from s3 and store it into local storage
$contents  = Storage::disk('s3')->get($file_name);
$zip_local_name =  'my_file.zip';
Storage::disk('local')->put($zip_local_name, $contents);

// use laravel-zip to remove the unwanted pdf file from the result
$manager = new ZipManager();
$file_path = storage_path('app').'\\'.$zip_local_name; // register existing zips
$manager->addZip(Zip::open($file_path));
$zip = $manager->getZip(0);
$zip->delete($data["Iso_Bus"]["field_name"].'.pdf');
$zip->close();
</code>```

I made sure that the file exists on s3, so I think my main problem is that the file is not stored in the local storage.
Any help is appreciated

Edit filesystems configrations:

```<code>'disks' => [

        'local' => [
            'driver' => 'local',
            'root' => storage_path('app'),
        ],

        'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],

        's3' => [
            'driver' => 's3',
            'key' => '***',
            'secret' => '***',
            'region' => '***',
            'bucket' => '****',
            'url' => '****',
        ],

    ],
</code>```

答:
You're getting full path for the file wrongly, try this one instead:

$file_path = Storage::disk('local')->path($zip_local_name);
```

<p>Note: It's better to check if the <code>Storage::put</code> was successful before continue:</p>

<pre class="lang-php prettyprint-override"><code>// get the file from s3 and store it into local storage
$contents  = Storage::disk('s3')->get($file_name);
$zip_local_name =  'my_file.zip';

if (Storage::disk('local')->put($zip_local_name, $contents)) {
    // `Storage::put` returns `true` on success, `false` on failure.
    // use laravel-zip to remove the unwanted pdf file from the result
    $manager = new ZipManager();
    $file_path = $file_path = Storage::disk('local')->path($zip_local_name);
    $manager->addZip(Zip::open($file_path));
    $zip = $manager->getZip(0);
    $zip->delete($data["Iso_Bus"]["field_name"].'.pdf');
    $zip->close();
}
</code>```

Body:
I have a laravel application deployed on Elasticbeanstalk, I'm working on a feature where I need to get a zip file from s3 bucket, store it into the local storage in order to be able to use laravel-zip to remove a pdf file from that zip.
the code is working locally, but I'm receiving 'No Such file error' after testing on production:

// get the file from s3 and store it into local storage
$contents  = Storage::disk('s3')->get($file_name);
$zip_local_name =  'my_file.zip';
Storage::disk('local')->put($zip_local_name, $contents);

// use laravel-zip to remove the unwanted pdf file from the result
$manager = new ZipManager();
$file_path = storage_path('app').'\\'.$zip_local_name; // register existing zips
$manager->addZip(Zip::open($file_path));
$zip = $manager->getZip(0);
$zip->delete($data["Iso_Bus"]["field_name"].'.pdf');
$zip->close();

I made sure that the file exists on s3, so I think my main problem is that the file is not stored in the local storage.
Any help is appreciated

Edit filesystems configrations:

'disks' => [

        'local' => [
            'driver' => 'local',
            'root' => storage_path('app'),
        ],

        'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],

        's3' => [
            'driver' => 's3',
            'key' => '***',
            'secret' => '***',
            'region' => '***',
            'bucket' => '****',
            'url' => '****',
        ],

    ],

Body:
You're getting full path for the file wrongly, try this one instead:

$file_path = Storage::disk('local')->path($zip_local_name);

Note: It's better to check if the Storage::put was successful before continue:

// get the file from s3 and store it into local storage
$contents  = Storage::disk('s3')->get($file_name);
$zip_local_name =  'my_file.zip';

if (Storage::disk('local')->put($zip_local_name, $contents)) {
    // `Storage::put` returns `true` on success, `false` on failure.
    // use laravel-zip to remove the unwanted pdf file from the result
    $manager = new ZipManager();
    $file_path = $file_path = Storage::disk('local')->path($zip_local_name);
    $manager->addZip(Zip::open($file_path));
    $zip = $manager->getZip(0);
    $zip->delete($data["Iso_Bus"]["field_name"].'.pdf');
    $zip->close();
}


问:
How to make a diamond using nested for loops
So I was assigned to make a diamond with asterisks in Java and I'm really stumped. Here's what I've come up with so far:

public class Lab1 {
    public static void main(String[] args) {
        for (int i = 5; i > -5; i--) {
            for (int j = 0; j = i; j--) {
                System.out.print(" ");
            }
            System.out.println("*");
        }
    }
}
```

答:
Try this

public class Main {
    public static void main(String[] args) {
        int n = 50;
        int space = n - 1;

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < space; j++) {
                System.out.print(" ");
            }

            for (int j = 0; j <= i; j++) {
                System.out.print("* ");
            }
            System.out.println("");
            space--;
        }

        space = 0;

        for (int i = n; i > 0; i--) {
            for (int j = 0; j < space; j++) {
                System.out.print(" ");
            }

            for (int j = 0; j < i; j++) {
                System.out.print("* ");
            }

            System.out.println("");
            space++;
        }
    }
}
```


问:
How to send data from client socket to server socket using Python?
Main machine running python3.8.0

Second machine python 3.7.5

I created a server socket on my main machine:

```<code>import socket

HOST = ''
PORT = 65432

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    conn, addr = s.accept()
    with conn:
        print('Connected by', addr)
        while True:
            data = conn.recv(1024)
            if not data:
                break
            conn.sendall(data)
</code>```

and I also created a client socket on a second machine:

```<code>import socket

HOST = ''  # The server's hostname or IP address
PORT = 65432        # The port used by the server

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    s.sendall(b'Hello, world')
    data = s.recv(1024)

print('Received', repr(data))
</code>```

My understanding is that if I run the server socket and then connect by running the client socket, my server socket should print :
"connected by [client ip], [specified port]"

At the same time the client should print : "Received b'Hello, world'.

What happens is my server prints "connected by [server ip], [random port]" and client prints "Received b'Hello, world'".

My questions are:

Why does the server print the server ip and not the client ip? And why is the port random if I specified the port?

If my server socket is running, how can I send data from a connecting client socket to the server socket?

For example: x = 'random string'. Upon the client socket connecting, how do I send 'x' so that I receive it on the server side?

答:
Computer just always use the random port to connect, that is normal. About why it print the server IP, that you wrong, there no reason to print the server IP, the server IP is 127.0.0.1. I think you have run both server and client on the same machine.

Let's I provide you what have you do:

SERVER   <-----create the connection----->    CLIENT

SERVER   ---------------------------------    CLIENT

|\________________

|There is a connection!|

SERVER   <----------Hello world-----------    CLIENT

SERVER   -----------Hello world---------->    CLIENT

SERVER   ---------------------------------    CLIENT

```<code>                      _____________________/|

                     |Received 'Hello world'|
</code>```

That why your client print 'Hello world', not server. Look at this:

Server

```<code>with conn:
        print('Connected by', addr)
        while True:
            data = conn.recv(1024) # The server has received 'Hello world'
            if not data:
                break
            conn.sendall(data) # The server has sent back 'Hello world'
</code>```

Client:

```<code>s.connect((HOST, PORT)) # Connected
s.sendall(b'Hello, world') # Send 'Hello world'
data = s.recv(1024) # The server has received it but sent back so now the client received again
</code>```

Body:
Main machine running python3.8.0

Second machine python 3.7.5

I created a server socket on my main machine:

import socket

HOST = ''
PORT = 65432

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    conn, addr = s.accept()
    with conn:
        print('Connected by', addr)
        while True:
            data = conn.recv(1024)
            if not data:
                break
            conn.sendall(data)

and I also created a client socket on a second machine:

import socket

HOST = ''  # The server's hostname or IP address
PORT = 65432        # The port used by the server

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    s.sendall(b'Hello, world')
    data = s.recv(1024)

print('Received', repr(data))

My understanding is that if I run the server socket and then connect by running the client socket, my server socket should print :
"connected by [client ip], [specified port]"

At the same time the client should print : "Received b'Hello, world'.

What happens is my server prints "connected by [server ip], [random port]" and client prints "Received b'Hello, world'".

My questions are:

Why does the server print the server ip and not the client ip? And why is the port random if I specified the port?

If my server socket is running, how can I send data from a connecting client socket to the server socket?

For example: x = 'random string'. Upon the client socket connecting, how do I send 'x' so that I receive it on the server side?

Body:
Computer just always use the random port to connect, that is normal. About why it print the server IP, that you wrong, there no reason to print the server IP, the server IP is 127.0.0.1. I think you have run both server and client on the same machine.

Let's I provide you what have you do:

SERVER   <-----create the connection----->    CLIENT

SERVER   ---------------------------------    CLIENT

|\________________

|There is a connection!|

SERVER   <----------Hello world-----------    CLIENT

SERVER   -----------Hello world---------->    CLIENT

SERVER   ---------------------------------    CLIENT

                      _____________________/|

                     |Received 'Hello world'|

That why your client print 'Hello world', not server. Look at this:

Server

with conn:
        print('Connected by', addr)
        while True:
            data = conn.recv(1024) # The server has received 'Hello world'
            if not data:
                break
            conn.sendall(data) # The server has sent back 'Hello world'

Client:

s.connect((HOST, PORT)) # Connected
s.sendall(b'Hello, world') # Send 'Hello world'
data = s.recv(1024) # The server has received it but sent back so now the client received again


问:
g++ user-defined global new and delete operators on dynamically linked libraries
On g++, code from dynamically linked libraries uses operator delete from the main program.
With the -Wl,-Bsymbolic option, the dynamically linked library used its own operator new but uses the main program's operator delete.
Compiling using clang++ with the -Wl,-Bsymbolic option has the dynamically linked library using its own operator new and delete.
On linux (ubuntu)

```<code>// base_program.cpp
#include <dlfcn.h>
#include <stdio.h>
#include <cstdlib>
typedef void dllFunc();

void *operator new(std::size_t count) {
    printf("base_program new\n");
    void *result = malloc(count);
    return result;
}
void *operator new[](std::size_t count) {
    printf("base_program new[]\n");
    void *result = malloc(count);
    return result;
}
void operator delete(void *ptr) noexcept {
    printf("base_program delete\n");
    free(ptr);
}
void operator delete[](void *ptr) noexcept {
    printf("base_program delete[]\n");
    free(ptr);
}

int main(int nArgs, char **args) {
    void *handle = dlopen(DLLFILE, RTLD_LAZY);
    dllFunc *func = (dllFunc*) dlsym(handle, "testFunc");
    printf("Linking with %s\n", DLLFILE);
    int *a = new int;
    delete a;
    func();
    printf("\n");
    return 0;
}
// linking.cpp
#include <stdio.h>
#include <cstdlib>
void *operator new(std::size_t count) {
    printf("linking new\n");
    void *result = malloc(count);
    return result;
}
void *operator new[](std::size_t count) {
    printf("linking new[]\n");
    void *result = malloc(count);
    return result;
}
void operator delete(void *ptr) noexcept {
    printf("linking delete\n");
    free(ptr);
}
void operator delete[](void *ptr) noexcept {
    printf("linking delete[]\n");
    free(ptr);
}

extern "C" void testFunc() {
    int *a = new int;
    delete a;
}
// build.sh
g++ -g -fPIC -DDLLFILE="\"linking_g.so\"" base_program.cpp -o base_program_g -ldl
g++ -g -fPIC -shared linking.cpp -o linking_g.so -Wl,-Bsymbolic

clang++ -g -fPIC -DDLLFILE="\"linking_clang.so\"" base_program.cpp -o base_program_clang -ldl
clang++ -g -fPIC -shared linking.cpp -o linking_clang.so -Wl,-Bsymbolic

</code>```

Running ./build.sh; ./base_program_g; ./base_program_clang results in the following

```<code>Linking with linking_g.so
base_program new
base_program delete
linking new
base_program delete

Linking with linking_clang.so
base_program new
base_program delete
linking new
linking delete

</code>```

How do I get the clang++ behaviour in g++?

答:
operator delete has different declarations in different C++ standards. Your definitions with noexcept require C++11.

You probably use an old g++ version that compiles in C++03 dialect by default.

A fix is to explicitly set C++11 or newer standard on the command line. I tested with -std=gnu++11 and it fixes your issue.

Body:
On g++, code from dynamically linked libraries uses operator delete from the main program.
With the -Wl,-Bsymbolic option, the dynamically linked library used its own operator new but uses the main program's operator delete.
Compiling using clang++ with the -Wl,-Bsymbolic option has the dynamically linked library using its own operator new and delete.
On linux (ubuntu)

// base_program.cpp
#include <dlfcn.h>
#include <stdio.h>
#include <cstdlib>
typedef void dllFunc();

void *operator new(std::size_t count) {
    printf("base_program new\n");
    void *result = malloc(count);
    return result;
}
void *operator new[](std::size_t count) {
    printf("base_program new[]\n");
    void *result = malloc(count);
    return result;
}
void operator delete(void *ptr) noexcept {
    printf("base_program delete\n");
    free(ptr);
}
void operator delete[](void *ptr) noexcept {
    printf("base_program delete[]\n");
    free(ptr);
}

int main(int nArgs, char **args) {
    void *handle = dlopen(DLLFILE, RTLD_LAZY);
    dllFunc *func = (dllFunc*) dlsym(handle, "testFunc");
    printf("Linking with %s\n", DLLFILE);
    int *a = new int;
    delete a;
    func();
    printf("\n");
    return 0;
}
// linking.cpp
#include <stdio.h>
#include <cstdlib>
void *operator new(std::size_t count) {
    printf("linking new\n");
    void *result = malloc(count);
    return result;
}
void *operator new[](std::size_t count) {
    printf("linking new[]\n");
    void *result = malloc(count);
    return result;
}
void operator delete(void *ptr) noexcept {
    printf("linking delete\n");
    free(ptr);
}
void operator delete[](void *ptr) noexcept {
    printf("linking delete[]\n");
    free(ptr);
}

extern "C" void testFunc() {
    int *a = new int;
    delete a;
}
// build.sh
g++ -g -fPIC -DDLLFILE="\"linking_g.so\"" base_program.cpp -o base_program_g -ldl
g++ -g -fPIC -shared linking.cpp -o linking_g.so -Wl,-Bsymbolic

clang++ -g -fPIC -DDLLFILE="\"linking_clang.so\"" base_program.cpp -o base_program_clang -ldl
clang++ -g -fPIC -shared linking.cpp -o linking_clang.so -Wl,-Bsymbolic

Running ./build.sh; ./base_program_g; ./base_program_clang results in the following

Linking with linking_g.so
base_program new
base_program delete
linking new
base_program delete

Linking with linking_clang.so
base_program new
base_program delete
linking new
linking delete

How do I get the clang++ behaviour in g++?


问:
Apache nifi as cosumer to recieve messages from kafka topic
I have a scenario where I will have to cosume messages in Nifi Kafka consumer processor from messages sent thru Kafka producer Jar invoked locally ..i am able to consume messages in kafka cosumer console but not in Nifi...how to view messgaes in nifi consumer, if message is in json format</p>

答:
setup your consume kafka processor and link it to a stopped processor.

right clik on queue > list queue > view details > view .


问:
BeautifulSoup module error (html parser) while using Seaborn
I am using seaborn to draw a graph.

First I wanted to get the names of the sample dataset.

sns.get_dataset_names()

but this returned an error :

```<code>The code that caused this warning is on line 384 of the file C:\Users\pc\Anaconda3\envs\seaborn\lib\site-packages\seaborn\utils.py. To get rid of this warning, pass the additional argument 'features="html.parser"' to the BeautifulSoup constructor
</code>```

How can I fix this problem? I know I can just ignore this error but I want to get rid of it so that it doesn't show.

答:
To be clear, this is not an error. It is simply a warning.
You would have to step into that seaborn function in utils.py to add that in.

```<code>def get_dataset_names():
    """Report available example datasets, useful for reporting issues."""
    # delayed import to not demand bs4 unless this function is actually used
    from bs4 import BeautifulSoup
    http = urlopen('https://github.com/mwaskom/seaborn-data/')
    gh_list = BeautifulSoup(http, 'html.parser')  #<-- you'd need to add the parameter here

    return [l.text.replace('.csv', '')
            for l in gh_list.find_all("a", {"class": "js-navigation-open"})
            if l.text.endswith('.csv')]
</code>```

Body:
I am using seaborn to draw a graph.

First I wanted to get the names of the sample dataset.

sns.get_dataset_names()

but this returned an error :

The code that caused this warning is on line 384 of the file C:\Users\pc\Anaconda3\envs\seaborn\lib\site-packages\seaborn\utils.py. To get rid of this warning, pass the additional argument 'features="html.parser"' to the BeautifulSoup constructor

How can I fix this problem? I know I can just ignore this error but I want to get rid of it so that it doesn't show.

Body:
To be clear, this is not an error. It is simply a warning.
You would have to step into that seaborn function in utils.py to add that in.

def get_dataset_names():
    """Report available example datasets, useful for reporting issues."""
    # delayed import to not demand bs4 unless this function is actually used
    from bs4 import BeautifulSoup
    http = urlopen('https://github.com/mwaskom/seaborn-data/')
    gh_list = BeautifulSoup(http, 'html.parser')  #<-- you'd need to add the parameter here

    return [l.text.replace('.csv', '')
            for l in gh_list.find_all("a", {"class": "js-navigation-open"})
            if l.text.endswith('.csv')]