问:
Running Winscp from SSIS execute process task
I am trying to implement solution in SSIS in which we have to download files from SFTP using Winzip. Filenames in SFTP are like ABC_CNT_03_06_2019_02-05_AM.csv. The requirement is to download the current date file. In this case we have to ignore the time part in the file name.

Currently, I am trying to implement the below solution:

Created a variable (User::Filename) in ssis to create the file name ABC_CNT_03_06_2018*.csv

In Execute process task : have selected C:\Program Files (x86)\WinSCP\WinSCP.com in executable

Arguments : /script="F:\Upload.txt /parameter " + User::Filename

upload.txt ha the below text

option batch on
option confirm off
open username: password@sftp2.ftpname.com
get /%1%  F:\downloadfolder
close exit

Trying to run the package but it is not working.
Can you please suggest further?

答:
For something like this I’d recommend using a Script Task with the WinSCP .NET assembly, which will allow you to use C# functionality to verify the date on the file prior to the transfer.  An example of this process is below.  Since you’re storing the beginning of the file name (including date) in a variable, the String.StartsWith method is used on the Name property, as this only returns the file name without the folder path.  The String.EndsWith method is also used to match only CSV files as mentioned in your post.  The SSIS variable holding the file name will need to be added in the ReadOnlyVariables field of the Script Task, as well as the variables holding folder paths if that’s how you’re storing these.  If you encounter an error relating to loading the WinSCP assembly,the ResolveEventHandler delegate can be used to resolve this as done below.  The location where the WinSCP dll was downloaded will be the path sent to the LoadFile method.  While it looks like you are only expecting one file per day, a list is used in the event that there will be multiple files on a single day.

```<code>using System.Linq;
using WinSCP;
using System.Collections.Generic;

//load WinSCPnet.dll
 static ScriptMain()
 {
     AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
 }
 static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
 {
     if (args.Name.ToUpper().Contains("WINSCPNET"))
     {
         string path = @"C:\WinSCP Download Path\";
         return System.Reflection.Assembly.LoadFile(System.IO.Path.Combine(path, "WinSCPnet.dll"));
     }
     return null;
 }

    public void Main()
    {
      //get file name and local/remote paths from SSIS variables.
      string fileDateName = Dts.Variables[“User::FileDateName”].Value.ToString();
      string remotePath = Dts.Variables[“User::RemoteFilePath”].Value.ToString();
      string localPath = Dts.Variables[“User::LocalFilePath”].Value.ToString();

 SessionOptions sessOpt = new SessionOptions
   {
     Protocol = Protocol.Sftp,
     HostName = "SFTPsite.com",
     UserName = "user",
     Password = "password",
     SshHostKeyFingerprint = "Your SshHostKeyFingerprint"
   };

 using (Session session = new Session())
 {
   session.Open(sessOpt);

   TransferOptions transferOptions = new TransferOptions();
   transferOptions.TransferMode = TransferMode.Binary;

   RemoteDirectoryInfo rdi = session.ListDirectory(remotePath);

   //confirm beginning of file name and extension
   List<string> fileList = rdi.Files.Where(file => (file.Name.StartsWith(fileDateName))
   && (file.FullName.EndsWith(".csv"))).Select(file => file.FullName).ToList();

   foreach (string s in fileList)
   {
       //transfer files
       session.GetFiles(s, localPath, false, transferOptions);
   }

 }

}
</code>```

Body:
For something like this I’d recommend using a Script Task with the WinSCP .NET assembly, which will allow you to use C# functionality to verify the date on the file prior to the transfer.  An example of this process is below.  Since you’re storing the beginning of the file name (including date) in a variable, the String.StartsWith method is used on the Name property, as this only returns the file name without the folder path.  The String.EndsWith method is also used to match only CSV files as mentioned in your post.  The SSIS variable holding the file name will need to be added in the ReadOnlyVariables field of the Script Task, as well as the variables holding folder paths if that’s how you’re storing these.  If you encounter an error relating to loading the WinSCP assembly,the ResolveEventHandler delegate can be used to resolve this as done below.  The location where the WinSCP dll was downloaded will be the path sent to the LoadFile method.  While it looks like you are only expecting one file per day, a list is used in the event that there will be multiple files on a single day.

using System.Linq;
using WinSCP;
using System.Collections.Generic;

//load WinSCPnet.dll
 static ScriptMain()
 {
     AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
 }
 static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
 {
     if (args.Name.ToUpper().Contains("WINSCPNET"))
     {
         string path = @"C:\WinSCP Download Path\";
         return System.Reflection.Assembly.LoadFile(System.IO.Path.Combine(path, "WinSCPnet.dll"));
     }
     return null;
 }

    public void Main()
    {
      //get file name and local/remote paths from SSIS variables.
      string fileDateName = Dts.Variables[“User::FileDateName”].Value.ToString();
      string remotePath = Dts.Variables[“User::RemoteFilePath”].Value.ToString();
      string localPath = Dts.Variables[“User::LocalFilePath”].Value.ToString();

 SessionOptions sessOpt = new SessionOptions
   {
     Protocol = Protocol.Sftp,
     HostName = "SFTPsite.com",
     UserName = "user",
     Password = "password",
     SshHostKeyFingerprint = "Your SshHostKeyFingerprint"
   };

 using (Session session = new Session())
 {
   session.Open(sessOpt);

   TransferOptions transferOptions = new TransferOptions();
   transferOptions.TransferMode = TransferMode.Binary;

   RemoteDirectoryInfo rdi = session.ListDirectory(remotePath);

   //confirm beginning of file name and extension
   List<string> fileList = rdi.Files.Where(file => (file.Name.StartsWith(fileDateName))
   && (file.FullName.EndsWith(".csv"))).Select(file => file.FullName).ToList();

   foreach (string s in fileList)
   {
       //transfer files
       session.GetFiles(s, localPath, false, transferOptions);
   }

 }

}


来源: stackexchange

问:
Javascript Canvas how to scale up image
I'm using the scale() function with canvas but I'm not sure how it works because it doesn't seem to work in the way you'd guess it would. I simply want to scale the image up by two.

```<code>const imageData = tempcanv.getContext('2d').getImageData(0, 0, tempcanv.width, tempcanv.height);
const canvas2 = document.createElement("canvas");
const ctx2 = canvas2.getContext('2d');
canvas2.width = tempcanv.width * 2, canvas2.height = tempcanv.height * 2;
ctx2.scale(2, 2);
ctx2.putImageData(imageData, 0, 0);
</code>```

This simply makes the image inside of a bigger canvas, but the image size itself has not changed. Is this not what scale() is supposed to do or am I doing something else wrong?

答:
Using putImageData it is not affected by the current transformations on your canvas - in your case the scale will not have any effect.

Instead, what you can do is use the drawImage function to draw your temp canvas onto your other canvas at your desired scale, e.g.:

```<code>...
// Syntax: ctx.drawImage(image, dx, dy, dWidth, dHeight);
ctx2.drawImage(tempcanv, 0, 0, tempcanv.width * 2, tempcanv.height * 2);
...
</code>```

Here is a basic example drawing one canvas onto the other.

var canv1 = document.getElementById('canvas1');
var canv2 = document.getElementById('canvas2');
// Draw a rect on our source canvas as an example image
canv1.getContext('2d').fillRect(1, 1, 40, 40);
// Draw our first canvas onto our second at 2x
canv2.getContext('2d').drawImage(canv1, 0, 0, canv1.width * 2, canv1.height * 2);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <canvas id="canvas1" width="100" height="100"></canvas>
</div>
<div>
  <canvas id="canvas2" width="200" height="200"></canvas>
</div></code>```

ContentLicense: CC BY-SA 4.0

Title: Javascript Canvas how to scale up image

Body:
I'm using the scale() function with canvas but I'm not sure how it works because it doesn't seem to work in the way you'd guess it would. I simply want to scale the image up by two.

const imageData = tempcanv.getContext('2d').getImageData(0, 0, tempcanv.width, tempcanv.height);
const canvas2 = document.createElement("canvas");
const ctx2 = canvas2.getContext('2d');
canvas2.width = tempcanv.width * 2, canvas2.height = tempcanv.height * 2;
ctx2.scale(2, 2);
ctx2.putImageData(imageData, 0, 0);

This simply makes the image inside of a bigger canvas, but the image size itself has not changed. Is this not what scale() is supposed to do or am I doing something else wrong?

Body:
Using putImageData it is not affected by the current transformations on your canvas - in your case the scale will not have any effect.

Instead, what you can do is use the drawImage function to draw your temp canvas onto your other canvas at your desired scale, e.g.:

...
// Syntax: ctx.drawImage(image, dx, dy, dWidth, dHeight);
ctx2.drawImage(tempcanv, 0, 0, tempcanv.width * 2, tempcanv.height * 2);
...

Here is a basic example drawing one canvas onto the other.

var canv1 = document.getElementById('canvas1');
var canv2 = document.getElementById('canvas2');
// Draw a rect on our source canvas as an example image
canv1.getContext('2d').fillRect(1, 1, 40, 40);
// Draw our first canvas onto our second at 2x
canv2.getContext('2d').drawImage(canv1, 0, 0, canv1.width * 2, canv1.height * 2);

<div>
  <canvas id="canvas1" width="100" height="100"></canvas>
</div>
<div>
  <canvas id="canvas2" width="200" height="200"></canvas>
</div>


问:
How to test if a category already exists? PrestaShop
I get the category from other database web service and I put them on PrestaShop when I refresh the file to add categories I wanna make sure if the category id exists, if exist I wanna update the category.</p>

```<code>$XMLRQString = '<?xml version="1.0" encoding="utf-8"?>'.
    '<x:Winmax4GetFamiliesRQ xmlns:x="urn:Winmax4GetFamiliesRQ">'.
    '</x:Winmax4GetFamiliesRQ >';

$return = $client->GetFamilies($Params);
$XMLRSString = new SimpleXMLElement($return->GetFamiliesResult);
if ($XMLRSString->Code > 0)
    echo '</br>Error: '.$XMLRSString->Code." ".$XMLRSString->Message;
else{

        foreach ($XMLRSString->Families->Family as $family)
        {

            $category = new Category();

            $category->id = $family->Code;

            $category->force_id = true;

            $category->is_root_category = false;

            $category->name = array((int)Configuration::get('PS_LANG_DEFAULT') => $family->Designation);

            $category->link_rewrite = array((int)Configuration::get('PS_LANG_DEFAULT') =>  $family->Code);

            $category->id_parent = Configuration::get('PS_HOME_CATEGORY');

            $category->add();

        }
    }
</code>```

答:
In general, If you have large data (and also safe data), it's better to insert your data directly to your database. Use Db class instead of Category class.

Otherwise, you must use a save() method instead of add() method

Body:
I get the category from other database web service and I put them on PrestaShop when I refresh the file to add categories I wanna make sure if the category id exists, if exist I wanna update the category.

$XMLRQString = '<?xml version="1.0" encoding="utf-8"?>'.
    '<x:Winmax4GetFamiliesRQ xmlns:x="urn:Winmax4GetFamiliesRQ">'.
    '</x:Winmax4GetFamiliesRQ >';

$return = $client->GetFamilies($Params);
$XMLRSString = new SimpleXMLElement($return->GetFamiliesResult);
if ($XMLRSString->Code > 0)
    echo '
Error: '.$XMLRSString->Code." ".$XMLRSString->Message;
else{

        foreach ($XMLRSString->Families->Family as $family)
        {

            $category = new Category();

            $category->id = $family->Code;

            $category->force_id = true;

            $category->is_root_category = false;

            $category->name = array((int)Configuration::get('PS_LANG_DEFAULT') => $family->Designation);

            $category->link_rewrite = array((int)Configuration::get('PS_LANG_DEFAULT') =>  $family->Code);

            $category->id_parent = Configuration::get('PS_HOME_CATEGORY');

            $category->add();

        }
    }


问:
AWS Lambda + Nodejs + MySQL
I am writing a simple lambda code to insert some values to mysql table (rds) but i have no clue why it is not working. After reperted tries sometimes it works and subsequent tries again stop working

everytime it fails (does not insert to table) i get the below response

```<code>Response:
null

