问:
Laravel command called from Laravel job
I have a command named MyCommand, and I am calling it from a job named MyJob. I cannot see the command outputs when it's called from job. But if I run the command directly from command line, command output is seen.

MyCommand.php code:

```<code>namespace App\Console\Commands;

use Illuminate\Console\Command;

class MyCommand extends Command
{

    protected $signature = 'mycommand:doit';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $this->info('Process started');

        //Some process is done here

        $this->info('Process completed');
    }
}
</code>```

MyJob.php code:

```<code>namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Artisan;

class MyJob implements ShouldQueue
{
    public function __construct()
    {

    }

    public function handle()
    {
        Artisan::call('mycommand:doit');
    }
}
</code>```

答: use Artisan::output method to get output from last executed command by Artisan facade.

Title: Laravel command called from Laravel job

Body:
I have a command named MyCommand, and I am calling it from a job named MyJob. I cannot see the command outputs when it's called from job. But if I run the command directly from command line, command output is seen.

MyCommand.php code:

namespace App\Console\Commands;

use Illuminate\Console\Command;

class MyCommand extends Command
{

    protected $signature = 'mycommand:doit';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $this->info('Process started');

        //Some process is done here

        $this->info('Process completed');
    }
}

MyJob.php code:

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Artisan;

class MyJob implements ShouldQueue
{
    public function __construct()
    {

    }

    public function handle()
    {
        Artisan::call('mycommand:doit');
    }
}


来源: stackexchange

问:
Code executing both if and else statements together how do i fix?
the code is running to match username with password and if both correct redirecting to another page but that and the else statements both run

Code:

```<code>if (isset($_POST['Login'])) {
    $IncorrectDetails = 0;
    $Username=$_REQUEST['Username'];
    $Password=$_REQUEST['Password'];

    echo "<p> $Username  $Password</p>";

    $myfile = fopen("bin\Account Details.txt", "r") or die("Unable to open file!");
    //reads raw file
    $string = fread($myfile,filesize("bin\Account Details.txt"));
    //turns the string to array
    $a = explode(',', $string);

    foreach ($a as $result) {
        $b = explode('. ', $result);
        $AccountDetails[trim($b[0])] = trim($b[1]);
    }

    //closes file
    fclose($myfile);
    print_r($AccountDetails);

    foreach ($AccountDetails as $StoredUsername => $StoredPassword) {
        if ($StoredUsername == $Username){
            if ($StoredPassword == $Password) {
                header('Location: Main.php');
            }
            else {
                $IncorrectDetails = 1;
            }
        }
        else {
            $IncorrectDetails = 1;
        }
    }

    if ($IncorrectDetails == 1){
        echo "<script type='text/javascript'>alert('Incorrect login details');</script>";
    }
}
</code>```

its expected to come up with a popup when incorrect and redirect when correct

答:
```<code>if (isset($_POST['Login'])) {
    $IncorrectDetails = 0;
    $Username=$_REQUEST['Username'];
    $Password=$_REQUEST['Password'];

    echo "<p> $Username  $Password</p>";

    $myfile = fopen("bin\Account Details.txt", "r") or die("Unable to open file!");
    //reads raw file
    $string = fread($myfile,filesize("bin\Account Details.txt"));
    //turns the string to array
    $a = explode(',', $string);

    foreach ($a as $result) {
        $b = explode('. ', $result);
        $AccountDetails[trim($b[0])] = trim($b[1]);
    }

    //closes file
    fclose($myfile);

    foreach ($AccountDetails as $StoredUsername => $StoredPassword) {
        if ($StoredUsername == $Username && $StoredPassword == $Password){
           $CorrectDetails = 1;
        } else {
            $IncorrectDetails = 1;
        }
    }
  if(isset($CorrectDetails) && $CorrectDetails == 1){
   header('Location: Main.php');
  }else ($IncorrectDetails == 1){
        echo "<script type='text/javascript'>alert('Incorrect login details');</script>";
    }
}
</code>```

You are redirect to another page it's not a proper way instead of that you can use a variable just like you have used in else and outside the loop you can redirect to another page.

ContentLicense: CC BY-SA 4.0

Body:
the code is running to match username with password and if both correct redirecting to another page but that and the else statements both run

Code:

if (isset($_POST['Login'])) {
    $IncorrectDetails = 0;
    $Username=$_REQUEST['Username'];
    $Password=$_REQUEST['Password'];

    echo "
 $Username  $Password
";

    $myfile = fopen("bin\Account Details.txt", "r") or die("Unable to open file!");
    //reads raw file
    $string = fread($myfile,filesize("bin\Account Details.txt"));
    //turns the string to array
    $a = explode(',', $string);

    foreach ($a as $result) {
        $b = explode('. ', $result);
        $AccountDetails[trim($b[0])] = trim($b[1]);
    }

    //closes file
    fclose($myfile);
    print_r($AccountDetails);

    foreach ($AccountDetails as $StoredUsername => $StoredPassword) {
        if ($StoredUsername == $Username){
            if ($StoredPassword == $Password) {
                header('Location: Main.php');
            }
            else {
                $IncorrectDetails = 1;
            }
        }
        else {
            $IncorrectDetails = 1;
        }
    }

    if ($IncorrectDetails == 1){
        echo "";
    }
}

its expected to come up with a popup when incorrect and redirect when correct

Body:
if (isset($_POST['Login'])) {
    $IncorrectDetails = 0;
    $Username=$_REQUEST['Username'];
    $Password=$_REQUEST['Password'];

    echo "<p> $Username  $Password</p>";

    $myfile = fopen("bin\Account Details.txt", "r") or die("Unable to open file!");
    //reads raw file
    $string = fread($myfile,filesize("bin\Account Details.txt"));
    //turns the string to array
    $a = explode(',', $string);

    foreach ($a as $result) {
        $b = explode('. ', $result);
        $AccountDetails[trim($b[0])] = trim($b[1]);
    }

    //closes file
    fclose($myfile);

    foreach ($AccountDetails as $StoredUsername => $StoredPassword) {
        if ($StoredUsername == $Username && $StoredPassword == $Password){
           $CorrectDetails = 1;
        } else {
            $IncorrectDetails = 1;
        }
    }
  if(isset($CorrectDetails) && $CorrectDetails == 1){
   header('Location: Main.php');
  }else ($IncorrectDetails == 1){
        echo "<script type='text/javascript'>alert('Incorrect login details');</script>";
    }
}

You are redirect to another page it's not a proper way instead of that you can use a variable just like you have used in else and outside the loop you can redirect to another page.


问:
Type mismatch when processing a stream with maxBy()
I'm writing a code to handle Mountain Huts in different municipalities in different provinces. I'm trying to compute the maximum number of beds available in a single mountain hut per altitude range. If the altitude of the mountain hut is not available, i'll use the
altitude of its municipality.
I would like my method to return a Map<String, Optional<Integer>> but i'm getting a Map <String , Optional<MountainHut>> . Now i am aware of the fact that the Optional i am getting is actually the one who has the maximum bed number but i am struggling to get the right data type.

```<code>public Map<String, Optional<Integer>> maximumBedsNumberPerAltitudeRange()
{
    return this.getMountainHuts().stream()
        .collect(
            Collectors.groupingBy((MountainHut mountainHut) ->
                this.getAltitudeRange(
                    mountainHut.getAltitude().orElse(mountainHut.getMunicipality().getAltitude())
                ),
                Collectors.maxBy(Comparator.comparing(MountainHut::getBedsNumber))
            )
        );
}
</code>```

For completeness i'll post also the getAltitudeRange method, the other
methods are just getters.

```<code>public String getAltitudeRange(Integer altitude) {
    Range r = ranges.stream()
        .filter((x) -> altitude>= x.getMin() || altitude <= x.getMax())
        .findFirst()
        .orElse(new Range(0,Integer.MAX_VALUE));
    ranges.stream().close();
    if(r.getMax() == Integer.MAX_VALUE)
    {
        return (0 +" - "+ "INF");
    }
    return (r.getMin() + " - " + r.getMax());
}
</code>```

Altitude is an Optional attribute of the class MountainHut

As expected the error message is the following:
Type mismatch: cannot convert from Map> to
 Map>

答:
maxBy doesn't transform, it just compare. Your extracting the key (i.e. bed number) is implementation detail of your Comparator which maxBy has no knowledge of.

You are actually very close though. You just need to add an intermediate step between groupingBy and maxBy.

```<code>public Map<String, Optional<Integer>> maximumBedsNumberPerAltitudeRange()
{
    return this.getMountainHuts().stream()
        .collect(
            Collectors.groupingBy((MountainHut mountainHut) ->
                this.getAltitudeRange(
                    mountainHut.getAltitude().orElse(mountainHut.getMunicipality().getAltitude())
                ),
                Collectors.mapping(MountainHut::getBedsNumber, Collectors.maxBy(Comparator.naturalOrder()))
            )
        );
}
</code>```

PS: In stream heavy classes you can add an import static java.util.stream.Collectors.* to get rid of boilerplate.

Body:
I'm writing a code to handle Mountain Huts in different municipalities in different provinces. I'm trying to compute the maximum number of beds available in a single mountain hut per altitude range. If the altitude of the mountain hut is not available, i'll use the
altitude of its municipality.
I would like my method to return a Map<String, Optional<Integer>> but i'm getting a Map <String , Optional<MountainHut>> . Now i am aware of the fact that the Optional i am getting is actually the one who has the maximum bed number but i am struggling to get the right data type.

public Map<String, Optional<Integer>> maximumBedsNumberPerAltitudeRange()
{
    return this.getMountainHuts().stream()
        .collect(
            Collectors.groupingBy((MountainHut mountainHut) ->
                this.getAltitudeRange(
                    mountainHut.getAltitude().orElse(mountainHut.getMunicipality().getAltitude())
                ),
                Collectors.maxBy(Comparator.comparing(MountainHut::getBedsNumber))
            )
        );
}

For completeness i'll post also the getAltitudeRange method, the other
methods are just getters.

public String getAltitudeRange(Integer altitude) {
    Range r = ranges.stream()
        .filter((x) -> altitude>= x.getMin() || altitude <= x.getMax())
        .findFirst()
        .orElse(new Range(0,Integer.MAX_VALUE));
    ranges.stream().close();
    if(r.getMax() == Integer.MAX_VALUE)
    {
        return (0 +" - "+ "INF");
    }
    return (r.getMin() + " - " + r.getMax());
}

Altitude is an Optional attribute of the class MountainHut

As expected the error message is the following:
Type mismatch: cannot convert from Map> to
 Map>

Body:
maxBy doesn't transform, it just compare. Your extracting the key (i.e. bed number) is implementation detail of your Comparator which maxBy has no knowledge of.

You are actually very close though. You just need to add an intermediate step between groupingBy and maxBy.

public Map<String, Optional<Integer>> maximumBedsNumberPerAltitudeRange()
{
    return this.getMountainHuts().stream()
        .collect(
            Collectors.groupingBy((MountainHut mountainHut) ->
                this.getAltitudeRange(
                    mountainHut.getAltitude().orElse(mountainHut.getMunicipality().getAltitude())
                ),
                Collectors.mapping(MountainHut::getBedsNumber, Collectors.maxBy(Comparator.naturalOrder()))
            )
        );
}

