问:
Why is MATLAB so slow on my Windows server?
I have Matlab R2017a installed on a server running MS Windows Server 2008 R2 Enterprise v 6.1 (SP1) and the benchmark results are awful:

```<code>bench
3.6424   0.5267   0.2114   5.0303   1.5557   3.4980
</code>```

[columns = LU, FFT, ODE, Sparse, 2-D, 3-D]

Note that it is particularly slow for LU and Sparse.

The server has this hardware:
CPU: Intel Xeon E7320 @ 2.13GHz (4 physical processors, 16 logical)
128 GB RAM
64-bit operating system

Matlab Version: 9.2.0.556344 (R2017a)
Java version: Java 1.7.0_60-b19 with Oracle corporation Java Hotspot(TM) 64-Bit Server VM mixed mode.

There are also other users that can be online on the server but I can see that they are not stressing the system and have verified that these running times are stable (have tested multiple times the past week.

My question is this: is there any other library or something that Matlab relies on that could be "wrong"? I have another similar setup on a similar but slightly newer server that gets bench results much closer to what I'd expect based on the specs. I'm wondering if it's using a "wrong" linear algebra module or something.

Alternative explanation I know that Matlab ran extremely slowly on a particular AMD Opteron CPU (I happen to also have worked on such a server in Matlab, link https://se.mathworks.com/matlabcentral/answers/33939-poor-matlab-performance-on-amd-based-computer). Is it possible that it's a similar issue with the Intel Xeon E7320?

Edit: Xeon E7320 as suggested by Peter.

答:
Update: I'm not sure whether Matlab's bench takes advantage of just a single CPU core, multiple CPU cores, or also a GPU (OpenCL / CUDA).  If it can use GPU acceleration, that would make a huge difference.  (Especially if you don't have one at all in your "slow" server).

As discussed in comments, a dual-core Sandybridge laptop is 10x faster on some of the benchmarks, but only 2 or 1.5x faster on some other components.  (But I'm not sure if the version of Matlab was controlled for; that thread you linked mentioned that different version of Matlab do a different amount of work in their bench).

The rest of this answer was written with the assumption that your test takes advantage of all your CPU cores (otherwise there's no point using an old many-core machine).  But without considering GPU.

I think your CPU is actually a 65nm Core2-based Xeon E7320, not "E3720" (no google hits).  What are you comparing against?  Your Tigerton CPUs are ancient (about 10 years old), of course they're slow.  (Tigerton is the same microarchitecture as Conroe/Merom, first-gen Core2).

You have very low memory bandwidth and cache speeds compared to a modern CPU, as well as only having SSSE3, not AVX or FMA.  These CPUs don't have a memory controller built-in, so all 4 sockets are sharing the memory controller hub (MCH) via separate 1066MHz Front-Side Buses.  Memory bandwidth doesn't scale with number of sockets, and is not great.  Memory bandwidth has grown faster than per-core performance over the years.  According to that link, a quad-socket 16-core Tigerton (like you have) is barely better than a quad-socket 8-core Barcelona Opteron.  It's not so bad for CPU-bound workloads, but memory-bound workloads will do quite badly.

As well as the low clock speed, it's significantly slower clock-for-clock than a modern CPU.  IDK what those times are supposed to be like (I'm here for the [performance] tag, not Matlab), but it's totally plausible that a 3GHz quad-core i5 or i7 Haswell / Skylake desktop or high-power laptop would be faster than your 16-core dinosaur machine.

(Actually, does that benchmark even scale with the number of cores?  If not, the single-threaded memory bandwidth is probably really not good.)

A very big jump in performance happened with Sandybridge (for all code, including non-SIMD workloads), and there were several other smaller jumps in between your machine and modern CPUs as well.  SnB can run 2 load instructions per clock, vs. 1 for previous Intel (like your Core2).

For FP-specific stuff that optimized libraries will take advantage of, x86 ISA extensions have been important:  AVX doubles the SIMD vector width, doubling FLOPS (on Intel CPUs with full-width execution units).  FMA does a mul+add in one instruction, potentially doubling FLOPS.  Microarchitectural improvements are important, too: Haswell has two FMA units vs. earlier CPUs having one FP adder and one FP multiplier, again potentially doubling FLOPS.  Only contiguous memory and high computation vs. memory workloads will fully take advantage of this, e.g. a dense matmul, but in that case one Haswell core is doing as much work as 8 Tigerton cores.

I assume Matlab can take advantage of AVX + FMA if the CPU has it.

And BTW, it's not just 16 "logical" processors.  You don't have hyperthreading, so you have a 4-socket system with four quad-core CPUs, for 16 physical cores.  (And these "quad core" chips are actually two separate dual-core dies in the same package, according to wikipedia.

So as far as the number of physical chips that need to communicate with each other, there are 8 (two in each package).  That's a lot of hops to reach other CPUs, so synchronization between cores is more expensive than for a single-die quad-core.  (And probably worse even than a modern dual-socket Xeon box with a pair of 18-core CPUs or something).

Note that high latency to memory can also hurt memory bandwidth: see the "latency bound platforms" part of this answer about optimizing memcpy/memset and how store bandwidth works in Intel CPUs.

Body:
I have Matlab R2017a installed on a server running MS Windows Server 2008 R2 Enterprise v 6.1 (SP1) and the benchmark results are awful:

bench
3.6424   0.5267   0.2114   5.0303   1.5557   3.4980

[columns = LU, FFT, ODE, Sparse, 2-D, 3-D]

Note that it is particularly slow for LU and Sparse.

The server has this hardware:
CPU: Intel Xeon E7320 @ 2.13GHz (4 physical processors, 16 logical)
128 GB RAM
64-bit operating system

Matlab Version: 9.2.0.556344 (R2017a)
Java version: Java 1.7.0_60-b19 with Oracle corporation Java Hotspot(TM) 64-Bit Server VM mixed mode.

There are also other users that can be online on the server but I can see that they are not stressing the system and have verified that these running times are stable (have tested multiple times the past week.

My question is this: is there any other library or something that Matlab relies on that could be "wrong"? I have another similar setup on a similar but slightly newer server that gets bench results much closer to what I'd expect based on the specs. I'm wondering if it's using a "wrong" linear algebra module or something.

Alternative explanation I know that Matlab ran extremely slowly on a particular AMD Opteron CPU (I happen to also have worked on such a server in Matlab, link https://se.mathworks.com/matlabcentral/answers/33939-poor-matlab-performance-on-amd-based-computer). Is it possible that it's a similar issue with the Intel Xeon E7320?

Edit: Xeon E7320 as suggested by Peter.


来源: stackexchange

问:
How to close  tags using javascript?
I have a html string example as below:

```<code>html = "<html><body><img src = "" style = ""></body></html>
</code>```

How could I achieve the following:

```<code>html = "<html><body><img src = ""  style = ""></img></body></html>
</code>```

I want to close the image tags for a standard XHTML format. Would appreciate any suggestions. Thanks

答:
There is no need for a closing img tag because its a void element.

```<code>eg:-

<img src="smiley.gif" alt="Smiley face">
</code>```

Reference: https://www.codecademy.com/en/forum_questions/51ffd01c80ff33d5ba007c7c

ContentLicense: CC BY-SA 3.0

Title: How to close <img> tags using javascript?

Body:
I have a html string example as below:

html = "

How could I achieve the following:

html = "

I want to close the image tags for a standard XHTML format. Would appreciate any suggestions. Thanks

Body:
There is no need for a closing img tag because its a void element.

eg:-

<img src="smiley.gif" alt="Smiley face">

Reference: https://www.codecademy.com/en/forum_questions/51ffd01c80ff33d5ba007c7c


问:
PHP How can I suppress errors thrown by file_get_contents?
Trying to suppress errors for file_get_contents ONLY but neither of these methods work.. is there another way?</p>

```<code>$data=@file_get_contents('invalid');

try { $data=@file_get_contents('invalid'); } catch($e Exception) { echo "error"; }
</code>```

答:
Fix problems, don't hide them.

Errors, Warnings, and Notices, should be fixed rather hidden ("supressed").

For your case, all you need do is a check for is_readable.

```<code>function getFile(string $filename = 'invalid')
{
    if (!is_readable($filename)) {
        return false;
    }

    return file_get_contents($filename);
}

$fileContents = getFile('maybevalid');
if (false !== $fileContents) {
    // success
} else {
    // couldn't read
}
</code>```

Body:
Trying to suppress errors for file_get_contents ONLY but neither of these methods work.. is there another way?

$data=@file_get_contents('invalid');

try { $data=@file_get_contents('invalid'); } catch($e Exception) { echo "error"; }

Body:
Fix problems, don't hide them.

Errors, Warnings, and Notices, should be fixed rather hidden ("supressed").

For your case, all you need do is a check for is_readable.

function getFile(string $filename = 'invalid')
{
    if (!is_readable($filename)) {
        return false;
    }

    return file_get_contents($filename);
}

$fileContents = getFile('maybevalid');
if (false !== $fileContents) {
    // success
} else {
    // couldn't read
}


问:
Finding all Negative numbers
My dataframe looks like this:

```<code>Person    Number
 BOB       1.23
 BOB      -1.23
 Jeff      18.01
 Jack      82.04
 Jack      14.02
 Jeff     -18.01
</code>```

what I want to do is look at the Persons columns and then say if there are multiple people under the name BOB and we know that BOB is unique so its the same person. I want to then look at the Number column and if their is a negative value present for BOB as well as a Postive I want to change both numbers to Zero. Furthermore, for cases like Jack where there are two positive numbers I dont want to do anything for him. So all I want to do is find where the Person is the same and if their is a presence of a negative value and a positive value under the same name then change both numbers to 0

So the final dataframe would look like such...

```<code>Person    Number
 BOB       0
 BOB       0
 Jeff      0
 Jack      82.04
 Jack      14.02
 Jeff      0
</code>```

Another issue I am having is that Python isn't detecting the negatives appropriately so it changes negatives to look like this ($4.00) instead of keeping it like -1.23. I am just not sure how I can achieve the designated answer so any help would be greatly appreciated, thank you

答:
You can find those Persons with positive values, negative values and then the intersection.

```<code>pos = set(df.loc[df.Number > 0, 'Person'])
neg = set(df.loc[df.Number < 0, 'Person'])
intersection = pos & neg
</code>```

And then set Number = 0 where Person is in this intersection.

```<code>df.loc[df.Person.isin(intersection), 'Number'] = 0

df
    Person  Number
0   BOB     0.00
1   BOB     0.00
2   Jeff    0.00
3   Jack    82.04
4   Jack    14.02
5   Jeff    0.00
</code>```

Note that the output is different from what you've posted as the expected output, but to me it seems there's a bit of contradiction between what you've asked and the expected output. I've gone with:

So all I want to do is find where the Person is the same and if their is a presence of a negative value and a positive value under the same name then change both numbers to 0

Title: Finding all Negative numbers

Body:
My dataframe looks like this:

Person    Number
 BOB       1.23
 BOB      -1.23
 Jeff      18.01
 Jack      82.04
 Jack      14.02
 Jeff     -18.01

what I want to do is look at the Persons columns and then say if there are multiple people under the name BOB and we know that BOB is unique so its the same person. I want to then look at the Number column and if their is a negative value present for BOB as well as a Postive I want to change both numbers to Zero. Furthermore, for cases like Jack where there are two positive numbers I dont want to do anything for him. So all I want to do is find where the Person is the same and if their is a presence of a negative value and a positive value under the same name then change both numbers to 0

So the final dataframe would look like such...

Person    Number
 BOB       0
 BOB       0
 Jeff      0
 Jack      82.04
 Jack      14.02
 Jeff      0

Another issue I am having is that Python isn't detecting the negatives appropriately so it changes negatives to look like this ($4.00) instead of keeping it like -1.23. I am just not sure how I can achieve the designated answer so any help would be greatly appreciated, thank you

Body:
You can find those Persons with positive values, negative values and then the intersection.

pos = set(df.loc[df.Number > 0, 'Person'])
neg = set(df.loc[df.Number < 0, 'Person'])
intersection = pos & neg

And then set Number = 0 where Person is in this intersection.

df.loc[df.Person.isin(intersection), 'Number'] = 0

df
    Person  Number
0   BOB     0.00
1   BOB     0.00
2   Jeff    0.00
3   Jack    82.04
4   Jack    14.02
5   Jeff    0.00

Note that the output is different from what you've posted as the expected output, but to me it seems there's a bit of contradiction between what you've asked and the expected output. I've gone with:

So all I want to do is find where the Person is the same and if their is a presence of a negative value and a positive value under the same name then change both numbers to 0


问:
Sequence Number Calculation TCP
two host A and B are communicating with each other using TCP. Assume that the sequence number field starts at 0 and the receiver employs cummulative ACK. A has successfully send 465 bytes of data which were also acked by B. Suppose A were now to send 3 segment of size 110, 40, 60 size. what sequence number will the third segment carry ??</p>

答:
This is very simple to work out, and it sounds a lot like a homework problem.  I usually won't answer these, but...

Remember that the initial SYN consumes 1 byte in the connection.  This means that the initial SYN with sequence number zero is ACKed as 1.

We now transfer 465 bytes.  This means that the last sequence number ACKed will be 466, and 466 will now appear as the sequence number from A to B.

We now send 110 bytes.  The sequence number in the packet will be 466 with a data payload of 110.  The ACK will be for 576.

Following this, 40 more bytes are sent.  This will have a sequence number of 576 in the packet with 40 bytes of payload and the ACK will be for 616.

That brings us to the last segment.  The sequence number in the segment should be 616, as long as I've done the maths correctly in my head, and this is the sequence number in the packet that you are asking about.  The ACK for that will be for 676.

Title: Sequence Number Calculation TCP


问:
Android background service problem
I've declared a background service from the android manifest, this service is to be started from within the main Activity of the application and run in an infinite loop to perform location updates to an external server.

This background service runs in a separate process than the process of the main activity of the application (using the android:process tag in the manifest declaration of the service). The issue I am having is that when requesting GPS location updates from within the service, then the LocationListener's onLocationChanged() method is never called, even when I send mock location using DDMS/geo command. But on the other hand, requesting GPS location updates from the main activity of the application does work and the onLocationChanged() method is being called properly when a fix is received, so I am wondering what is needed to be modified in order to get the same behaviour from within a service rather than an activity.

Thanks in advance for your help;
Hass.

答:
this service is to be started from within the main Activity of the application and run in an infinite loop to perform location updates to an external server.

Please don't do that, as you waste memory. Please use AlarmManager to trigger a self-stopping Service (like an IntentService) periodically. And, since you appear to be getting locations, consider using my LocationPoller service.

This background service runs in a separate process than the process of the main activity of the application (using the android:process tag in the manifest declaration of the service).

Please don't do that. You waste memory and add no value. It may also be contributing to your problems.

so I am wondering what is needed to be modified in order to get the same behaviour from within a service rather than an activity.

Getting locations within a service works just fine. See the LocationPoller for an example of this in use.

ContentLicense: CC BY-SA 2.5

Title: Android background service problem


问:
sample sequence of successive integer of an interval
I have a question about sampling: I would like to sample successive number in a vector without replacement. Is there a simple way to do so?
For example,

```<code>sample(c(1:100), 10, replace = F)
76 99 94 53 12 34  5 82 75 30
</code>```

gives me 10 number between 1 and 100. Now I would like to have 10 sequence of 3 successive integer without replacement: c(2,3,4), c(10,11,12), c(82,83,84)  etc.

The different sequences can't overlap, that is if c(2,3,4) is my first sampling, then none of the following one can have these numbers.

I would even look for the possibility of sampling 10 sequences of different sizes, the sizes given by a vector like

```<code>sizevec <- sample(c(1:4),10,replace = T)
</code>```

Thanks for the help

Body:
I have a question about sampling: I would like to sample successive number in a vector without replacement. Is there a simple way to do so?
For example,

sample(c(1:100), 10, replace = F)
76 99 94 53 12 34  5 82 75 30

gives me 10 number between 1 and 100. Now I would like to have 10 sequence of 3 successive integer without replacement: c(2,3,4), c(10,11,12), c(82,83,84)  etc.

The different sequences can't overlap, that is if c(2,3,4) is my first sampling, then none of the following one can have these numbers.

I would even look for the possibility of sampling 10 sequences of different sizes, the sizes given by a vector like

sizevec <- sample(c(1:4),10,replace = T)

Thanks for the help

Body:
set.seed(42)
lapply(sample(1:10, 1) + cumsum(sample(4:10, 10, TRUE)), function(x) x + 1:3)
# [[1]]
# [1] 21 22 23

# [[2]]
# [1] 27 28 29

# [[3]]
# [1] 36 37 38

# [[4]]
# [1] 44 45 46

# [[5]]
# [1] 51 52 53

# [[6]]
# [1] 60 61 62

# [[7]]
# [1] 64 65 66

# [[8]]
# [1] 72 73 74

# [[9]]
# [1] 80 81 82

# [[10]]
# [1] 87 88 89


问:
Convert OpenCV matrix to C Array to be used with CUDA
I used this function to fill openCV with a certain C array:

```<code>float data[9] = { 1, 0.5,-51,0,1,50,0,0,1};
Mat myH = cv::Mat(3, 3, CV_32F, data);
</code>```

but I wonder if there is another function that does the opposite like this for matrix A:

```<code>float myArray [Size_Of_A] = Mat A;
</code>```

I know I can do it with a loop, but it's my last option if there is no function to do it.
The loop would be like:

```<code>float myArray[size_of_A];
for (int row = 0; row < A.rows; row++)
    for (int col = 0; col < A.cols; col++)
        myArray[row * A.cols + col ] = A.at<float>(row, col);
</code>```

I need that to send an image to CUDA kernel.

答:
I got this answer from Miki comment, </p>

```<code>float* myArray = myH.ptr<float>();
</code>```

<p>so no need to duplicate the data on the host side, and we can copy to the device using the new pointer 'myArray'. </p>

Body:
I used this function to fill openCV with a certain C array:

float data[9] = { 1, 0.5,-51,0,1,50,0,0,1};
Mat myH = cv::Mat(3, 3, CV_32F, data);

but I wonder if there is another function that does the opposite like this for matrix A:

float myArray [Size_Of_A] = Mat A;

I know I can do it with a loop, but it's my last option if there is no function to do it.
The loop would be like:

float myArray[size_of_A];
for (int row = 0; row < A.rows; row++)
    for (int col = 0; col < A.cols; col++)
        myArray[row * A.cols + col ] = A.at<float>(row, col);

I need that to send an image to CUDA kernel.

Body:
I got this answer from Miki comment,

float* myArray = myH.ptr<float>();

so no need to duplicate the data on the host side, and we can copy to the device using the new pointer 'myArray'.


问:
Populate the array in php using mysql dynamically
I have the database and i want to create a matrix or probably 2d array in PHP where the first column comes from first query and then i loop again another query. I am getting it but when it comes to the matrix i want first column populate from the first column and the rest of the column in that row should populate depending on the data for that particular query. you might better understand after looking at the code

```<code> <!DOCTYPE html>

<html>

<?php
require ('connect.php');
$pro_name = $_POST['project'];
$sheet_type = $_POST['sheet_set'];
echo $pro_name ."-";
echo $sheet_type . "<br/>";

?>

<?php
$doc_num_data = array();
$qry_doc_num = "SELECT DISTINCT document_number FROM `$pro_name`.Instruments";
$result_doc_num = mysqli_query($connection, $qry_doc_num) or die(mysqli_error($connection));

while($doc_num = mysqli_fetch_row($result_doc_num)){

    if($doc_num[0] != ''){
        $qry_ins = "SELECT CONCAT(tag_letters,'-',tag_numbers) FROM `$pro_name`.Instruments WHERE document_number = '$doc_num[0]'";
        $result_qry_ins = mysqli_query($connection, $qry_ins) or die(mysqli_error($connection));
     //   array_push($doc_num_data, $doc_num);
       // $doc_num_data = array();
        while($ins_doc = mysqli_fetch_row($result_qry_ins)){
            $instruments_tag = $ins_doc[0];
            array_push($doc_num_data, $doc_num);
        }
    }
}
echo "```";
print_r($doc_num_data);
echo "```";
?>

</html>
</code>```

I want something like this

```<code>[doc1] [ins1] [ins2] []
[doc2] [ins1] []     []
[doc3] [ins1] [ins2] [ins3]
[doc4] [ins1] [ins2] []
</code>```

thats the result what i get basically each element is saving in different array

```<code>Array (
 [0] => Array
     (
         [0] => test1
     )

 [1] => Array
     (
         [0] => PIT-100
     )

 [2] => Array
     (
         [0] => test1
     )

 [3] => Array
     (
         [0] => PIT-330
     )

 [4] => Array
     (
         [0] => PIT-330
     )

 [5] => Array
     (
         [0] => PIT-330
     )

 [6] => Array
     (
         [0] => test2
     )

 [7] => Array
     (
         [0] => PIT-300
     )

 [8] => Array
     (
         [0] => PIT-300
     )

 [9] => Array
     (
         [0] => PIT-300
     )

 [10] => Array
     (
         [0] => PIT-300
     )

 [11] => Array
     (
         [0] => PIT-300
     )
</code>```

答:
Array
(
    [0] => Array
        (
            [0] => test1
            [1] => PIT-100
            [2] => PIT-330
        )

```<code>[1] => Array
    (
        [0] => test2
        [1] => PIT-300
    )

[2] => Array
    (
        [0] => test3
        [1] => TIT-100
    )

[3] => Array
    (
        [0] => test5
        [1] => TIT-200
        [2] => TIT-900
        [3] => PIT-000
    )

[4] => Array
    (
        [0] => test4
        [1] => TIT-1000
    )

[5] => Array
    (
        [0] => test6
        [1] => TIT-999
    )
</code>```

)

using this code

```<code><?php
$doc_num_data = array();
$qry_doc_num = "SELECT DISTINCT document_number FROM `$pro_name`.Instruments";
$result_doc_num = mysqli_query($connection, $qry_doc_num) or die(mysqli_error($connection));
$i=0;
while($doc_num = mysqli_fetch_row($result_doc_num)){
    $j=1;
    if($doc_num[0] != ''){
        $qry_ins = "SELECT CONCAT(tag_letters,'-',tag_numbers) FROM `$pro_name`.Instruments WHERE document_number = '$doc_num[0]'";
        $result_qry_ins = mysqli_query($connection, $qry_ins) or die(mysqli_error($connection));
        //echo  $doc_num[0];
        $doc_num_data[$i][0] = $doc_num[0];
        //echo $doc_num_data[$i];
       // $doc_num_data = array();
        while($ins_doc = mysqli_fetch_row($result_qry_ins)){
            $instruments_tag = $ins_doc[0];
            $doc_num_data[$i][$j]= $instruments_tag;
            $j=$j+1;
        }
    }
    $i= $i+1;
}
</code>```

Body:
I have the database and i want to create a matrix or probably 2d array in PHP where the first column comes from first query and then i loop again another query. I am getting it but when it comes to the matrix i want first column populate from the first column and the rest of the column in that row should populate depending on the data for that particular query. you might better understand after looking at the code

 <!DOCTYPE html>

<?php
require ('connect.php');
$pro_name = $_POST['project'];
$sheet_type = $_POST['sheet_set'];
echo $pro_name ."-";
echo $sheet_type . "
";

?>

<?php
$doc_num_data = array();
$qry_doc_num = "SELECT DISTINCT document_number FROM `$pro_name`.Instruments";
$result_doc_num = mysqli_query($connection, $qry_doc_num) or die(mysqli_error($connection));

while($doc_num = mysqli_fetch_row($result_doc_num)){

    if($doc_num[0] != ''){
        $qry_ins = "SELECT CONCAT(tag_letters,'-',tag_numbers) FROM `$pro_name`.Instruments WHERE document_number = '$doc_num[0]'";
        $result_qry_ins = mysqli_query($connection, $qry_ins) or die(mysqli_error($connection));
     //   array_push($doc_num_data, $doc_num);
       // $doc_num_data = array();
        while($ins_doc = mysqli_fetch_row($result_qry_ins)){
            $instruments_tag = $ins_doc[0];
            array_push($doc_num_data, $doc_num);
        }
    }
}
echo "
";
print_r($doc_num_data);
echo "
";
?>

I want something like this

[doc1] [ins1] [ins2] []
[doc2] [ins1] []     []
[doc3] [ins1] [ins2] [ins3]
[doc4] [ins1] [ins2] []

thats the result what i get basically each element is saving in different array

Array (
 [0] => Array
     (
         [0] => test1
     )

 [1] => Array
     (
         [0] => PIT-100
     )

 [2] => Array
     (
         [0] => test1
     )

 [3] => Array
     (
         [0] => PIT-330
     )

 [4] => Array
     (
         [0] => PIT-330
     )

 [5] => Array
     (
         [0] => PIT-330
     )

 [6] => Array
     (
         [0] => test2
     )

 [7] => Array
     (
         [0] => PIT-300
     )

 [8] => Array
     (
         [0] => PIT-300
     )

 [9] => Array
     (
         [0] => PIT-300
     )

 [10] => Array
     (
         [0] => PIT-300
     )

 [11] => Array
     (
         [0] => PIT-300
     )

Body:
Array
(
    [0] => Array
        (
            [0] => test1
            [1] => PIT-100
            [2] => PIT-330
        )

[1] => Array
    (
        [0] => test2
        [1] => PIT-300
    )

[2] => Array
    (
        [0] => test3
        [1] => TIT-100
    )

[3] => Array
    (
        [0] => test5
        [1] => TIT-200
        [2] => TIT-900
        [3] => PIT-000
    )

[4] => Array
    (
        [0] => test4
        [1] => TIT-1000
    )

[5] => Array
    (
        [0] => test6
        [1] => TIT-999
    )

)

using this code

<?php
$doc_num_data = array();
$qry_doc_num = "SELECT DISTINCT document_number FROM `$pro_name`.Instruments";
$result_doc_num = mysqli_query($connection, $qry_doc_num) or die(mysqli_error($connection));
$i=0;
while($doc_num = mysqli_fetch_row($result_doc_num)){
    $j=1;
    if($doc_num[0] != ''){
        $qry_ins = "SELECT CONCAT(tag_letters,'-',tag_numbers) FROM `$pro_name`.Instruments WHERE document_number = '$doc_num[0]'";
        $result_qry_ins = mysqli_query($connection, $qry_ins) or die(mysqli_error($connection));
        //echo  $doc_num[0];
        $doc_num_data[$i][0] = $doc_num[0];
        //echo $doc_num_data[$i];
       // $doc_num_data = array();
        while($ins_doc = mysqli_fetch_row($result_qry_ins)){
            $instruments_tag = $ins_doc[0];
            $doc_num_data[$i][$j]= $instruments_tag;
            $j=$j+1;
        }
    }
    $i= $i+1;
}


问:
A transport-level error has occurred (provider: TCP Provider, error: 0 - The semaphore timeout period has expired.)
I have read both these SO questions and the MS Docs:

Unexplained SQL errors in production environment - possibly network related

"The semaphore timeout period has expired" SQL Azure

https://learn.microsoft.com/en-us/azure/sql-database/sql-database-connectivity-issues#retry-logic-for-transient-errors

And have the same error. I did not have any of these in my ConnectionString:
ConnectRetryCount, ConnectRetryInterval or Connection Timeout.

This is a method of my DB class:

```<code>public DataTable ExecuteSqlCommand(SqlCommand com)
{
    var retryStrategy = new Incremental(5, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2));
    var retryPolicy = new RetryPolicy<SqlDatabaseTransientErrorDetectionStrategy>(retryStrategy);

    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DataContext"].ToString());

    com.Connection = con;
    SqlDataAdapter da = new SqlDataAdapter(com);
    DataTable dt = new DataTable();
    try
    {
        retryPolicy.ExecuteAction(() =>
        {
            con.Open();
            da.Fill(dt);
        });
    }
    catch (Exception e)
    {
        var telemetry = new TelemetryClient(); // app insights (azure)
        telemetry.TrackException(e);
    }
    finally
    {
        con.Close();
    }
    return dt;
}
</code>```

So what would be better? Remove the retry stuff from my code and use the attributes in my connection string? Let the framework do the work? Or is my current retry code sufficient? I have the feeling that the enterprise lib and retry stuff is obsolete, but cannot find a good source to confirm my thoughts.

I am using 4.7 and also have EF 6.2, but most queries are just SqlCommands using the code from above.

答:
Make sure the user/login you use on your connection string has access to the master database on your Azure SQL Database server also, not only to the user database. That will provide faster connections and timeouts may disappear.

Using SQL Azure Execution Estrategy may help you with this issue.

```<code>public class MyConfiguration : DbConfiguration
{
    public MyConfiguration()
    {
        SetExecutionStrategy("System.Data.SqlClient", () => new SqlAzureExecutionStrategy());
    }
}

public class MyConfiguration : DbConfiguration
{
    public MyConfiguration()
    {
        SetExecutionStrategy(
            "System.Data.SqlClient",
            () => new SqlAzureExecutionStrategy(1, TimeSpan.FromSeconds(30)));
    }
}
</code>```

For more information about SQL Azure Execution Strategy please visit this URL.

Body:
I have read both these SO questions and the MS Docs:

Unexplained SQL errors in production environment - possibly network related

"The semaphore timeout period has expired" SQL Azure

https://learn.microsoft.com/en-us/azure/sql-database/sql-database-connectivity-issues#retry-logic-for-transient-errors

And have the same error. I did not have any of these in my ConnectionString:
ConnectRetryCount, ConnectRetryInterval or Connection Timeout.

This is a method of my DB class:

public DataTable ExecuteSqlCommand(SqlCommand com)
{
    var retryStrategy = new Incremental(5, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(2));
    var retryPolicy = new RetryPolicy<SqlDatabaseTransientErrorDetectionStrategy>(retryStrategy);

    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DataContext"].ToString());

    com.Connection = con;
    SqlDataAdapter da = new SqlDataAdapter(com);
    DataTable dt = new DataTable();
    try
    {
        retryPolicy.ExecuteAction(() =>
        {
            con.Open();
            da.Fill(dt);
        });
    }
    catch (Exception e)
    {
        var telemetry = new TelemetryClient(); // app insights (azure)
        telemetry.TrackException(e);
    }
    finally
    {
        con.Close();
    }
    return dt;
}

So what would be better? Remove the retry stuff from my code and use the attributes in my connection string? Let the framework do the work? Or is my current retry code sufficient? I have the feeling that the enterprise lib and retry stuff is obsolete, but cannot find a good source to confirm my thoughts.

I am using 4.7 and also have EF 6.2, but most queries are just SqlCommands using the code from above.

Body:
Make sure the user/login you use on your connection string has access to the master database on your Azure SQL Database server also, not only to the user database. That will provide faster connections and timeouts may disappear.

Using SQL Azure Execution Estrategy may help you with this issue.

public class MyConfiguration : DbConfiguration
{
    public MyConfiguration()
    {
        SetExecutionStrategy("System.Data.SqlClient", () => new SqlAzureExecutionStrategy());
    }
}

public class MyConfiguration : DbConfiguration
{
    public MyConfiguration()
    {
        SetExecutionStrategy(
            "System.Data.SqlClient",
            () => new SqlAzureExecutionStrategy(1, TimeSpan.FromSeconds(30)));
    }
}

For more information about SQL Azure Execution Strategy please visit this URL.


问:
Undefinded Index in Mongodb Array When Calling From Laravel
I have Laravel set up with Moloquent in order to use a seperate Mongodb I have set up. I'm using the database Articles, which has a collection "articles", where each article is an array with info like title, url, image, etc. Some things I can pull just fine, like title and source, but if I try to call others (like url or content) i get and "Undefined index: url" error from Laravel.

```<code>use App\Articles;
$articles = App\Articles:all();

@foreach ($articles as $article)
<li>{{ $article['title'] }} - {{ $article['source'] }} </li> //this will work great
<li>{{ $article['title'] }} - {{ $article['url'] }} </li> //this will throw an error
@endforeach
</code>```

Here's my Articles.php model:

```<code><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Articles extends Model
{protected $table = 'articles';}
</code>```

Also, if I just show $article (after $article = App\Articles:all();) I get all the information. Any ideas would be helpful.

Edit: here's the mongoose schema as well:

```<code>const mongoose = require('mongoose');
let articleSchema = new mongoose.Schema({
    title: String,
    article: String,
    image: String,
    source: String,
    url: String,
    categories: String,
    dateCrawled: Date,
    dateWritten: String
});
let Article = mongoose.model('Article', articleSchema);
module.exports = Article;
</code>```

答:
I ended up just switching to Postgres.  Mongo was causing too many issues, and I was able to port everything over in just a couple hours.

If you're just getting started with Laravel I highly recommend using either MYSQL or Postgres since they work great right out of the box, and you shouldn't have any major issues (the above was only one MongoDB related issue, I've had quite a few more...)

Body:
I have Laravel set up with Moloquent in order to use a seperate Mongodb I have set up. I'm using the database Articles, which has a collection "articles", where each article is an array with info like title, url, image, etc. Some things I can pull just fine, like title and source, but if I try to call others (like url or content) i get and "Undefined index: url" error from Laravel.

use App\Articles;
$articles = App\Articles:all();

@foreach ($articles as $article)

{{ $article['title'] }} - {{ $article['source'] }}
 //this will work great

{{ $article['title'] }} - {{ $article['url'] }}
 //this will throw an error
@endforeach

Here's my Articles.php model:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Articles extends Model
{protected $table = 'articles';}

Also, if I just show $article (after $article = App\Articles:all();) I get all the information. Any ideas would be helpful.

Edit: here's the mongoose schema as well:

const mongoose = require('mongoose');
let articleSchema = new mongoose.Schema({
    title: String,
    article: String,
    image: String,
    source: String,
    url: String,
    categories: String,
    dateCrawled: Date,
    dateWritten: String
});
let Article = mongoose.model('Article', articleSchema);
module.exports = Article;


问:
Put a new prestashop under a prestashop, the url is not working. backend office works perfoect
I currently have prestashop running on the server. Then a uploaded a new one with new folder under the old one the structure would be like this

\-- root folder
    |-- folder for the old prestashop
    |-- folder for the old prestashop
    |-- folder for the old prestashop
    |-- folder for the old prestashop
    |-- folder for the old prestashop
    |-- new prestashop folder
    |   -- folder for the new prestashop
    |   -- folder for the new prestashop
    |   -- folder for the new prestashop
    |   -- folder for the new prestashop

I put the two prestashops table into one database with different prefix, so they will not mix up.

I also changed the settings.inc.php database users and password and the prefix of course. I changed the

shop_url table:
domain: current domain
domain_ssl: current doamin
physical_uri: folder name for the new prestashop

This setting will take me to the old prerstashop front page.
I can still go to the backed office of the new prestashop.

I also tried to set the virtual_uri to the folder name for the new prestashop. still not working.

Why? Did I miss something?

prestashop version: 1.6.1.7

Thanks for you help!!!

答:
Have you tried regenerating the .htaccess file in your second store's root folder ?

You can regenerate the .htaccess file by clicking the save button in the "Seo & URLs" menu.


问:
How to access a JSON object that is inside an object having no name
I have this JSON

```<code>{
    "success": true,
    "shippingMethod": [
        {
            "flat": {
                "code": "flat.flat",
                "title": "Flat Shipping Rate",
                "cost": "5.00",
                "tax_class_id": "9",
                "text": "$5.00"
            }
        },
        {
            "zajil": {
                "code": "zajil.zajil",
                "title": "Zajil Shipping",
                "cost": "26",
                "tax_class_id": "0",
                "text": "$26.00"
            }
        }
    ]
}
</code>```

Notice that every real object in array is within an unnecessary object that has no name i.e. flat and zajil in the above code are in another object.

I just need the data within those nested objects flat and zajil. When I try this code

```<code>JSONArray shippingMethods = response.optJSONArray("shippingMethod");
          for (int i = 0; i < shippingMethods.length(); i++) {
          JSONObject shippingObj = shippingMethods.optJSONObject(i);
          JSONObject shippingMethod = shippingObj.optJSONObject("");
          Iterator<?> keys = shippingObj.keys();
             shippingMethod.optString("title");
             shippingMethod.optString("cost");
       }
</code>```

I supposed I can get the Object that has no name like

```<code>JSONObject shippingMethod = shippingObj.optJSONObject("");
</code>```

But it does not work and throw NullPointerException when getting something from it. Then I try to iterate for keys like

```<code>Iterator<?> keys = shippingObj.keys();
</code>```

It does not show anything as this object does not contain any key directly. So My question is how can I get the required data title and cost from the above JSON.
I can't change JSON as it is the default structure of the customer's website.

Any help would be appreciated.

答:
How to access a JSON object that is inside an object having no name

All the objects have names in your JSON.

I just need the data within those nested objects flat and zajil.

flat and zajil are the names of the objects. The fact that you happen to not care about those names does not mean that the names do not exist.

If your JSON is set up that each of those objects contains exactly one nested object, use keys() or names() to find the name, then retrieve the object by that name. You are trying to retrieve the object by "", and neither flat nor zajil are "".

It does not show anything as this object does not contain any key directly

Yes, it does. The keys are flat and zajil, respectively.

When i is 0, shippingMethods.optJSONObject(i) will return a JSONObject containing:

```<code>    {
        "flat": {
            "code": "flat.flat",
            "title": "Flat Shipping Rate",
            "cost": "5.00",
            "tax_class_id": "9",
            "text": "$5.00"
        }
    }
</code>```

Calling keys() on that JSONObject will return an Iterator; if you get the first value from it, that value will be flat.

Body:
I have this JSON

{
    "success": true,
    "shippingMethod": [
        {
            "flat": {
                "code": "flat.flat",
                "title": "Flat Shipping Rate",
                "cost": "5.00",
                "tax_class_id": "9",
                "text": "$5.00"
            }
        },
        {
            "zajil": {
                "code": "zajil.zajil",
                "title": "Zajil Shipping",
                "cost": "26",
                "tax_class_id": "0",
                "text": "$26.00"
            }
        }
    ]
}

Notice that every real object in array is within an unnecessary object that has no name i.e. flat and zajil in the above code are in another object.

I just need the data within those nested objects flat and zajil. When I try this code

JSONArray shippingMethods = response.optJSONArray("shippingMethod");
          for (int i = 0; i < shippingMethods.length(); i++) {
          JSONObject shippingObj = shippingMethods.optJSONObject(i);
          JSONObject shippingMethod = shippingObj.optJSONObject("");
          Iterator<?> keys = shippingObj.keys();
             shippingMethod.optString("title");
             shippingMethod.optString("cost");
       }

I supposed I can get the Object that has no name like

JSONObject shippingMethod = shippingObj.optJSONObject("");

But it does not work and throw NullPointerException when getting something from it. Then I try to iterate for keys like

Iterator<?> keys = shippingObj.keys();

It does not show anything as this object does not contain any key directly. So My question is how can I get the required data title and cost from the above JSON.
I can't change JSON as it is the default structure of the customer's website.

Any help would be appreciated.

Body:
How to access a JSON object that is inside an object having no name

All the objects have names in your JSON.

I just need the data within those nested objects flat and zajil.

flat and zajil are the names of the objects. The fact that you happen to not care about those names does not mean that the names do not exist.

If your JSON is set up that each of those objects contains exactly one nested object, use keys() or names() to find the name, then retrieve the object by that name. You are trying to retrieve the object by "", and neither flat nor zajil are "".

It does not show anything as this object does not contain any key directly

Yes, it does. The keys are flat and zajil, respectively.

When i is 0, shippingMethods.optJSONObject(i) will return a JSONObject containing:

    {
        "flat": {
            "code": "flat.flat",
            "title": "Flat Shipping Rate",
            "cost": "5.00",
            "tax_class_id": "9",
            "text": "$5.00"
        }
    }

Calling keys() on that JSONObject will return an Iterator; if you get the first value from it, that value will be flat.


问:
Python 3.6.3 OpenCV3.3.1+Contrib Windows VideoCapture SDP file not working
As the title says my cv2.VideoCapture("bebop.sdp") is not working. The only debug information I can get is that isOpened() returns False.

```<code>videoFeed = cv2.VideoCapture("bebop.sdp")
while True:

    ret, currentVideoFrame = videoFeed.read()
    if ret:
        cv2.imshow('frame',currentVideoFrame)
        cv2.waitKey(1)
    else:
        print("FrameError - %s" % videoFeed.isOpened())
</code>```

Replacing bebop.sdp with a sample.mp4 file works fine. bebop.sdp is definitely in the working directory (alongside sample.mp4). I have an ffmpeg dll here: "C:\Users\uname\AppData\Local\Programs\Python\Python36\opencv_ffmpeg331_64.dll". The code worked fine with python2.7 (although I do remember having a similar problem, but the dll fixed that.

I can open the bebop.sdp file in VLC and I receive the video I expect.

Is there any debugging information I can get access to?

Thanks in advance!

答: I managed to circumvent the problem by downloading python3.4.4 and installing OpenCV version 3.1.0.5. No idea why later versions are problematic!</p>

Body:
As the title says my cv2.VideoCapture("bebop.sdp") is not working. The only debug information I can get is that isOpened() returns False.

videoFeed = cv2.VideoCapture("bebop.sdp")
while True:

    ret, currentVideoFrame = videoFeed.read()
    if ret:
        cv2.imshow('frame',currentVideoFrame)
        cv2.waitKey(1)
    else:
        print("FrameError - %s" % videoFeed.isOpened())

Replacing bebop.sdp with a sample.mp4 file works fine. bebop.sdp is definitely in the working directory (alongside sample.mp4). I have an ffmpeg dll here: "C:\Users\uname\AppData\Local\Programs\Python\Python36\opencv_ffmpeg331_64.dll". The code worked fine with python2.7 (although I do remember having a similar problem, but the dll fixed that.

I can open the bebop.sdp file in VLC and I receive the video I expect.

Is there any debugging information I can get access to?

Thanks in advance!


问:
QT disappearing second window
I am new to QT and have used QT 5 for programming in python. I have a main window but when I try to click a button for the second window, it shows but quickly disappears. Does anyone know how I can fix this issue?</p>

```<code>def SecondWindow():
    qw = QWidget()
    qw.resize(800, 800)
    qw.move(300, 300)
    qw.show()
</code>```

答:
Python is different than C++: in the latter, the code would work as desired, even if you'd leak the widget. Technically we wouldn't leak the widget since it's accessible from QApplication::topLevelWidgets.

In Python, there are no references to qw after SecondWindow finishes: it is a local variable. Thus the widget is destroyed immediately, since Python first uses reference counting for object lifetime management - and a garbage collector only to collect objects that form cycles, and that's not the case here.

The solution is to keep a reference to the widget you've created:

```<code>class MyClass(QObject):
  @pyqtSlot()
  def second_windowClick(self):
     self.SecondWindow()

  def SecondWindow(self):
     qw = QWidget()
     qw.resize(800, 800)
     qw.move(300, 300)
     qw.show()
     self.qw = qw
</code>```

Title: QT disappearing second window

Body:
I am new to QT and have used QT 5 for programming in python. I have a main window but when I try to click a button for the second window, it shows but quickly disappears. Does anyone know how I can fix this issue?

def SecondWindow():
    qw = QWidget()
    qw.resize(800, 800)
    qw.move(300, 300)
    qw.show()

Body:
Python is different than C++: in the latter, the code would work as desired, even if you'd leak the widget. Technically we wouldn't leak the widget since it's accessible from QApplication::topLevelWidgets.

In Python, there are no references to qw after SecondWindow finishes: it is a local variable. Thus the widget is destroyed immediately, since Python first uses reference counting for object lifetime management - and a garbage collector only to collect objects that form cycles, and that's not the case here.

The solution is to keep a reference to the widget you've created:

class MyClass(QObject):
  @pyqtSlot()
  def second_windowClick(self):
     self.SecondWindow()

  def SecondWindow(self):
     qw = QWidget()
     qw.resize(800, 800)
     qw.move(300, 300)
     qw.show()
     self.qw = qw


问:
AJAX appended content does not execute Javascript
I've seen this problem posted on Stack Overflow couple of times, but the solution I found is usually very old and talks about delegate method which is deprecated.

I am looking for a solution for jQuery 3.x. This is my AJAX call:

```<code>$.ajax({
  type: "get",
  url: "/content",
  data: {
    name: {{ name }}
  },
  success: function(data) {
    $("#appendsection").append(data);
  }
});
</code>```

Here I am appending the success data to a div called appendsection
This appendsection div does not execute any javascript, it executes CSS, but no javascript and no jquery. I see this problem most of the time, any data I get from ajax call does not want to execute javascript.

This is the appended content

```<code><div class="sortingbuttons">
        <select id="sort">
        Sort By
          <option value="name">Relevance</option>
          <option value="price">Cheapest</option>
          <option value="recommend">Recommended</option>
        </select>
</div>
</code>```

The #sort id is executed on app.js

```<code>$('#sort').change(function(){
            $('.section').hide();
            $('#' + $(this).val()).show();
        });
</code>```

So, the sorting does not work on the appended content, so the javascript is not working on the appended content.

答:
I apparently, solved this problem by running the necessary javascript code on the success function

```<code>$.ajax({
  type: "get",
  url: "/content",
  data: {
    name: {{ name }}
  },
  success: function(data) {
    $("#appendsection").append(data);
    //execute necessary javascript after this
    $('#sort').change(function(){
        $('.section').hide();
        $('#' + $(this).val()).show();
    });
  }
});
</code>```

This might be one of the ways to delegate the javascript, but I am sure that this is not the best way to do it. But for the moment, this is the only solution that worked for me.

Body:
I've seen this problem posted on Stack Overflow couple of times, but the solution I found is usually very old and talks about delegate method which is deprecated.

I am looking for a solution for jQuery 3.x. This is my AJAX call:

$.ajax({
  type: "get",
  url: "/content",
  data: {
    name: {{ name }}
  },
  success: function(data) {
    $("#appendsection").append(data);
  }
});

Here I am appending the success data to a div called appendsection
This appendsection div does not execute any javascript, it executes CSS, but no javascript and no jquery. I see this problem most of the time, any data I get from ajax call does not want to execute javascript.

This is the appended content

        <select id="sort">
        Sort By
          <option value="name">Relevance</option>
          <option value="price">Cheapest</option>
          <option value="recommend">Recommended</option>
        </select>

The #sort id is executed on app.js

$('#sort').change(function(){
            $('.section').hide();
            $('#' + $(this).val()).show();
        });

So, the sorting does not work on the appended content, so the javascript is not working on the appended content.

Body:
I apparently, solved this problem by running the necessary javascript code on the success function

$.ajax({
  type: "get",
  url: "/content",
  data: {
    name: {{ name }}
  },
  success: function(data) {
    $("#appendsection").append(data);
    //execute necessary javascript after this
    $('#sort').change(function(){
        $('.section').hide();
        $('#' + $(this).val()).show();
    });
  }
});

This might be one of the ways to delegate the javascript, but I am sure that this is not the best way to do it. But for the moment, this is the only solution that worked for me.


问:
Angular 2 error Error: Type dataGrid is part of the declarations of 2 modules(same module): DataGridModule and DataGridModule
I have many feature modules which imports DataGridModule. When I traverse such that when one feature module is loaded and navigate to another feature module, I get the below error,

EXCEPTION: Uncaught (in promise): Error: Type dataGrid is part of the
  declarations of 2 modules: DataGridModule and DataGridModule! Please
  consider moving dataGrid to a higher module that imports
  DataGridModule and DataGridModule. You can also create a new NgModule
  that exports and includes dataGrid then import that NgModule in
  DataGridModule and DataGridModule.

DataGridModule:

```<code>import {Compiler, Component,NgModule} from '@angular/core';
import { CommonModule }   from '@angular/common';
import {dataGrid} from './dataGrid';
import { DataTableModule,SharedModule,DataScrollerModule } from 'primeng/primeng';

@NgModule({
      imports: [DataTableModule,SharedModule,DataScrollerModule,CommonModule],
      declarations: [dataGrid],
      entryComponents: []  ,
      exports:[dataGrid]
    })

export class DataGridModule { }
</code>```

Zone.Module.ts

```<code>import {NgModule} from '@angular/core';
import {SharedFormModule} from '../../../../../../../UMSToolkit/UIToolkit/shared/shared-form.module';
import {DataGridModule} from '../../../../../../../UMSToolkit/UIToolkit/xdata/view/datagrid.module';
import {ZoneRoutingModule} from './Zone-routing.module';
import {RevertModule} from '../../shared/Revert.module'

@NgModule({
    imports:      [SharedFormModule,DataGridModule,ZoneRoutingModule,RevertModule],
    declarations: [],
    bootstrap:    [ ],
    entryComponents: [],
    providers: []
  })

  export class ZoneModule { }
</code>```

BasicDataGrid module

```<code>import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {DataGridModule} from '../../../../../../../../UMSToolkit/UIToolkit/xdata/view/dataGrid.module';
import {BasicDataGridComponent} from './basic-datagrid.component';

@NgModule({
    imports: [DataGridModule,CommonModule],
    declarations: [BasicDataGridComponent]
})
export class BasicDataGridModule
{

}
</code>```

答:
It was the typo error with case. Notice that BasicGridComponent was have dataGrid.module with a capital G causing the issue.

Thanks,

Body:
I have many feature modules which imports DataGridModule. When I traverse such that when one feature module is loaded and navigate to another feature module, I get the below error,

EXCEPTION: Uncaught (in promise): Error: Type dataGrid is part of the
  declarations of 2 modules: DataGridModule and DataGridModule! Please
  consider moving dataGrid to a higher module that imports
  DataGridModule and DataGridModule. You can also create a new NgModule
  that exports and includes dataGrid then import that NgModule in
  DataGridModule and DataGridModule.

DataGridModule:

import {Compiler, Component,NgModule} from '@angular/core';
import { CommonModule }   from '@angular/common';
import {dataGrid} from './dataGrid';
import { DataTableModule,SharedModule,DataScrollerModule } from 'primeng/primeng';

@NgModule({
      imports: [DataTableModule,SharedModule,DataScrollerModule,CommonModule],
      declarations: [dataGrid],
      entryComponents: []  ,
      exports:[dataGrid]
    })

export class DataGridModule { }

Zone.Module.ts

import {NgModule} from '@angular/core';
import {SharedFormModule} from '../../../../../../../UMSToolkit/UIToolkit/shared/shared-form.module';
import {DataGridModule} from '../../../../../../../UMSToolkit/UIToolkit/xdata/view/datagrid.module';
import {ZoneRoutingModule} from './Zone-routing.module';
import {RevertModule} from '../../shared/Revert.module'

@NgModule({
    imports:      [SharedFormModule,DataGridModule,ZoneRoutingModule,RevertModule],
    declarations: [],
    bootstrap:    [ ],
    entryComponents: [],
    providers: []
  })

  export class ZoneModule { }

BasicDataGrid module

import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {DataGridModule} from '../../../../../../../../UMSToolkit/UIToolkit/xdata/view/dataGrid.module';
import {BasicDataGridComponent} from './basic-datagrid.component';

@NgModule({
    imports: [DataGridModule,CommonModule],
    declarations: [BasicDataGridComponent]
})
export class BasicDataGridModule
{

}


问:
Which benefits Smarty gives when using with PHP or better to use pure PHP?
I am deciding if to use some template engine in php code or no.
Now I take close look to Smarty.

To be honest, it is not clear for me its benefits.

My impressions are not very good from the very beginning.
I tried to go through the demo application: http://www.smarty.net/sampleapp1. And from the very beginning I obtained notices . I fixed this by passing values to forms.
I changes the code from

```<code>// adding a guestbook entry
$guestbook->displayForm();
</code>```

to

```<code>// adding a guestbook entry
$guestbook->displayForm(array('Name' => '', 'Comment' => ''));
</code>```

While guessing this I understand that it complicates debugging the code.
And this also makes me to learn one more language - it is easy, but most easy is not to learn something new at all if there is no needed.
Alternative is to use PHP itself.

Syntax comparison  http://www.smarty.net/syntax_comparison is most funny for me: calculate number of symbols.... But I am familiar with PHP and this is easy for me to write on it, and Smarty is new for me. And I don't think that for Web Designers are so difficult to learn some simple php constructs, and Smarty is so simpler in this respect. If I am wrong it would be good to hear web designer here.

Smarty parses the code and this is in fact time overhead.

But at the same time many people use it. And that is why I would like to understand the reasons for this?
Where are the benefits? Am I missing something?

If you know good alternative to Smarty, it would be good to know about.
Thanks!

UPDATE:

I have found also the question on subject: How to use Smarty better with PHP?. In general it is also about not to use Smarty. But this is 1.5 years old. Possibly something changed?

答:
I use it in a production environment, and I would say: Not Very Many.

If you're concerned with the look of your code (not an unimportant concern), smarty can make things look a little bit cleaner:

```<code><?php echo $some_var; ?>
</code>```

vs.:

```<code>{$some_var}
</code>```

this can make your template files much more readable.

It also enforces a stricter separation between your controller and view logic. (since you have to make sure to pass all the relevant variables into the smarty object)

The syntax is straight-forward enough (more so for later versions), so that's not much of a problem.

It can complicate debugging, if only because it is a magical separation layer between your control and view, but in a perfect world you would be verifying each separately anyways.....

Drawbacks? I think there's a couple:

-Obviously you now have a whole other library to deal with, include, etc.

-Some previous smarty versions had some ridiculous syntax for loops and other stuff that should have been simple.

-When you need to put a simple javascript statement somewhere in your template, like this:

```<code><script type='text/javascript'>
    $(document).ready(function(){
        //foo
    });
</script>
</code>```

ok, you might include that in a js file instead of inline, but there's a lot of cases where you just need those couple of lines of js. smarty doesn't like the curly braces and you have to wrap them in an ugly tag that looks like this:

```<code>{literal}{\literal}
</code>```

in that case so much for making your code any cleaner....

If I had to choose, I probably would just use the non-standard short-form tag and be done with it.

Body:
I am deciding if to use some template engine in php code or no.
Now I take close look to Smarty.

To be honest, it is not clear for me its benefits.

My impressions are not very good from the very beginning.
I tried to go through the demo application: http://www.smarty.net/sampleapp1. And from the very beginning I obtained notices . I fixed this by passing values to forms.
I changes the code from

// adding a guestbook entry
$guestbook->displayForm();

to

// adding a guestbook entry
$guestbook->displayForm(array('Name' => '', 'Comment' => ''));

While guessing this I understand that it complicates debugging the code.
And this also makes me to learn one more language - it is easy, but most easy is not to learn something new at all if there is no needed.
Alternative is to use PHP itself.

Syntax comparison  http://www.smarty.net/syntax_comparison is most funny for me: calculate number of symbols.... But I am familiar with PHP and this is easy for me to write on it, and Smarty is new for me. And I don't think that for Web Designers are so difficult to learn some simple php constructs, and Smarty is so simpler in this respect. If I am wrong it would be good to hear web designer here.

Smarty parses the code and this is in fact time overhead.

But at the same time many people use it. And that is why I would like to understand the reasons for this?
Where are the benefits? Am I missing something?

If you know good alternative to Smarty, it would be good to know about.
Thanks!

UPDATE:

I have found also the question on subject: How to use Smarty better with PHP?. In general it is also about not to use Smarty. But this is 1.5 years old. Possibly something changed?

Body:
I use it in a production environment, and I would say: Not Very Many.

If you're concerned with the look of your code (not an unimportant concern), smarty can make things look a little bit cleaner:

<?php echo $some_var; ?>

vs.:

{$some_var}

this can make your template files much more readable.

It also enforces a stricter separation between your controller and view logic. (since you have to make sure to pass all the relevant variables into the smarty object)

The syntax is straight-forward enough (more so for later versions), so that's not much of a problem.

It can complicate debugging, if only because it is a magical separation layer between your control and view, but in a perfect world you would be verifying each separately anyways.....

Drawbacks? I think there's a couple:

-Obviously you now have a whole other library to deal with, include, etc.

-Some previous smarty versions had some ridiculous syntax for loops and other stuff that should have been simple.

-When you need to put a simple javascript statement somewhere in your template, like this:

<script type='text/javascript'>
    $(document).ready(function(){
        //foo
    });
</script>

ok, you might include that in a js file instead of inline, but there's a lot of cases where you just need those couple of lines of js. smarty doesn't like the curly braces and you have to wrap them in an ugly tag that looks like this:

{literal}{\literal}

in that case so much for making your code any cleaner....

If I had to choose, I probably would just use the non-standard short-form tag and be done with it.


问:
Why some dates being shown as BST and some as GMT when formatting Date?
I have following 2 input strings:

```<code>String string1 = "2017-01-30T13:00:00+0000"
String string2 = "2018-06-23T16:00:00+0000"
</code>```

For string1 I am getting following as a date when I do:

```<code>SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
Date startDate = formatter.parse(string1);
</code>```

result - Mon Jan 30 13:00:00 GMT 2017

But when I do the same for string2 I get the following in my debugger:

```<code>Sat Jun 23 17:00:00 BST 2018
</code>```

Why am I getting different timezones here?

答:
tl;dr

```<code>OffsetDateTime.parse( "2017-01-30T13:00:00+0000" )
</code>```

java.time

Among the many design flaws of the troublesome old legacy classes you are using is that the Date::toString method applies your JVM’s current default time zone while generating the string. So while the value internally is actually in UTC, it confusingly appears to have another time zone. Add to that that your current default time zone experiences a Daylight Saving Time cutover between your two dates.

Instead use modern java.time classes. Parse your input strings as OffsetDateTime objects.

```<code>OffsetDateTime odt = OffsetDateTime.parse( "2017-01-30T13:00:00+0000" ) ;
</code>```

A bug in Java 8 and Java 9 might bite on parsing your offset-from-UTC lacking a colon between hours and minutes. As a workaround, add the colon.

```<code>OffsetDateTime odt = OffsetDateTime.parse( "2017-01-30T13:00:00+0000".replace( "+0000" , "+00:00" ) ;
</code>```

Call toString to generate a String in standard ISO 8601 format. Result is not adulterated by any time zone dynamically applied, unlike Date.

If desired, assign a ZoneId to get a ZonedDateTime.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as BST or EST or IST as they are not true time zones, not standardized, and not even unique(!).

```<code>ZoneId z = ZoneId.of( "Europe/London" ) ;
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;
</code>```

See complete code for both inputs run live at IdeOne.com.

```<code>String input2017 = "2017-01-30T13:00:00+0000".replace( "+0000" , "+00:00" ) ;  // Workaround Java 8 bug where omitted colon in offset-from-UTC fails to parse. Fixed in Java 9.
OffsetDateTime odt2017 = OffsetDateTime.parse( input2017 ) ;

String input2018 = "2018-06-23T16:00:00+0000".replace( "+0000" , "+00:00" ) ;  // Workaround Java 8 bug where omitted colon in offset-from-UTC fails to parse. Fixed in Java 9.
OffsetDateTime odt2018 = OffsetDateTime.parse( input2018 ) ;

ZoneId z = ZoneId.of( "Europe/London" ) ;
ZonedDateTime zdt2017 = odt2017.atZoneSameInstant( z ) ;
ZonedDateTime zdt2018 = odt2018.atZoneSameInstant( z ) ;
</code>```

Dump to console.

```<code>System.out.println( "input2017: " + input2017 ) ;
System.out.println( "odt2017: " + odt2017 ) ;
System.out.println( "zdt2017: " + zdt2017 ) ;
System.out.println( "" ) ;  // Blank line.

System.out.println( "input2018: " + input2018 ) ;
System.out.println( "odt2018: " + odt2018 ) ;
System.out.println( "zdt2018: " + zdt2018 ) ;
</code>```

Note how in June 2018, Europe/London time jumps forward an hour because of Daylight Saving Time (DST). In winter, London zone is on UTC but in summer, one hour ahead of UTC.

2017

input2017: 2017-01-30T13:00:00+00:00

odt2017: 2017-01-30T13:00Z

zdt2017: 2017-01-30T13:00Z[Europe/London]

2018

input2018: 2018-06-23T16:00:00+00:00

odt2018: 2018-06-23T16:00Z

zdt2018: 2018-06-23T17:00+01:00[Europe/London]

Search Stack Overflow for much more info as this topic has been handled many many times already.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Java SE 8, Java SE 9, and later

Built-in.

Part of the standard Java API with a bundled implementation.

Java 9 adds some minor features and fixes.

Java SE 6 and Java SE 7

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

Android

Later versions of Android bundle implementations of the java.time classes.

For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Body:
I have following 2 input strings:

String string1 = "2017-01-30T13:00:00+0000"
String string2 = "2018-06-23T16:00:00+0000"

For string1 I am getting following as a date when I do:

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
Date startDate = formatter.parse(string1);

result - Mon Jan 30 13:00:00 GMT 2017

But when I do the same for string2 I get the following in my debugger:

Sat Jun 23 17:00:00 BST 2018

Why am I getting different timezones here?

Body:
tl;dr

OffsetDateTime.parse( "2017-01-30T13:00:00+0000" )

java.time

Among the many design flaws of the troublesome old legacy classes you are using is that the Date::toString method applies your JVM’s current default time zone while generating the string. So while the value internally is actually in UTC, it confusingly appears to have another time zone. Add to that that your current default time zone experiences a Daylight Saving Time cutover between your two dates.

Instead use modern java.time classes. Parse your input strings as OffsetDateTime objects.

OffsetDateTime odt = OffsetDateTime.parse( "2017-01-30T13:00:00+0000" ) ;

A bug in Java 8 and Java 9 might bite on parsing your offset-from-UTC lacking a colon between hours and minutes. As a workaround, add the colon.

OffsetDateTime odt = OffsetDateTime.parse( "2017-01-30T13:00:00+0000".replace( "+0000" , "+00:00" ) ;

Call toString to generate a String in standard ISO 8601 format. Result is not adulterated by any time zone dynamically applied, unlike Date.

If desired, assign a ZoneId to get a ZonedDateTime.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as BST or EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "Europe/London" ) ;
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;

See complete code for both inputs run live at IdeOne.com.

String input2017 = "2017-01-30T13:00:00+0000".replace( "+0000" , "+00:00" ) ;  // Workaround Java 8 bug where omitted colon in offset-from-UTC fails to parse. Fixed in Java 9.
OffsetDateTime odt2017 = OffsetDateTime.parse( input2017 ) ;

String input2018 = "2018-06-23T16:00:00+0000".replace( "+0000" , "+00:00" ) ;  // Workaround Java 8 bug where omitted colon in offset-from-UTC fails to parse. Fixed in Java 9.
OffsetDateTime odt2018 = OffsetDateTime.parse( input2018 ) ;

ZoneId z = ZoneId.of( "Europe/London" ) ;
ZonedDateTime zdt2017 = odt2017.atZoneSameInstant( z ) ;
ZonedDateTime zdt2018 = odt2018.atZoneSameInstant( z ) ;

Dump to console.

System.out.println( "input2017: " + input2017 ) ;
System.out.println( "odt2017: " + odt2017 ) ;
System.out.println( "zdt2017: " + zdt2017 ) ;
System.out.println( "" ) ;  // Blank line.

System.out.println( "input2018: " + input2018 ) ;
System.out.println( "odt2018: " + odt2018 ) ;
System.out.println( "zdt2018: " + zdt2018 ) ;

Note how in June 2018, Europe/London time jumps forward an hour because of Daylight Saving Time (DST). In winter, London zone is on UTC but in summer, one hour ahead of UTC.

2017

input2017: 2017-01-30T13:00:00+00:00

odt2017: 2017-01-30T13:00Z

zdt2017: 2017-01-30T13:00Z[Europe/London]

2018

input2018: 2018-06-23T16:00:00+00:00

odt2018: 2018-06-23T16:00Z

zdt2018: 2018-06-23T17:00+01:00[Europe/London]

Search Stack Overflow for much more info as this topic has been handled many many times already.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Java SE 8, Java SE 9, and later

Built-in.

Part of the standard Java API with a bundled implementation.

Java 9 adds some minor features and fixes.

Java SE 6 and Java SE 7

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

Android

Later versions of Android bundle implementations of the java.time classes.

For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


问:
Pandas Python: Slice / Transform URL to get item and item counts
If I have column data, for example 100 entries that fall under two formats; under the column name URL:

```<code>http//mysportswebsite.com/shop/?Baseball+Bat=5

http//memoribilia.com/checkout?autograph=1
</code>```

How can I extract the item and number purchased?

Ideally I would like to add new columns (if they did not exist already) for in this example Baseball Bat and autograph then add the respective count of 5 and 1 to their columns (or just add to columns if they existed from a prior example),to infer purchasing counts from this data.

I would want to do this to the entire URL column in python

答:
for this question (which has a bit limited information) I would propose:

if your df looks like this:

```<code>df = pd.DataFrame(data={"url": ["http//mysportswebsite.com/shop/?Baseball+Bat=5", "http//memoribilia.com/checkout?autograph=1"]})

                                              url
0  http//mysportswebsite.com/shop/?Baseball+Bat=5
1      http//memoribilia.com/checkout?autograph=1
</code>```

you could do this:

```<code>df['product_count_tuple'] = df.url.apply(lambda x: x.split('?')[1].split('='))
df['product'] = df.product_count_tuple.apply(lambda x: x[0].replace('+', ' '))
df['count'] = df.product_count_tuple.apply(lambda x: x[1])
df = df.drop('product_count_tuple', 1)
</code>```

which results in:

```<code>                                              url       product count
0  http//mysportswebsite.com/shop/?Baseball+Bat=5  Baseball Bat     5
1      http//memoribilia.com/checkout?autograph=1     autograph     1
</code>```

Body:
If I have column data, for example 100 entries that fall under two formats; under the column name URL:

http//mysportswebsite.com/shop/?Baseball+Bat=5

http//memoribilia.com/checkout?autograph=1

How can I extract the item and number purchased?

Ideally I would like to add new columns (if they did not exist already) for in this example Baseball Bat and autograph then add the respective count of 5 and 1 to their columns (or just add to columns if they existed from a prior example),to infer purchasing counts from this data.

I would want to do this to the entire URL column in python

Body:
for this question (which has a bit limited information) I would propose:

if your df looks like this:

df = pd.DataFrame(data={"url": ["http//mysportswebsite.com/shop/?Baseball+Bat=5", "http//memoribilia.com/checkout?autograph=1"]})

                                              url
0  http//mysportswebsite.com/shop/?Baseball+Bat=5
1      http//memoribilia.com/checkout?autograph=1

you could do this:

df['product_count_tuple'] = df.url.apply(lambda x: x.split('?')[1].split('='))
df['product'] = df.product_count_tuple.apply(lambda x: x[0].replace('+', ' '))
df['count'] = df.product_count_tuple.apply(lambda x: x[1])
df = df.drop('product_count_tuple', 1)

which results in:

                                              url       product count
0  http//mysportswebsite.com/shop/?Baseball+Bat=5  Baseball Bat     5
1      http//memoribilia.com/checkout?autograph=1     autograph     1


问:
git clone in remote windows doesn't work
I have a Windows 7 machine to which I have SSH access. I want to clone a git repo in a particular directory in that machine using SSH protocol. I am trying to clone the repo by logging into the remote Windows 7 machine using SSH(PuTTY) but I get the following error at the console:

```<code>git@xyz-github.com: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

But I am able to clone the same repo if I do it via Remote Desktop(mstsc) or VNC viewer. Can someone help me with what is missing here in the PuTTY approach? Eventually, I want to automate the cloning process using Python & fabric.

Here's the output of ssh git@xyz-github.com -v :

```<code>OpenSSH_7.6p1, OpenSSL 1.0.2m  2 Nov 2017
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Connecting to xyz-github.com [xxx.yyy.zzz.www] port 22.
debug1: Connection established.
debug1: identity file /c/Users/admin/.ssh/id_rsa type 0
debug1: key_load_public: No such file or directory
debug1: identity file /c/Users/admin/.ssh/id_rsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /c/Users/admin/.ssh/id_dsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /c/Users/admin/.ssh/id_dsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /c/Users/admin/.ssh/id_ecdsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /c/Users/admin/.ssh/id_ecdsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /c/Users/admin/.ssh/id_ed25519 type -1
debug1: key_load_public: No such file or directory
debug1: identity file /c/Users/admin/.ssh/id_ed25519-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_7.6
debug1: Remote protocol version 2.0, remote software version libssh-0.7.0
debug1: no match: libssh-0.7.0
debug1: Authenticating to xyz-github.com:22 as 'git'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: algorithm: curve25519-sha256@libssh.org
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: aes128-ctr MAC: hmac-sha2-256 compression: none
debug1: kex: client->server cipher: aes128-ctr MAC: hmac-sha2-256 compression: none
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:YppvE1IGqHnKCcW9FqBzT4wBdyHxS0XBChnQNu4zCn0
debug1: Host 'xyz-github.com' is known and matches the ECDSA host key.
debug1: Found key in /c/Users/admin/.ssh/known_hosts:1
debug1: rekey after 4294967296 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: rekey after 4294967296 blocks
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Offering public key: RSA SHA256:yJ5QUUudzMLgW4w8x1o5idxyGbqmeoLilEPiKQnM5gs /c/Users/admin/.ssh/id_rsa
debug1: Server accepts key: pkalg ssh-rsa blen 279
debug1: Authentication succeeded (publickey).
Authenticated to xyz-github.com ([xxx.yyy.zzz.www]:22).
debug1: channel 0: new [client-session]
debug1: Entering interactive session.
debug1: pledge: network
PTY allocation request failed on channel 0
debug1: client_input_channel_req: channel 0 rtype exit-status reply 0
Hi rakesh! You've successfully authenticated, but GitHub does not provide shell access.
debug1: channel 0: free: client-session, nchannels 1
Connection to xyz-github.com closed.
Transferred: sent 2880, received 1384 bytes, in 0.5 seconds
Bytes per second: sent 5594.4, received 2688.4
debug1: Exit status 1
</code>```

答:
Perhaps a credential helper does the job?

In the end git config --list --show-origin should look like this:

```<code>file:"C:\\Git\\mingw64/etc/gitconfig"   credential.helper=manager
file:C:/Users/user/.gitconfig    credential.helper=wincred
file:.git/config        remote.origin.url=https://github.com/xy
</code>```

For details see this question.

Body:
I have a Windows 7 machine to which I have SSH access. I want to clone a git repo in a particular directory in that machine using SSH protocol. I am trying to clone the repo by logging into the remote Windows 7 machine using SSH(PuTTY) but I get the following error at the console:

git@xyz-github.com: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

But I am able to clone the same repo if I do it via Remote Desktop(mstsc) or VNC viewer. Can someone help me with what is missing here in the PuTTY approach? Eventually, I want to automate the cloning process using Python & fabric.

Here's the output of ssh git@xyz-github.com -v :

OpenSSH_7.6p1, OpenSSL 1.0.2m  2 Nov 2017
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Connecting to xyz-github.com [xxx.yyy.zzz.www] port 22.
debug1: Connection established.
debug1: identity file /c/Users/admin/.ssh/id_rsa type 0
debug1: key_load_public: No such file or directory
debug1: identity file /c/Users/admin/.ssh/id_rsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /c/Users/admin/.ssh/id_dsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /c/Users/admin/.ssh/id_dsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /c/Users/admin/.ssh/id_ecdsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /c/Users/admin/.ssh/id_ecdsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /c/Users/admin/.ssh/id_ed25519 type -1
debug1: key_load_public: No such file or directory
debug1: identity file /c/Users/admin/.ssh/id_ed25519-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_7.6
debug1: Remote protocol version 2.0, remote software version libssh-0.7.0
debug1: no match: libssh-0.7.0
debug1: Authenticating to xyz-github.com:22 as 'git'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: algorithm: curve25519-sha256@libssh.org
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: aes128-ctr MAC: hmac-sha2-256 compression: none
debug1: kex: client->server cipher: aes128-ctr MAC: hmac-sha2-256 compression: none
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:YppvE1IGqHnKCcW9FqBzT4wBdyHxS0XBChnQNu4zCn0
debug1: Host 'xyz-github.com' is known and matches the ECDSA host key.
debug1: Found key in /c/Users/admin/.ssh/known_hosts:1
debug1: rekey after 4294967296 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: rekey after 4294967296 blocks
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Offering public key: RSA SHA256:yJ5QUUudzMLgW4w8x1o5idxyGbqmeoLilEPiKQnM5gs /c/Users/admin/.ssh/id_rsa
debug1: Server accepts key: pkalg ssh-rsa blen 279
debug1: Authentication succeeded (publickey).
Authenticated to xyz-github.com ([xxx.yyy.zzz.www]:22).
debug1: channel 0: new [client-session]
debug1: Entering interactive session.
debug1: pledge: network
PTY allocation request failed on channel 0
debug1: client_input_channel_req: channel 0 rtype exit-status reply 0
Hi rakesh! You've successfully authenticated, but GitHub does not provide shell access.
debug1: channel 0: free: client-session, nchannels 1
Connection to xyz-github.com closed.
Transferred: sent 2880, received 1384 bytes, in 0.5 seconds
Bytes per second: sent 5594.4, received 2688.4
debug1: Exit status 1

Body:
Perhaps a credential helper does the job?

In the end git config --list --show-origin should look like this:

file:"C:\\Git\\mingw64/etc/gitconfig"   credential.helper=manager
file:C:/Users/user/.gitconfig    credential.helper=wincred
file:.git/config        remote.origin.url=https://github.com/xy

For details see this question.


问:
How to find the second minimum number without using arrays or loops
I tried to write a program that receive from the user 5 integers and print the second minimum number.

Here is a sample of what I've tried:

```<code>#include <iostream>
using namespace std;
int main () {
int a,b,c,d,e;
cin>>a>>b>>c>>d>>e;
if (a>b && a<c && a<d && a<e)
    cout<<a<<endl;
if (b>a && b<c && b<d && b<e)
    cout<<b<<endl;
if (c>a && c<b && c<d && c<e)
    cout<<c<<endl;
if (d>a && d<b && d<c && d<e)
    cout <<d<<endl;
if (e>a && e<b && e<c && e<d)
cout <<e<<endl;
return 0;

}
</code>```

When I enter 1 2 3 4 5 it prints the second minimum, but when I enter

5 4 3 2 1 Nothing will print on the screen. What am I doing wrong with this? Is there any other way to write my program?

答:
There are 120 possible permutations on 5 elements. Your code should output the correct number for all of them. So a fool-proof code would use 120 repetitions of a check, like the following:

```<code>if (a > b && b > c && c > d && d > e) // the order is a>b>c>d>e
    cout << d;
else if (a > b && b > c && c > e && e > d) // the order is a>b>c>e>d
    cout << e;
...
else if (e > d && d > c && c > a && e > b) // the order is e>d>c>a>b
    cout << a;
else // the order is e>d>c>b>a
    cout << b;
</code>```

This is very long, inefficient and tricky code. If you do a typo in just one variable, it will output a wrong answer in some rare cases. Also, it doesn't handle the possibility of some inputs being equal.

If the number of inputs to a sorting algorithm is a known small constant, you can use an approach called sorting networks. This is a well-defined computer science problem, which has well-known optimal solutions for small numbers of inputs, and 5 certainly is small. An optimal sorting network for 5 inputs contains 9 comparators, and is described e.g. here.

Since you don't need to sort the numbers, but only to know the second smallest input, you can reduce the size of the network further, to 7 comparators.

The full sorting network (without the reduction from 9 to 7) translated to C++:

```<code>if (b < c)
    swap(b, c);
if (d < e)
    swap(d, e);
if (b < d)
    swap(b, d);
if (a < c)
    swap(a, c);
if (c < e)
    swap(c, e);
if (a < d)
    swap(a, d);
if (a < b)
    swap(a, b);
if (c < d)
    swap(c, d);
if (b < c)
    swap(b, c);
// now the order is a ≥ b ≥ c ≥ d ≥ e
cout << d;
</code>```

This code is also obscure - not obvious at all how and why it works - but at least it is small and in a sense optimal. Also, it's clear that it always prints something (so it fixes the original problem) and supports the case of partially equal inputs.

If you ever use such code in a larger project, you should document where you took it from, and test it. Fortunately, there are exactly 120 different possibilities (or 32, if you use the
zero-one principle), so there is a way to prove that this code has no bugs.

Body:
I tried to write a program that receive from the user 5 integers and print the second minimum number.

Here is a sample of what I've tried:

#include <iostream>
using namespace std;
int main () {
int a,b,c,d,e;
cin>>a>>b>>c>>d>>e;
if (a>b && a<c && a<d && a<e)
    cout<<a<<endl;
if (b>a && b<c && b<d && b<e)
    cout<<b<<endl;
if (c>a && c<b && c<d && c<e)
    cout<<c<<endl;
if (d>a && d<b && d<c && d<e)
    cout <<d<<endl;
if (e>a && e<b && e<c && e<d)
cout <<e<<endl;
return 0;

}

When I enter 1 2 3 4 5 it prints the second minimum, but when I enter

5 4 3 2 1 Nothing will print on the screen. What am I doing wrong with this? Is there any other way to write my program?

Body:
There are 120 possible permutations on 5 elements. Your code should output the correct number for all of them. So a fool-proof code would use 120 repetitions of a check, like the following:

if (a > b && b > c && c > d && d > e) // the order is a>b>c>d>e
    cout << d;
else if (a > b && b > c && c > e && e > d) // the order is a>b>c>e>d
    cout << e;
...
else if (e > d && d > c && c > a && e > b) // the order is e>d>c>a>b
    cout << a;
else // the order is e>d>c>b>a
    cout << b;

This is very long, inefficient and tricky code. If you do a typo in just one variable, it will output a wrong answer in some rare cases. Also, it doesn't handle the possibility of some inputs being equal.

If the number of inputs to a sorting algorithm is a known small constant, you can use an approach called sorting networks. This is a well-defined computer science problem, which has well-known optimal solutions for small numbers of inputs, and 5 certainly is small. An optimal sorting network for 5 inputs contains 9 comparators, and is described e.g. here.

Since you don't need to sort the numbers, but only to know the second smallest input, you can reduce the size of the network further, to 7 comparators.

The full sorting network (without the reduction from 9 to 7) translated to C++:

if (b < c)
    swap(b, c);
if (d < e)
    swap(d, e);
if (b < d)
    swap(b, d);
if (a < c)
    swap(a, c);
if (c < e)
    swap(c, e);
if (a < d)
    swap(a, d);
if (a < b)
    swap(a, b);
if (c < d)
    swap(c, d);
if (b < c)
    swap(b, c);
// now the order is a ≥ b ≥ c ≥ d ≥ e
cout << d;

This code is also obscure - not obvious at all how and why it works - but at least it is small and in a sense optimal. Also, it's clear that it always prints something (so it fixes the original problem) and supports the case of partially equal inputs.

If you ever use such code in a larger project, you should document where you took it from, and test it. Fortunately, there are exactly 120 different possibilities (or 32, if you use the
zero-one principle), so there is a way to prove that this code has no bugs.


问:
View does not update to add object that was previously ignored
There is no document in view after the document has been inserted in bucket.

My document:

```<code>{
  "state": 1,
  "rdbms_id": 0,
  "startDate": 1511882685998,
  "endDate": -1,
  "type": "kv",
  "userid": 1222,
  "uuid": "84fd36ad-b8bd-4abb-90ac-eae407f9364a",
  "amount": 1234,
  "source_id": 12
}
</code>```

View index code:

```<code>function (doc, meta) {
  if(meta.type=="json"){
    if(doc.type && doc.type === "kv"){
      if(doc.startDate && doc.startDate<=Date.now()){
        if(doc.endDate && (doc.endDate>=Date.now() || doc.endDate==-1)){
          if(doc.state && doc.state==1){
          emit([doc.userid,doc.source_id], null);
          }
        }
      }
    }
  }
}
</code>```

My view query:

```<code>curl http://Administrator:pass@localhost:8092/bss_write/_design/fihrist/_view/forUcrKVIds?limit=6&stale=false&connection_timeout=60000&inclusive_end=true&skip=0
</code>```

View is updated when adding document with curl.

```<code>curl -H "Content-Type: application/json" -X POST -v -d 'Jsondocument' 'http://Administrator:pass@localhost:8091/pools/default/buckets/bss_write/docs/kv-84fd36ad-b8bd-4abb-90ac-eae407f9364a'
</code>```

But the view is not updated when you add it with the program.

```<code>Cluster cluster = CouchbaseCluster.create("localhost");
cluster.authenticate("username", "");
Bucket bucket = cluster.openBucket("bss_write");

JsonObject doc = JsonObject.fromJson(Jsondocument);

bucket.upsert(JsonDocument.create(type+"-"+uuid, doc));
</code>```

Do I need to run a procedure to programmatically update the view?

Update 2:

The problem is the time difference. When the document is added, the view is not updated because the date condition is not matched.

However, the view is not updated even if the view conditions are met after the document is added.

For example:

```<code>My computer timestamp is 1512054982454.
Couchbase server timestamp is 1512054876554.

function (doc, meta) {
  if(meta.type=="json"){
    if(doc.type && doc.type === "kv"){
---->if(doc.startDate && doc.startDate<=Date.now()){ //This returns false.
        if(doc.endDate && (doc.endDate>=Date.now() || doc.endDate==-1)){
          if(doc.state && doc.state==1){
          emit([doc.userid,doc.source_id], null);
          }
        }
      }
    }
  }
}
</code>```

答:
Background

Let's break down what is going on here, from a high level:

A document is added to the bucket

The view engine processes the document to determine if it gets added to the view.

If a series of conditions are met, as described in your question, the document is added to the view. If not, the document is ignored. Specifically,

if(doc.startDate && doc.startDate<=Date.now())

If, at a later time, the document is updated, then the view will re-process it and it may or may not get included.

The issue

A basic issue exists, and that is the distinction between compilation of the view and query from the view.  When you compile the view, it needs to include all possible combinations that you may want to select in the future. When you query from the view, only those items that meet the given query criteria are to be returned.

The problem here is that the view compilation phase is performing the query phase. The compile logic runs once for each object, and will not run again unless the object changes or you tell CB to recompute the view. If your compilation does not include the object in the first place, it never will.

The solution

Change your map/reduce function to emit all objects that you want, removing any dependencies on Date.Now.  Change your query code to select only items matching the given criteria that is presently defined in your query.

Note that it may be more efficient to load the results of a broad query of the view into memory on your web service host, using java code to perform granular selection prior to serving the results to the client. I have found extremely high performance to result from this approach.

Body:
There is no document in view after the document has been inserted in bucket.

My document:

{
  "state": 1,
  "rdbms_id": 0,
  "startDate": 1511882685998,
  "endDate": -1,
  "type": "kv",
  "userid": 1222,
  "uuid": "84fd36ad-b8bd-4abb-90ac-eae407f9364a",
  "amount": 1234,
  "source_id": 12
}

View index code:

function (doc, meta) {
  if(meta.type=="json"){
    if(doc.type && doc.type === "kv"){
      if(doc.startDate && doc.startDate<=Date.now()){
        if(doc.endDate && (doc.endDate>=Date.now() || doc.endDate==-1)){
          if(doc.state && doc.state==1){
          emit([doc.userid,doc.source_id], null);
          }
        }
      }
    }
  }
}

My view query:

curl http://Administrator:pass@localhost:8092/bss_write/_design/fihrist/_view/forUcrKVIds?limit=6&stale=false&connection_timeout=60000&inclusive_end=true&skip=0

View is updated when adding document with curl.

curl -H "Content-Type: application/json" -X POST -v -d 'Jsondocument' 'http://Administrator:pass@localhost:8091/pools/default/buckets/bss_write/docs/kv-84fd36ad-b8bd-4abb-90ac-eae407f9364a'

But the view is not updated when you add it with the program.

Cluster cluster = CouchbaseCluster.create("localhost");
cluster.authenticate("username", "");
Bucket bucket = cluster.openBucket("bss_write");

JsonObject doc = JsonObject.fromJson(Jsondocument);

bucket.upsert(JsonDocument.create(type+"-"+uuid, doc));

Do I need to run a procedure to programmatically update the view?

Update 2:

The problem is the time difference. When the document is added, the view is not updated because the date condition is not matched.

However, the view is not updated even if the view conditions are met after the document is added.

For example:

My computer timestamp is 1512054982454.
Couchbase server timestamp is 1512054876554.

function (doc, meta) {
  if(meta.type=="json"){
    if(doc.type && doc.type === "kv"){
---->if(doc.startDate && doc.startDate<=Date.now()){ //This returns false.
        if(doc.endDate && (doc.endDate>=Date.now() || doc.endDate==-1)){
          if(doc.state && doc.state==1){
          emit([doc.userid,doc.source_id], null);
          }
        }
      }
    }
  }
}


问:
Several actions with same name in react-redux
I have actions from different packages which have the same name like this:

```<code>import { bindActionCreators } from 'redux';
import { setActiveLanguage } from 'react-localize-redux';
import * as actionCreators from '../actions/actionCreators';
import * as toggleActions from '../actions/toggleActions';
import {actions as rrfActions} from 'react-redux-form';

function mapDispatchToProps(dispatch) {
    return bindActionCreators(
      {
        ...actionCreators,
        ...toggleActions,
        setActiveLanguage,
        ...rrfActions
      },
      dispatch);
  }

export default mapDispatchToProps
</code>```

As both toggleActions and rrfActions have a toggle action, nesting the rrfActions could do the trick (?) to call the action, but I can't prevent the reducers from listening to the same TOGGLE action type. Is there a workaround other than not having a general mapDispatchToProps for all connected components, rather very specific ones

Cheers!

答:
The way I solved this was with renaming actions:</p>

```<code>import { bindActionCreators } from 'redux';
import { setActiveLanguage } from 'react-localize-redux';
import * as actionCreators from '../actions/actionCreators';
import * as toggleActions from '../actions/toggleActions';
import { actions as rrfActions } from 'react-redux-form';

let renamedActions = {};
Object.keys(rrfActions).map((v,k)=> {
  renamedActions['rrf' + v.replace(/\b\w/g, l => l.toUpperCase())] = rrfActions[v]
  // toggle -> rrfToggle
  return null;
})

function mapDispatchToProps(dispatch) {
  return bindActionCreators(
    {
      ...actionCreators,
      ...toggleActions,
      setActiveLanguage,
      ...renamedActions
    },
    dispatch);
}

export default mapDispatchToProps
</code>```

Body:
I have actions from different packages which have the same name like this:

import { bindActionCreators } from 'redux';
import { setActiveLanguage } from 'react-localize-redux';
import * as actionCreators from '../actions/actionCreators';
import * as toggleActions from '../actions/toggleActions';
import {actions as rrfActions} from 'react-redux-form';

function mapDispatchToProps(dispatch) {
    return bindActionCreators(
      {
        ...actionCreators,
        ...toggleActions,
        setActiveLanguage,
        ...rrfActions
      },
      dispatch);
  }

export default mapDispatchToProps

As both toggleActions and rrfActions have a toggle action, nesting the rrfActions could do the trick (?) to call the action, but I can't prevent the reducers from listening to the same TOGGLE action type. Is there a workaround other than not having a general mapDispatchToProps for all connected components, rather very specific ones

Cheers!

Body:
The way I solved this was with renaming actions:

import { bindActionCreators } from 'redux';
import { setActiveLanguage } from 'react-localize-redux';
import * as actionCreators from '../actions/actionCreators';
import * as toggleActions from '../actions/toggleActions';
import { actions as rrfActions } from 'react-redux-form';

let renamedActions = {};
Object.keys(rrfActions).map((v,k)=> {
  renamedActions['rrf' + v.replace(/\b\w/g, l => l.toUpperCase())] = rrfActions[v]
  // toggle -> rrfToggle
  return null;
})

function mapDispatchToProps(dispatch) {
  return bindActionCreators(
    {
      ...actionCreators,
      ...toggleActions,
      setActiveLanguage,
      ...renamedActions
    },
    dispatch);
}

export default mapDispatchToProps