Request ID:
"6814c4b8-65c5-4401-b7c1-ae06426f186c"

Function Logs:
START RequestId: 6814c4b8-65c5-4401-b7c1-ae06426f186c Version: $LATEST
END RequestId: 6814c4b8-65c5-4401-b7c1-ae06426f186c
REPORT RequestId: 6814c4b8-65c5-4401-b7c1-ae06426f186c  Duration: 317.80 ms Billed Duration: 400 ms     Memory Size: 128 MB Max Memory Used: 75 MB
</code>```

My Code to insert data or query data is as simple as

```<code>const mysql = require('mysql');
const con = mysql.createConnection({
  host     : process.env.RDS_HOSTNAME,
  user     : process.env.RDS_USERNAME,
  password : process.env.RDS_PASSWORD,
  port     : process.env.RDS_PORT,
  database : process.env.RDS_DATABASE
});
exports.handler = (event, context, callback) => {
  // allows for using callbacks as finish/error-handlers
  context.callbackWaitsForEmptyEventLoop = false;
  const sql = "INSERT INTO MESSAGE (message) VALUES ('I am MySQL')";
  con.query(sql, (err, res) => {
    if (err) {
      throw err
    }
    callback(null, '1 records inserted.');
  })
};
</code>```

I have double checked the security group settings and it seems to be correct

I have been referring to

``
https://medium.com/@hk_it_er/create-lambda-and-api-gateway-nodejs-aws-serverless-to-rds-mysql-6a75243e61cc

``

Any pointers as to what is wrong or what should i check ?

P.S: In a day after 100 attempts i have managed to insert 3 rows with the same code and settings.

答: the issue was with node v 10. I switched to node 8 and it seems to be working with ease. Guess node 10 has made some calls async.</p>

Title: AWS Lambda + Nodejs + MySQL

Body:
I am writing a simple lambda code to insert some values to mysql table (rds) but i have no clue why it is not working. After reperted tries sometimes it works and subsequent tries again stop working

everytime it fails (does not insert to table) i get the below response

Response:
null

Request ID:
"6814c4b8-65c5-4401-b7c1-ae06426f186c"

Function Logs:
START RequestId: 6814c4b8-65c5-4401-b7c1-ae06426f186c Version: $LATEST
END RequestId: 6814c4b8-65c5-4401-b7c1-ae06426f186c
REPORT RequestId: 6814c4b8-65c5-4401-b7c1-ae06426f186c  Duration: 317.80 ms Billed Duration: 400 ms     Memory Size: 128 MB Max Memory Used: 75 MB

My Code to insert data or query data is as simple as

const mysql = require('mysql');
const con = mysql.createConnection({
  host     : process.env.RDS_HOSTNAME,
  user     : process.env.RDS_USERNAME,
  password : process.env.RDS_PASSWORD,
  port     : process.env.RDS_PORT,
  database : process.env.RDS_DATABASE
});
exports.handler = (event, context, callback) => {
  // allows for using callbacks as finish/error-handlers
  context.callbackWaitsForEmptyEventLoop = false;
  const sql = "INSERT INTO MESSAGE (message) VALUES ('I am MySQL')";
  con.query(sql, (err, res) => {
    if (err) {
      throw err
    }
    callback(null, '1 records inserted.');
  })
};

I have double checked the security group settings and it seems to be correct

I have been referring to

``
https://medium.com/@hk_it_er/create-lambda-and-api-gateway-nodejs-aws-serverless-to-rds-mysql-6a75243e61cc

``

Any pointers as to what is wrong or what should i check ?

P.S: In a day after 100 attempts i have managed to insert 3 rows with the same code and settings.


问:
Download exact replica of source to destination, by deleting user created local files in destination
I have artifactory source folder with the following contents:
a->a1.txt, a2.txt
b->b1.txt, b3.txt

In the local directory, I have extra files in Local machine:
a->a1.txt, a2.txt, a3.txt
b->b1.txt, b2.txt, b3.txt

When I download files from artifactory using jfrog-cli, I need to have a exact replica of Artifactory source by deleting the user defined files of a3.txt & b3.txt

Final Output:
a->a1.txt, a2.txt
b->b1.txt, b3.txt

答:
Right now there is no option to do that using the JFrog CLI. Really the only option you have right now is to write a script that removes all files and downloads the content from JFrog Artifactory after that.

If you want, you can create a new GitHub issue for the JFrog team here so they can evaluate the request.


问:
Initializing properties inside ngOnInit scope
I'm using ngOnInit in order to get a response from a Loopback API call.
The property I initialize inside this scope can't be used outside the subscribe scope. I know this is a simple answer but I'm just not seeing it

```<code>private siteData: Kiosk;

  constructor(private dataService: DataService){}

 ngOnInit(){
    this.dataService.getDataByID(this.dataService.getSiteID())
        .subscribe((data:Site) => {
             this.siteData = data;
             console.log(this.siteData); // This outputs correctly
    });
    console.log(this.siteData); // This is undefined
  }

  site: any[] = [{
    title: this.siteData.title, // this is undefined and throws error
  }];
</code>```

I expect output to not be undefined and be the data that is in the response

答:
```<code>console.log(this.siteData); // This is undefined
</code>```

because this doesn't  wait for this.dataService.getDataByID to finish  use the one inside if you don't want it to be undefined

Body:
I'm using ngOnInit in order to get a response from a Loopback API call.
The property I initialize inside this scope can't be used outside the subscribe scope. I know this is a simple answer but I'm just not seeing it

private siteData: Kiosk;

  constructor(private dataService: DataService){}

 ngOnInit(){
    this.dataService.getDataByID(this.dataService.getSiteID())
        .subscribe((data:Site) => {
             this.siteData = data;
             console.log(this.siteData); // This outputs correctly
    });
    console.log(this.siteData); // This is undefined
  }

  site: any[] = [{
    title: this.siteData.title, // this is undefined and throws error
  }];

I expect output to not be undefined and be the data that is in the response

Body:
console.log(this.siteData); // This is undefined

because this doesn't  wait for this.dataService.getDataByID to finish  use the one inside if you don't want it to be undefined


问:
JSON returning as undefined
Hello I have an ajax request that submits a form and sends and email, if the email is submitted successfully, I encode a PHP array that looks like this,

$success = array("state" => "Email Sent");

I am then checking the state of data in my ajax request to see if state matches "Email Sent" however when I alert(data) i get undefined, what am I doing wrong? Below is my javascript,

```<code>$.ajax({
                    url: "<?php echo base_url(); ?>home/callback",
                    data: $("#callback").serialize(),
                    type: "POST",
                    dataType: "JSON",
                    success: function(data){
                        $("#fancybox-content div").html(data);
                        alert(data.state);
                    }
                });
</code>```

答:
use

```<code>json_decode($success, true);
</code>```

When TRUE, returned objects will be  converted into associative arrays.

ContentLicense: CC BY-SA 3.0

Title: JSON returning as undefined

Body:
Hello I have an ajax request that submits a form and sends and email, if the email is submitted successfully, I encode a PHP array that looks like this,

$success = array("state" => "Email Sent");

I am then checking the state of data in my ajax request to see if state matches "Email Sent" however when I alert(data) i get undefined, what am I doing wrong? Below is my javascript,

$.ajax({
                    url: "<?php echo base_url(); ?>home/callback",
                    data: $("#callback").serialize(),
                    type: "POST",
                    dataType: "JSON",
                    success: function(data){
                        $("#fancybox-content div").html(data);
                        alert(data.state);
                    }
                });

Body:
use

json_decode($success, true);

When TRUE, returned objects will be  converted into associative arrays.


问:
Order a Map that contains String, but strings might represent a number
I have this kind of values inside a Map:

```<code>Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1,"mark");
map.put(2,"1.1");
map.put(3,"google");
map.put(4,"12");
map.put(5,"2.2);
</code>```

I need to order this Map, ordering both numbers and strings.

What I get now is this (as you can see numbers are not "ordered" since are String)

```<code>1.1
12
2.2
google
mark
</code>```

What I should  get is:

```<code>1.1
2.2
12
google
mark
</code>```

How can I do it? I'm a little confused.

答:
If you really need a map you can use a LinkedHashMap which is sorted by insertion order. To compare the values you can create your own comparator:

```<code>Comparator<String> stringAndNumberComparator = (s1, s2) -> {
    try {
        return Double.valueOf(s1).compareTo(Double.valueOf(s2));
    } catch (NumberFormatException e) {
        return s1.compareTo(s2);
    }
};
</code>```

Now you can use a java stream to sort the entry set of your map and collect it back to a LinkedHashMap:

```<code>Map<Integer, String> sorted = map.entrySet().stream()
        .sorted(Map.Entry.comparingByValue(stringAndNumberComparator))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (s1, s2) -> s1, LinkedHashMap::new));
</code>```

Alternatively you can use the comparator provided in the answer from Karol Dowbecki with Map.Entry.comparingByValue().

The result will be {2=1.1, 5=2.2, 4=12, 3=google, 1=mark};

If you just need a list of your values you can just use this:

```<code>List<String> sorted = map.values().stream()
        .sorted(stringAndNumberComparator)
        .collect(Collectors.toList());