PS: In stream heavy classes you can add an import static java.util.stream.Collectors.* to get rid of boilerplate.


问:
Access an element while splitting a string
I want to retrieve a last element of the array. Array is a splitted string retrieved as follows:

my @net_info = split(/\//,'10.0.0.2/8');

I am interested only in the last element of the array, that is the CIDR value in one line. I was thinking of:

    my $cidr = ${split(/\//,'10.0.0.2/8')}[-1];

but that resulted in:

Can't use string ("2") as an ARRAY ref while "strict refs" in use at...

Is it possible to get last element directly? What is the right syntax to achieve it?

Body:
The right syntax is:

my $cidr = (split(/\//,'10.0.0.2/8'))[-1];


问:
Difference between events and delegates and its respective applications
I don't see advantages of using events over delegates, other than being syntactical sugar. Perhaps I am misunderstanding, but it seems that event is just a placeholder for delegate.

Would you explain to me the differences and when to use which?  What are the advantages and disadvantages? Our code is heavily rooted with events, and I want to get to the bottom of it.

When would you use delegates over events and vice versa? Please state your real world experience with both, say in the production code.

答:
Events are syntactical sugar.  They are delicious.  When I see an event, I know what to do.  When I see a delegate, I'm not so sure.

Combining events with interfaces (more sugar) makes for a mouth watering snack.  Delegates and pure virtual abstract classes are much less appetizing.

OwnerDisplayName: Sasha

LastEditorDisplayName: RoBorg

ContentLicense: CC BY-SA 3.0

OwnerDisplayName: Sean

ContentLicense: CC BY-SA 2.5


问:
iPhone/iPad Base64->NSData->PDF how to?
Obj-C or Monotouch.Net C# answers are fine.

I have a Base64 string that is a PDF document received over a web service. I can get the NSData.

How do I take the NSData and save it as a PDF?

-- I get the NSData this way --

```<code>byte[] encodedDataAsBytes = System.Convert.FromBase64String (myBase64String);
string decoded = System.Text.Encoding.Unicode.GetString (encodedDataAsBytes);
NSData data = NSData.FromString (decoded, NSStringEncoding.ASCIIStringEncoding);
</code>```

答:
I'm working on a project where I recently had to accomplish the same thing you are describing. I get base64 encoded PDF files as strings from a .NET web service which need to be decoded to their original and saved as PDF files in the applications documents directory.

My solution was:

Use ASIHTTPRequest to communicate with the web service.

I then use TBXML to parse incoming xml and get the base64 as an NSString.

To decode the string I use a method from QSUtilities library called decodeBase64WithString.

Finally I save the result with NSData's writeToFile.

I have tested and successfully used this method with PDF files that are up to 25mb. I also had a couple of test runs with a 48mb file but that file made the decodeBase64WithString method take up too much memory and my app crashed. Haven't found a solution to this yet..

If you are working with multiple large files be sure to free up your memory once in a while. I got all my files in one loop in which I had to use my own nsautorelease pool and drain it at the end of the loop to free up any autoreleased objects.

Title: iPhone/iPad Base64->NSData->PDF how to?

Body:
Obj-C or Monotouch.Net C# answers are fine.

I have a Base64 string that is a PDF document received over a web service. I can get the NSData.

How do I take the NSData and save it as a PDF?

-- I get the NSData this way --

byte[] encodedDataAsBytes = System.Convert.FromBase64String (myBase64String);
string decoded = System.Text.Encoding.Unicode.GetString (encodedDataAsBytes);
NSData data = NSData.FromString (decoded, NSStringEncoding.ASCIIStringEncoding);


问:
React-sortable-tree - How to get search window
Hi I am implementing tree view. Can somebody help me to get search window.

```<code>   this.state = {
        treeData: [{ title: 'Region', children: [{ title: 'Substation' }] }],
        searchQuery: null
    };

  <SortableTree
          treeData={this.state.treeData}
          onChange={treeData => this.setState({ treeData })}
          theme={FileExplorerTheme}
          searchQuery={this.state.searchQuery}
          searchMethod={this.props.defaultSearchMethod}
 />
</code>```

I am not able to get search window using this

答:
You need to add this.</p>
```<code>   <input type="search" onChange={this.handleSearchOnChange} className="form-control" />

    handleSearchOnChange = e => {
        this.setState({
             searchQuery: e.target.value,
         });
      };
</code>```

Body:
Hi I am implementing tree view. Can somebody help me to get search window.

   this.state = {
        treeData: [{ title: 'Region', children: [{ title: 'Substation' }] }],
        searchQuery: null
    };

  <SortableTree
          treeData={this.state.treeData}
          onChange={treeData => this.setState({ treeData })}
          theme={FileExplorerTheme}
          searchQuery={this.state.searchQuery}
          searchMethod={this.props.defaultSearchMethod}
 />

I am not able to get search window using this

Body:
You need to add this.

   <input type="search" onChange={this.handleSearchOnChange} className="form-control" />

    handleSearchOnChange = e => {
        this.setState({
             searchQuery: e.target.value,
         });
      };


问:
reuse a calculated field in the same query
I have this query.

```<code>SELECT carte.nome, sum(amount) AS total, (1500-sum(amount)) AS residuo
FROM movimenti_carta JOIN carte ON movimenti_carta.banca=carte.id
WHERE data BETWEEN '2019-05-01' AND '2019-05-31'
GROUP by banca
</code>```

The goal of this query is to sum some amounts (sum(amount)) in a period of time. I also set a floor to this amount at 1500 so I want to do the math in the third field. I tried to do

```<code>SELECT carte.nome, sum(amount) AS total, (1500-total) AS residuo
FROM movimenti_carta JOIN carte ON movimenti_carta.banca=carte.id
WHERE data BETWEEN '2019-05-01' AND '2019-05-31'
GROUP by banca
</code>```

but mysql complains that totale is not a known field (it is a derived one).
The first query works but it is not efficient. What am I missing for the second one to work?

答:
Column aliases cannot be re-used in the SELECT where they are defined -- and for a simple reason.  MySQL (in particular) and SQL in general does not guarantee the order of evaluation of expressions in the SELECT.

In your case, the simplest solution is to repeat the expression, because it is so simple.

You have another problem in your query, though.  You are aggregating by banca but only selecting nome.

Here is a better way to write the query:

```<code>SELECT c.nome, sum(?.amount) AS total,
       (1500 - sum(?.amount)) AS residuo
FROM movimenti_carta mc JOIN
     carte c
     ON mc.banca = c.id
WHERE ?.data >= '2019-05-01' AND
      ?.data < '2019-06-01'
GROUP by c.nome;
</code>```

Note the changes:

All column references should be qualified.  The ? is for the alias for the table where the column comes from.

Use table aliases, which are abbreviations of the table names.

The unaggregated columns in the SELECT are in the GROUP BY.

The date arithmetic works for both dates and date/time values.

Body:
I have this query.

SELECT carte.nome, sum(amount) AS total, (1500-sum(amount)) AS residuo
FROM movimenti_carta JOIN carte ON movimenti_carta.banca=carte.id
WHERE data BETWEEN '2019-05-01' AND '2019-05-31'
GROUP by banca

The goal of this query is to sum some amounts (sum(amount)) in a period of time. I also set a floor to this amount at 1500 so I want to do the math in the third field. I tried to do

SELECT carte.nome, sum(amount) AS total, (1500-total) AS residuo
FROM movimenti_carta JOIN carte ON movimenti_carta.banca=carte.id
WHERE data BETWEEN '2019-05-01' AND '2019-05-31'
GROUP by banca

but mysql complains that totale is not a known field (it is a derived one).
The first query works but it is not efficient. What am I missing for the second one to work?

Body:
Column aliases cannot be re-used in the SELECT where they are defined -- and for a simple reason.  MySQL (in particular) and SQL in general does not guarantee the order of evaluation of expressions in the SELECT.

In your case, the simplest solution is to repeat the expression, because it is so simple.

You have another problem in your query, though.  You are aggregating by banca but only selecting nome.

Here is a better way to write the query:

SELECT c.nome, sum(?.amount) AS total,
       (1500 - sum(?.amount)) AS residuo
FROM movimenti_carta mc JOIN
     carte c
     ON mc.banca = c.id
WHERE ?.data >= '2019-05-01' AND
      ?.data < '2019-06-01'
GROUP by c.nome;

Note the changes:

All column references should be qualified.  The ? is for the alias for the table where the column comes from.

Use table aliases, which are abbreviations of the table names.

The unaggregated columns in the SELECT are in the GROUP BY.

The date arithmetic works for both dates and date/time values.


问:
Equivalent of web.xml <jsp-config> for Spring Boot MVC?
The JSP specification allows me to serve .html files as JSP (that is, have the container process them as JSP files) using a <jsp-config> section in web.xml, e.g.:

```<code><web-app …>
  <jsp-config>
    <jsp-property-group>
      <url-pattern>*.html</url-pattern>
    </jsp-property-group>
  </jsp-config>
</web-app>
</code>```

But when I switch to running a @SpringBootApplication with embedded Tomcat, it completely bypasses the web.xml file. Is there an equivalent setting in Spring Boot MVC to set the JSP configuration of a JSP property group, as per standard web.xml, that will configure the existing embedded Tomcat JSP servlet?

(Another example of a JSP setting I might want to configure is <trim-directive-whitespaces>.)

Possible duplicates

I am aware of the extensive answer by walkeros, but that answer only considers adding a new JSP servlet. It does not address adding a new JSP property group to the existing JSP servlet, and indeed doesn't mention the <jsp-config> section in web.xml at all.

答:
You may find a way to make Spring Boot work with XML configurations, but that is not the way it is supposed to be.
To apply special JSP configurations to your application, you could do that as follows:

Create a JSP configuration class that implements JspConfigDescriptor , ex:

```<code>public class MyJspConfigDescriptor implements JspConfigDescriptor {

    private Collection<JspPropertyGroupDescriptor> jspPropertyGroups =
            new LinkedHashSet<JspPropertyGroupDescriptor>();

    private Collection<TaglibDescriptor> taglibs =
            new HashSet<TaglibDescriptor>();

    @Override
    public Collection<JspPropertyGroupDescriptor> getJspPropertyGroups() {
        JspPropertyGroup newPropertyGroup = new JspPropertyGroup();
        newPropertyGroup.addUrlPattern("*.html");
        // You can add more configurations as you wish!
        JspPropertyGroupDescriptorImpl jspDescriptor = new JspPropertyGroupDescriptorImpl(newPropertyGroup);
        jspPropertyGroups.add(jspDescriptor);
        return jspPropertyGroups;
    }

    @Override
    public Collection<TaglibDescriptor> getTaglibs() {
        return taglibs;
    }

}
</code>```

Inform your SpringBootServletInitializer that there are new configurations that you would like to add, you can do so by overriding the onStartup method and add them there:

```<code>@Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        super.onStartup(servletContext);
        servletContext.getJspConfigDescriptor().getJspPropertyGroups().addAll((new MyJspConfigDescriptor()).getJspPropertyGroups());
    }
</code>```

I believe that this would work, but I didn't really test it!

Body:
The JSP specification allows me to serve .html files as JSP (that is, have the container process them as JSP files) using a <jsp-config> section in web.xml, e.g.:

<web-app …>
  <jsp-config>
    <jsp-property-group>
      <url-pattern>*.html</url-pattern>
    </jsp-property-group>
  </jsp-config>
</web-app>

But when I switch to running a @SpringBootApplication with embedded Tomcat, it completely bypasses the web.xml file. Is there an equivalent setting in Spring Boot MVC to set the JSP configuration of a JSP property group, as per standard web.xml, that will configure the existing embedded Tomcat JSP servlet?

(Another example of a JSP setting I might want to configure is <trim-directive-whitespaces>.)

Possible duplicates

I am aware of the extensive answer by walkeros, but that answer only considers adding a new JSP servlet. It does not address adding a new JSP property group to the existing JSP servlet, and indeed doesn't mention the <jsp-config> section in web.xml at all.

Body:
You may find a way to make Spring Boot work with XML configurations, but that is not the way it is supposed to be.
To apply special JSP configurations to your application, you could do that as follows:

Create a JSP configuration class that implements JspConfigDescriptor , ex:

public class MyJspConfigDescriptor implements JspConfigDescriptor {

    private Collection<JspPropertyGroupDescriptor> jspPropertyGroups =
            new LinkedHashSet<JspPropertyGroupDescriptor>();

    private Collection<TaglibDescriptor> taglibs =
            new HashSet<TaglibDescriptor>();

    @Override
    public Collection<JspPropertyGroupDescriptor> getJspPropertyGroups() {
        JspPropertyGroup newPropertyGroup = new JspPropertyGroup();
        newPropertyGroup.addUrlPattern("*.html");
        // You can add more configurations as you wish!
        JspPropertyGroupDescriptorImpl jspDescriptor = new JspPropertyGroupDescriptorImpl(newPropertyGroup);
        jspPropertyGroups.add(jspDescriptor);
        return jspPropertyGroups;
    }

    @Override
    public Collection<TaglibDescriptor> getTaglibs() {
        return taglibs;
    }

}

Inform your SpringBootServletInitializer that there are new configurations that you would like to add, you can do so by overriding the onStartup method and add them there:

@Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        super.onStartup(servletContext);
        servletContext.getJspConfigDescriptor().getJspPropertyGroups().addAll((new MyJspConfigDescriptor()).getJspPropertyGroups());
    }

I believe that this would work, but I didn't really test it!


问:
STS Role Trust relationship
I have defined a trust relationship in destination account using

```<code>{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::[SOURCE_ACCOUNT_NUMBER]:root"
      },
      "Action": "sts:AssumeRole",
      "Condition": {}
    }
  ]
}
</code>```

I want to add a condition to allow only a specific user to have access to this account when using federations (STS). So I've modified the trust relationship as:

```<code>{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::[SOURCE_ACCOUNT_NUMBER]:root"
      },
      "Action": "sts:AssumeRole",
      "Condition": {
        "Bool": {
          "aws:user-name": "[USER-NAME-FROM-SOURCE-ACCOUNT]"
        }
      }
    }
  ]
}
</code>```

However, this condition is not getting evaluated. Is aws:user-name right in this case for verifying this condition?

Reference: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user.html

答:
You can actually specify a specific user in the principal field if you specify the user arn, e.g.:</p>

```<code>"Principal": {
  "AWS": "arn:aws:iam::123456789012:user/<username>"
},
</code>```

Title: STS Role Trust relationship

Body:
I have defined a trust relationship in destination account using

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::[SOURCE_ACCOUNT_NUMBER]:root"
      },
      "Action": "sts:AssumeRole",
      "Condition": {}
    }
  ]
}