</code>```

The result in this case will be [1.1, 2.2, 12, google, mark].

Body:
I have this kind of values inside a Map:

Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1,"mark");
map.put(2,"1.1");
map.put(3,"google");
map.put(4,"12");
map.put(5,"2.2);

I need to order this Map, ordering both numbers and strings.

What I get now is this (as you can see numbers are not "ordered" since are String)

1.1
12
2.2
google
mark

What I should  get is:

1.1
2.2
12
google
mark

How can I do it? I'm a little confused.

Body:
If you really need a map you can use a LinkedHashMap which is sorted by insertion order. To compare the values you can create your own comparator:

Comparator<String> stringAndNumberComparator = (s1, s2) -> {
    try {
        return Double.valueOf(s1).compareTo(Double.valueOf(s2));
    } catch (NumberFormatException e) {
        return s1.compareTo(s2);
    }
};

Now you can use a java stream to sort the entry set of your map and collect it back to a LinkedHashMap:

Map<Integer, String> sorted = map.entrySet().stream()
        .sorted(Map.Entry.comparingByValue(stringAndNumberComparator))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (s1, s2) -> s1, LinkedHashMap::new));

Alternatively you can use the comparator provided in the answer from Karol Dowbecki with Map.Entry.comparingByValue().

The result will be {2=1.1, 5=2.2, 4=12, 3=google, 1=mark};

If you just need a list of your values you can just use this:

List<String> sorted = map.values().stream()
        .sorted(stringAndNumberComparator)
        .collect(Collectors.toList());

The result in this case will be [1.1, 2.2, 12, google, mark].


问:
Cannot route to page using blazor route with parameter
I have an issue with routing in my blazor server side app. I have specified @page "/intent/{intentid:int}" in my razor view and I am using a link tag to navigate to it on the side bar ex: Test. the address bar url changes on link click but my intent c# code behind OnInit is not being fired ??? any suggestions ?

I've tried using UriHelper to navigate to the page but again page OnInit doesn't get fired.

intent view:

```<code>@page "/"
@page "/intent/{intentid:int}"
</code>```

intent code behind:

```<code>[Parameter]
private int IntentId { get; set; }
</code>```

NavMenu page:

```<code><a class="btn btn-primary" href="Intent/@(item.Key)">@intentClassifier.Text</a>
</code>```

I expect to hit the OnInit on my intent page once the a link is clicked and receive the parameter value for intentid.
but only url changes in the address bar and thats all

答: You'll need to override OnParametersSetAsync, this gets called when the parameters are changed.</p>

Body:
I have an issue with routing in my blazor server side app. I have specified @page "/intent/{intentid:int}" in my razor view and I am using a link tag to navigate to it on the side bar ex: Test. the address bar url changes on link click but my intent c# code behind OnInit is not being fired ??? any suggestions ?

I've tried using UriHelper to navigate to the page but again page OnInit doesn't get fired.

intent view:

@page "/"
@page "/intent/{intentid:int}"

intent code behind:

[Parameter]
private int IntentId { get; set; }

NavMenu page:

@intentClassifier.Text

I expect to hit the OnInit on my intent page once the a link is clicked and receive the parameter value for intentid.
but only url changes in the address bar and thats all


问:
how to make the whole downstream flow of an executor-channel task retry-able?
In the same way as you can easily add an advice to a poller (for a queue-channel) so as to apply it to the entire downstream flow, is there a way to make the whole downstream flow of an executor-channel task retry-able ?</p>

答: Implement a HandleMessageAdvice with a RetryTemplate and add it to the first component's advice chain.


答:
You will need to initialize the variables inside the subscribe method with the values which you are doing already.

Now You can access them in the HTML once the request is completed. Make sure to add a check in the HTML i.e if siteData using *ngIf & then use those variables normally

Title: Initializing properties inside ngOnInit scope


问:
Json to dataframe (empty observations, different lengths)
Through an API I accessed weather information in Json format. I want to convert this data to a dataframe. The problem is that not for every date-city combination the api returns weather conditions, so a few rows are empty. Second , not every combination that does return gives the same aspects of the weather. My goal is to convert the Json to a dataframe, where rows that are empty are still showed in the dataframe (which does not happen when I unlist them)  and the different aspects of the weather are properly showed under the right variable  with NA values if there is no record for that particular variable. I've tried enlisting them and putting it into a dataframe, flattening the table etc (getting the error: arguments imply differing number of rows: 0, 1) . I've searched for this topic but none of them worked for my case  (or maybe because I'm not that experienced I applied them wrong), but every tip is welcome!

The input looks like this:

```<code>reviewid    dateofwriting   lon         lat
98338143    28-02-11        11,41693611 22,3193039
58929813    18-03-10        -3,7037902  40,4167754
65945346    31-05-10        -3,188267   55,953252
</code>```

The output looks like this (the second observation returns 36 columns and the third one 38. the first entry is missing because there was no observation for that day and is not displayed)

enter image description here

```<code>    [{},
    {"daily":
       [{"time":"2010-03-18",
       "summary":"Partly cloudy throughout the day.",
       "icon":"partly-cloudy-day",
       "sunriseTime":"2010-03-18 07:22:51",
       "sunsetTime":"2010-03-18 19:25:28",
       "moonPhase":0.08,
       "precipIntensity":0,
       "precipIntensityMax":0,
       "precipProbability":0,
       "temperatureHigh":63.14,
       "temperatureHighTime":1268928000,
       "temperatureLow":45.16,
       "temperatureLowTime":1268971200,
       "apparentTemperatureHigh":63.14,
       "apparentTemperatureHighTime":1268928000,
       "apparentTemperatureLow":45.16,
       "apparentTemperatureLowTime":1268971200,
       "dewPoint":36.97,
       "humidity":0.58,
       "pressure":1025.96,
       "windSpeed":1.24,
       "windGust":7.87,
       "windGustTime":1268866800,
       "windBearing":48,
       "cloudCover":0.54,
       "uvIndex":5,
       "uvIndexTime":1268913600,
       "visibility":6.19,
       "temperatureMin":43.97,
       "temperatureMinTime":"2010-03-18 07:00:00",
       "temperatureMax":63.14,
       "temperatureMaxTime":"2010-03-18 17:00:00",
       "apparentTemperatureMin":42.03,
       "apparentTemperatureMinTime":"2010-03-18 08:00:00",
       "apparentTemperatureMax":63.14,
       "apparentTemperatureMaxTime":"2010-03-18 17:00:00"}]},

    {"daily":
       [{"time":"2010-05-30 01:00:00",
       "summary":"Mostly cloudy until evening.",
       "icon":"partly-cloudy-day",
       "sunriseTime":"2010-05-30 05:38:39",
       "sunsetTime":"2010-05-30 22:44:55",
       "moonPhase":0.58,
       "precipIntensity":0.0038,
       "precipIntensityMax":0.0766,
       "precipIntensityMaxTime”:"2010-05-30 04:00:00",
       "precipProbability":1,
       "precipType":"rain",
       "temperatureHigh":58.99,
       "temperatureHighTime":1275242400,
       "temperatureLow":36.62,
       "temperatureLowTime":1275278400,
       "apparentTemperatureHigh":58.99,
       "apparentTemperatureHighTime":1275242400,
       "apparentTemperatureLow":36.62,
       "apparentTemperatureLowTime":1275278400,
       "dewPoint":43.61,
       "humidity":0.76,
       "pressure":1011.52,
       "windSpeed":4.65,
       "windGust":21.4,
       "windGustTime":1275224400,
       "windBearing":350,
       "cloudCover":0.61,
       "uvIndex":5,
       "uvIndexTime":1275213600,
       "visibility":5.85,
       "temperatureMin":45.99,
       "temperatureMinTime":"2010-05-30 07:00:00",
       "temperatureMax":58.99,
       "temperatureMaxTime":"2010-05-30 20:00:00",
       "apparentTemperatureMin":43.31,
       "apparentTemperatureMinTime":"2010-05-30 06:00:00",
       "apparentTemperatureMax":58.99,
       "apparentTemperatureMaxTime":"2010-05-30 20:00:00"}]}]
</code>```

The goal is to add these rows to the input excel above.

```<code>icon                sunrisetime     sunsettime      etc.
NA                  NA              NA              etc.
partly-cloudy-day   18-03-10 07:22  18-03-10 19:25  etc.
partly-cloudy-day   30-05-10 05:38  30-05-10 22:44  etc.
</code>```

答:
There is a problem dealing with the responses that return NULL.  To simplify the issue, it is easier to remove these non responses and then parse the remaining JSON response. If desired, one can go back and add the empty rows for the non responses.</p>

```<code>library(jsonlite)
library(dplyr)

#test<- result from converting the JSON response.
#vector of reviewid, used to make the initial request to the API
reviewid<-c(98338143, 58929813, 65945346)

#find only the responses that are not Null or blank
valid<-which(sapply(1:nrow(test),  function(j) {length(test[[1]][[j]])}) >0)
NullResponses<-which(sapply(1:nrow(test),  function(j) {length(test[[1]][[j]])}) == 0)

#create a list of data frames with the data from row of the response
dflist<-lapply( valid, function(j) {
  temp<-t(as.matrix(unlist(test[j,])))
  df<-data.frame(reviewid=reviewid[j], temp, stringsAsFactors = FALSE)
  df
  })
#bind the rows together.
answer<-bind_rows(dflist)
</code>```

Body:
Through an API I accessed weather information in Json format. I want to convert this data to a dataframe. The problem is that not for every date-city combination the api returns weather conditions, so a few rows are empty. Second , not every combination that does return gives the same aspects of the weather. My goal is to convert the Json to a dataframe, where rows that are empty are still showed in the dataframe (which does not happen when I unlist them)  and the different aspects of the weather are properly showed under the right variable  with NA values if there is no record for that particular variable. I've tried enlisting them and putting it into a dataframe, flattening the table etc (getting the error: arguments imply differing number of rows: 0, 1) . I've searched for this topic but none of them worked for my case  (or maybe because I'm not that experienced I applied them wrong), but every tip is welcome!

The input looks like this:

reviewid    dateofwriting   lon         lat
98338143    28-02-11        11,41693611 22,3193039
58929813    18-03-10        -3,7037902  40,4167754
65945346    31-05-10        -3,188267   55,953252

The output looks like this (the second observation returns 36 columns and the third one 38. the first entry is missing because there was no observation for that day and is not displayed)

enter image description here

    [{},
    {"daily":
       [{"time":"2010-03-18",
       "summary":"Partly cloudy throughout the day.",
       "icon":"partly-cloudy-day",
       "sunriseTime":"2010-03-18 07:22:51",
       "sunsetTime":"2010-03-18 19:25:28",
       "moonPhase":0.08,
       "precipIntensity":0,
       "precipIntensityMax":0,
       "precipProbability":0,
       "temperatureHigh":63.14,
       "temperatureHighTime":1268928000,
       "temperatureLow":45.16,
       "temperatureLowTime":1268971200,
       "apparentTemperatureHigh":63.14,
       "apparentTemperatureHighTime":1268928000,
       "apparentTemperatureLow":45.16,
       "apparentTemperatureLowTime":1268971200,
       "dewPoint":36.97,
       "humidity":0.58,
       "pressure":1025.96,
       "windSpeed":1.24,
       "windGust":7.87,
       "windGustTime":1268866800,
       "windBearing":48,
       "cloudCover":0.54,
       "uvIndex":5,
       "uvIndexTime":1268913600,
       "visibility":6.19,
       "temperatureMin":43.97,
       "temperatureMinTime":"2010-03-18 07:00:00",
       "temperatureMax":63.14,
       "temperatureMaxTime":"2010-03-18 17:00:00",
       "apparentTemperatureMin":42.03,
       "apparentTemperatureMinTime":"2010-03-18 08:00:00",
       "apparentTemperatureMax":63.14,
       "apparentTemperatureMaxTime":"2010-03-18 17:00:00"}]},

    {"daily":
       [{"time":"2010-05-30 01:00:00",
       "summary":"Mostly cloudy until evening.",
       "icon":"partly-cloudy-day",
       "sunriseTime":"2010-05-30 05:38:39",
       "sunsetTime":"2010-05-30 22:44:55",
       "moonPhase":0.58,
       "precipIntensity":0.0038,
       "precipIntensityMax":0.0766,
       "precipIntensityMaxTime”:"2010-05-30 04:00:00",
       "precipProbability":1,
       "precipType":"rain",
       "temperatureHigh":58.99,
       "temperatureHighTime":1275242400,
       "temperatureLow":36.62,
       "temperatureLowTime":1275278400,
       "apparentTemperatureHigh":58.99,
       "apparentTemperatureHighTime":1275242400,
       "apparentTemperatureLow":36.62,
       "apparentTemperatureLowTime":1275278400,
       "dewPoint":43.61,
       "humidity":0.76,
       "pressure":1011.52,
       "windSpeed":4.65,
       "windGust":21.4,
       "windGustTime":1275224400,
       "windBearing":350,
       "cloudCover":0.61,
       "uvIndex":5,
       "uvIndexTime":1275213600,
       "visibility":5.85,
       "temperatureMin":45.99,
       "temperatureMinTime":"2010-05-30 07:00:00",
       "temperatureMax":58.99,
       "temperatureMaxTime":"2010-05-30 20:00:00",
       "apparentTemperatureMin":43.31,
       "apparentTemperatureMinTime":"2010-05-30 06:00:00",
       "apparentTemperatureMax":58.99,
       "apparentTemperatureMaxTime":"2010-05-30 20:00:00"}]}]

The goal is to add these rows to the input excel above.

icon                sunrisetime     sunsettime      etc.
NA                  NA              NA              etc.
partly-cloudy-day   18-03-10 07:22  18-03-10 19:25  etc.
partly-cloudy-day   30-05-10 05:38  30-05-10 22:44  etc.

Body:
There is a problem dealing with the responses that return NULL.  To simplify the issue, it is easier to remove these non responses and then parse the remaining JSON response. If desired, one can go back and add the empty rows for the non responses.

library(jsonlite)
library(dplyr)

#test<- result from converting the JSON response.
#vector of reviewid, used to make the initial request to the API
reviewid<-c(98338143, 58929813, 65945346)

#find only the responses that are not Null or blank
valid<-which(sapply(1:nrow(test),  function(j) {length(test[[1]][[j]])}) >0)
NullResponses<-which(sapply(1:nrow(test),  function(j) {length(test[[1]][[j]])}) == 0)

#create a list of data frames with the data from row of the response
dflist<-lapply( valid, function(j) {
  temp<-t(as.matrix(unlist(test[j,])))
  df<-data.frame(reviewid=reviewid[j], temp, stringsAsFactors = FALSE)
  df
  })
#bind the rows together.
answer<-bind_rows(dflist)


问:
How to align two elements on the same line from PHP
Screenshots:
Inspect element shows:
The "7 in stock" i want to align with the "10" bellow

I would like to align two $elements to display on the same line.

```<code><span class="max">
    <?php echo $tickets_sold, $max_tickets; ?>
</span>
</code>```

When the $tickets_sold is not included, the $max_tickets goes on the top. But when it's included, it immediately goes on the next line.

I've tried many different options as &&, and, but they never appear on the same line. I am sure the solution is easy, but I am a beginner.

```<code>$max_tickets = $product->get_max_tickets();
$tickets_sold = wc_get_stock_html( $product );
</code>```

PHP code

```<code> <div class="wcl-progress-meter <?php if($product->is_max_tickets_met()) echo 'full' ?>">
    <progress  max="<?php echo $max_tickets ?>" value="<?php echo $lottery_participants_count ?>"  low="<?php echo $min_tickets ?>"></progress></br>
    <span class="zero">0 </span>
    <span class="max">  <?php echo $tickets_sold, $max_tickets?></div></span>
</div>
</code>```

CSS file

```<code>.wcl-progress-meter meter::-webkit-meter-suboptimum-value {
  box-shadow: 0 5px 5px -5px #999 inset;
  background: #cb132b;
  display:inline-block;

}

.wcl-progress-meter .zero {
  display: inline-block;
  position: absolute;
  top: -100%;
}

.wcl-progress-meter .min {
  display: inline-block;
  position: absolute;
  top: -100%;
}

.wcl-progress-meter .max {
  display: inline-block;
  position: absolute;
  top: -100%;
  right: 0;
  vertical-align: middle;
}
</code>```

答:
Just tweak your HTML a bit and all should work as you desire:

```<code><style>
    .flex-parent{display:flex;}
    .flex-child{flex-basis:content;margin-right:10px;}
</style>
<div class="max flex-parent">
    <div class="flex-child"><?php echo $tickets_sold;?></div>
    <div class="flex-child"><?php echo $max_tickets;?></div>
</div>
</code>```

tickets_sold

max_tickets

```
</div>
</div>
</p>
<hr />
<p>Or, you could also just use display:inline:</p>
```

<?php echo $tickets_sold;?>

<?php echo $max_tickets;?>

```
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-html lang-html prettyprint-override"><code><style>
    .inline-block{display:inline-block;margin-right:10px;}
</style>
<div class="max">
    <div class="inline-block">tickets_sold</div>
    <div class="inline-block">max_tickets</div>
</div></code>```

Update:

Note the change to the first example code - I neglected to add the flex-parent class (a className I invented, not a convention) to the .max div.

To center the items in the parent, add justify-content:center; to the parent:

```<code><style>
    .flex-parent{display:flex;}
    .flex-child{flex-basis:content;margin-right:10px;justify-content:center;}
</style>
<div class="max flex-parent">
    <div class="flex-child"><?php echo $tickets_sold;?></div>
    <div class="flex-child"><?php echo $max_tickets;?></div>
</div>
</code>```

Using the display:inline-block method:

```<code><style>
    .inline-parent{text-align:center;}
    .inline-block{display:inline-block;margin-right:10px;}
</style>
<div class="max inline-parent">
    <div class="inline-block"><?php echo $tickets_sold;?></div>
    <div class="inline-block"><?php echo $max_tickets;?></div>
</div>
</code>```

tickets_sold

max_tickets

```

Body:
Screenshots:
Inspect element shows:
The "7 in stock" i want to align with the "10" bellow

I would like to align two $elements to display on the same line.

    <?php echo $tickets_sold, $max_tickets; ?>

When the $tickets_sold is not included, the $max_tickets goes on the top. But when it's included, it immediately goes on the next line.

I've tried many different options as &&, and, but they never appear on the same line. I am sure the solution is easy, but I am a beginner.

$max_tickets = $product->get_max_tickets();
$tickets_sold = wc_get_stock_html( $product );

PHP code

 <div class="wcl-progress-meter <?php if($product->is_max_tickets_met()) echo 'full' ?>">
    <progress  max="<?php echo $max_tickets ?>" value="<?php echo $lottery_participants_count ?>"  low="<?php echo $min_tickets ?>"></progress>

    0
      <?php echo $tickets_sold, $max_tickets?>

CSS file

.wcl-progress-meter meter::-webkit-meter-suboptimum-value {
  box-shadow: 0 5px 5px -5px #999 inset;
  background: #cb132b;
  display:inline-block;

}

.wcl-progress-meter .zero {
  display: inline-block;
  position: absolute;
  top: -100%;
}

.wcl-progress-meter .min {
  display: inline-block;
  position: absolute;
  top: -100%;
}

.wcl-progress-meter .max {
  display: inline-block;
  position: absolute;
  top: -100%;
  right: 0;
  vertical-align: middle;
}

Body:
Just tweak your HTML a bit and all should work as you desire:

<style>
    .flex-parent{display:flex;}
    .flex-child{flex-basis:content;margin-right:10px;}
</style>
<div class="max flex-parent">
    <div class="flex-child"><?php echo $tickets_sold;?></div>
    <div class="flex-child"><?php echo $max_tickets;?></div>
</div>

<style>
    .flex-parent{display:flex;}
    .flex-child{flex-basis:content;margin-right:10px;}
</style>
<div class="max flex-parent">
    <div class="flex-child">tickets_sold</div>
    <div class="flex-child">max_tickets</div>
</div>

Or, you could also just use display:inline:

<style>
    .inline-block{display:inline-block;margin-right:10px;}
</style>
<div class="max">
    <div class="inline-block"><?php echo $tickets_sold;?></div>
    <div class="inline-block"><?php echo $max_tickets;?></div>
</div>

<style>
    .inline-block{display:inline-block;margin-right:10px;}
</style>
<div class="max">
    <div class="inline-block">tickets_sold</div>
    <div class="inline-block">max_tickets</div>
</div>

Update:

Note the change to the first example code - I neglected to add the flex-parent class (a className I invented, not a convention) to the .max div.

To center the items in the parent, add justify-content:center; to the parent:

<style>
    .flex-parent{display:flex;}
    .flex-child{flex-basis:content;margin-right:10px;justify-content:center;}
</style>
<div class="max flex-parent">
    <div class="flex-child"><?php echo $tickets_sold;?></div>
    <div class="flex-child"><?php echo $max_tickets;?></div>
</div>

Using the display:inline-block method:

<style>
    .inline-parent{text-align:center;}
    .inline-block{display:inline-block;margin-right:10px;}
</style>
<div class="max inline-parent">
    <div class="inline-block"><?php echo $tickets_sold;?></div>
    <div class="inline-block"><?php echo $max_tickets;?></div>
</div>

    <style>
        .inline-parent{text-align:center;}
        .inline-block{display:inline-block;margin-right:10px;}
    </style>
    <div class="max inline-parent">
        <div class="inline-block">tickets_sold</div>
        <div class="inline-block">max_tickets</div>
    </div>


问:
Nhibernate(Fluent) SchemaExport and SQlite Problem!
I am using Nhibernate(Fluent) with Sqlite and it worked with no problems what I have done:

Create the POCO EntityClasses for each table like this:

```<code>public class tbl_Manufactor : BusinessObject<tbl_Manufactor>
{
    public virtual string Name { get; set; }
}
</code>```

The Entity Classes all inherit from BusinessObject which contains the ID Property and simple CRUD functions
I have also other 6 Entity Classes

Create the Mappings with FluentHibernate like this:

```<code>using Database.Entitites;
using FluentNHibernate.Mapping;

namespace Database.Mappings
{
    public class tbl_ManufactorMap : ClassMap<tbl_Manufactor>
    {
        public tbl_ManufactorMap()
        {
            Id(x => x.ID);
            Map(x => x.Name);
        }
    }
}
</code>```

Create the Fluent Config like this:

```<code> var Config = Fluently.Configure()
            .Database(SQLiteConfiguration.Standard
                .ConnectionString(c=>c.FromConnectionStringWithKey("dbconnection"))
                .ShowSql())
            .Mappings(m =>
                m.FluentMappings.AddFromAssemblyOf<tbl_Manufactor>())
            .ExposeConfiguration(cfg =>  _configuration = cfg)

            sessionFactory = Config.BuildSessionFactory();
</code>```

Do a SchemaExport to Create the Schema with:

```<code>new SchemaExport(_configuration)
                .Create(false, true);
</code>```

Then Nhibernate created a fully working SQlite Database with the right tables!

But then I wanted to add 2 entity classes(I have done it in the same way as before) but when I run my test(which created my first database schema) it not add the new classes(tables) to the database!

The craziest thing is, that the test is always deleting any created database and recreate it with SchemaExport every time I run the test.

Could someone help me?

答:
You also have the option of using Execute directly for database updates:

```<code>bool script = false;
bool update = true;
new SchemaExport(_configuration).Execute(script, update);
</code>```

Edit: Make sure the mapping classes are public.

Body:
I am using Nhibernate(Fluent) with Sqlite and it worked with no problems what I have done:

Create the POCO EntityClasses for each table like this:

public class tbl_Manufactor : BusinessObject<tbl_Manufactor>
{
    public virtual string Name { get; set; }
}

The Entity Classes all inherit from BusinessObject which contains the ID Property and simple CRUD functions
I have also other 6 Entity Classes

Create the Mappings with FluentHibernate like this:

using Database.Entitites;
using FluentNHibernate.Mapping;

namespace Database.Mappings
{
    public class tbl_ManufactorMap : ClassMap<tbl_Manufactor>
    {
        public tbl_ManufactorMap()
        {
            Id(x => x.ID);
            Map(x => x.Name);
        }
    }
}

Create the Fluent Config like this:

 var Config = Fluently.Configure()
            .Database(SQLiteConfiguration.Standard
                .ConnectionString(c=>c.FromConnectionStringWithKey("dbconnection"))
                .ShowSql())
            .Mappings(m =>
                m.FluentMappings.AddFromAssemblyOf<tbl_Manufactor>())
            .ExposeConfiguration(cfg =>  _configuration = cfg)

            sessionFactory = Config.BuildSessionFactory();

Do a SchemaExport to Create the Schema with:

new SchemaExport(_configuration)
                .Create(false, true);

Then Nhibernate created a fully working SQlite Database with the right tables!

But then I wanted to add 2 entity classes(I have done it in the same way as before) but when I run my test(which created my first database schema) it not add the new classes(tables) to the database!

The craziest thing is, that the test is always deleting any created database and recreate it with SchemaExport every time I run the test.

Could someone help me?

Body:
You also have the option of using Execute directly for database updates:

bool script = false;
bool update = true;
new SchemaExport(_configuration).Execute(script, update);

Edit: Make sure the mapping classes are public.


问:
List prime numbers
I am an amateur java student, and my teacher gave me this assignment which is to write a code that list the first 100 prime numbers. Here is what I have I tried so far.

```<code>for(int i =1; true; i++) {
    int k = 0;
    for(int j = 1; j <= i; j++) {
        if(i % j == 0){
            k ++;
        }

        if(k == 2) {
            System.out.println(i);
        }
    }
}
</code>```

The problem I encountered is I couldn't not stop the console to stop after a count of 100, even if I used possible mechanisms I am familiar with. for instance:

```<code>for( int i =1; true; i++) {
    int k = 0;
    for(int j = 1; j <= i; j++) {
        if(i % j == 0) {
            k ++;
        }

        int m = 0;
        if(k == 2) {
            System.out.println(i);
            m++;
            if(m==100) {
                break;
            }
        }
    }
}
</code>```

Can I get help in terminating the loop after a count of 100 primes ?

答:
To answer your question how to stop at 100:

```<code>for( int i =1; i<=100; i++){
</code>```

The second argument of the for statement is the condition to continue. If this condition evaluates to false, the for loop stops iterating.