I want to add a condition to allow only a specific user to have access to this account when using federations (STS). So I've modified the trust relationship as:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::[SOURCE_ACCOUNT_NUMBER]:root"
      },
      "Action": "sts:AssumeRole",
      "Condition": {
        "Bool": {
          "aws:user-name": "[USER-NAME-FROM-SOURCE-ACCOUNT]"
        }
      }
    }
  ]
}

However, this condition is not getting evaluated. Is aws:user-name right in this case for verifying this condition?

Reference: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user.html

Body:
You can actually specify a specific user in the principal field if you specify the user arn, e.g.:

"Principal": {
  "AWS": "arn:aws:iam::123456789012:user/<username>"
},


问:
How to Pop-up Form on Right Click?
I need to be able to pop-up a TForm when I right click on a TPaintBox (the content of the form will be dependent upon where I click).  If the user clicks anywhere else I'd like the original form to be destroyed (or at least disappear).  If the new click happens to be another right-click on the TPaintBox, a new TForm must appear.  Basically, it's a right-click properties query type action i.e. right-click to get the properties of the area of the TPaintBox.

This seems to be more difficult than I imagined.  I first tried to destroy the pop-up form when the pop was deactivated using the OnDeactivate event.  This resulted in the popup not being shown.

答:
Here's my solution (tested and working)...

```<code>type
  TForm1 = class(TForm)
    ...
  private
    ContextForm: TfrmContext;
  end;

...

implementation

procedure TForm1.Button1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
  if ContextForm <> nil then
    FreeAndNil(ContextForm);
 if Button = mbRight then
  begin
    ContextForm := TfrmContext.Create(Application);
    ContextForm.SetParentComponent(Application);
    ContextForm.Left := Mouse.CursorPos.X;
    ContextForm.Top := Mouse.CursorPos.Y;
    ContextForm.Show;
  end;
end;

procedure TForm1.FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
  if ContextForm <> nil then
    FreeAndNil(ContextForm);
end;
</code>```

In this demo, a right-click on Button1 will create your "Context Form" (which is a TForm) and set its position so the top-left of your "context form" will sit exactly where your mouse cursor is.

A click anywhere else on your form will destroy the Context Form.

Enjoy!

Title: How to Pop-up Form on Right Click?

Body:
Here's my solution (tested and working)...

type
  TForm1 = class(TForm)
    ...
  private
    ContextForm: TfrmContext;
  end;

...

implementation

procedure TForm1.Button1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
  if ContextForm <> nil then
    FreeAndNil(ContextForm);
 if Button = mbRight then
  begin
    ContextForm := TfrmContext.Create(Application);
    ContextForm.SetParentComponent(Application);
    ContextForm.Left := Mouse.CursorPos.X;
    ContextForm.Top := Mouse.CursorPos.Y;
    ContextForm.Show;
  end;
end;

procedure TForm1.FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
  if ContextForm <> nil then
    FreeAndNil(ContextForm);
end;

In this demo, a right-click on Button1 will create your "Context Form" (which is a TForm) and set its position so the top-left of your "context form" will sit exactly where your mouse cursor is.

A click anywhere else on your form will destroy the Context Form.

Enjoy!


问:
Copy .txt file and capitalise first letter of each word and write to new file
I'm making a small script that opens the file_name and writes a copy of it to the destination .txt file but the first letter of each word is capitalised and all whitespace is just replaced by a singular space. I was trying to do this with the .capitalize method or the .capwords method.

```<code>def capitalise_words(file_name, destination):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        capped = text_str.capwords()

    with open(destination, "w") as writefile:
        writefile.write(capped)
</code>```

I can't figure out how I can get this to work. Perhaps slicing to the first character of each word if I split them into a list and capitalizing it using .capitalize?

答:
You can use regex to replace all spaces with single space in a string and .title() to make first letter of every word as capital.

Try this,

```<code>import re

def capitalise_words(file_name, destination):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        capped = re.sub(' +', ' ', text_str).title()

    with open(destination, "w") as writefile:
        writefile.write(capped)
</code>```

Ex:

```<code>>>> text_str = 'this   string    is created to      testing   '
>>> re.sub(' +', ' ', text_str).title()
'This String Is Created To Testing '
</code>```

Body:
I'm making a small script that opens the file_name and writes a copy of it to the destination .txt file but the first letter of each word is capitalised and all whitespace is just replaced by a singular space. I was trying to do this with the .capitalize method or the .capwords method.

def capitalise_words(file_name, destination):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        capped = text_str.capwords()

    with open(destination, "w") as writefile:
        writefile.write(capped)

I can't figure out how I can get this to work. Perhaps slicing to the first character of each word if I split them into a list and capitalizing it using .capitalize?

Body:
You can use regex to replace all spaces with single space in a string and .title() to make first letter of every word as capital.

Try this,

import re

def capitalise_words(file_name, destination):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        capped = re.sub(' +', ' ', text_str).title()

    with open(destination, "w") as writefile:
        writefile.write(capped)

Ex:

>>> text_str = 'this   string    is created to      testing   '
>>> re.sub(' +', ' ', text_str).title()
'This String Is Created To Testing '


问:
Failed to add the host to the list of know hosts
Mac OSX Lion 10.7.