Title: List prime numbers

Body:
I am an amateur java student, and my teacher gave me this assignment which is to write a code that list the first 100 prime numbers. Here is what I have I tried so far.

for(int i =1; true; i++) {
    int k = 0;
    for(int j = 1; j <= i; j++) {
        if(i % j == 0){
            k ++;
        }

        if(k == 2) {
            System.out.println(i);
        }
    }
}

The problem I encountered is I couldn't not stop the console to stop after a count of 100, even if I used possible mechanisms I am familiar with. for instance:

for( int i =1; true; i++) {
    int k = 0;
    for(int j = 1; j <= i; j++) {
        if(i % j == 0) {
            k ++;
        }

        int m = 0;
        if(k == 2) {
            System.out.println(i);
            m++;
            if(m==100) {
                break;
            }
        }
    }
}

Can I get help in terminating the loop after a count of 100 primes ?

Body:
To answer your question how to stop at 100:

for( int i =1; i<=100; i++){

The second argument of the for statement is the condition to continue. If this condition evaluates to false, the for loop stops iterating.


问:
How to get email checkbox checked by default?
I have defined connection alternatives for email and SMS. I want to have email checked by default.
I wondered if I can add attribute checked in Razor without changing model or controller.
Because if I use plain HTML, then it works but with Razor and when I inspection the page, there is no checked attribute.

```<code>@checked = "checked"
@checked = checked
@checked = "true"
@checked = true
new{@checked = "checked"}

<div class="checkbox-wrapper">
                    <label>
                        @Html.CheckBoxFor(m => m.Email, new { @class = "form-check-input", id = "E-post", @checked = "checked" })
                        <label for="E-post">E-post</label>
                    </label>
                </div>
</code>```

email checkbox checked when the page is loaded

答:
I found that CheckBoxFor does not have an attribute checked. The solution is to use CheckBox and then the second attribute is the boolean true or false which is the answer to the attribute isChecked.

```<code>@Html.CheckBox("name",true,new {@class="className",id="idName"})
</code>```

Body:
I have defined connection alternatives for email and SMS. I want to have email checked by default.
I wondered if I can add attribute checked in Razor without changing model or controller.
Because if I use plain HTML, then it works but with Razor and when I inspection the page, there is no checked attribute.

@checked = "checked"
@checked = checked
@checked = "true"
@checked = true
new{@checked = "checked"}

                        @Html.CheckBoxFor(m => m.Email, new { @class = "form-check-input", id = "E-post", @checked = "checked" })
                        E-post

email checkbox checked when the page is loaded

Body:
I found that CheckBoxFor does not have an attribute checked. The solution is to use CheckBox and then the second attribute is the boolean true or false which is the answer to the attribute isChecked.

@Html.CheckBox("name",true,new {@class="className",id="idName"})


问:
How much time it will take to learn ionic framework?
I already know html,css, javascript  how much time it will take to learn ionic framework and how it is different from angularjs?</p>

答:
Question could probably be considered off-topic, but I'll post answer since I had a similar question when I got started, as I didn't really understand what benefit Ionic was providing.

First off, Angular is a front-end Javascript framework used for making Web Apps.

The ionic framework provides a set of Web Components that will work across platforms, so you can code once as web project and port your project to different platforms (iOS, Android, even desktop :-o).

So, Ionic doesn't replace Angular, but rather can use Angular.  Actually in Ionic V4, the Ionic CLI just uses the Angluar CLI under the hood.

In my case, my goal was to use Angular to build web app, then wrap with Cordova to make an iOS mobile app out of it.  I decided not to use Ionic initially because I didn't understand what it was really doing and it seemed like "one more thing to learn" at a time when I was already learning Angular.

However, I ended up switching over to Ionic because I was running into weird UI problems when the iOS keyboard was displayed / not displayed (worked fine in web, but native iOS was wacky).  Seems like a silly reason, but the ionic components handled this scenario flawlessly.

Other benefits that I gained pretty much "for free" after switching over to ionic were:

app menu with animation

navigation transitions

slide to reveal options for lists

I found learning to use the Ionic components was pretty straight forward and their documentation is pretty solid.

It's pretty easy to follow the Documentation and spin up a new project to play with.

While I can't say how long it will take for you to learn, I hope this info helps... :-)


问:
importing an svg icon in material ui
I have this svg icon and I want to import that svg icon .
Here is the material ui code to convert that svg into an icon and finally using it .

```<code>let InstallIcon =
<SvgIcon>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M0 0h24v24H0z" fill="none"/><path d="M6 18c0 .55.45 1 1 1h1v3.5c0 .83.67 1.5 1.5 1.5s1.5-.67 1.5-1.5V19h2v3.5c0 .83.67 1.5 1.5 1.5s1.5-.67 1.5-1.5V19h1c.55 0 1-.45 1-1V8H6v10zM3.5 8C2.67 8 2 8.67 2 9.5v7c0 .83.67 1.5 1.5 1.5S5 17.33 5 16.5v-7C5 8.67 4.33 8 3.5 8zm17 0c-.83 0-1.5.67-1.5 1.5v7c0 .83.67 1.5 1.5 1.5s1.5-.67 1.5-1.5v-7c0-.83-.67-1.5-1.5-1.5zm-4.97-5.84l1.3-1.3c.2-.2.2-.51 0-.71-.2-.2-.51-.2-.71 0l-1.48 1.48C13.85 1.23 12.95 1 12 1c-.96 0-1.86.23-2.66.63L7.85.15c-.2-.2-.51-.2-.71 0-.2.2-.2.51 0 .71l1.31 1.31C6.97 3.26 6 5.01 6 7h12c0-1.99-.97-3.75-2.47-4.84zM10 5H9V4h1v1zm5 0h-1V4h1v1z"/></svg>
</SvgIcon>;
export default InstallIcon;

</code>```

import InstallIcon
Now I am using this Svg icon inside material Ui bottom navigation .

```<code>        <BottomNavigation
          value={getIndexForRoute(pathname)}
          onChange={this.handleChange}
          showLabels
          classes={{root:classes.root}}
        >
              <BottomNavigationAction  classes={{selected:classes.selected}} label="Trending" icon={<InstallIcon/>} /> // i don't see this InstallIcon working
       </BottomNavigation>

</code>```

Is this a corect way to create icons out of svg for material ui ?

Title: importing an svg icon in material ui

Body:
I have this svg icon and I want to import that svg icon .
Here is the material ui code to convert that svg into an icon and finally using it .

let InstallIcon =
<SvgIcon>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M0 0h24v24H0z" fill="none"/><path d="M6 18c0 .55.45 1 1 1h1v3.5c0 .83.67 1.5 1.5 1.5s1.5-.67 1.5-1.5V19h2v3.5c0 .83.67 1.5 1.5 1.5s1.5-.67 1.5-1.5V19h1c.55 0 1-.45 1-1V8H6v10zM3.5 8C2.67 8 2 8.67 2 9.5v7c0 .83.67 1.5 1.5 1.5S5 17.33 5 16.5v-7C5 8.67 4.33 8 3.5 8zm17 0c-.83 0-1.5.67-1.5 1.5v7c0 .83.67 1.5 1.5 1.5s1.5-.67 1.5-1.5v-7c0-.83-.67-1.5-1.5-1.5zm-4.97-5.84l1.3-1.3c.2-.2.2-.51 0-.71-.2-.2-.51-.2-.71 0l-1.48 1.48C13.85 1.23 12.95 1 12 1c-.96 0-1.86.23-2.66.63L7.85.15c-.2-.2-.51-.2-.71 0-.2.2-.2.51 0 .71l1.31 1.31C6.97 3.26 6 5.01 6 7h12c0-1.99-.97-3.75-2.47-4.84zM10 5H9V4h1v1zm5 0h-1V4h1v1z"/></svg>
</SvgIcon>;
export default InstallIcon;

import InstallIcon
Now I am using this Svg icon inside material Ui bottom navigation .

        <BottomNavigation
          value={getIndexForRoute(pathname)}
          onChange={this.handleChange}
          showLabels
          classes={{root:classes.root}}
        >
              <BottomNavigationAction  classes={{selected:classes.selected}} label="Trending" icon={<InstallIcon/>} /> // i don't see this InstallIcon working
       </BottomNavigation>

Is this a corect way to create icons out of svg for material ui ?

Body:
If you just have the SVG, CRA lets you do something like

import { ReactComponent as MyIcon } from './icon.svg';

The SVG Icon component takes a path as it's child.

const MyIcon = (props) => (
    <SvgIcon {...props}>
        <path d="M0 0h24v24H0z" fill="none"/>
        <path d="M6 18c0 .55.45 1 1 1h1v3.5c0 .83.67 1.5 1.5 1.5s1.5-.67 1.5-1.5V19h2v3.5c0 .83.67 1.5 1.5 1.5s1.5-.67 1.5-1.5V19h1c.55 0 1-.45 1-1V8H6v10zM3.5 8C2.67 8 2 8.67 2 9.5v7c0 .83.67 1.5 1.5 1.5S5 17.33 5 16.5v-7C5 8.67 4.33 8 3.5 8zm17 0c-.83 0-1.5.67-1.5 1.5v7c0 .83.67 1.5 1.5 1.5s1.5-.67 1.5-1.5v-7c0-.83-.67-1.5-1.5-1.5zm-4.97-5.84l1.3-1.3c.2-.2.2-.51 0-.71-.2-.2-.51-.2-.71 0l-1.48 1.48C13.85 1.23 12.95 1 12 1c-.96 0-1.86.23-2.66.63L7.85.15c-.2-.2-.51-.2-.71 0-.2.2-.2.51 0 .71l1.31 1.31C6.97 3.26 6 5.01 6 7h12c0-1.99-.97-3.75-2.47-4.84zM10 5H9V4h1v1zm5 0h-1V4h1v1z"/>
    </SvgIcon>
);

export default MyIcon;

You can also just take the SVG and export it as a component:

const MyIcon = () => (
    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
        <path d="M0 0h24v24H0z" fill="none"/><path d="M6 18c0 .55.45 1 1 1h1v3.5c0 .83.67 1.5 1.5 1.5s1.5-.67 1.5-1.5V19h2v3.5c0 .83.67 1.5 1.5 1.5s1.5-.67 1.5-1.5V19h1c.55 0 1-.45 1-1V8H6v10zM3.5 8C2.67 8 2 8.67 2 9.5v7c0 .83.67 1.5 1.5 1.5S5 17.33 5 16.5v-7C5 8.67 4.33 8 3.5 8zm17 0c-.83 0-1.5.67-1.5 1.5v7c0 .83.67 1.5 1.5 1.5s1.5-.67 1.5-1.5v-7c0-.83-.67-1.5-1.5-1.5zm-4.97-5.84l1.3-1.3c.2-.2.2-.51 0-.71-.2-.2-.51-.2-.71 0l-1.48 1.48C13.85 1.23 12.95 1 12 1c-.96 0-1.86.23-2.66.63L7.85.15c-.2-.2-.51-.2-.71 0-.2.2-.2.51 0 .71l1.31 1.31C6.97 3.26 6 5.01 6 7h12c0-1.99-.97-3.75-2.47-4.84zM10 5H9V4h1v1zm5 0h-1V4h1v1z"/>
    </svg>
);

export default MyIcon;


问:
got error while download gattlib via pip3
I use Ubuntu 16.04 64bit OS

when I run

```<code>$ sudo pip3 install gattlib
</code>```

I got this error message

/usr/bin/ld: cannot find -lboost_python-py34

      collect2: error: ld returned 1 exit status

      error: command 'x86_64-linux-gnu-g++' failed with exit status 1

I tried googling how to solve this but nothing works for me

I want to use gatttool at python, so I need to install this

How can I solve this?

PS. I already downloaded libboost-dev

答:
And for python 3.7 you should do:</p>

```<code>pip3 download gattlib
tar xvzf ./gattlib-0.20150805.tar.gz
cd gattlib-0.20150805/
sed -ie 's/boost_python-py34/boost_python37/' setup.py
pip3 install .
</code>```

Body:
I use Ubuntu 16.04 64bit OS

when I run

$ sudo pip3 install gattlib

I got this error message

/usr/bin/ld: cannot find -lboost_python-py34

      collect2: error: ld returned 1 exit status

      error: command 'x86_64-linux-gnu-g++' failed with exit status 1

I tried googling how to solve this but nothing works for me

I want to use gatttool at python, so I need to install this

How can I solve this?

PS. I already downloaded libboost-dev

Body:
And for python 3.7 you should do:

pip3 download gattlib
tar xvzf ./gattlib-0.20150805.tar.gz
cd gattlib-0.20150805/
sed -ie 's/boost_python-py34/boost_python37/' setup.py
pip3 install .


问:
in TF2, how do you save models/weights when not using the tf.keras API?
In the documentation it seems they focus on how to save and restore tf.keras.models, but i was wondering how do you save and restore models trained customly through some basic iteration loop?

Now that there isnt a graph or a session, how do we save structure defined in a tf function that is customly built without using layer abstractions?

答:
You can do it in a similar way you are used to in Tensorflow 1.x - by using a checkpoint object and, news introduced in Tensorflow 2.0, a checkpoint manager.

ckpt = tf.train.Checkpoint(step=tf.Variable(1), optimizer=opt, net=net)
manager = tf.train.CheckpointManager(ckpt, './tf_ckpts', max_to_keep=3)
ckpt.restore(manager.latest_checkpoint)
if manager.latest_checkpoint:
  print("Restored from {}".format(manager.latest_checkpoint))
else:
  print("Initializing from scratch.")

for example in toy_dataset():
  loss = train_step(net, example, opt)
```

You can give a look at the Training checkpoints guide

Body:
You can do it in a similar way you are used to in Tensorflow 1.x - by using a checkpoint object and, news introduced in Tensorflow 2.0, a checkpoint manager.

ckpt = tf.train.Checkpoint(step=tf.Variable(1), optimizer=opt, net=net)
manager = tf.train.CheckpointManager(ckpt, './tf_ckpts', max_to_keep=3)
ckpt.restore(manager.latest_checkpoint)
if manager.latest_checkpoint:
  print("Restored from {}".format(manager.latest_checkpoint))
else:
  print("Initializing from scratch.")

for example in toy_dataset():
  loss = train_step(net, example, opt)

You can give a look at the Training checkpoints guide


问:
extern declaration and definition in C
a global variable may one to two different storage classes in C, to my best knowledge, and the declaration may be given with two different keywords, correspodingly

```<code>extern int foo; //default
static int bar;
</code>```

Static variables are only visible within the module of declaration, and cannot be exported. In case of extern declaration, the variable is in the common namespace of all modules linked, unless shadowed by static variable.

Whereas static variables have to be defined in their module, an extern variable may be defined somewhere else. It has to be defined if ever used.

My compiler (GCC) accepts

```<code>static int bar = 5;
</code>```

but casts a complain at

```<code>extern int foo = 4;
</code>```

It seems to be expected that extern variables are never defined with the keyword 'extern'. This leads to the following question:

What kind of storage class does the Object 'foo' in the example above have in the module where it is defined?

答: The default storage class is auto.

Title: extern declaration and definition in C

Body:
a global variable may one to two different storage classes in C, to my best knowledge, and the declaration may be given with two different keywords, correspodingly

extern int foo; //default
static int bar;

Static variables are only visible within the module of declaration, and cannot be exported. In case of extern declaration, the variable is in the common namespace of all modules linked, unless shadowed by static variable.

Whereas static variables have to be defined in their module, an extern variable may be defined somewhere else. It has to be defined if ever used.

My compiler (GCC) accepts

static int bar = 5;

but casts a complain at

extern int foo = 4;

It seems to be expected that extern variables are never defined with the keyword 'extern'. This leads to the following question:

What kind of storage class does the Object 'foo' in the example above have in the module where it is defined?

Body: The default storage class is auto.


问:
Does @x ||= work like return @x if @x.present?
Is this:

```<code>def x?
  return @x if @x.present?

  @x = #boolean calculation
end
</code>```

Equivalent to this for boolean values of @x?

```<code>def x?
  @x ||= #boolean calculation
end
</code>```

答:
TL;DR: No

Just to add more examples to the answers already above:

```<code>def x1?(new_value)
  return @x if @x.present?

  @x = new_value
end

def x2?(new_value)
  @x ||= new_value
end
</code>```

say @x was a Number:

```<code>@x = 123
x1?('new value')
@x
# => 123

@x = 123
x2?('new value')
@x
# => 123

# 123 == 123, so this works for `Number`
</code>```

but let's say @x was an empty Array:

```<code>@x = []
x1?('new value')
@x
# => 'new value'

@x = []
x2?('new value')
@x
# => []

# 'new value' != [], so it doesn't work for empty Array.
</code>```

^ and there are all other "types" that this doesn't work as well not just empty Array, some of which have already been answered by others here.

Body:
Is this:

def x?
  return @x if @x.present?

  @x = #boolean calculation
end

Equivalent to this for boolean values of @x?

def x?
  @x ||= #boolean calculation
end

Body:
TL;DR: No

Just to add more examples to the answers already above:

def x1?(new_value)
  return @x if @x.present?

  @x = new_value
end

def x2?(new_value)
  @x ||= new_value
end

say @x was a Number:

@x = 123
x1?('new value')
@x
# => 123

@x = 123
x2?('new value')
@x
# => 123

# 123 == 123, so this works for `Number`

but let's say @x was an empty Array:

@x = []
x1?('new value')
@x
# => 'new value'

@x = []
x2?('new value')
@x
# => []

# 'new value' != [], so it doesn't work for empty Array.

^ and there are all other "types" that this doesn't work as well not just empty Array, some of which have already been answered by others here.


问:
Should Custom React Hooks Cause Re-Renders of Dependent Components?
I just created a custom hook that uses useState and useEffect internally.

When I import that hook into another React function component, call it ComponentA, ComponentA re-renders whenever the state in the custom hook changes.

Is it correct that ComponentA should re-render, when hooks that it uses returns new values?

See comments in the code, for additional question clarifications.

Code:

```<code>const ComponentA = props => {
  const myValue = useMyValue();

  // COMMENTS:
  // Whenever myValue returns a new value, ComponentA re-renders
  // This in turn will cause the useMyValue() function to run.
  // Seems unnatural with such a circular effect.
  // Is my suspicion unfounded? Is this how it should work?
}
</code>```

答: A custom can be treated as a function simply which is executed from within the functional component and effectively the hooks that are present in the custom hook are transferred on to the component. So any change that would normally cause the component to re-render if the code within the custom hook was directly written within functional component will cause a re-render even if the hook is a custom hook.</p>

Body:
I just created a custom hook that uses useState and useEffect internally.

When I import that hook into another React function component, call it ComponentA, ComponentA re-renders whenever the state in the custom hook changes.

Is it correct that ComponentA should re-render, when hooks that it uses returns new values?

See comments in the code, for additional question clarifications.

Code:

const ComponentA = props => {
  const myValue = useMyValue();

  // COMMENTS:
  // Whenever myValue returns a new value, ComponentA re-renders
  // This in turn will cause the useMyValue() function to run.
  // Seems unnatural with such a circular effect.
  // Is my suspicion unfounded? Is this how it should work?
}


问:
Drawing pixel circle of given area
I have some area X by Y pixels and I need to fill it up pixel by pixel. The problem is that at any given moment the drawn shape should be as round as possible.

I think that this algorithm is subset of Ordered Dithering, when converting grayscale images to one-bit, but I could not find any references nor could I figure it out myself.

I am aware of Bresenham's Circle, but it is used to draw circle of certain radius not area.

I created animation of all filling percents for 10 by 10 pixel grid. As full area is 10x10=100px, then each frame is exactly 1% inc.

答:
A filled disk has the equation

```<code>(X - Xc)² + (Y - Yc)² ≤ C.
</code>```

When you increase C, the number of points that satisfies the equation increases, but because of symmetry it increases in bursts.

To obtain the desired filling effect, you can compute (X - Xc)² + (Y - Yc)² for every pixel, sort on this value, and let the pixels appear one by one (or in a single go if you know the desired number of pixels).

You can break ties in different ways:

keep the original order as when you computed the pixels, by using a stable sort;

shuffle the runs of equal values;

slightly alter the center coordinates so that there are no ties.

Filling with the de-centering trick.

Values:

Order:

Title: Drawing pixel circle of given area

Body:
A filled disk has the equation

(X - Xc)² + (Y - Yc)² ≤ C.

When you increase C, the number of points that satisfies the equation increases, but because of symmetry it increases in bursts.

To obtain the desired filling effect, you can compute (X - Xc)² + (Y - Yc)² for every pixel, sort on this value, and let the pixels appear one by one (or in a single go if you know the desired number of pixels).

You can break ties in different ways:

keep the original order as when you computed the pixels, by using a stable sort;

shuffle the runs of equal values;

slightly alter the center coordinates so that there are no ties.

Filling with the de-centering trick.

Values:

Order:


问:
How to disable "heading" for all firebird subrequests
I have a request for firebird with concatenation and using nested select and list (), and then written this to the file. The first command is SET HEADING OFF;

SET HEADING OFF;
SELECT DISTINCT '"' || REPLACE(TRIM(COALESCE(x.column, '')), '"', '""')
|| '"; "' || REPLACE(TRIM(COALESCE(x.column2, '')), '"', '""')
|| '"; "' || REPLACE(TRIM(COALESCE(list(DISTINCT x.column3, ','), '')), '"', '""')
|| '";'
FROM (
     SELECT ycolumn AS column, ycolumn1 AS column1, ycolumn2 AS column2, list(DISTINCT ycolumn3, ',') AS column3
FROM (
     SELECT d.column AS ycolumn, c.column1 AS ycolumn1, dc.column2 AS ycolumn2, ws.column3 AS ycolumn3
     FROM ...
     )y
     GROUP BY ycolumn, ycolumn1, ycolumn2
) x
GROUP BY x.column, x.column1, x.column3
;
```

<p>The problem is that the headers for the nested SELECTs are not disabled and outputs file is like this:</p>

```==============================================================================
            0:218
==============================================================================
CONCATENATION:
"field"; "field1"; "field2"; "field3";
```

Is it possible to disable headers for all requests?

答:
The problem is that LIST produces a BLOB SUB_TYPE TEXT, and ISQL defaults to using configuration BLOBDISPLAY set to 1 (to show BLOB SUB_TYPE TEXT). With this setting, ISQL will automatically output all text blobs inline per row, but to discern which blob is which, it will include the column alias when showing the blob content.

You could turn off blobdisplay using SET BLOBDISPLAY OFF, but then your query result will only show the blob-id and not the blob content which is probably not what you want. For the query in your question it would only show:

```<code>            0:218
</code>```

The alternative is to cast the query to a VARCHAR of sufficient size:

SELECT DISTINCT cast('"' || REPLACE(TRIM(COALESCE(x.column, '')), '"', '""')
|| '"; "' || REPLACE(TRIM(COALESCE(x.column2, '')), '"', '""')
|| '"; "' || REPLACE(TRIM(COALESCE(list(DISTINCT x.column3, ','), '')), '"', '""')
|| '";' as varchar(8191))
FROM ...
```

Max VARCHAR size is 8191 for character set UTF8, or 32765 for a single byte character set, but there are additional constraints to row length (maximum 64KB total).

Body:
I have a request for firebird with concatenation and using nested select and list (), and then written this to the file. The first command is SET HEADING OFF;

SET HEADING OFF;
SELECT DISTINCT '"' || REPLACE(TRIM(COALESCE(x.column, '')), '"', '""')
|| '"; "' || REPLACE(TRIM(COALESCE(x.column2, '')), '"', '""')
|| '"; "' || REPLACE(TRIM(COALESCE(list(DISTINCT x.column3, ','), '')), '"', '""')
|| '";'
FROM (
     SELECT ycolumn AS column, ycolumn1 AS column1, ycolumn2 AS column2, list(DISTINCT ycolumn3, ',') AS column3
FROM (
     SELECT d.column AS ycolumn, c.column1 AS ycolumn1, dc.column2 AS ycolumn2, ws.column3 AS ycolumn3
     FROM ...
     )y
     GROUP BY ycolumn, ycolumn1, ycolumn2
) x
GROUP BY x.column, x.column1, x.column3
;

The problem is that the headers for the nested SELECTs are not disabled and outputs file is like this:

==============================================================================
            0:218
==============================================================================
CONCATENATION:
"field"; "field1"; "field2"; "field3";

Is it possible to disable headers for all requests?

Body:
The problem is that LIST produces a BLOB SUB_TYPE TEXT, and ISQL defaults to using configuration BLOBDISPLAY set to 1 (to show BLOB SUB_TYPE TEXT). With this setting, ISQL will automatically output all text blobs inline per row, but to discern which blob is which, it will include the column alias when showing the blob content.

You could turn off blobdisplay using SET BLOBDISPLAY OFF, but then your query result will only show the blob-id and not the blob content which is probably not what you want. For the query in your question it would only show:

            0:218

The alternative is to cast the query to a VARCHAR of sufficient size:

SELECT DISTINCT cast('"' || REPLACE(TRIM(COALESCE(x.column, '')), '"', '""')
|| '"; "' || REPLACE(TRIM(COALESCE(x.column2, '')), '"', '""')
|| '"; "' || REPLACE(TRIM(COALESCE(list(DISTINCT x.column3, ','), '')), '"', '""')
|| '";' as varchar(8191))
FROM ...

Max VARCHAR size is 8191 for character set UTF8, or 32765 for a single byte character set, but there are additional constraints to row length (maximum 64KB total).


问:
WiX Bundle gets "Failed to verify hash of payload" when trying to install .net core hosting bundle from web
I have a burn/bootstrapper WiX bundle with:

        <?define DotNetVersion = "2.1.11"?>

        <Variable Name='MinDotNetVersion' Type='string' Value='2.1.0' bal:Overridable='no'/>
        <Variable Name='NextDotNetVersion' Type='string' Value='2.2.0' bal:Overridable='no'/>

        <?define HostingBundleUrl = "https://www.microsoft.com/net/download/thank-you/dotnet-runtime-$(var.DotNetVersion)-windows-hosting-bundle-installer" ?>
        <util:RegistrySearch Id="DotNetHostingBundle86"
                             Root="HKLM"
                             Key="SOFTWARE\dotnet\Setup\InstalledVersions\$(var.Platform)\sharedhost"
                             Value="Version"
                             Variable="DotNetHostingBundleVersion" />

        <util:RegistrySearch Id="DotNetHostingBundle64"
                             After="DotNetHostingBundle86"
                             Condition="NOT DotNetHostingBundleVersion AND VersionNT64"
                             Root="HKLM"
                             Key="SOFTWARE\dotnet\Setup\InstalledVersions\$(var.Platform)\sharedhost"
                             Value="Version"
                             Variable="DotNetHostingBundleVersion"
                             Win64="yes"/>

        <Chain>
            <ExePackage Id="DotNetCoreHostingBundle"
                        Vital="yes"
                        Name=".Net Hosting Bundle Setup"
                        DownloadUrl="$(var.HostingBundleUrl)"
                        Compressed="no"
                        SourceFile=".\ExtResourcesCopy\dotnet-hosting-$(var.DotNetVersion)-win.exe"
                        InstallCondition="NOT DotNetHostingBundleVersion OR (DotNetHostingBundleVersion < MinDotNetVersion OR DotNetHostingBundleVersion >= NextDotNetVersion)"
                        Description="Installing .Net Hosting Bundle $(var.DotNetVersion). This includes the 32 bit and 64 bit runtimes, the Asp.net runtime packages (Microsoft.AspNetCore.App and .All), and the IIS Hosting Components."
                         />
            ...
```

<p>I've downloaded the dotnet-hosting-2.1.11-win.exe file into the ExtResourcesCopy folder, and since I set the SourceFile to this it gets its own Payload data. </p>

<p>I then build my .exe and run it on another computer and get the following error:</p>

```Acquiring package: DotNetCoreHostingBundle, payload: DotNetCoreHostingBundle, download from: https://www.microsoft.com/net/download/thank-you/dotnet-runtime-2.1.11-windows-hosting-bundle-installer
Error 0x80091007: Hash mismatch for path: C:\ProgramData\Package Cache\.unverified\DotNetCoreHostingBundle, expected: 1ED626AD403D6E5D99AB69DB7C281FB8E8A8D0A2, actual: F21BF2F13F89D1C9DFD2844D57728102D5714EAA
Error 0x80091007: Failed to verify hash of payload: DotNetCoreHostingBundle
Failed to verify payload: DotNetCoreHostingBundle at path: C:\ProgramData\Package Cache\.unverified\DotNetCoreHostingBundle, error: 0x80091007. Deleting file.
```

<p>I then checked the SHA1 hash on the target computer by downloading the dotnet-hosting-2.1.11-win.exe file manually from Microsoft, using the exact url from the log file, and running:</p>

```certutil -hashfile dotnet-hosting-2.1.11-win.exe
```

This gave me the expected hash of: 1ed626ad403d6e5d99ab69db7c281fb8e8a8d0a2

So where is this "actual" hash of F21BF2F13F89D1C9DFD2844D57728102D5714EAA coming from? Is there a way of pausing the installer so I can inspect the file in the .unverified folder? And/or what can I do about this?

答: The URL you're using is an HTML page that uses JavaScript to download the package. Burn just sees the HTML.</p>

Body:
I have a burn/bootstrapper WiX bundle with:

        <?define DotNetVersion = "2.1.11"?>

        <Variable Name='MinDotNetVersion' Type='string' Value='2.1.0' bal:Overridable='no'/>
        <Variable Name='NextDotNetVersion' Type='string' Value='2.2.0' bal:Overridable='no'/>

        <?define HostingBundleUrl = "https://www.microsoft.com/net/download/thank-you/dotnet-runtime-$(var.DotNetVersion)-windows-hosting-bundle-installer" ?>
        <util:RegistrySearch Id="DotNetHostingBundle86"
                             Root="HKLM"
                             Key="SOFTWARE\dotnet\Setup\InstalledVersions\$(var.Platform)\sharedhost"
                             Value="Version"
                             Variable="DotNetHostingBundleVersion" />

        <util:RegistrySearch Id="DotNetHostingBundle64"
                             After="DotNetHostingBundle86"
                             Condition="NOT DotNetHostingBundleVersion AND VersionNT64"
                             Root="HKLM"
                             Key="SOFTWARE\dotnet\Setup\InstalledVersions\$(var.Platform)\sharedhost"
                             Value="Version"
                             Variable="DotNetHostingBundleVersion"
                             Win64="yes"/>

        <Chain>
            <ExePackage Id="DotNetCoreHostingBundle"
                        Vital="yes"
                        Name=".Net Hosting Bundle Setup"
                        DownloadUrl="$(var.HostingBundleUrl)"
                        Compressed="no"
                        SourceFile=".\ExtResourcesCopy\dotnet-hosting-$(var.DotNetVersion)-win.exe"
                        InstallCondition="NOT DotNetHostingBundleVersion OR (DotNetHostingBundleVersion < MinDotNetVersion OR DotNetHostingBundleVersion >= NextDotNetVersion)"
                        Description="Installing .Net Hosting Bundle $(var.DotNetVersion). This includes the 32 bit and 64 bit runtimes, the Asp.net runtime packages (Microsoft.AspNetCore.App and .All), and the IIS Hosting Components."
                         />
            ...

I've downloaded the dotnet-hosting-2.1.11-win.exe file into the ExtResourcesCopy folder, and since I set the SourceFile to this it gets its own Payload data.

I then build my .exe and run it on another computer and get the following error:

Acquiring package: DotNetCoreHostingBundle, payload: DotNetCoreHostingBundle, download from: https://www.microsoft.com/net/download/thank-you/dotnet-runtime-2.1.11-windows-hosting-bundle-installer
Error 0x80091007: Hash mismatch for path: C:\ProgramData\Package Cache\.unverified\DotNetCoreHostingBundle, expected: 1ED626AD403D6E5D99AB69DB7C281FB8E8A8D0A2, actual: F21BF2F13F89D1C9DFD2844D57728102D5714EAA
Error 0x80091007: Failed to verify hash of payload: DotNetCoreHostingBundle
Failed to verify payload: DotNetCoreHostingBundle at path: C:\ProgramData\Package Cache\.unverified\DotNetCoreHostingBundle, error: 0x80091007. Deleting file.

I then checked the SHA1 hash on the target computer by downloading the dotnet-hosting-2.1.11-win.exe file manually from Microsoft, using the exact url from the log file, and running:

certutil -hashfile dotnet-hosting-2.1.11-win.exe

This gave me the expected hash of: 1ed626ad403d6e5d99ab69db7c281fb8e8a8d0a2

So where is this "actual" hash of F21BF2F13F89D1C9DFD2844D57728102D5714EAA coming from? Is there a way of pausing the installer so I can inspect the file in the .unverified folder? And/or what can I do about this?


问:
Cannot get last child of div
I am trying to get the last child of a
 but I am failing. Here is the code that I use for it but it always returns undefined.

```<code>$('#output:last-child').attr('class');
</code>```

What is wrong? How can I fix it?

This is supposed to be the last element:

```<code><div class='hisout ${hisclass}'><p class="he">` + message + '</p></div>
</code>```

答:
Your selector is retrieving the #output element that is the last child of its parent.

From the description it sounds like you want to find the last child within #output, as such you need to separate the selectors:

```<code>$('#output div:last-child').attr('class');
</code>```

Title: Cannot get last child of div

Body:
I am trying to get the last child of a
 but I am failing. Here is the code that I use for it but it always returns undefined.

$('#output:last-child').attr('class');

What is wrong? How can I fix it?

This is supposed to be the last element:

` + message + '

Body:
Your selector is retrieving the #output element that is the last child of its parent.

From the description it sounds like you want to find the last child within #output, as such you need to separate the selectors:

$('#output div:last-child').attr('class');


问:
How to capture the output of a process in Scala
I'm trying to capture the output of a main class launch by sbt via a ProcessBuilder but that doesn't work. What am I missing here ?

The result is printed in the console but not by the println

```<code>val result = Seq("sbt", "runMain example.Hello")
  .#<(new ByteArrayInputStream("a".getBytes()))
  .!!
println(s"result=$result")
</code>```

答:
We had a similar situation when trying to use beeline.

This worked for us:

```<code>val stdout = new StringBuilder
val stderr = new StringBuilder

var commandSeq = Seq("beeline"
  , "-u"
  , ConfigProvider.config.BeelineConfig.Url
  , "-n"
  , ConfigProvider.config.BeelineConfig.UserName
  , "-p"
  , ConfigProvider.config.BeelineConfig.Password
  , "--outputformat=xmlattr"
  , "-f"
  , filePath)

hiveConfArgs.foreach(arg => {
  commandSeq = commandSeq :+ "--hivevar"
  commandSeq = commandSeq :+ arg
})

commandSeq ! ProcessLogger(stdout append _, stderr append _ + "\n")

(stdout.toString, stderr.toString)
</code>```

Body:
I'm trying to capture the output of a main class launch by sbt via a ProcessBuilder but that doesn't work. What am I missing here ?

The result is printed in the console but not by the println

val result = Seq("sbt", "runMain example.Hello")
  .#<(new ByteArrayInputStream("a".getBytes()))
  .!!
println(s"result=$result")

Body:
We had a similar situation when trying to use beeline.

This worked for us:

val stdout = new StringBuilder
val stderr = new StringBuilder

var commandSeq = Seq("beeline"
  , "-u"
  , ConfigProvider.config.BeelineConfig.Url
  , "-n"
  , ConfigProvider.config.BeelineConfig.UserName
  , "-p"
  , ConfigProvider.config.BeelineConfig.Password
  , "--outputformat=xmlattr"
  , "-f"
  , filePath)

hiveConfArgs.foreach(arg => {
  commandSeq = commandSeq :+ "--hivevar"
  commandSeq = commandSeq :+ arg
})

commandSeq ! ProcessLogger(stdout append _, stderr append _ + "\n")

(stdout.toString, stderr.toString)


答:
You can try with the children() and last() functions:

```<code>$('#output').children().last().attr('class')
</code>```

To specifically filter a type of child, you can specify the type in the children() call:

```<code>...children('div')...
</code>```

Using a selector may be faster, though.

Title: Cannot get last child of div

Body:
You can try with the children() and last() functions:

$('#output').children().last().attr('class')

To specifically filter a type of child, you can specify the type in the children() call:

...children('div')...

Using a selector may be faster, though.


问:
ATG - How to override RQL for insert statements
I need to insert records to an Oracle DB table that already has records in it by using the table's sequence.

I tried using RQL which creates an auto-generated id for the primary key but sometimes those generated ids already exist in the database and as a result, a constraint violation error is thrown.

ATG documentation provides an alternative named Overriding RQL-Generated SQL but I didn't manage to make it work for insert statements.

```<code>GSARepository repo =
   (GSARepository)request.resolveName("/examples/TestRepository");
RepositoryView view = repo.getView("canard");
Object params[] = new Object[4];
  params[0] = new Integer (25);
  params[1] = new Integer (75);
  params[2] = "french";
  params[3] = "greek";
Builder builder = (Builder)view.getQueryBuilder();
String str = "SELECT * FROM usr_tbl WHERE (age_col > 0 AND age_col < 1
AND EXISTS (SELECT * from subjects_tbl where id = usr_tbl.id AND subject
IN (2, 3)))";

RepositoryItem[] items =
    view.executeQuery (builder.createSqlPassthroughQuery(str, params));

</code>```

Is there any way to use table's sequence for insert statements via ATG Repository API?

答:
Eventually, I did not manage to make it work but I found the following solution.

I retrieved the sequence number as below and then used it in the RQL insert statement.

```<code>RepositoryView view = getRestServiceDetailsRepository().getView("wsLog");
String sql = "select log_seq.nextval from dual";

Object[] params = {};
Builder builder = (Builder) view.getQueryBuilder();
Query query = builder.createSqlPassthroughQuery(sql, params);
RepositoryItem[] items = view.executeQuery(query);
if (items != null && items.length > 0) {
    items[0].getRepositoryId();
}
</code>```

Body:
I need to insert records to an Oracle DB table that already has records in it by using the table's sequence.

I tried using RQL which creates an auto-generated id for the primary key but sometimes those generated ids already exist in the database and as a result, a constraint violation error is thrown.

ATG documentation provides an alternative named Overriding RQL-Generated SQL but I didn't manage to make it work for insert statements.

GSARepository repo =
   (GSARepository)request.resolveName("/examples/TestRepository");
RepositoryView view = repo.getView("canard");
Object params[] = new Object[4];
  params[0] = new Integer (25);
  params[1] = new Integer (75);
  params[2] = "french";
  params[3] = "greek";
Builder builder = (Builder)view.getQueryBuilder();
String str = "SELECT * FROM usr_tbl WHERE (age_col > 0 AND age_col < 1
AND EXISTS (SELECT * from subjects_tbl where id = usr_tbl.id AND subject
IN (2, 3)))";

RepositoryItem[] items =
    view.executeQuery (builder.createSqlPassthroughQuery(str, params));

Is there any way to use table's sequence for insert statements via ATG Repository API?

Body:
Eventually, I did not manage to make it work but I found the following solution.

I retrieved the sequence number as below and then used it in the RQL insert statement.

RepositoryView view = getRestServiceDetailsRepository().getView("wsLog");
String sql = "select log_seq.nextval from dual";

Object[] params = {};
Builder builder = (Builder) view.getQueryBuilder();
Query query = builder.createSqlPassthroughQuery(sql, params);
RepositoryItem[] items = view.executeQuery(query);
if (items != null && items.length > 0) {
    items[0].getRepositoryId();
}


问:
Is it safe to assume pid_t is always an int type (as defined in the standard)?
I wanted to atomically compare and swap pid_t variable. I read in standard it is int type.

I know as a matter of atomic_compare_exchange_strong_explicit() can manage things on its own. All I need to do is set type as _Atomic(pid_t).

But as I am working on macOS and I want to make it compatible with OSX old library as well which is libkern/OSAtomic.h that would need to know the type and size of the type to CAS it.

Like in case of size_t I could simply do like,

```<code>#   ifdef __LP64__
#       define CAS_size_t(old, new, mem) \
        OSAtomicCompareAndSwap64((int64_t) (*old), (int64_t) (new), (volatile int64_t *) (mem))
#   else
#       define CAS_size_t(old, new, mem) \
        OSAtomicCompareAndSwap32((int32_t) (*old), (int32_t) (new), (volatile int32_t *) (mem))
#   endif
</code>```