In an effort to get around weird environment stuff (homebrew wasn't installing wget, and I had all sorts of weird blocks and errors), I uninstalled zschrc and homebrew and a bunch of other stuff, then installed fish shell.

Now, whenever I try to push/pull to/from github, I get this error:

```<code>The authenticity of host 'github.com (204.232.175.90)' can't be established.
RSA key fingerprint is <string of colon-separated chars that I should probs keep private>.
Are you sure you want to continue connecting (yes/no)? yes
Failed to add the host to the list of known hosts (/Users/sasha/.ssh/known_hosts).
</code>```

So I tried to check the permissions of my ~./ssh folder, and got this, which looks fine to me:

```<code>-rw-r--r--  1 sasha  staff    97B Jul  9 22:56 config
-rw-------  1 sasha  staff   1.7K May 16  2012 id_rsa
-rw-r--r--  1 sasha  staff   403B May 16  2012 id_rsa.pub
drwx------  5 sasha  staff   170B Jul 15 09:56 known_hosts
</code>```

All that's in known_hosts is a pem file I used for ssh'ing (also with the "authenticity..." prompt) to an Amazon ec2 instance, though I tried copying id_rsa and id_rsa.pub there when things got desperate.

Any idea what's going on? I'd love to fix this so I don't get prompted all the many times I push/pull.

EDIT I followed these instructions successfully a while ago, so I do have my ssh keys on Github, and they're recognized, so that when I run ssh -T git@github.com, I get

```<code>Hi sashafklein! You've successfully authenticated, but GitHub does not provide shell access.
</code>```

It seems to be exclusively my local computer that's unhappy with my ssh situation.

答:
Check permissions of the file, if it is good check parent directories

I had to correct

/home/sravindr/.ssh permissions which worked for me

Body:
Mac OSX Lion 10.7.

In an effort to get around weird environment stuff (homebrew wasn't installing wget, and I had all sorts of weird blocks and errors), I uninstalled zschrc and homebrew and a bunch of other stuff, then installed fish shell.

Now, whenever I try to push/pull to/from github, I get this error:

The authenticity of host 'github.com (204.232.175.90)' can't be established.
RSA key fingerprint is <string of colon-separated chars that I should probs keep private>.
Are you sure you want to continue connecting (yes/no)? yes
Failed to add the host to the list of known hosts (/Users/sasha/.ssh/known_hosts).

So I tried to check the permissions of my ~./ssh folder, and got this, which looks fine to me:

-rw-r--r--  1 sasha  staff    97B Jul  9 22:56 config
-rw-------  1 sasha  staff   1.7K May 16  2012 id_rsa
-rw-r--r--  1 sasha  staff   403B May 16  2012 id_rsa.pub
drwx------  5 sasha  staff   170B Jul 15 09:56 known_hosts

All that's in known_hosts is a pem file I used for ssh'ing (also with the "authenticity..." prompt) to an Amazon ec2 instance, though I tried copying id_rsa and id_rsa.pub there when things got desperate.

Any idea what's going on? I'd love to fix this so I don't get prompted all the many times I push/pull.

EDIT I followed these instructions successfully a while ago, so I do have my ssh keys on Github, and they're recognized, so that when I run ssh -T git@github.com, I get

Hi sashafklein! You've successfully authenticated, but GitHub does not provide shell access.

It seems to be exclusively my local computer that's unhappy with my ssh situation.


问:
Custom TabbedPage with buttons
I need to create a navigation with 'TabbedPage' and add 2 buttons (icons) to perform other actions in my application, similar to the image below:

In a test I did I came up with the result below but I have no idea how to keep the tabs on the same level as the icons.

MainPage.xaml

```<code><?xml version="1.0" encoding="UTF-8"?>
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:TabbedPageWithNavigationPage;assembly=TabbedPageWithNavigationPage" x:Class="TabbedPageWithNavigationPage.MainPage">
        <local:TodayPage />

        <TabbedPage.ToolbarItems>
            <ToolbarItem Name="MenuItem1" Order="Primary" Icon="icon.png" Text="Item 1" Priority="0" />
            <ToolbarItem Name="MenuItem2" Order="Primary" Icon="icon.png" Text="Item 2" Priority="1" />
        </TabbedPage.ToolbarItems>

        <NavigationPage Title="Schedule" Icon="schedule.png">
            <x:Arguments>
                <local:SchedulePage />
            </x:Arguments>
        </NavigationPage>
        <local:SettingsPage />

    </TabbedPage>
</code>```

答:
You can use the Tabs control I created here:

https://github.com/roubachof/Sharpnado.Presentation.Forms

The post explaining the component can be found here:

https://www.sharpnado.com/pure-xamarin-forms-tabs/

It's implemented with grid, so you could totally implement your design with something like:

```<code><Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="50 />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="50" />
        <ColumnDefinition Width="50" />
    </Grid.ColumnDefinitions>

    <tabs:TabHostView Grid.Row="0"
                      Grid.Column="0"
                      SelectedIndex="{Binding Source={x:Reference Switcher}, Path=SelectedIndex, Mode=TwoWay}">
        <tabs:BottomTabItem
            IconImageSource="flash.png"
            SelectedTabColor="{StaticResource White}"
            UnselectedLabelColor="{StaticResource White}"
            UnselectedIconColor="{StaticResource White}"
            Label="Tab 1" />
        <tabs:BottomTabItem
            IconImageSource="flash.png"
            SelectedTabColor="{StaticResource White}"
            UnselectedLabelColor="{StaticResource White}"
            UnselectedIconColor="{StaticResource White}"
            Label="Tab 2" />
    </tabs:TabHostView>
    <ImageButton Grid.Column="1" ImageSource="hamburger.png" />
    <ImageButton Grid.Column="2" ImageSource="icon.png" />

    <ScrollView Grid.Row="1" Grid.ColumnSpan="3">
        <tabs:ViewSwitcher x:Name="Switcher"
                           Animate="True"
                           SelectedIndex="{Binding SelectedViewModelIndex, Mode=TwoWay}">
            <details:Tab1View Animate="True" BindingContext="{Binding Tab1ViewModel}" />
            <details:Tab2View Animate="True" BindingContext="{Binding Tab2ViewModel}" />
        </tabs:ViewSwitcher>
    </ScrollView>

</Grid>
</code>```

Title: Custom TabbedPage with buttons

Body:
I need to create a navigation with 'TabbedPage' and add 2 buttons (icons) to perform other actions in my application, similar to the image below:

In a test I did I came up with the result below but I have no idea how to keep the tabs on the same level as the icons.

MainPage.xaml

<?xml version="1.0" encoding="UTF-8"?>
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:TabbedPageWithNavigationPage;assembly=TabbedPageWithNavigationPage" x:Class="TabbedPageWithNavigationPage.MainPage">
        <local:TodayPage />

        <TabbedPage.ToolbarItems>
            <ToolbarItem Name="MenuItem1" Order="Primary" Icon="icon.png" Text="Item 1" Priority="0" />
            <ToolbarItem Name="MenuItem2" Order="Primary" Icon="icon.png" Text="Item 2" Priority="1" />
        </TabbedPage.ToolbarItems>

        <NavigationPage Title="Schedule" Icon="schedule.png">
            <x:Arguments>
                <local:SchedulePage />
            </x:Arguments>
        </NavigationPage>
        <local:SettingsPage />

    </TabbedPage>

Body:
You can use the Tabs control I created here:

https://github.com/roubachof/Sharpnado.Presentation.Forms

The post explaining the component can be found here:

https://www.sharpnado.com/pure-xamarin-forms-tabs/

It's implemented with grid, so you could totally implement your design with something like:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="50 />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="50" />
        <ColumnDefinition Width="50" />
    </Grid.ColumnDefinitions>

    <tabs:TabHostView Grid.Row="0"
                      Grid.Column="0"
                      SelectedIndex="{Binding Source={x:Reference Switcher}, Path=SelectedIndex, Mode=TwoWay}">
        <tabs:BottomTabItem
            IconImageSource="flash.png"
            SelectedTabColor="{StaticResource White}"
            UnselectedLabelColor="{StaticResource White}"
            UnselectedIconColor="{StaticResource White}"
            Label="Tab 1" />
        <tabs:BottomTabItem
            IconImageSource="flash.png"
            SelectedTabColor="{StaticResource White}"
            UnselectedLabelColor="{StaticResource White}"
            UnselectedIconColor="{StaticResource White}"
            Label="Tab 2" />
    </tabs:TabHostView>
    <ImageButton Grid.Column="1" ImageSource="hamburger.png" />
    <ImageButton Grid.Column="2" ImageSource="icon.png" />

    <ScrollView Grid.Row="1" Grid.ColumnSpan="3">
        <tabs:ViewSwitcher x:Name="Switcher"
                           Animate="True"
                           SelectedIndex="{Binding SelectedViewModelIndex, Mode=TwoWay}">
            <details:Tab1View Animate="True" BindingContext="{Binding Tab1ViewModel}" />
            <details:Tab2View Animate="True" BindingContext="{Binding Tab2ViewModel}" />
        </tabs:ViewSwitcher>
    </ScrollView>

</Grid>


问:
How to sort a Cakephp query using a post calculated field and pass it to the paginate?
Have a formatResults callback function that adds a "custom calculated" field into the entities post returned from a model query in my Cakephp. I would like to sort by this field and use this on a paginate is this possible?

So far i cannot accomplish this because the paginate limits the records fetched and therefore only records less than the paginator limit get sorted and not all the resultset...

Current code:

```<code>    $owners = $this->Owners->find('all');

    $owners->formatResults(function (\Cake\Collection\CollectionInterface $owners) {

        $owners = $owners->map(function ($entity) {

            $entity->random = rand(0,1);

            return $entity;

        });

        return $owners->sortBy(function ($item){

            return $item->random;

        },SORT_DESC);

    });
</code>```

This works as expected:

```<code>$owners->toArray();
</code>```

This does not:

```<code>$owners = $this->paginate($owners);
$owners->toArray();
</code>```

Mainly because its "callback processing" only the first 10 records, i would like to process the whole resultset.

答:
After diggin around ive found a similar topic opened by a previous user on the this link, it seems that is not possible to use pagination sort in other than the fields in the database.

As a result, i would suggest:

1 - Either alter your model logic, to accommodate your requirements by creating virtual fields or alter database schema to include this data.

2 - If the data requires further or live processing and it cannot be added or calculated in the database, perhaps programming a component that will replicate the paginate functionality on a cakephp collection would be a good option.The downside of this approach is that all records will be returned from the database which may present performance issues on large resultsets.

Body:
Have a formatResults callback function that adds a "custom calculated" field into the entities post returned from a model query in my Cakephp. I would like to sort by this field and use this on a paginate is this possible?

So far i cannot accomplish this because the paginate limits the records fetched and therefore only records less than the paginator limit get sorted and not all the resultset...

Current code:

    $owners = $this->Owners->find('all');

    $owners->formatResults(function (\Cake\Collection\CollectionInterface $owners) {

        $owners = $owners->map(function ($entity) {

            $entity->random = rand(0,1);

            return $entity;

        });

        return $owners->sortBy(function ($item){

            return $item->random;

        },SORT_DESC);

    });

This works as expected:

$owners->toArray();

This does not:

$owners = $this->paginate($owners);
$owners->toArray();

Mainly because its "callback processing" only the first 10 records, i would like to process the whole resultset.


问:
Cannot import YAML from Ruamel.yaml
I am trying to use ruamel.yaml and am using this code straight from the ruamel's documentation but I get the error:

Traceback (most recent call last):
  File "ruameltest.py", line 12, in
    yaml = YAML()
NameError: name 'YAML' is not defined

I am using Linux (RHEL)

Python 3.4.9

rpm package: python34-ruamel-yaml-0.13.14-1.el7.x86_64

How could I fix this issue?

```<code>import sys
from ruamel.yaml import YAML

inp = """\
# example
name:
  # details
  family: Smith   # very common
  given: Alice    # one of the siblings
"""

yaml = YAML()
code = yaml.load(inp)
code['name']['given'] = 'Bob'

yaml.dump(code, sys.stdout)
</code>```

答:
Your system installed ruamel.yaml version is severely outdated, it is now (May 2019) at 0.15.96. The API that introduced the YAML class, that your program can't find was introduced two years ago.

Additionally your Python (3.4) has been end-of-life since 2019-03-18.

You can either follow the old, PyYAML, API:

```<code>import sys
from ruamel.yaml import RoundTripLoader, RoundTripDumper, load, dump

inp = """\
# example
name:
  # details
  family: Smith   # very common
  given: Alice    # one of the siblings
"""

data = load(inp, Loader=RoundTripLoader)
data['name']['given'] = 'Bob'
dump(data, sys.stdout, Dumper=RoundTripDumper)
</code>```

which gives:

```<code># example
name:
  # details
  family: Smith   # very common
  given: Bob      # one of the siblings
</code>```

Please note that you load data from YAML not code.

It would of course be better to use an up-to-date version of ruamel.yaml and a maintained
version of Python. If you cannot install a newer Python version, or compile it yourself, you
still can install a newer  version of ruamel.yaml:

```<code>$ python3 -m venv ~/venv/yamltest
$ source ~/venv/yamltest/bin/activate
$ pip install -U pip
$ pip install 'ruamel.yaml<=0.15.94'
</code>```

And then you should be able to use your program as is.

newer versions, released after 0.15.94, do not include .whl files
for Python 3.4, those versions will probably still work, but you might
need to have a compiler installed to make use of the C extensions, and
if you do you should just download and install Python 3.7

Title: Cannot import YAML from Ruamel.yaml

Body:
I am trying to use ruamel.yaml and am using this code straight from the ruamel's documentation but I get the error:

Traceback (most recent call last):
  File "ruameltest.py", line 12, in
    yaml = YAML()
NameError: name 'YAML' is not defined

I am using Linux (RHEL)

Python 3.4.9

rpm package: python34-ruamel-yaml-0.13.14-1.el7.x86_64

How could I fix this issue?

import sys
from ruamel.yaml import YAML

inp = """\
# example
name:
  # details
  family: Smith   # very common
  given: Alice    # one of the siblings
"""

yaml = YAML()
code = yaml.load(inp)
code['name']['given'] = 'Bob'

yaml.dump(code, sys.stdout)

Body:
Your system installed ruamel.yaml version is severely outdated, it is now (May 2019) at 0.15.96. The API that introduced the YAML class, that your program can't find was introduced two years ago.

Additionally your Python (3.4) has been end-of-life since 2019-03-18.

You can either follow the old, PyYAML, API:

import sys
from ruamel.yaml import RoundTripLoader, RoundTripDumper, load, dump

inp = """\
# example
name:
  # details
  family: Smith   # very common
  given: Alice    # one of the siblings
"""

data = load(inp, Loader=RoundTripLoader)
data['name']['given'] = 'Bob'
dump(data, sys.stdout, Dumper=RoundTripDumper)

which gives:

# example
name:
  # details
  family: Smith   # very common
  given: Bob      # one of the siblings

Please note that you load data from YAML not code.

It would of course be better to use an up-to-date version of ruamel.yaml and a maintained
version of Python. If you cannot install a newer Python version, or compile it yourself, you
still can install a newer  version of ruamel.yaml:

$ python3 -m venv ~/venv/yamltest
$ source ~/venv/yamltest/bin/activate
$ pip install -U pip
$ pip install 'ruamel.yaml<=0.15.94'

And then you should be able to use your program as is.

newer versions, released after 0.15.94, do not include .whl files
for Python 3.4, those versions will probably still work, but you might
need to have a compiler installed to make use of the C extensions, and
if you do you should just download and install Python 3.7


问:
How to use replace() function to change string items in global list?
I`ve tried to use replace function inside of while loop. My main aim is change specific index item with different string in a global list name is tryList in the code block.

when I checktryList[counter][3].replace(tryList[counter][3],newItem) output by using print() function;

I am able to see expected string value is given but at the end when I control global list, nothing is changed.

tryList=[["asd","poi","ujm","ytr"],["qaz","plm","rfv","wxs"],["edc","wer","cvc","yhn"]] #the list has 3 different list inside
newItem="ana" #this is the string which I want to replace with tryList`s each 3rd items of lists
loop=len(tryList)
counter=0
while counter<loop:
    tryList[counter][3].replace(tryList[counter][3],newItem)
    counter=counter+1
```

Could you please help me what am I doing wrong?

答:
Strings are immutable, so you replace method does not alter the string itself, it creates a new, modified string. So, instead of

```<code>  lst[3].replace.replace("a", "b)
</code>```

write

```<code>  lst[3] = lst[3].replace("a", "b)
</code>```

Body:
I`ve tried to use replace function inside of while loop. My main aim is change specific index item with different string in a global list name is tryList in the code block.

when I checktryList[counter][3].replace(tryList[counter][3],newItem) output by using print() function;

I am able to see expected string value is given but at the end when I control global list, nothing is changed.

tryList=[["asd","poi","ujm","ytr"],["qaz","plm","rfv","wxs"],["edc","wer","cvc","yhn"]] #the list has 3 different list inside
newItem="ana" #this is the string which I want to replace with tryList`s each 3rd items of lists
loop=len(tryList)
counter=0
while counter<loop:
    tryList[counter][3].replace(tryList[counter][3],newItem)
    counter=counter+1

Could you please help me what am I doing wrong?

Body:
Strings are immutable, so you replace method does not alter the string itself, it creates a new, modified string. So, instead of

  lst[3].replace.replace("a", "b)

write

  lst[3] = lst[3].replace("a", "b)


问:
Oracle - Transpose rows into columns
Here is a sample from the table I have been working on:

```<code>CREATE TABLE TEST_MC
(
 CLUSTER_K INTEGER,
 PROCESS_PHASE INTEGER,
 SEM_AGG CHAR(1)
);

CLUSTER_K  PROCESS_PHASE   SEM_AGG
==================================
    328          1            M
----------------------------------
    328          2            A
----------------------------------
    328          3            A
</code>```

Now, I would like to transpose and collapse rows obtaining the following result:

```<code> CLUSTER_K  SEM_AGG_1   SEM_AGG_2   SEM_AGG_3
=============================================
    328         M           A           A
</code>```

How i can achieve this (Pivot and/or analytical functions)?

Any help is greatly appreciated.

答:
You could do it with a GROUP BY:</p>

```<code>select CLUSTER_K,
  max(case when PROCESS_PHASE=1 then SEM_AGG else null end) SEM_AGG_1,
  max(case when PROCESS_PHASE=2 then SEM_AGG else null end) SEM_AGG_2,
  max(case when PROCESS_PHASE=3 then SEM_AGG else null end) SEM_AGG_3
from test_mc
group by CLUSTER_K
</code>```

Title: Oracle - Transpose rows into columns

Body:
Here is a sample from the table I have been working on:

CREATE TABLE TEST_MC
(
 CLUSTER_K INTEGER,
 PROCESS_PHASE INTEGER,
 SEM_AGG CHAR(1)
);

CLUSTER_K  PROCESS_PHASE   SEM_AGG
==================================
    328          1            M
----------------------------------
    328          2            A
----------------------------------
    328          3            A

Now, I would like to transpose and collapse rows obtaining the following result:

 CLUSTER_K  SEM_AGG_1   SEM_AGG_2   SEM_AGG_3
=============================================
    328         M           A           A

How i can achieve this (Pivot and/or analytical functions)?

Any help is greatly appreciated.

Body:
You could do it with a GROUP BY:

select CLUSTER_K,
  max(case when PROCESS_PHASE=1 then SEM_AGG else null end) SEM_AGG_1,
  max(case when PROCESS_PHASE=2 then SEM_AGG else null end) SEM_AGG_2,
  max(case when PROCESS_PHASE=3 then SEM_AGG else null end) SEM_AGG_3
from test_mc
group by CLUSTER_K


问:
Testing localizations in an iOS playground
Is there a way to get localized strings into an iOS playground? I have a number of right-to-left language translations that include format codes that I had to edit with a hex editor (to ensure the codes were in the correct byte order), and I wish to manually examine the output of the formatted string to make sure it worked.

As an aside, are there any Mac OS text editors that allow you to display Arabic and Hebrew in left-to-right mode?

答:
I was able to get this working by making an en.lproj in the Resources folder of a playground (note that my system is in English, you may have to put it in the lproj for your language to get this to work on your system).

One thing to note is that if you're using a plurals stringsDict, I always forget that you have to specify that the key is a localized string. You can't just do:

String.localizedStringWithFormat("next_step", beer)
```

<p>You have to do: </p>

<pre class="lang-swift prettyprint-override"><code>String.localizedStringWithFormat(NSLocalizedString("next_step", comment: ""), beer)
</code>```

Here's a gist of what I did:
https://gist.github.com/designatednerd/fdfb916cc4d4ad3f33c25e917a95a2be

Body:
I was able to get this working by making an en.lproj in the Resources folder of a playground (note that my system is in English, you may have to put it in the lproj for your language to get this to work on your system).

One thing to note is that if you're using a plurals stringsDict, I always forget that you have to specify that the key is a localized string. You can't just do:

String.localizedStringWithFormat("next_step", beer)

You have to do:

String.localizedStringWithFormat(NSLocalizedString("next_step", comment: ""), beer)

Here's a gist of what I did:
https://gist.github.com/designatednerd/fdfb916cc4d4ad3f33c25e917a95a2be


问:
When should i use @android:id/?
I've found some code examples with the @android:id/xyz attribute set instead of @+id/xyz.

When and why is it necessary to use Android ids instead of the user's id?

答:
The plus-symbol means that the resource is new and it must be created and added to the resources in the R.java file.

Omitting the plus symbol references an already existing resource.

Title: When should i use @android:id/?


问:
Accessing dock icon right-click menu items with AppleScript
Is there any way to get an AppleScript to access the menu items that come up when you right click on a dock icon?

Specifically, here's what I want to do:

I use Google Chrome as my web browser on MacOS X Snow Leopard.  I am a keyboard shortcut addict, and I use QuickSilver to create keyboard shortcuts for anything I can.  One of the most common things that I do is to open a new web browser window.  But I use Spaces frequently to partition my tasks that I am currently working on, and when I open a web browser or web page with a QuickSilver trigger, spaces switches to the last space that I used Chrome on and opens a new tab, which often distracts me for hours because it brings me to a different space and thus a different task.  I can fix this by right-clicking on the Google Chrome icon and clicking the "New Window" option, which opens a new window on the current space.  But in AppleScript, to do anything with Google Chrome, the first thing I have to do is activate it, which brings me back to the original problem!  Can anyone think of a solution to this problem, AppleScript or otherwise?  It has become a serious problem.  Back when I used Firefox, I solved the problem by changing a preference item that says "Always open pop-up links in a new window" or something like that, which was kind of a sledge hammer approach, but it worked.  I can always go back to Firefox, but I thought I'd ask my question here first.  Anyone with any ideas?

答:
Alternatively you could also invoke this hidden option:

```<code>defaults write com.apple.dock workspaces-auto-swoosh -bool NO
killall Dock
</code>```

It also has the, for me, positive effect that you aren't thrown around on desktops anymore when switching applications. Simply do Cmd+N with Chrome as the active app.

Btw you can go to spaces directly with Fn+1, Fn+2 etc. if you set it up instead of ⌃1, ⌃2 etc. You have to make the spaces before the keyboard shortcuts can be set in Keyboard -> Shortcuts preferences.

Body:
Alternatively you could also invoke this hidden option:

defaults write com.apple.dock workspaces-auto-swoosh -bool NO
killall Dock

It also has the, for me, positive effect that you aren't thrown around on desktops anymore when switching applications. Simply do Cmd+N with Chrome as the active app.

Btw you can go to spaces directly with Fn+1, Fn+2 etc. if you set it up instead of ⌃1, ⌃2 etc. You have to make the spaces before the keyboard shortcuts can be set in Keyboard -> Shortcuts preferences.


问:
R-CNN in R for analyzing aerial photos
I have 8,000 drone photos on which we want to detect almost circular holes in the ground (no UFOs..). I have been reading and practicing quite a lot with using CNNs in R, using both Keras and Tensorflow. However, I think what I need is a R-CNN instead of a conventional CNN, to be able to scan through the photos looking for the object.

But is there any way to work with R-CNN or even Mask R-CNN in R? I have no experience with Python.

答:
As you are familiar with using Keras and Tensorflow in R, you should be able to implement the architecture as per your needs. You will be able to find the rough architecture of most models with a simple Google search and then tweak it to fit your use case.

For example - Faster RCNN architecture.

Title: R-CNN in R for analyzing aerial photos


问:
Using "excludes" config in Findbugs and Checkstyle plugin in Gradle
I have the following Gradle build file: https://github.com/markuswustenberg/jsense/blob/a796055f984ec309db3cc0f3e8340cbccac36e4e/jsense-protobuf/build.gradle which includes:

```<code>checkstyle {
  // TODO The excludes are not working, ignore failures for now
  //excludes '**/org/jsense/serialize/protobuf/gen/**'
  ignoreFailures = true
  showViolations = false
}

findbugs {
  // TODO The excludes are not working, ignore failures for now
  //excludes '**/org/jsense/serialize/protobuf/gen/**'
  ignoreFailures = true
}
</code>```

As you can see, I'm trying to exclude auto-generated code in the package org.jsense.serialize.protobuf.gen. I cannot figure out the format of the strings given to the excludes parameter, and the documentation isn't of much help: http://www.gradle.org/docs/1.10/dsl/org.gradle.api.plugins.quality.FindBugs.html#org.gradle.api.plugins.quality.FindBugs:excludes (it just says "The set of exclude patterns.").

So my question is: How should the excludes pattern strings be formatted for both the Findbugs and Checkstyle plugins?

I'm running Gradle 1.10.

Thanks!

EDIT 1: I got the Checkstyle exclude working with the following:

```<code>tasks.withType(Checkstyle) {
  exclude '**/org/jsense/serialize/protobuf/gen/**'
}
</code>```

However, using the exact same exclude on the Findbugs plugin doesn't work:

```<code>tasks.withType(FindBugs) {
  exclude '**/org/jsense/serialize/protobuf/gen/*'
}
</code>```

EDIT 2: The accepted answer works, and so does using an XML file and filtering on that, like so:

```<code>findbugs {
  excludeFilter = file("$projectDir/config/findbugs/excludeFilter.xml")
}
</code>```

and

```<code><?xml version="1.0" encoding="UTF-8"?>
<FindBugsFilter>
  <Match>
    <Package name="org.jsense.serialize.protobuf.gen"/>
  </Match>
</FindBugsFilter>
</code>```

EDIT 3: This works great, and no XML file is needed:

```<code>def excludePattern = 'org/jsense/serialize/protobuf/gen/'
def excludePatternAntStyle = '**/' + excludePattern + '*'
tasks.withType(FindBugs) {
    classes = classes.filter {
        !it.path.contains(excludePattern)
    }
}
tasks.withType(Checkstyle) {
    exclude excludePatternAntStyle
}
tasks.withType(Pmd) {
    exclude excludePatternAntStyle
}
</code>```

答:
If someone looking for a modern day solution:

For checkstyle, you can use something like this in build.gradle:

```<code>checkstyleMain.exclude '**/org/jsense/serialize/protobuf/gen/**'
</code>```

If you want to exclude more than one path

solution 1:

```<code>checkstyleMain.exclude '**/org/jsense/serialize/protobuf/gen/**'
checkstyleMain.exclude '**/org/example/some/random/path/**'
</code>```

solution 2:

```<code>checkstyleMain {
    setExcludes(new HashSet(['**/org/jsense/serialize/protobuf/gen/**', '**/org/example/some/random/path/**']))
}
</code>```

Body:
I have the following Gradle build file: https://github.com/markuswustenberg/jsense/blob/a796055f984ec309db3cc0f3e8340cbccac36e4e/jsense-protobuf/build.gradle which includes:

checkstyle {
  // TODO The excludes are not working, ignore failures for now
  //excludes '**/org/jsense/serialize/protobuf/gen/**'
  ignoreFailures = true
  showViolations = false
}

findbugs {
  // TODO The excludes are not working, ignore failures for now
  //excludes '**/org/jsense/serialize/protobuf/gen/**'
  ignoreFailures = true
}

As you can see, I'm trying to exclude auto-generated code in the package org.jsense.serialize.protobuf.gen. I cannot figure out the format of the strings given to the excludes parameter, and the documentation isn't of much help: http://www.gradle.org/docs/1.10/dsl/org.gradle.api.plugins.quality.FindBugs.html#org.gradle.api.plugins.quality.FindBugs:excludes (it just says "The set of exclude patterns.").

So my question is: How should the excludes pattern strings be formatted for both the Findbugs and Checkstyle plugins?

I'm running Gradle 1.10.

Thanks!

EDIT 1: I got the Checkstyle exclude working with the following:

tasks.withType(Checkstyle) {
  exclude '**/org/jsense/serialize/protobuf/gen/**'
}

However, using the exact same exclude on the Findbugs plugin doesn't work:

tasks.withType(FindBugs) {
  exclude '**/org/jsense/serialize/protobuf/gen/*'
}

EDIT 2: The accepted answer works, and so does using an XML file and filtering on that, like so:

findbugs {
  excludeFilter = file("$projectDir/config/findbugs/excludeFilter.xml")
}

and

<?xml version="1.0" encoding="UTF-8"?>
<FindBugsFilter>
  <Match>
    <Package name="org.jsense.serialize.protobuf.gen"/>
  </Match>
</FindBugsFilter>

EDIT 3: This works great, and no XML file is needed:

def excludePattern = 'org/jsense/serialize/protobuf/gen/'
def excludePatternAntStyle = '**/' + excludePattern + '*'
tasks.withType(FindBugs) {
    classes = classes.filter {
        !it.path.contains(excludePattern)
    }
}
tasks.withType(Checkstyle) {
    exclude excludePatternAntStyle
}
tasks.withType(Pmd) {
    exclude excludePatternAntStyle
}

Body:
If someone looking for a modern day solution:

For checkstyle, you can use something like this in build.gradle:

checkstyleMain.exclude '**/org/jsense/serialize/protobuf/gen/**'

If you want to exclude more than one path

solution 1:

checkstyleMain.exclude '**/org/jsense/serialize/protobuf/gen/**'
checkstyleMain.exclude '**/org/example/some/random/path/**'

solution 2:

checkstyleMain {
    setExcludes(new HashSet(['**/org/jsense/serialize/protobuf/gen/**', '**/org/example/some/random/path/**']))
}


问:
Unit tests - How to use Spring MockMVC to call soap service
I am unit testing my rest service using the code listed below and the request is successfully hitting the service.

```<code>     import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;

     private MockMvc mvc;

     private URI = "/order/1"

     this.mvc.perform(
            post(URI).headers(headers)
                    .contentType(MediaType.APPLICATION_JSON_UTF8)
                    .content(mapper.writeValueAsString(request))
                    .accept(MediaType.APPLICATION_JSON_UTF8))
            .andExpect(result -> {
                response[0] = result.getResponse().getContentAsString();
                statusCode[0] = result.getResponse().getStatus();
            });
</code>```

I am trying to test my soap service (http://localhost:8080/OrderService/13.08.wsdl) using similar code. The endpoint seems to be up when I hit via browser , but seeing 404 in the result -

```<code>import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;

     private MockMvc mvc;

     private URI = "http://localhost:8080/OrderService/13.08.wsdl";

     this.mvc.perform(
            post(URI).headers(headers)
                    .contentType(MediaType.TEXT_XML)
                    .content(request.toString())
                    .accept(MediaType.TEXT_XML))
            .andExpect(result -> {
                response[0] = result.getResponse().getContentAsString();
                statusCode[0] = result.getResponse().getStatus();
            });
</code>```

答:
@WebMvcTest annotation will load only the controller layer of the application. This will scan only the @Controller/@RestController annotation and will not load the fully ApplicationContext.

Reference: https://springbootdev.com/2018/02/22/spring-boot-test-writing-unit-tests-for-the-controller-layers-with-webmvctest/

Body:
I am unit testing my rest service using the code listed below and the request is successfully hitting the service.

     import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;

     private MockMvc mvc;

     private URI = "/order/1"

     this.mvc.perform(
            post(URI).headers(headers)
                    .contentType(MediaType.APPLICATION_JSON_UTF8)
                    .content(mapper.writeValueAsString(request))
                    .accept(MediaType.APPLICATION_JSON_UTF8))
            .andExpect(result -> {
                response[0] = result.getResponse().getContentAsString();
                statusCode[0] = result.getResponse().getStatus();
            });

I am trying to test my soap service (http://localhost:8080/OrderService/13.08.wsdl) using similar code. The endpoint seems to be up when I hit via browser , but seeing 404 in the result -

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;

     private MockMvc mvc;

     private URI = "http://localhost:8080/OrderService/13.08.wsdl";

     this.mvc.perform(
            post(URI).headers(headers)
                    .contentType(MediaType.TEXT_XML)
                    .content(request.toString())
                    .accept(MediaType.TEXT_XML))
            .andExpect(result -> {
                response[0] = result.getResponse().getContentAsString();
                statusCode[0] = result.getResponse().getStatus();
            });


问:
Compare a two column with the same table to remove duplicate
A sample table with two column and I need to compare the column 1 and column 2 to the same table records and need to remove the column 1 + column 2 = column 2+column 1.

I tried to do self join and case condition. But its not working

答:
If I understand correctly, you can run a simple select like this if you have all reversed pairs in the table:

```<code>select col1, col2
from t
where col1 < col2;
</code>```

If you have some singletons, then:

```<code>select col1, col2
from t
where col1 < col2 or
      (col1 > col2 and
       not exists (select 1
                   from t t2
                   where t2.col1 = t.col2 and
                         t2.col2 = t.col1
                  )
      );
</code>```

Body:
If I understand correctly, you can run a simple select like this if you have all reversed pairs in the table:

select col1, col2
from t
where col1 < col2;

If you have some singletons, then:

select col1, col2
from t
where col1 < col2 or
      (col1 > col2 and
       not exists (select 1
                   from t t2
                   where t2.col1 = t.col2 and
                         t2.col2 = t.col1
                  )
      );


问:
How can I validate multiple text fields on submit form in fabric UI with reactJS and typescript?
I wrote text fields like below in form tag. Both text fields call the same function. should I call  {this._getErrorMessage} multiple times in the same time

I declare function outside the form like below.this function checks null value.

```<code>    _getErrorMessage = (value: any) => {
    value.trim().length === 0 ? required : ""
   }

    <Textfield
    id={AppIDConst`enter code here`ants.EMP_NAME}
    type={fieldPropertyConstants.TEXT}
    label={filedLabelConstants.EMP_NAME}
    onChange={this.handleChange.bind(this)}
    required={true}
    validateOnLoad={false}
    onGetErrorMessage= {this._getErrorMessage}
/>

<Textfield
    id={AppIDConstants.EMP_ADHAR_NO}
    type={fieldPropertyConstants.NUMBER}
    label={filedLabelConstants.ADHAR_NUMBER}
    required={true}
    onChange={this.handleChange.bind(this)}
    onGetErrorMessage= {this._getErrorMessage}
/>
</code>```

答:
If you want to use submit validation instead of input validation, you'll need to add the validator function to the form instead.

```<code>onSubmit(form) {
  form.preventDefault();
  // retrieve form values and validate here...
}

render() {
  return (
    <form onSubmit={this.onSubmit}>
      // rest of form...
    </form>
  );
}
</code>```

Remember to bind your form in the constructor

```<code>constructor(props) {
  super(props)
  this.onSubmit = this.onSubmit.bind(this)
}
</code>```

Body:
I wrote text fields like below in form tag. Both text fields call the same function. should I call  {this._getErrorMessage} multiple times in the same time

I declare function outside the form like below.this function checks null value.

    _getErrorMessage = (value: any) => {
    value.trim().length === 0 ? required : ""
   }

    <Textfield
    id={AppIDConst`enter code here`ants.EMP_NAME}
    type={fieldPropertyConstants.TEXT}
    label={filedLabelConstants.EMP_NAME}
    onChange={this.handleChange.bind(this)}
    required={true}
    validateOnLoad={false}
    onGetErrorMessage= {this._getErrorMessage}
/>

<Textfield
    id={AppIDConstants.EMP_ADHAR_NO}
    type={fieldPropertyConstants.NUMBER}
    label={filedLabelConstants.ADHAR_NUMBER}
    required={true}
    onChange={this.handleChange.bind(this)}
    onGetErrorMessage= {this._getErrorMessage}
/>

Body:
If you want to use submit validation instead of input validation, you'll need to add the validator function to the form instead.

onSubmit(form) {
  form.preventDefault();
  // retrieve form values and validate here...
}

render() {
  return (
    <form onSubmit={this.onSubmit}>
      // rest of form...
    </form>
  );
}

Remember to bind your form in the constructor

constructor(props) {
  super(props)
  this.onSubmit = this.onSubmit.bind(this)
}


问:
How to deference member fields that have already been initialized when constructor throws an error
```<code>class XYZ {

   FileInputStream fis;  //opens a file stream
   DBConnection connection; //this is used to connect to a database

   XYZ(String fileName, String dbName) {
       fis = new FileInputStream(fileName);
       connection = getDBConnection(dbName); //assume that this line would throw error
   }
}
</code>```

Consider the following scenario: object of class XYZ is created as XYZ obj = new XYZ() - now during the object creation, when constructor is called, let us assume that fis is successfully initialized, but call to the next statement throws an error.
W.r.t to the above scenario:

Does fis contain a valid reference? (since the statement executed successfully but the next statement failed)

If fis holds a valid reference, how to ensure that fis would be closed, so as to not have a memory leak (One way would be to define a finalize method for this class, but Java GC does not guarantee finalize() would be called)

答:
If the creation of the connection fails, fis contains a valid reference.

You could try the following in order to resolve this:

```<code>class XYZ
{
  ...

  public XYZ(String fileName, String dbName)
    throws Exception
  {
    // Initialize attributes; not strictly necessary
    fis = null;
    connection = null;

    // Open fis
    fis = new FileInputStream(fileName);

    // Open connection
    try
    {
      connection = getDBConnection(dbName);
    }
    catch (Exception e)
    {
      fis.close();
      fis = null;
      throw e;
    }

  } // constructor

} // class XYZ
</code>```

Body:
class XYZ {

   FileInputStream fis;  //opens a file stream
   DBConnection connection; //this is used to connect to a database

   XYZ(String fileName, String dbName) {
       fis = new FileInputStream(fileName);
       connection = getDBConnection(dbName); //assume that this line would throw error
   }
}

Consider the following scenario: object of class XYZ is created as XYZ obj = new XYZ() - now during the object creation, when constructor is called, let us assume that fis is successfully initialized, but call to the next statement throws an error.
W.r.t to the above scenario:

Does fis contain a valid reference? (since the statement executed successfully but the next statement failed)

If fis holds a valid reference, how to ensure that fis would be closed, so as to not have a memory leak (One way would be to define a finalize method for this class, but Java GC does not guarantee finalize() would be called)

Body:
If the creation of the connection fails, fis contains a valid reference.

You could try the following in order to resolve this:

class XYZ
{
  ...

  public XYZ(String fileName, String dbName)
    throws Exception
  {
    // Initialize attributes; not strictly necessary
    fis = null;
    connection = null;

    // Open fis
    fis = new FileInputStream(fileName);

    // Open connection
    try
    {
      connection = getDBConnection(dbName);
    }
    catch (Exception e)
    {
      fis.close();
      fis = null;
      throw e;
    }

  } // constructor

} // class XYZ


答:
You need import the string module and then you can use string.capwords():

```<code>import string

...

text_str = wordfile.read()
capped = string.capwords(text_str)
</code>```

The reason for this is that capwords() is not a method of str object, it is a helper function in the string module.

So your original fixed:

```<code>import string

def capitalise_words(file_name, destination):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        capped = string.capwords(text_str)

    with open(destination, "w") as writefile:
        writefile.write(capped)
</code>```

Edit:

If you don't want to import anything, you can simply use:

```<code>text_str = wordfile.read()
capped = ' '.join(word.capitalize() for word in text_str.split())
</code>```

which is exactly what string.capwords() is actually doing under the hood.

Title: Copy .txt file and capitalise first letter of each word and write to new file

Body:
I'm making a small script that opens the file_name and writes a copy of it to the destination .txt file but the first letter of each word is capitalised and all whitespace is just replaced by a singular space. I was trying to do this with the .capitalize method or the .capwords method.

def capitalise_words(file_name, destination):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        capped = text_str.capwords()

    with open(destination, "w") as writefile:
        writefile.write(capped)

I can't figure out how I can get this to work. Perhaps slicing to the first character of each word if I split them into a list and capitalizing it using .capitalize?

Body:
You need import the string module and then you can use string.capwords():

import string

...

text_str = wordfile.read()
capped = string.capwords(text_str)

The reason for this is that capwords() is not a method of str object, it is a helper function in the string module.

So your original fixed:

import string

def capitalise_words(file_name, destination):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        capped = string.capwords(text_str)

    with open(destination, "w") as writefile:
        writefile.write(capped)

Edit:

If you don't want to import anything, you can simply use:

text_str = wordfile.read()
capped = ' '.join(word.capitalize() for word in text_str.split())

which is exactly what string.capwords() is actually doing under the hood.


问:
SQLite data fetching problem after row Delete?
friends,

i am trying to delete row and then when i try to fetch all records from database
i get exception any one guide me what mistake am i doing?

```<code>private static final String DATABASE_NAME = "example.db";
   private static final int DATABASE_VERSION = 1;
   private static final String TABLE_NAME = "table1";

   private Context context;
   private SQLiteDatabase db;

 public dbHelper(Context context) {
      this.context = context;
      OpenHelper openHelper = new OpenHelper(this.context);
      this.db = openHelper.getWritableDatabase();
      this.insertStmt = this.db.compileStatement(INSERT);
   }

    public List<String> selectAll() {
          List<String> list = new ArrayList<String>();
          Cursor cursor = this.db.query(TABLE_NAME, new String[] { "name" },
            null, null, null, null, "name desc");
          if (cursor.moveToFirst()) {
             do {
                list.add(cursor.getString(0));
             } while (cursor.moveToNext());
          }
          if (cursor != null && !cursor.isClosed()) {
             cursor.close();
          }
          return list;
       }

       public int DeleteName(String name)
       {
           int rowsEffected = this.db.delete(TABLE_NAME,"name=?", new String[] {name});
           this.db.close();
           return rowsEffected;
       }
</code>```

any help would be appreciated.

答:
Have you opened db before call selectAll()?
You closed it in delete method.

Anyway it is good practice to open db before work with it and close it after the work is done.

Body:
friends,

i am trying to delete row and then when i try to fetch all records from database
i get exception any one guide me what mistake am i doing?

private static final String DATABASE_NAME = "example.db";
   private static final int DATABASE_VERSION = 1;
   private static final String TABLE_NAME = "table1";

   private Context context;
   private SQLiteDatabase db;

 public dbHelper(Context context) {
      this.context = context;
      OpenHelper openHelper = new OpenHelper(this.context);
      this.db = openHelper.getWritableDatabase();
      this.insertStmt = this.db.compileStatement(INSERT);
   }

    public List<String> selectAll() {
          List<String> list = new ArrayList<String>();
          Cursor cursor = this.db.query(TABLE_NAME, new String[] { "name" },
            null, null, null, null, "name desc");
          if (cursor.moveToFirst()) {
             do {
                list.add(cursor.getString(0));
             } while (cursor.moveToNext());
          }
          if (cursor != null && !cursor.isClosed()) {
             cursor.close();
          }
          return list;
       }

       public int DeleteName(String name)
       {
           int rowsEffected = this.db.delete(TABLE_NAME,"name=?", new String[] {name});
           this.db.close();
           return rowsEffected;
       }

any help would be appreciated.


问:
Laravel 5.8.11 getting 419 page expired all forms affected
Started with Laravel 5.5 upgraded to 5.8 (current version 5.8.11). The problem is that when I test locally everything works as it should, when I upload my project to my hosting (dedicated server / shared hosting tried on both) I get a 419 page expired but this is not unique to login all forms are affected and give 419 page expired.

5.5 -> 5.6

```<code>update dependency: "fideloper/proxy": "^4.0", updated all other dependencies to latest versions
update php unit: 7
removed php artisan optimize from composer.json
</code>```

5.6 -> 5.6.30
no changes

5.6 -> 5.7
update laravel/framework dependency to 5.7 in composer.json
changed assets dir

```<code>From resources/assets/js/* to resources/js/*
From resources/assets/sass/* to resources/sass/*
</code>```

update mix.js

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

5.7 -> 5.8
Update laravel/framework dependency to 5.8 in composer.json

Created fresh 5.8 installation and moved files to it, currently moving only the files I have edited for created (making 2 versions 5.5 and 5.8) but this will take some time.

Generated new app key (no change)
Set default session domain to my domain (no change)
Tested on Firefox and chrome + incognito mode to see if cached session are a problem

Ran following commands:

```<code>composer dump-autolaod
php artisan cache:clear
php artisan config:cache
php artisan route:cache
</code>```

All forms have csrf_field(), also present in head

What might be causing this issue?

答:
So what worked for me was creating a new laravel 5.8 installation and copied its files into my existing project and skip any files it wants to overwrite, run composer update and done. so i assume somewhere i was missing a file.

It may not be the best solution but this worked for me.

Body:
Started with Laravel 5.5 upgraded to 5.8 (current version 5.8.11). The problem is that when I test locally everything works as it should, when I upload my project to my hosting (dedicated server / shared hosting tried on both) I get a 419 page expired but this is not unique to login all forms are affected and give 419 page expired.

5.5 -> 5.6

update dependency: "fideloper/proxy": "^4.0", updated all other dependencies to latest versions
update php unit: 7
removed php artisan optimize from composer.json

5.6 -> 5.6.30
no changes

5.6 -> 5.7
update laravel/framework dependency to 5.7 in composer.json
changed assets dir

From resources/assets/js/* to resources/js/*
From resources/assets/sass/* to resources/sass/*

update mix.js

mix.js('resources/js/app.js', 'public/js')
.sass('resources/sass/app.scss', 'public/css');

5.7 -> 5.8
Update laravel/framework dependency to 5.8 in composer.json

Created fresh 5.8 installation and moved files to it, currently moving only the files I have edited for created (making 2 versions 5.5 and 5.8) but this will take some time.

Generated new app key (no change)
Set default session domain to my domain (no change)
Tested on Firefox and chrome + incognito mode to see if cached session are a problem

Ran following commands:

composer dump-autolaod
php artisan cache:clear
php artisan config:cache
php artisan route:cache

All forms have csrf_field(), also present in head

What might be causing this issue?


问:
High CPU usage with Android emulator (qemu-system-i386.exe)
The emulator qemu-system-i386.exe cpu usage almost constantly running between 7~9

Android studio 2.1
Android SDK Tools: 25.1.3
Host Operating System: Windows 7 - i7 2630QM - 8GB Ram
Intel x86 Atom System Image installed

No matter what setting i change in the emulator like: emulated performance, multi-core CPU, x86-64 image, always the same thing

It is really annoying fan always on

Anyone had a fix for this issue?

答:
To find out what on the virtual device is using the most CPU:

```<code>adb shell

$ top

</code>```

This will show you a list of processes with the highest CPU usage atop.

This will help you determine whether it's a process (such as your app) inside the emulator, another process inside the emulator, or just the emulation itself using a lot of CPU.

In the latter case, try optimizing the emulator by installing HAX (Native intel instructions) or perhaps enable hardware acceleration using the AVD profile editor.

Body:
To find out what on the virtual device is using the most CPU:

adb shell

$ top

This will show you a list of processes with the highest CPU usage atop.

This will help you determine whether it's a process (such as your app) inside the emulator, another process inside the emulator, or just the emulation itself using a lot of CPU.

In the latter case, try optimizing the emulator by installing HAX (Native intel instructions) or perhaps enable hardware acceleration using the AVD profile editor.


问:
How is the Big O of this function O(n^3)?
I am stuck on this Big O notation on how it is supposed to be O(n^3). Where did my thought process go wrong?

I know that a nested for loop is O(n^2) and that the while loop is probably a O(nlogn) function because the for loop is a O(n) function and the value for the while loop is being multiplied by two which makes it O(logn). That being said, the answer is stated to be O(n^3) and I'm confused how this came to be unless the recursive part of the function has something to do with it?

def do_stuff2(n, x=1.23):
    if n <= 0:
        return 0
    val = 1
    for i in range(n//2):
        for j in range(n//4):
            x += 2*x + j/2 + i*1.2
    while val <= n:
        for i in range(n):
            x += val**2 + i//2
        val *= 2
    x += do_stuff2(n - 1, x/2)
    return x
```

I believe that the x does not affect the big o notation because it is a constant because it is not used in deciding how many times any of the loops loop.

So again, I expected the output of the function to be O(n^2), but the actual output is O(n^3)

答:
Your function has two nested for loops, that's O(n^2):

```<code>for i in range(n//2):
    for j in range(n//4):
        x += 2*x + j/2 + i*1.2
</code>```

But on top of that, your do_stuff2() function takes an argument n and calls itself until n <= 0, meaning that's one more O(n).

Body:
I am stuck on this Big O notation on how it is supposed to be O(n^3). Where did my thought process go wrong?

I know that a nested for loop is O(n^2) and that the while loop is probably a O(nlogn) function because the for loop is a O(n) function and the value for the while loop is being multiplied by two which makes it O(logn). That being said, the answer is stated to be O(n^3) and I'm confused how this came to be unless the recursive part of the function has something to do with it?

def do_stuff2(n, x=1.23):
    if n <= 0:
        return 0
    val = 1
    for i in range(n//2):
        for j in range(n//4):
            x += 2*x + j/2 + i*1.2
    while val <= n:
        for i in range(n):
            x += val**2 + i//2
        val *= 2
    x += do_stuff2(n - 1, x/2)
    return x

I believe that the x does not affect the big o notation because it is a constant because it is not used in deciding how many times any of the loops loop.

So again, I expected the output of the function to be O(n^2), but the actual output is O(n^3)

Body:
Your function has two nested for loops, that's O(n^2):

for i in range(n//2):
    for j in range(n//4):
        x += 2*x + j/2 + i*1.2

But on top of that, your do_stuff2() function takes an argument n and calls itself until n <= 0, meaning that's one more O(n).


问:
UIScrollView setContentOffset:animated not working in iOS11
I added a method to make the scroll view to scroll to top of it. This is working as expected in iOS10. But when I upgraded to iOS11 with Xcode 9, it is not working. Is there anything that am missing respective to iOS11.

Below code was working:

```<code>[self setContentOffset:CGPointZero animated:YES];
</code>```

Updating question after comment from OP (UPDATE)

I find the reason why setContentOffset:animated is not working, I use UITableView and I make some custom cell in my tableview, tableview has a property "estimatedRowHeight" , we should make this property equal "0", I guess when iOS11 calculate it's content size it will use "estimatedRowHeight", if we don't set this property , it will use system default.

This is very useful and should be more visible

答: Setting estimatedRowHeight = 0, estimatedSectionHeaderHeight = 0, estimatedSectionFooterHeight = 0 for the scrollview solved the issue. whenever the content offset is changed, the heights of rows, header and footers of each section is calculated by the UIKit to scroll to the new offset. estimatedRowHeight, estimatedSectionHeaderHeight, estimatedSectionFooterHeight will be -1 by default</p>

Body:
I added a method to make the scroll view to scroll to top of it. This is working as expected in iOS10. But when I upgraded to iOS11 with Xcode 9, it is not working. Is there anything that am missing respective to iOS11.

Below code was working:

[self setContentOffset:CGPointZero animated:YES];

Updating question after comment from OP (UPDATE)

I find the reason why setContentOffset:animated is not working, I use UITableView and I make some custom cell in my tableview, tableview has a property "estimatedRowHeight" , we should make this property equal "0", I guess when iOS11 calculate it's content size it will use "estimatedRowHeight", if we don't set this property , it will use system default.

This is very useful and should be more visible


问:
Issues with POST and PUT in table with comma separated numeric values
I am running into issues with POST and PUT for my backend. The relevant table structure can be seen here

```<code>DROP TABLE IF EXISTS coordinate;
CREATE TABLE coordinate
(
   id                    int(10) NOT NULL auto_increment,
   longitude             double(8,4) NOT NULL,
   latitude              double(8,4) NOT NULL,
   measurementId         int(10) default NULL,
   PRIMARY KEY (id),
   FOREIGN KEY (measurementId)
        REFERENCES measurement (id)
        ON DELETE CASCADE
);
</code>```

It has a corresponding Model, which looks like this

```<code>public class Coordinate
{
    public Coordinate()
    {

    }

    public int ID { get; set; }

    public double Latitude { get; set; }

    public double Longitude { get; set; }

    public int MeasurementId { get; set; }

    ...
}
</code>```

I am trying to insert numeric values into coordinate like so:

```<code>sql = "UPDATE coordinate SET longitude = '" + coordinate.Longitude + "," + " latitude = " + coordinate.Latitude + "," + " measurementId = " + coordinate.MeasurementId + "' WHERE id = " + id.ToString();
</code>```

Notice the inclusion of the single bracket before the double bracket after longitude = '" and + "' WHERE ...

When I run this with a debugger the string sql is constructed like so:

```<code>sql = "UPDATE coordinate SET longitude = '55,6, latitude = 70,33, measurementId = 2' WHERE id = 2'
</code>```

And my backend throws the following error:

```<code>{
 "Message": "An error has occurred.",
 "ExceptionMessage": "Data truncated for column 'longitude' at row 1",
 "ExceptionType": "MySql.Data.MySqlClient.MySqlException",
 ...
}
</code>```

My hunch is that the sql string is not constructed properly because of the inclusion of the single bracket, so I remove it like and construct a new sql string like so:

```<code>sql = "UPDATE coordinate SET longitude = " + coordinate.Longitude + "," + " latitude = " + coordinate.Latitude + "," + " measurementId = " + coordinate.MeasurementId + " WHERE id = " + id.ToString();
</code>```

Notice the removal of the single bracket ' in the places it was present before. Now, in the debugger, the string sql is constructed like so:

```<code>sql = "UPDATE coordinate SET longitude 55,6 latitude = 70,33, measurementId = 2 WHERE id = 2"
</code>```

It's my impression that the numeric values should be separated by a . and not a ,, which could by why the backend now throws this error:

```<code>{
 "Message": "An error has occurred.",
 "ExceptionMessage": "You have an error in your SQL syntax; check the manual
 that corresponds to your MySQL server version for the right syntax to use
 near '6, latitude = 70,33, measurementId = 2 WHERE id = 2' at line 1",
}
</code>```

I am a bit at a loss on how to then handle the insertion of numeric values in my database. Any help is much appreciated.

答:
Try the following.</p>

```<code>sql = "UPDATE coordinate SET longitude = '" + coordinate.Longitude + "', latitude = '" + coordinate.Latitude + "', measurementId = '" + coordinate.MeasurementId + "' WHERE id = " + id.ToString();
</code>```

Body:
I am running into issues with POST and PUT for my backend. The relevant table structure can be seen here

DROP TABLE IF EXISTS coordinate;
CREATE TABLE coordinate
(
   id                    int(10) NOT NULL auto_increment,
   longitude             double(8,4) NOT NULL,
   latitude              double(8,4) NOT NULL,
   measurementId         int(10) default NULL,
   PRIMARY KEY (id),
   FOREIGN KEY (measurementId)
        REFERENCES measurement (id)
        ON DELETE CASCADE
);

It has a corresponding Model, which looks like this

public class Coordinate
{
    public Coordinate()
    {

    }

    public int ID { get; set; }

    public double Latitude { get; set; }

    public double Longitude { get; set; }

    public int MeasurementId { get; set; }

    ...
}

I am trying to insert numeric values into coordinate like so:

sql = "UPDATE coordinate SET longitude = '" + coordinate.Longitude + "," + " latitude = " + coordinate.Latitude + "," + " measurementId = " + coordinate.MeasurementId + "' WHERE id = " + id.ToString();

Notice the inclusion of the single bracket before the double bracket after longitude = '" and + "' WHERE ...

When I run this with a debugger the string sql is constructed like so:

sql = "UPDATE coordinate SET longitude = '55,6, latitude = 70,33, measurementId = 2' WHERE id = 2'

And my backend throws the following error:

{
 "Message": "An error has occurred.",
 "ExceptionMessage": "Data truncated for column 'longitude' at row 1",
 "ExceptionType": "MySql.Data.MySqlClient.MySqlException",
 ...
}

My hunch is that the sql string is not constructed properly because of the inclusion of the single bracket, so I remove it like and construct a new sql string like so:

sql = "UPDATE coordinate SET longitude = " + coordinate.Longitude + "," + " latitude = " + coordinate.Latitude + "," + " measurementId = " + coordinate.MeasurementId + " WHERE id = " + id.ToString();

Notice the removal of the single bracket ' in the places it was present before. Now, in the debugger, the string sql is constructed like so:

sql = "UPDATE coordinate SET longitude 55,6 latitude = 70,33, measurementId = 2 WHERE id = 2"

It's my impression that the numeric values should be separated by a . and not a ,, which could by why the backend now throws this error:

{
 "Message": "An error has occurred.",
 "ExceptionMessage": "You have an error in your SQL syntax; check the manual
 that corresponds to your MySQL server version for the right syntax to use
 near '6, latitude = 70,33, measurementId = 2 WHERE id = 2' at line 1",
}

I am a bit at a loss on how to then handle the insertion of numeric values in my database. Any help is much appreciated.

Body:
Try the following.

sql = "UPDATE coordinate SET longitude = '" + coordinate.Longitude + "', latitude = '" + coordinate.Latitude + "', measurementId = '" + coordinate.MeasurementId + "' WHERE id = " + id.ToString();