But in case of pid_t I am not sure because even if __LP64__ is not defined then it can be int64_t, int32_t, int16_t or something?

答:
Just check the sizeof of the value inside the macro:

```<code>#define OSAtomicCompareAndSwap(old, new, mem)  do{ \
     if (sizeof(*old) == sizeof(int32_t)) { \
        OSAtomicCompareAndSwap32((int32_t)(*old), (int32_t) (new), (volatile int32_t *) (mem));  \
     } else if (sizeof(*old) == sizeof(int64_t)) { \
        OSAtomicCompareAndSwap64((int64_t)(*old), (int64_t) (new), (volatile int64_t *) (mem));  \
     } else assert(0); }while(0)
</code>```

The checks should be optimized out by the compiler anyway. It's not type checking (for that we would need C++-ish typeid), only the size is checked.

If you need to return a value, if think you'll need to pass another variable:

```<code>#define OSAtomicCompareAndSwap(ret, old, new, mem)  do{ \
     if (sizeof(*old) == sizeof(int32_t)) { \
        ret = OSAtomicCompareAndSwap32((int32_t)(*old), (int32_t) (new), (volatile int32_t *) (mem));  \
     } else if (sizeof(*old) == sizeof(int64_t)) { \
        ret = OSAtomicCompareAndSwap64((int64_t)(*old), (int64_t) (new), (volatile int64_t *) (mem));  \
     } else assert(0); }while(0)
</code>```

or ex. pass a pointer to a variable to be memcpy-ied with the result or such. Or you could use statement expression gcc extension.

With a statement expression that could look like:

```<code>#define OSAtomicCompareAndSwap(old, new, mem)  __extension__({ \
     int64_t ret = 0; \
     if (sizeof(*old) == sizeof(int32_t)) { \
        ret = OSAtomicCompareAndSwap32((int32_t)(*old), (int32_t) (new), (volatile int32_t *) (mem));  \
     } else if (sizeof(*old) == sizeof(int64_t)) { \
        ret = OSAtomicCompareAndSwap64((int64_t)(*old), (int64_t) (new), (volatile int64_t *) (mem));  \
     } else { \
          assert(0); \
     } \
     ret; \
})
</code>```

Body:
I wanted to atomically compare and swap pid_t variable. I read in standard it is int type.

I know as a matter of atomic_compare_exchange_strong_explicit() can manage things on its own. All I need to do is set type as _Atomic(pid_t).

But as I am working on macOS and I want to make it compatible with OSX old library as well which is libkern/OSAtomic.h that would need to know the type and size of the type to CAS it.

Like in case of size_t I could simply do like,

#   ifdef __LP64__
#       define CAS_size_t(old, new, mem) \
        OSAtomicCompareAndSwap64((int64_t) (*old), (int64_t) (new), (volatile int64_t *) (mem))
#   else
#       define CAS_size_t(old, new, mem) \
        OSAtomicCompareAndSwap32((int32_t) (*old), (int32_t) (new), (volatile int32_t *) (mem))
#   endif

But in case of pid_t I am not sure because even if __LP64__ is not defined then it can be int64_t, int32_t, int16_t or something?

Body:
Just check the sizeof of the value inside the macro:

#define OSAtomicCompareAndSwap(old, new, mem)  do{ \
     if (sizeof(*old) == sizeof(int32_t)) { \
        OSAtomicCompareAndSwap32((int32_t)(*old), (int32_t) (new), (volatile int32_t *) (mem));  \
     } else if (sizeof(*old) == sizeof(int64_t)) { \
        OSAtomicCompareAndSwap64((int64_t)(*old), (int64_t) (new), (volatile int64_t *) (mem));  \
     } else assert(0); }while(0)

The checks should be optimized out by the compiler anyway. It's not type checking (for that we would need C++-ish typeid), only the size is checked.

If you need to return a value, if think you'll need to pass another variable:

#define OSAtomicCompareAndSwap(ret, old, new, mem)  do{ \
     if (sizeof(*old) == sizeof(int32_t)) { \
        ret = OSAtomicCompareAndSwap32((int32_t)(*old), (int32_t) (new), (volatile int32_t *) (mem));  \
     } else if (sizeof(*old) == sizeof(int64_t)) { \
        ret = OSAtomicCompareAndSwap64((int64_t)(*old), (int64_t) (new), (volatile int64_t *) (mem));  \
     } else assert(0); }while(0)

or ex. pass a pointer to a variable to be memcpy-ied with the result or such. Or you could use statement expression gcc extension.

With a statement expression that could look like:

#define OSAtomicCompareAndSwap(old, new, mem)  __extension__({ \
     int64_t ret = 0; \
     if (sizeof(*old) == sizeof(int32_t)) { \
        ret = OSAtomicCompareAndSwap32((int32_t)(*old), (int32_t) (new), (volatile int32_t *) (mem));  \
     } else if (sizeof(*old) == sizeof(int64_t)) { \
        ret = OSAtomicCompareAndSwap64((int64_t)(*old), (int64_t) (new), (volatile int64_t *) (mem));  \
     } else { \
          assert(0); \
     } \
     ret; \
})


问:
Custom Pipe Not Found
I am having issues with a custom pipe not being found when I call it.

I have imported the pipe in my app.module.ts file and declared it in the declarations. I followed a few tutorials on how to do it and also have looked at a few questions already asked on here and by what I am seeing it should work but it is still throwing the error: "The pipe 'getOrderType' could not be found"

```<code>import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'getOrderType'})
export class GetOrderTypePipe implements PipeTransform {
    transform(orderType: String, delivered: Boolean, requestType: String): LoadTypeEnum {
        if (delivered&& requestType !== 'mobile') {
            return 'Mobile devlivery';
          } else if (requestType === 'web') {
            return 'Web';
          } else {
            return 'N/A';
          }
    }
}
</code>```

and here is how I am calling it in my html:

```<code>{{ this.orderType| getOrderType: this.order.requestType: this.delivered}}
</code>```

答:
Somewhere youare using the PipeName as getLoadType instead of getOrderType

QuickFix: do a free text search on the source code and do a replace with getOrderType.

Title: Custom Pipe Not Found

Body:
I am having issues with a custom pipe not being found when I call it.

I have imported the pipe in my app.module.ts file and declared it in the declarations. I followed a few tutorials on how to do it and also have looked at a few questions already asked on here and by what I am seeing it should work but it is still throwing the error: "The pipe 'getOrderType' could not be found"

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'getOrderType'})
export class GetOrderTypePipe implements PipeTransform {
    transform(orderType: String, delivered: Boolean, requestType: String): LoadTypeEnum {
        if (delivered&& requestType !== 'mobile') {
            return 'Mobile devlivery';
          } else if (requestType === 'web') {
            return 'Web';
          } else {
            return 'N/A';
          }
    }
}

and here is how I am calling it in my html:

{{ this.orderType| getOrderType: this.order.requestType: this.delivered}}