问:
Bootstrap div- align to center of page
I'm trying to center a col-span-6 div to the center of the page using Twitter Bootstrap 3. Unfortunately, nothing I do is working. I used Firefox developer tools to discern the issue was most likely stemming from the fact that the col-span-6 class was floated left. Therefore, I added a style="float: none !important;" to the col-span-6 element, but that did nothing.

Help!!

```<code><div class="panel-group col-sm-6" style="float: none;">
<div class="panel panel-default">
    <div class="panel-heading">
        <h5 class="card-title">test</h5>
    </div>
    <div class="panel-body">
        <p class="card-text">test</p>
    </div>
</div>
</div>
</code>```

答:
Use column offset with "col-sm-6" to make it in center. Here is an example:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

test

test

```

It automatically push the column in center.

Title: Bootstrap div- align to center of page

Body:
I'm trying to center a col-span-6 div to the center of the page using Twitter Bootstrap 3. Unfortunately, nothing I do is working. I used Firefox developer tools to discern the issue was most likely stemming from the fact that the col-span-6 class was floated left. Therefore, I added a style="float: none !important;" to the col-span-6 element, but that did nothing.

Help!!

test

test

Body:
Use column offset with "col-sm-6" to make it in center. Here is an example:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="panel-group col-sm-6 col-sm-offset-3">
 <div class="panel panel-default">
     <div class="panel-heading">
         <h5 class="card-title">test</h5>
     </div>
     <div class="panel-body">
         <p class="card-text">test</p>
     </div>
 </div>
</div>

It automatically push the column in center.


来源: stackexchange

问:
Add item to specific position otherwise push zero in array in javascript
I have empty array in that I want to add specific items at specific position which are coming from web api and want to add zero(0) to remaining positions dynamically using javscript.
Here is my Code :-

```<code>let arraydata = [0, 0, 0, 0, 0,0,0,0,0,0,0,0]
arraydata.splice(5, 0, 4)
document.querySelector("#app").innerHTML = arraydata;
</code>```

My Code

Right now I have added zero manually,I want to add 0 upto 12 index and want to add 4 at 5th position synamicaaly.

答:
You can build a generic function like this

let desiredArr = (length, value, from, to)=>{
  let arr = new Array(length).fill(0)
  arr.splice(value, from, to)
  return arr
}

console.log(desiredArr(12, 5, 0 ,4))```
</div>
</div>
</p>

<p>If there's always only one index you want to update than you can simply do this</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let arr = new Array(12).fill(0)
arr[5] = 4

console.log(arr)</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have empty array in that I want to add specific items at specific position which are coming from web api and want to add zero(0) to remaining positions dynamically using javscript.
Here is my Code :-

let arraydata = [0, 0, 0, 0, 0,0,0,0,0,0,0,0]
arraydata.splice(5, 0, 4)
document.querySelector("#app").innerHTML = arraydata;

My Code

Right now I have added zero manually,I want to add 0 upto 12 index and want to add 4 at 5th position synamicaaly.

Body:
You can build a generic function like this

let desiredArr = (length, value, from, to)=>{
  let arr = new Array(length).fill(0)
  arr.splice(value, from, to)
  return arr
}

console.log(desiredArr(12, 5, 0 ,4))

If there's always only one index you want to update than you can simply do this

let arr = new Array(12).fill(0)
arr[5] = 4

console.log(arr)


问:
Partially evaluate expression when doing non-standard evaluation in R
I'm digging my head into R's non-standard evaluation mechanisms. Halfway there, I'm still stuck from time to time. ;-)

I made a little calculator that pretty-prints the calculation together with the result:

```<code>calculator <- function(e) cat(deparse(substitute(e)), "=", e)
</code>```

This works fine:

```<code>calculator(1 + 2)
</code>```

prints:

```<code>1 + 2 = 3
</code>```

However, when calling the calculator with:

```<code>a <- 1; b <- 2
calculator(a + b)
</code>```

the output is:

```<code>a + b = 3
</code>```

How can I tweak my calculator in order it prints 1 + 2 = 3 also in the later case?

I tried:

```<code>calculator2 <- function(e) {
  ex <- lapply(substitute(e), function(x) ifelse(is.numeric(x), eval(x), x))
  cat(deparse(ex), "=", e)
}

calculator2(1 + 2)
# list(+, 1, 2) = 3
calculator2(a + b)
# list(+, a, b) = 3
</code>```

This obviously doesn't work. After the lapply call I have a list and cat prints list(+, 1, 2) to the console.

So I made another try:

```<code>calculator3 <- function(e) {
  ex <- substitute(e)
  for(i in 1:length(ex)) {
    if(is.numeric(ex[[i]])) ex[[i]] <- eval(ex[[i]])
  }
  cat(deparse(ex), "=", e)
}

calculator3(1 + 2)
# 1 + 2 = 3
calculator3(a + b)
# a + b = 3
</code>```

..which is the same as my first version..

答:
This works for an expression with one operator. For more complex expressions (which are nested function calls), you'll need to use recursion instead of the simple loops.</p>

```<code>a <- 1; b <- 2
calculator1 <- function(e) {
  expr <- substitute(e)
  evalexpr <- lapply(expr, eval) #evaluate each part of expression
  numind <- vapply(evalexpr, is.numeric, FUN.VALUE = logical(1))
  expr[numind] <- evalexpr[numind]
  cat(deparse(expr), "=", e)
}

calculator1(a + b)
#1 + 2 = 3
calculator1(1 + 2)
#1 + 2 = 3
</code>```

Body:
I'm digging my head into R's non-standard evaluation mechanisms. Halfway there, I'm still stuck from time to time. ;-)

I made a little calculator that pretty-prints the calculation together with the result:

calculator <- function(e) cat(deparse(substitute(e)), "=", e)

This works fine:

calculator(1 + 2)

prints:

1 + 2 = 3

However, when calling the calculator with:

a <- 1; b <- 2
calculator(a + b)

the output is:

a + b = 3

How can I tweak my calculator in order it prints 1 + 2 = 3 also in the later case?

I tried:

calculator2 <- function(e) {
  ex <- lapply(substitute(e), function(x) ifelse(is.numeric(x), eval(x), x))
  cat(deparse(ex), "=", e)
}

calculator2(1 + 2)
# list(+, 1, 2) = 3
calculator2(a + b)
# list(+, a, b) = 3

This obviously doesn't work. After the lapply call I have a list and cat prints list(+, 1, 2) to the console.

So I made another try:

calculator3 <- function(e) {
  ex <- substitute(e)
  for(i in 1:length(ex)) {
    if(is.numeric(ex[[i]])) ex[[i]] <- eval(ex[[i]])
  }
  cat(deparse(ex), "=", e)
}

calculator3(1 + 2)
# 1 + 2 = 3
calculator3(a + b)
# a + b = 3

..which is the same as my first version..

Body:
This works for an expression with one operator. For more complex expressions (which are nested function calls), you'll need to use recursion instead of the simple loops.

a <- 1; b <- 2
calculator1 <- function(e) {
  expr <- substitute(e)
  evalexpr <- lapply(expr, eval) #evaluate each part of expression
  numind <- vapply(evalexpr, is.numeric, FUN.VALUE = logical(1))
  expr[numind] <- evalexpr[numind]
  cat(deparse(expr), "=", e)
}

calculator1(a + b)
#1 + 2 = 3
calculator1(1 + 2)
#1 + 2 = 3


问:
Why is blue circle not spinning in the center of itself
Why is the blue circle not rotating in the center of its own axis?
Below you can find my previous code.

Here you can see my CSS with the proportionate SVG:

circle {
  animation: grow 2s infinite;
  transform-origin: center;
}

@keyframes grow {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(0.5);
  }
  100% {
    transform: scale(1);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg xmlns="http://www.w3.org/2000/svg"
     width="80"
     height="110"
     version="1.1">
     <rect width="70"
           height="100"
           x="5"
           y="5"
           fill="white"
           stroke="red"
           stroke-width="10"
           rx="5"/>
     <circle cx="40" cy="105" r="3" fill="blue"/>
</svg></code>```

答:
Because scale in SVG is different, it makes scale in X & Y axis. Additionally it scales "cx" and "cy" properties.
The best way is to make "cx" & "cy" at 0 and use the "translate" to coordinates you need

 <svg xmlns="http://www.w3.org/2000/svg" width="80" height="110" version="1.1">
      <rect
        width="70"
        height="100"
        x="5"
        y="5"
        fill="white"
        stroke="red"
        stroke-width="10"
        rx="5" />
     <circle cx="0" cy="0" r="3" fill="blue" transform="translate(40 105)">
      <animateTransform
                     attributeName="transform"
         type="scale"
         additive="sum"
         from="1 1"
         to="1 1"
         values="1 1; 0.5 0.5; 1 1"
         begin="0s"
         dur="2s"
         repeatCount="indefinite">

      </animateTransform>
     </circle>
    </svg>```

Enjoy!

Body:
Why is the blue circle not rotating in the center of its own axis?
Below you can find my previous code.

Here you can see my CSS with the proportionate SVG:

circle {
  animation: grow 2s infinite;
  transform-origin: center;
}

@keyframes grow {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(0.5);
  }
  100% {
    transform: scale(1);
  }
}

<svg xmlns="http://www.w3.org/2000/svg"
     width="80"
     height="110"
     version="1.1">
     <rect width="70"
           height="100"
           x="5"
           y="5"
           fill="white"
           stroke="red"
           stroke-width="10"
           rx="5"/>
     <circle cx="40" cy="105" r="3" fill="blue"/>
</svg>

Body:
Because scale in SVG is different, it makes scale in X & Y axis. Additionally it scales "cx" and "cy" properties.
The best way is to make "cx" & "cy" at 0 and use the "translate" to coordinates you need

 <svg xmlns="http://www.w3.org/2000/svg" width="80" height="110" version="1.1">
      <rect
        width="70"
        height="100"
        x="5"
        y="5"
        fill="white"
        stroke="red"
        stroke-width="10"
        rx="5" />
     <circle cx="0" cy="0" r="3" fill="blue" transform="translate(40 105)">
      <animateTransform
                     attributeName="transform"
         type="scale"
         additive="sum"
         from="1 1"
         to="1 1"
         values="1 1; 0.5 0.5; 1 1"
         begin="0s"
         dur="2s"
         repeatCount="indefinite">

      </animateTransform>
     </circle>
    </svg>

Enjoy!


问:
I want to plus the number form string datatype
I have the following input as string:

```<code>Num: 12345
</code>```

I would like to print out the sum of digits from the input (1+2+3+4+5 = 15):

```<code>total:15
</code>```

I tried, but there is a problem with atoi() in the for loop and I got an error:

[Error] invalid conversion from 'char' to 'const char*'

How can I fix that or how can I resolve it in an easier way?

```<code> #include <stdio.h>
 #include <ctype.h>
 #include <stdlib.h>
 #include <string.h>

 char numstr[100];
 int total = 0;

 main(){
     printf("Num:");
     scanf("%s", numstr);

     for(int i = 0; i < strlen(numstr); i++){
         total += atoi(numstr[i]);
     }
     printf("%d", total);
 }
</code>```

答:
A simpler approach to your problem could be to replace

```<code>total += atoi(numstr[i]);
</code>```

with

```<code>total += numstr[i] - '0';
</code>```

You might want to to check if isdigit(numstr[i]) is true first, for error checking.

Body:
I have the following input as string:

Num: 12345

I would like to print out the sum of digits from the input (1+2+3+4+5 = 15):

total:15

I tried, but there is a problem with atoi() in the for loop and I got an error:

[Error] invalid conversion from 'char' to 'const char*'

How can I fix that or how can I resolve it in an easier way?

 #include <stdio.h>
 #include <ctype.h>
 #include <stdlib.h>
 #include <string.h>

 char numstr[100];
 int total = 0;

 main(){
     printf("Num:");
     scanf("%s", numstr);

     for(int i = 0; i < strlen(numstr); i++){
         total += atoi(numstr[i]);
     }
     printf("%d", total);
 }

Body:
A simpler approach to your problem could be to replace

total += atoi(numstr[i]);

with

total += numstr[i] - '0';

You might want to to check if isdigit(numstr[i]) is true first, for error checking.


问:
bash redirect output to file - cant store temp texts
I search about this and didn't fine an answer for it.

So my question is not about simple output redirection in Linux shell. I want it to happen inside a bash script I'm writing and I want output and error of anyscripts or commands I run in that script be redirected into separate files.

This is what im currently using:

```<code>STATUSFILE=x.out
LOGFILE=x.log
exec > ${STATUSFILE} 2>${LOGFILE}
echo "bla bla"
#some other commands
</code>```

which works fine for normal outputs. But for example in part of my script I put to my backup server using ftp put. And when I run in manually I see kind of a progress bar saying how much time is passed and how much time its gonna take.

What im trying to do is to capture that kind of output which seems to be updating on the fly and kinda dynamic and currently I get other outputs stored in files but not that kinda dynamic ones.

And another question is if im following a good approach doing this. As I said I want the output and Im gonna use that by another process to see the progress and then use it to inform user trying to run a task with browser.

So for example in my case its uploading a big file into ftp storage which user will command it from browser and I run those scripts and I want to have kind of a progress bar showing up the status to the user. (I know how to handle it on client side - probably a socket connection or interval ajax request checking on a file or an event being triggered by server)

My second question is how should I get the progress of commands that have dynamic output.

If anything is unclear please let me know Ill try to fix it.

Thanks for your help guys.

答:
Good Morning,

So my question is not about simple output redirection in Linux shell. I want it to happen inside a bash script I'm writing

That is quite simple. You just need to enclose your commands in {}.

```<code>#!/bin/bash

{

  echo "hello world!"
  ls -la

} >> script.log
</code>```

I want output and error of anyscripts or commands I run in that script be redirected into separate files.

You could use tee if the same output should go in seperate files.

```<code>#!/bin/bash

{

  echo "hello world!"
  ls -la

} | tee foo bar baz
</code>```

If the output of different commands should go in different files, you would just use different {} blocks.

My second question is how should I get the progress of commands that have dynamic output.

Some tools tend to put the progress bar to STDERR. You can redirect STDOUT and STDERR to same file using 2>&1. 2 is the descriptor for STDERR, 1 for STDOUT and you are basically appending 2 on 1.

Thus you would rewrite the first script to:

```<code>#!/bin/bash

{

  echo "hello world!"
  ls -la

} >> script.log 2>&1
</code>```

Be carefull with that, though. Some tools use colors and carriage return to display such nice formatted progress bars. This will look ugly in the log file.

Body:
I search about this and didn't fine an answer for it.

So my question is not about simple output redirection in Linux shell. I want it to happen inside a bash script I'm writing and I want output and error of anyscripts or commands I run in that script be redirected into separate files.

This is what im currently using:

STATUSFILE=x.out
LOGFILE=x.log
exec > ${STATUSFILE} 2>${LOGFILE}
echo "bla bla"
#some other commands

which works fine for normal outputs. But for example in part of my script I put to my backup server using ftp put. And when I run in manually I see kind of a progress bar saying how much time is passed and how much time its gonna take.

What im trying to do is to capture that kind of output which seems to be updating on the fly and kinda dynamic and currently I get other outputs stored in files but not that kinda dynamic ones.

And another question is if im following a good approach doing this. As I said I want the output and Im gonna use that by another process to see the progress and then use it to inform user trying to run a task with browser.

So for example in my case its uploading a big file into ftp storage which user will command it from browser and I run those scripts and I want to have kind of a progress bar showing up the status to the user. (I know how to handle it on client side - probably a socket connection or interval ajax request checking on a file or an event being triggered by server)

My second question is how should I get the progress of commands that have dynamic output.

If anything is unclear please let me know Ill try to fix it.

Thanks for your help guys.

Body:
Good Morning,

So my question is not about simple output redirection in Linux shell. I want it to happen inside a bash script I'm writing

That is quite simple. You just need to enclose your commands in {}.

#!/bin/bash

{

  echo "hello world!"
  ls -la

} >> script.log

I want output and error of anyscripts or commands I run in that script be redirected into separate files.

You could use tee if the same output should go in seperate files.

#!/bin/bash

{

  echo "hello world!"
  ls -la

} | tee foo bar baz

If the output of different commands should go in different files, you would just use different {} blocks.

My second question is how should I get the progress of commands that have dynamic output.

Some tools tend to put the progress bar to STDERR. You can redirect STDOUT and STDERR to same file using 2>&1. 2 is the descriptor for STDERR, 1 for STDOUT and you are basically appending 2 on 1.

Thus you would rewrite the first script to:

#!/bin/bash

{

  echo "hello world!"
  ls -la

} >> script.log 2>&1

Be carefull with that, though. Some tools use colors and carriage return to display such nice formatted progress bars. This will look ugly in the log file.


答:
You can get the integer value of a digit character by subtracting the zero character from it.

total += numstr[i] - '0';

It is because the 0 character has value equal with 48 in decimal (or 0x30 in hexadecimal), 1 character is equal with 49 in decimal, 2 with 50 and so on..

Subtracting the 0 character from itself, results in 0 (decimal). Subtracting the 0 character from character 1 results in 1 (decimal) and so on..

Title: I want to plus the number form string datatype


问:
Asp.net forms authentication login loop
How do you solve the infinite login loop problem when you are using cookieless sessions and cannot change the name of login.aspx to a httphandler ?

i.e. When a user with admin rights hits the logout button and the return url to a restricted page is passed to login.aspx then another user without admin rights try's to login they get redirected back to the login page.

I have come across this solution but I cannot change the name of login.aspx to a http handler, and the isauthenticated function doesn't seem to work in the aspx page with cookieless auth because the forms auth ticket seems to be stripped from the url when redirected back to the login page.

EDIT:

Because this application is already in production I cannot alter the page flow of the login/logout/timeout process or rename the login page.

答:
Check if the user is authorized to access the page in the returnUrl, after log in on the login.aspx page. You might use this method of the UrlAuthorizationModule (or a custom one if it works best for you):

```<code>System.Web.Security.UrlAuthorizationModule.CheckUrlAccessForPrincipal(

     returnUrl,
     userPrincipal,
     GET");
</code>```

If the user isn't authorized, just redirect to a page that the user can access.

To get the user Principal:

```<code>var roles = System.Web.Security.Roles.GetRolesForUser(username);

var principal = new System.Security.Principal.GenericPrincipal(

   new System.Security.Principal.GenericIdentity(username),

   roles

);
</code>```

OwnerDisplayName: Element

ContentLicense: CC BY-SA 2.5

Title: Asp.net forms authentication login loop

LastEditorDisplayName: Element

Body:
Check if the user is authorized to access the page in the returnUrl, after log in on the login.aspx page. You might use this method of the UrlAuthorizationModule (or a custom one if it works best for you):

System.Web.Security.UrlAuthorizationModule.CheckUrlAccessForPrincipal(

     returnUrl,
     userPrincipal,
     GET");

If the user isn't authorized, just redirect to a page that the user can access.

To get the user Principal:

var roles = System.Web.Security.Roles.GetRolesForUser(username);

var principal = new System.Security.Principal.GenericPrincipal(

   new System.Security.Principal.GenericIdentity(username),

   roles

);

OwnerDisplayName: Freddy Rios

LastEditorDisplayName: Freddy Rios


问:
Scraping with Python?
I'd like to grab all the index words and its definitions from here. Is it possible to scrape web content with Python?

Firebug exploration shows the following URL returns my desirable contents including both index and its definition as to 'a'.

```<code>http://pali.hum.ku.dk/cgi-bin/cpd/pali?acti=xart&arid=14179&sphra=undefined
</code>```

what are the modules used? Is there any tutorial available?

I do not know how many words indexed in the dictionary. I`m absolute beginner in the programming.

答:
You should use urllib2 for gettting the URL contents and BeautifulSoup for parsing the HTML/XML.

Example - retrieving all questions from the StackOverflow.com main page:

```<code>import urllib2
from BeautifulSoup import BeautifulSoup

page = urllib2.urlopen("http://stackoverflow.com")
soup = BeautifulSoup(page)

for incident in soup('h3'):
    print [i.decode('utf8') for i in incident.contents]
    print
</code>```

This code sample was adapted from the BeautifulSoup documentation.

ContentLicense: CC BY-SA 3.0

Title: Scraping with Python?

Body:
I'd like to grab all the index words and its definitions from here. Is it possible to scrape web content with Python?

Firebug exploration shows the following URL returns my desirable contents including both index and its definition as to 'a'.

http://pali.hum.ku.dk/cgi-bin/cpd/pali?acti=xart&arid=14179&sphra=undefined

what are the modules used? Is there any tutorial available?

I do not know how many words indexed in the dictionary. I`m absolute beginner in the programming.

Body:
You should use urllib2 for gettting the URL contents and BeautifulSoup for parsing the HTML/XML.

Example - retrieving all questions from the StackOverflow.com main page:

import urllib2
from BeautifulSoup import BeautifulSoup

page = urllib2.urlopen("http://stackoverflow.com")
soup = BeautifulSoup(page)

for incident in soup('h3'):
    print [i.decode('utf8') for i in incident.contents]
    print

This code sample was adapted from the BeautifulSoup documentation.


问:
What are *.inc files in LLVM build
I am working with a debug build of llvm and writing a pass. It takes about 5-10 minutes to build every time I run 'make'. I see a lot of *.inc files getting build every time. What are those files and how can I make builds go faster?

Thanks

答: You are probably talking about files generated by TableGen utility. This process is slow for you because you've built it in Debug mode, probably. There is a CMake option called LLVM_OPTIMIZED_TABLEGEN to build TableGen in Release mode regardless the build type of all other projects.

Title: What are *.inc files in LLVM build


问:
store arabic in SQL database
I tried to store Arabic string in SQL 2008 database but it converted to " question mark " why ? and what should I do ?</p>

答:
Try using this:

the column Data type is nvarchar()

```<code>INSERT INTO CompanyMaster values(N'" + txtCompNameAR.Text + "',N'" + txtCompAddressAR.Text + "','" + txtPh.Text + "')
</code>```

Title: store arabic in SQL database

Body:
Try using this:

the column Data type is nvarchar()

INSERT INTO CompanyMaster values(N'" + txtCompNameAR.Text + "',N'" + txtCompAddressAR.Text + "','" + txtPh.Text + "')


问:
ireport cannot recognize the table from oracle 11g database
I am a beginner to ireports.I want to create an ireport with oracle 11g using the default tables present in xe. I used EMP table from xe and it showed error ORA-00942 table or view does not exist when i run the query select * from EMP.
Please help!!!</p>

答:
Generally speaking, you should connect to user that contains tables you'd like to use in the report you're creating. So, if it is EMP table and it belongs to Scott, connect as Scott.

By default, its username/password combination is scott/tiger (all lower case). There's a chance that it (user) is locked. If so, connect to the database via SQL*Plus or SQL Developer or any other tool you use (as a privileged user, such as SYS or SYSTEM if there's no other you have - I presume you don't) and do the following:

```<code>alter user scott account unlock;
alter user scott identified by tiger;
</code>```

After that, establish connection to Scott in iReport (providing previously mentioned credentials) and you should be able to query the EMP table.

Body:
Generally speaking, you should connect to user that contains tables you'd like to use in the report you're creating. So, if it is EMP table and it belongs to Scott, connect as Scott.

By default, its username/password combination is scott/tiger (all lower case). There's a chance that it (user) is locked. If so, connect to the database via SQL*Plus or SQL Developer or any other tool you use (as a privileged user, such as SYS or SYSTEM if there's no other you have - I presume you don't) and do the following:

alter user scott account unlock;
alter user scott identified by tiger;

After that, establish connection to Scott in iReport (providing previously mentioned credentials) and you should be able to query the EMP table.


问:
Php keep the modified date of files extracted from the zip
I am using ZipArchive to extract files from zip

Here is the code i am using

```<code>$zip = new ZipArchive;
$res = $zip->open($file);
if ($res === TRUE) {
    $zip->extractTo('test/');
    $zip->close();
}
</code>```

It works fine but the last modified date of extracted files changes to current time.

How i can keep the original last modified date of the extracted files?

答:
In zip archives, the date and time are encoded in standard MS-DOS format (https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT). This means that date and time are according to the local time of the system that created the zip archive.

The mtime returned by statIndex assumes that the local time of the system that created the zip archive was UTC (GMT), which is rarely true.

Body:
I am using ZipArchive to extract files from zip

Here is the code i am using

$zip = new ZipArchive;
$res = $zip->open($file);
if ($res === TRUE) {
    $zip->extractTo('test/');
    $zip->close();
}

It works fine but the last modified date of extracted files changes to current time.

How i can keep the original last modified date of the extracted files?


问:
Consuming HTTPS web service using WCF
I'm trying to consuming a client's web service using WCF. The client's web service is done over HTTPS, and I can consume it fine with the following Binding:

```<code><bindings>
  <basicHttpBinding>
    <binding name="PurchaseOrderSoap" closeTimeout="00:01:00" openTimeout="00:01:00"
        receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false"
        bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
        maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
        messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
        useDefaultWebProxy="true">
      <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
          maxBytesPerRead="4096" maxNameTableCharCount="16384" />
      <security mode="Transport" />
    </binding>
  </basicHttpBinding>
</bindings>
</code>```

However, our security team have told me I need to use Message or TransportWithMessageCredential security, because Fortify 360 complains that Transport security is too weak.

When I try Meesage I get this error:

```<code>System.InvalidOperationException: BasicHttp binding requires that
BasicHttpBinding.Security.Message.ClientCredentialType be equivalent to the
BasicHttpMessageCredentialType.Certificate credential type for secure messages. Select
Transport or TransportWithMessageCredential security for UserName credentials.
</code>```

And with TransportWithMessageCredential I get the following error:

```<code>System.InvalidOperationException: The username is not provided. Specify username in
ClientCredentials.
</code>```

I've not got a username/password (I can connect to it fine in my browser), so my question is:

Can I use Message or TransportWithMessageCredentials when consuming an existing HTTPS web service (without the publisher  making any changes)? If so, what changes do I need to make to my configuration?

Edited to clarify question.

答:
The basicHttpBinding only supports username and certificate message security. So one option is, if you don't have a mechanism for validating user credentials on your sysstem, is to use certificates.

```<code><security mode="TransportWithMessageCredential">
    ...
    <message clientCredentialType="UserName"/>
</security>
</code>```

The other option is to use a different binding, like wsHttpBinding which has message security enabled by default and also supports Windows and Issued Token credential types. Which of these you implement is largely dependent on your implementation requirements and environment.

Title: Consuming HTTPS web service using WCF

Body:
I'm trying to consuming a client's web service using WCF. The client's web service is done over HTTPS, and I can consume it fine with the following Binding:

<bindings>
  <basicHttpBinding>
    <binding name="PurchaseOrderSoap" closeTimeout="00:01:00" openTimeout="00:01:00"
        receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false"
        bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
        maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
        messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
        useDefaultWebProxy="true">
      <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
          maxBytesPerRead="4096" maxNameTableCharCount="16384" />
      <security mode="Transport" />
    </binding>
  </basicHttpBinding>
</bindings>

However, our security team have told me I need to use Message or TransportWithMessageCredential security, because Fortify 360 complains that Transport security is too weak.

When I try Meesage I get this error:

System.InvalidOperationException: BasicHttp binding requires that
BasicHttpBinding.Security.Message.ClientCredentialType be equivalent to the
BasicHttpMessageCredentialType.Certificate credential type for secure messages. Select
Transport or TransportWithMessageCredential security for UserName credentials.

And with TransportWithMessageCredential I get the following error:

System.InvalidOperationException: The username is not provided. Specify username in
ClientCredentials.

I've not got a username/password (I can connect to it fine in my browser), so my question is:

Can I use Message or TransportWithMessageCredentials when consuming an existing HTTPS web service (without the publisher  making any changes)? If so, what changes do I need to make to my configuration?

Edited to clarify question.

Body:
The basicHttpBinding only supports username and certificate message security. So one option is, if you don't have a mechanism for validating user credentials on your sysstem, is to use certificates.

<security mode="TransportWithMessageCredential">
    ...
    <message clientCredentialType="UserName"/>
</security>

The other option is to use a different binding, like wsHttpBinding which has message security enabled by default and also supports Windows and Issued Token credential types. Which of these you implement is largely dependent on your implementation requirements and environment.


问:
Why NotifyCollectionChangedEventArgs has NewItems and OldItems as plural?
I'm new to C# and OOP, just a question on NotifyCollectionChangedEventArgs. I don't understand why it has NewItems and OldItems rather than NewItem and OldItem.
For example, we use ObservableCollection as:

```<code>ObservableCollection<Person> people = new ObservableCollection<Person>()
// Wire up the CollectionChanged event.
people.CollectionChanged += people_CollectionChanged;

static void people_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
   if (e.Action == NotifyCollectionChangedAction.Add)
   {
     foreach (Person p in e.NewItems)
     {
        Console.WriteLine(p.ToString());
     }
   }

}
</code>```

so each time we add a new Person in the collection as:

```<code>people.Add(new Person("John", "Smith", 32));
</code>```

CollectionChanged trigger people_CollectionChanged, so e.NewItems will only contain one person (the one I just added), so what's the point to assume e.NewItems could have more than one item as it always can only have one item?

答:
The event you're subscribing to is actually defined by the INotifyCollectionChanged interface, and implemented by ObservableCollection.

While ObservableCollection doesn't have methods for adding multiple items at once, it does have a ClearItems method, which could remove multiple items at once. That's one reason I can think of for having plural names, since they could contain more than one item.

Also, since it's an interface, it could be implemented by other classes that do implement something like AddRange or RemoveWhere, etc. methods, which would again raise this event with multiple items.

Body:
I'm new to C# and OOP, just a question on NotifyCollectionChangedEventArgs. I don't understand why it has NewItems and OldItems rather than NewItem and OldItem.
For example, we use ObservableCollection as:

ObservableCollection<Person> people = new ObservableCollection<Person>()
// Wire up the CollectionChanged event.
people.CollectionChanged += people_CollectionChanged;

static void people_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
   if (e.Action == NotifyCollectionChangedAction.Add)
   {
     foreach (Person p in e.NewItems)
     {
        Console.WriteLine(p.ToString());
     }
   }

}

so each time we add a new Person in the collection as:

people.Add(new Person("John", "Smith", 32));

CollectionChanged trigger people_CollectionChanged, so e.NewItems will only contain one person (the one I just added), so what's the point to assume e.NewItems could have more than one item as it always can only have one item?


问:
EFOError when trying to connect Pyftpsync to remote server on port 22
I am trying to sync two folders via FTP, yes I know there are better or different ways but for now I need to implement it this way, I was trying the example code from pyftpsync since well, a sample code should work easily right? I am just trying to connect between some test folders I made, one is empty(local) and the remote has a single text file that I want to fetch. It tries to connect but after about 2 minutes I get this error.

Well, my FTP  does work outside of python. I can connect over WinSCP just fine.

Some places mentioned that a proxy could possibly cause this, but it seems I am not behind a proxy currently, but maybe I did not set that properly and it believes there should be a proxy somehow?

Here is my code, just using commands on the prompt for pyftpsync produces the same errors for me. So it is possible some input parameter is off causing all of this.

import time
import os
import re
import shutil
import string
import sys

from ftpsync.targets import FsTarget
from ftpsync.ftp_target import FtpTarget
from ftpsync.synchronizers import DownloadSynchronizer

#synchronize a local folder with ftp

local = FsTarget( "C:\\testfolder\\"  )
user = "login"
passwd = "password"
remote = FtpTarget("/my/folder/location/testfold/", "126.0.0.1",port=22, username=user,password=passwd,tls=False,timeout=None,extra_opts=None)
opts = {}
s=DownloadSynchronizer(local, remote, opts)
s.run()
```
<p>This is the output I am getting, I have edited out the folder names and IP addresses.</p>
<pre class="lang-none prettyprint-override"><code>INFO:keyring.backend:Loading KWallet
INFO:keyring.backend:Loading SecretService
INFO:keyring.backend:Loading Windows
INFO:keyring.backend:Loading chainer
INFO:keyring.backend:Loading macOS
INFO:pyftpsync:Download to C:\testfolder
                from ftp://126.0.0.1/.../testfold
INFO:pyftpsync:Encoding local: utf-8, remote: utf-8
Traceback (most recent call last):
  File "c:\..\.py", line 30, in <module>
    s.run()
  File "C:\\AppData\Local\Programs\Python\Python37-32\lib\site-
packages\ftpsync\synchronizers.py", line 1268, in run
  res = super(DownloadSynchronizer, self).run()
  File "C:\\AppData\Local\Programs\Python\Python37-
  32\lib\site-packages\ftpsync\synchronizers.py", line 827, in run
  res = super(BiDirSynchronizer, self).run()
  File "C:\\AppData\Local\Programs\Python\Python37-
  32\lib\site-packages\ftpsync\synchronizers.py", line 211, in run
  self.remote.open()
  File "C:\\AppData\Local\Programs\Python\Python37-
  32\lib\site-packages\ftpsync\ftp_target.py", line 141, in open
  self.ftp.connect(self.host, self.port)
  File "C:\\AppData\Local\Programs\Python\Python37-
  32\lib\ftplib.py", line 155, in connect
  self.welcome = self.getresp()
  File "C:\\Local\Programs\Python\Python37-
  32\lib\ftplib.py", line 236, in getresp
  resp = self.getmultiline()
  File "C:\\AppData\Local\Programs\Python\Python37-
  32\lib\ftplib.py", line 226, in getmultiline
  nextline = self.getline()
  File "C:\\AppData\Local\Programs\Python\Python37-
  32\lib\ftplib.py", line 210, in getline
  raise EOFError
  EOFError
</code>```

Anyways any possible troubleshooting ideas would help. Thank you.

答:
Pyftpsync uses FTP protocol.

You are connecting to port 22, which is used for SSH/SFTP.

So if your server is actually SFTP server, not FTP server, you cannot use Pyftpsync with it.

Body:
I am trying to sync two folders via FTP, yes I know there are better or different ways but for now I need to implement it this way, I was trying the example code from pyftpsync since well, a sample code should work easily right? I am just trying to connect between some test folders I made, one is empty(local) and the remote has a single text file that I want to fetch. It tries to connect but after about 2 minutes I get this error.

Well, my FTP  does work outside of python. I can connect over WinSCP just fine.

Some places mentioned that a proxy could possibly cause this, but it seems I am not behind a proxy currently, but maybe I did not set that properly and it believes there should be a proxy somehow?

Here is my code, just using commands on the prompt for pyftpsync produces the same errors for me. So it is possible some input parameter is off causing all of this.

import time
import os
import re
import shutil
import string
import sys

from ftpsync.targets import FsTarget
from ftpsync.ftp_target import FtpTarget
from ftpsync.synchronizers import DownloadSynchronizer

#synchronize a local folder with ftp

local = FsTarget( "C:\\testfolder\\"  )
user = "login"
passwd = "password"
remote = FtpTarget("/my/folder/location/testfold/", "126.0.0.1",port=22, username=user,password=passwd,tls=False,timeout=None,extra_opts=None)
opts = {}
s=DownloadSynchronizer(local, remote, opts)
s.run()

This is the output I am getting, I have edited out the folder names and IP addresses.

INFO:keyring.backend:Loading KWallet
INFO:keyring.backend:Loading SecretService
INFO:keyring.backend:Loading Windows
INFO:keyring.backend:Loading chainer
INFO:keyring.backend:Loading macOS
INFO:pyftpsync:Download to C:\testfolder
                from ftp://126.0.0.1/.../testfold
INFO:pyftpsync:Encoding local: utf-8, remote: utf-8
Traceback (most recent call last):
  File "c:\..\.py", line 30, in <module>
    s.run()
  File "C:\\AppData\Local\Programs\Python\Python37-32\lib\site-
packages\ftpsync\synchronizers.py", line 1268, in run
  res = super(DownloadSynchronizer, self).run()
  File "C:\\AppData\Local\Programs\Python\Python37-
  32\lib\site-packages\ftpsync\synchronizers.py", line 827, in run
  res = super(BiDirSynchronizer, self).run()
  File "C:\\AppData\Local\Programs\Python\Python37-
  32\lib\site-packages\ftpsync\synchronizers.py", line 211, in run
  self.remote.open()
  File "C:\\AppData\Local\Programs\Python\Python37-
  32\lib\site-packages\ftpsync\ftp_target.py", line 141, in open
  self.ftp.connect(self.host, self.port)
  File "C:\\AppData\Local\Programs\Python\Python37-
  32\lib\ftplib.py", line 155, in connect
  self.welcome = self.getresp()
  File "C:\\Local\Programs\Python\Python37-
  32\lib\ftplib.py", line 236, in getresp
  resp = self.getmultiline()
  File "C:\\AppData\Local\Programs\Python\Python37-
  32\lib\ftplib.py", line 226, in getmultiline
  nextline = self.getline()
  File "C:\\AppData\Local\Programs\Python\Python37-
  32\lib\ftplib.py", line 210, in getline
  raise EOFError
  EOFError

Anyways any possible troubleshooting ideas would help. Thank you.


问:
How to install php-redis extension using the official PHP Docker image approach?
I want to build my PHP-FPM image with php-redis extension based on the official PHP Docker image, for example, using this Dockerfile: php:5.6-fpm.

The docs say that I can install extensions this way, installing dependencies for extensions manually:

```<code>FROM php:5.6-fpm
# Install modules (iconv, mcrypt and gd extensions)
RUN apt-get update && apt-get install -y \
        libfreetype6-dev \
        libjpeg62-turbo-dev \
        libmcrypt-dev \
        libpng12-dev \
    && docker-php-ext-install iconv mcrypt \
    && docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/ \
    && docker-php-ext-install gd
CMD ["php-fpm"]
</code>```

Without Docker, I installed it with apt-get install php5-redis. But how can I install it using the approach above?

答:
This works for alpine images:

```<code>RUN set -xe \
    && apk add --no-cache --update --virtual .phpize-deps $PHPIZE_DEPS \
    && pecl install -o -f redis  \
    && echo "extension=redis.so" > /usr/local/etc/php/conf.d/redis.ini \
    && rm -rf /usr/share/php \
    && rm -rf /tmp/* \
    && apk del  .phpize-deps
</code>```

Edit: Added missing backslash

Body:
I want to build my PHP-FPM image with php-redis extension based on the official PHP Docker image, for example, using this Dockerfile: php:5.6-fpm.

The docs say that I can install extensions this way, installing dependencies for extensions manually:

FROM php:5.6-fpm
# Install modules (iconv, mcrypt and gd extensions)
RUN apt-get update && apt-get install -y \
        libfreetype6-dev \
        libjpeg62-turbo-dev \
        libmcrypt-dev \
        libpng12-dev \
    && docker-php-ext-install iconv mcrypt \
    && docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/ \
    && docker-php-ext-install gd
CMD ["php-fpm"]

Without Docker, I installed it with apt-get install php5-redis. But how can I install it using the approach above?

Body:
This works for alpine images:

RUN set -xe \
    && apk add --no-cache --update --virtual .phpize-deps $PHPIZE_DEPS \
    && pecl install -o -f redis  \
    && echo "extension=redis.so" > /usr/local/etc/php/conf.d/redis.ini \
    && rm -rf /usr/share/php \
    && rm -rf /tmp/* \
    && apk del  .phpize-deps

Edit: Added missing backslash


问:
C++ Exception bypassing catch on clang/llvm
I have a unit test like this:

```<code>TEST_F( SocketServerTest, ParseTest ) {
  try {
//    throw InvalidAddressException( "bla" );
//    auto x = dv::socket::parseEndpoint( "127.0.0.1" );
    EXPECT_THROW( auto x = dv::socket::parseEndpoint( "127.0.0.1" ), InvalidAddressException );
  } catch ( const InvalidAddressException &e ) {
    FAIL() << boost::diagnostic_information( e, true );
  } catch ( const std::exception &e ) {
    FAIL() << boost::diagnostic_information( e, true );
  } catch ( ... ) {
    FAIL() << "bla";
  }
}
</code>```

That works with GCC and MSVC but with clang somehow the exception is caught by the default google test catch and I get

```<code>unknown file: Failure
C++ exception with description "Invalid address 127.0.0.1 no port number" thrown in the test body.
</code>```

If I throw the exception directly in the test it works, if I call the code without the EXPECT_THROW it hits the default c++ exception handler and aborts the program.

It does the same thing on apple clang & clang 8 on osx, and clang 7 on fedora 29 but works with gcc on fedora 29 and msvc 2019 on win 10

The exception is in a shared library and is defined using preprocessor macros and cmake generated header file to do the visibility attributes.

Other exceptions that are defined in the same way work in other places and the same exception works when thrown from different code in the same library.

Ive tried pulling just this code out into a standalone cmake project but can't get it to fail in the same way

How can I debug why this is happening, I've been at it for days with no progress.

答: After writing all that I realized I had attribute((pure)) on parseEndpoint removing that and it all works.

Body:
I have a unit test like this:

TEST_F( SocketServerTest, ParseTest ) {
  try {
//    throw InvalidAddressException( "bla" );
//    auto x = dv::socket::parseEndpoint( "127.0.0.1" );
    EXPECT_THROW( auto x = dv::socket::parseEndpoint( "127.0.0.1" ), InvalidAddressException );
  } catch ( const InvalidAddressException &e ) {
    FAIL() << boost::diagnostic_information( e, true );
  } catch ( const std::exception &e ) {
    FAIL() << boost::diagnostic_information( e, true );
  } catch ( ... ) {
    FAIL() << "bla";
  }
}

That works with GCC and MSVC but with clang somehow the exception is caught by the default google test catch and I get

unknown file: Failure
C++ exception with description "Invalid address 127.0.0.1 no port number" thrown in the test body.

If I throw the exception directly in the test it works, if I call the code without the EXPECT_THROW it hits the default c++ exception handler and aborts the program.

It does the same thing on apple clang & clang 8 on osx, and clang 7 on fedora 29 but works with gcc on fedora 29 and msvc 2019 on win 10

The exception is in a shared library and is defined using preprocessor macros and cmake generated header file to do the visibility attributes.

Other exceptions that are defined in the same way work in other places and the same exception works when thrown from different code in the same library.

Ive tried pulling just this code out into a standalone cmake project but can't get it to fail in the same way

How can I debug why this is happening, I've been at it for days with no progress.


问:
How to convert LinkedHasMap Values into ArrayList/Array in right order?
I'm getting LinkedHashMap grades = courses.get(choise).getGrades();

I need to save the grades values in an array/arraylist.

I'm able to get values and keys in loop

```<code>String key = "";
String value = "";
for (Object o : grades.keySet()){
  key = o.toString();
  value = grades.get(o).toString();
}
</code>```

And print it like so

```<code>System.out.println("Grades: " + value);
</code>```

Example output is

```<code>Grades:[0, 3, 2, 5, 3]
</code>```

My goal is to have each grade separated in an array/list.

答:
The first thing you have to sort out, is the raw type:

```<code>LinkedHashMap grades = courses.get(choise).getGrades();
</code>```

You need the generic type on the variable type, even if you just use ?:

```<code>LinkedHashMap<?, ?> grades = courses.get(choise).getGrades();
</code>```

but if you know a more specific type than ?, you can use that - it looks from the question like your keys at least are Strings.

Then:

```<code>List<String> list =
    grades.values().stream()
        .map(Object::toString)
        .collect(Collectors.toList());
</code>```

Body:
I'm getting LinkedHashMap grades = courses.get(choise).getGrades();

I need to save the grades values in an array/arraylist.

I'm able to get values and keys in loop

String key = "";
String value = "";
for (Object o : grades.keySet()){
  key = o.toString();
  value = grades.get(o).toString();
}

And print it like so

System.out.println("Grades: " + value);

Example output is

Grades:[0, 3, 2, 5, 3]

My goal is to have each grade separated in an array/list.

Body:
The first thing you have to sort out, is the raw type:

LinkedHashMap grades = courses.get(choise).getGrades();

You need the generic type on the variable type, even if you just use ?:

LinkedHashMap<?, ?> grades = courses.get(choise).getGrades();

but if you know a more specific type than ?, you can use that - it looks from the question like your keys at least are Strings.

Then:

List<String> list =
    grades.values().stream()
        .map(Object::toString)
        .collect(Collectors.toList());


问:
Error when using IncludeFilter with Async; IncludeFilter does not support Async
I am using Include Filter to filter the include results but i am getting an error regarding IncludeFilter does not support Async</p>
```<code> public async Task<Voter> GetVoterById (int VoterId, int OrganzationId)
 {
 var Voter = await _context.Voters.Where (v => v.Id == VoterId).IncludeFilter
 (v => v.VotingYears.Where (y => y.OrganizationId ==
 OrganzationId)).FirstOrDefaultAsync ();
 return Voter;
 }
</code>```

答:
The easiest solution was to remove IncludeFilter</p>
```<code>var Voter = await _context.Voters.Where (v => v.Id == VoterId).Include(v => v.VotingYears).FirstOrDefaultAsync ();
Voter.VotingYears = Voter.VotingYears.Where (y => y.OrganizationId == OrganzationId);
return Voter;
</code>```

Body:
I am using Include Filter to filter the include results but i am getting an error regarding IncludeFilter does not support Async

 public async Task<Voter> GetVoterById (int VoterId, int OrganzationId)
 {
 var Voter = await _context.Voters.Where (v => v.Id == VoterId).IncludeFilter
 (v => v.VotingYears.Where (y => y.OrganizationId ==
 OrganzationId)).FirstOrDefaultAsync ();
 return Voter;
 }

Body:
The easiest solution was to remove IncludeFilter

var Voter = await _context.Voters.Where (v => v.Id == VoterId).Include(v => v.VotingYears).FirstOrDefaultAsync ();
Voter.VotingYears = Voter.VotingYears.Where (y => y.OrganizationId == OrganzationId);
return Voter;


问:
How to write this constraint in Gurobipy?
I am writing a linear program using Gurobipy and I am having trouble writing one of the constraints. I am confused about how to sum over the < 0 inequality.

The constraint is as follows: https://imgur.com/a/FP0aAKl

I have already initialized the variables xC and xP (I call this xPone). The parameter B has also already been defined and is contained in a dictionary called B. I refer to m̂ as mone.

This is my current code:

```<code>m = Model('LP')

m.addConstrs((xC_smp[s,m,p] == - quicksum (B[(s,n,m,p)] * xPone_slnmonep[s,l,n,mone,p])
                                       for m in materials for s in sites for l in lines
                                       for n in versions for p in periods for mone in materialones
                                       if B[(s,n,m,p)] < 0), name='c7')
</code>```

This currently returns an empty set {}. I expect there to be some values in there. I would really appreciate if someone could point out the problem. Thanks.

答:
This can be work:</p>

```<code>m.addConstrs( quicksum((xC_smp[s,m,p] for m in materials for s in sites for p in periods))  ==
            - quicksum ((B[(s,n,m,p)] * xPone_slnmonep[s,l,n,mone,p] for m in materials
                               for s in sites for l in lines for n in versions
                               for p in periods for mone in materialones
                                   if B[(s,n,m,p)] < 0), name='c7')
</code>```

Body:
I am writing a linear program using Gurobipy and I am having trouble writing one of the constraints. I am confused about how to sum over the < 0 inequality.

The constraint is as follows: https://imgur.com/a/FP0aAKl

I have already initialized the variables xC and xP (I call this xPone). The parameter B has also already been defined and is contained in a dictionary called B. I refer to m̂ as mone.

This is my current code:

m = Model('LP')

m.addConstrs((xC_smp[s,m,p] == - quicksum (B[(s,n,m,p)] * xPone_slnmonep[s,l,n,mone,p])
                                       for m in materials for s in sites for l in lines
                                       for n in versions for p in periods for mone in materialones
                                       if B[(s,n,m,p)] < 0), name='c7')

This currently returns an empty set {}. I expect there to be some values in there. I would really appreciate if someone could point out the problem. Thanks.

Body:
This can be work:

m.addConstrs( quicksum((xC_smp[s,m,p] for m in materials for s in sites for p in periods))  ==
            - quicksum ((B[(s,n,m,p)] * xPone_slnmonep[s,l,n,mone,p] for m in materials
                               for s in sites for l in lines for n in versions
                               for p in periods for mone in materialones
                                   if B[(s,n,m,p)] < 0), name='c7')


问:
How to select a Dev Spaces controller in Azure AKS
I'm setting up a testing environment and want to deploy our services to a k8s cluster using Dev Spaces.

Following this tutorial i got stuck when trying to run the code. After running the cmd "azds up" i got the error "No Azure Dev Spaces controller is selected. Run 'az aks use-dev-spaces' to get started."

Unfortunatelly this doesn't solve this issue. There is a controller in the Resource group in Azure which also contain the AKS and in the AKS, Dev Spaces is activated.

Any suggestions to at least come closer to a solution?

答:
For some reason i had to manually select the controller and the space using the CLI.</p>

```<code>azds controller select -g <resourceGroup> -n <controllerName>
azds space select
</code>```

Body:
For some reason i had to manually select the controller and the space using the CLI.

azds controller select -g <resourceGroup> -n <controllerName>
azds space select


问:
Override eloquent relationship result data
I use Laravel-Metable package in my project. This package return collection object using in key meta name and on value eloquent object.

Here you can see package data result screenshot.

How I can override result data and get this type of array data:

```<code>$meta = [
    [
        'id' => 1,
        'key' => "Meta Name",
        'value' => "Meta Value"

    ],

    [
        'id' => 2,
        'key' => "Meta Name",
        'value' => "Meta Value"

    ],
];
</code>```

I will load my models meta with lazy loading:

```<code>use Metable;

protected $with = ['meta'];
</code>```

答:
You can use the collection map method for that so it should be something like this:</p>

```<code>$result = $metaItems->map(function($meta) {
    return [
        'id' => $meta->id,
        'key' => $meta->key,
        'value' => $meta->value
    ];
})->values();

// then $result->toArray(); should give you the expected result
</code>```

Body:
I use Laravel-Metable package in my project. This package return collection object using in key meta name and on value eloquent object.

Here you can see package data result screenshot.

How I can override result data and get this type of array data:

$meta = [
    [
        'id' => 1,
        'key' => "Meta Name",
        'value' => "Meta Value"

    ],

    [
        'id' => 2,
        'key' => "Meta Name",
        'value' => "Meta Value"

    ],
];

I will load my models meta with lazy loading:

use Metable;

protected $with = ['meta'];

Body:
You can use the collection map method for that so it should be something like this:

$result = $metaItems->map(function($meta) {
    return [
        'id' => $meta->id,
        'key' => $meta->key,
        'value' => $meta->value
    ];
})->values();

// then $result->toArray(); should give you the expected result


问:
How to send an email template to multiple users (email addresses) in Odoo 12
I want to send an email to multiple users in Odoo 12 when a scheduler runs with custom data in email. I created my email template in the XML file. Also, I have a method which returns all my email addresses as a list. How can I loop over this list in email template in "email_to" field and get all email addresses and send the email to all of those emails?

Following is my email template:

```<code><?xml version="1.0" encoding="utf-8"?>
<odoo>
    <data noupdate="1">
        <record id="repayment_due_date_reminder_email_template" model="mail.template">
            <field name="name">Repayment Due Date Reminder Email Template</field>
            <field name="email_from">admin@netlinks.af</field>
            <field name="subject">Repayment Due Date Reminder</field>
            <field name="email_to">${for email in object.get_groups_usesr_email():
                                        }</field>
            <field name="lang">${object.lang}</field>
            <field name="model_id" ref="hr_payroll_advance_salary.model_loan_request"/>
            <field name="body_html">
                <![CDATA[
                <p>The following loan installment is due for repayment:<br/>
                Loan Recepient: ${(object.employee_id.name)}<br/>
                Total Loan Amount: ${(object.loan_amount)} ${(object.currency)} <br/>
                Installment Due: ${(object.loan_amount)} ${(object.currency)} <br/>
                Repayment Date: ${(object.repayment_schedule_ids.repayment_date)} <br/>
                You can view the loan record here for further details </p>
                ]]>
            </field>
        </record>
    </data>
</odoo>
</code>```

I call the email template using the below code:

```<code>template_rec = self.env.ref('hr_payroll_advance_salary.repayment_due_date_reminder_email_template')
template_rec.send_mail(loan.id, force_send=True)
</code>```

And this is the method which returns emails:

```<code>@api.multi
    def get_groups_usesr_email(self):
        emails = []
        user_ids = self.get_users_from_groups('group_nl_finance_manager')
        emails = self.get_users_email('group_nl_finance_manager', user_ids)
        user_ids = self.get_users_from_groups('group_nl_ceo')
        new_emails = self.get_users_email('group_nl_ceo', user_ids)
        for email in new_emails:
            emails.append(email)
        return emails
</code>```

I'm doing the above things in order to send an email to all users of two different groups and I am not sure if it's the appropriate way or not. Is it possible to do what I want to do or not or it can be done using another way?

答:
I sent the email template to all the email addresses using a loop on emails with below code and that works fine in my case.</p>

```<code>all_eamils = loan.get_groups_usesr_email()
    for email in all_eamils:
        template_rec = self.env.ref('hr_payroll_advance_salary.repayment_due_date_reminder_email_template')
        template_rec.write({'email_to': email})
        template_rec.send_mail(loan.id, force_send=True)
</code>```

Body:
I want to send an email to multiple users in Odoo 12 when a scheduler runs with custom data in email. I created my email template in the XML file. Also, I have a method which returns all my email addresses as a list. How can I loop over this list in email template in "email_to" field and get all email addresses and send the email to all of those emails?

Following is my email template:

<?xml version="1.0" encoding="utf-8"?>
<odoo>
    <data noupdate="1">
        <record id="repayment_due_date_reminder_email_template" model="mail.template">
            <field name="name">Repayment Due Date Reminder Email Template</field>
            <field name="email_from">admin@netlinks.af</field>
            <field name="subject">Repayment Due Date Reminder</field>
            <field name="email_to">${for email in object.get_groups_usesr_email():
                                        }</field>
            <field name="lang">${object.lang}</field>
            <field name="model_id" ref="hr_payroll_advance_salary.model_loan_request"/>
            <field name="body_html">
                <![CDATA[

The following loan installment is due for repayment:

                Loan Recepient: ${(object.employee_id.name)}

                Total Loan Amount: ${(object.loan_amount)} ${(object.currency)}

                Installment Due: ${(object.loan_amount)} ${(object.currency)}

                Repayment Date: ${(object.repayment_schedule_ids.repayment_date)}

                You can view the loan record here for further details

                ]]>
            </field>
        </record>
    </data>
</odoo>

I call the email template using the below code:

template_rec = self.env.ref('hr_payroll_advance_salary.repayment_due_date_reminder_email_template')
template_rec.send_mail(loan.id, force_send=True)

And this is the method which returns emails:

@api.multi
    def get_groups_usesr_email(self):
        emails = []
        user_ids = self.get_users_from_groups('group_nl_finance_manager')
        emails = self.get_users_email('group_nl_finance_manager', user_ids)
        user_ids = self.get_users_from_groups('group_nl_ceo')
        new_emails = self.get_users_email('group_nl_ceo', user_ids)
        for email in new_emails:
            emails.append(email)
        return emails

I'm doing the above things in order to send an email to all users of two different groups and I am not sure if it's the appropriate way or not. Is it possible to do what I want to do or not or it can be done using another way?

Body:
I sent the email template to all the email addresses using a loop on emails with below code and that works fine in my case.

all_eamils = loan.get_groups_usesr_email()
    for email in all_eamils:
        template_rec = self.env.ref('hr_payroll_advance_salary.repayment_due_date_reminder_email_template')
        template_rec.write({'email_to': email})
        template_rec.send_mail(loan.id, force_send=True)


问:
Implement asynchronous calls in .NET Remoting
I want to implement async call in .NET remoting. The remoting service is consumed by a windows application ( dont ask me why not WCF. This is a legacy application). Is there any standard procedures, standard patterns to implement.</p>

答: Here you go: http://msdn.microsoft.com/en-us/library/0sa925ka.aspx</p>


问:
md-table - How to update the column width
I have started using the md-table for my project, and I want fixed column width. Currently all columns width are divided into equal size.

Where can I get the documentation of data table dimensions?

https://material.angular.io/components/table/overview

答:
you can using fxFlex from "@angular/flex-layout" in th and td like this:

```<code><ng-container matColumnDef="value">
      <th mat-header-cell fxFlex="15%" *matHeaderCellDef>Value</th>
            <td mat-cell *matCellDef="let element" fxFlex="15%" fxLayoutAlign="start center">
                           {{'value'}}
            </td>
       </th>
</ng-container>
</code>```

Body:
you can using fxFlex from "@angular/flex-layout" in th and td like this:

<ng-container matColumnDef="value">
      <th mat-header-cell fxFlex="15%" *matHeaderCellDef>Value</th>
            <td mat-cell *matCellDef="let element" fxFlex="15%" fxLayoutAlign="start center">
                           {{'value'}}
            </td>
       </th>
</ng-container>


问:
Is calling a "private" variable from a parent class (as a child class) violating Encapsulation
I am trying to understand more about the scopes of python variables.

As of now, I do not want to break or violate encapsulation on variables that are declared to be private i.e., "self._variable".

I was wondering whether if it would be breaking encapsulation if a child class directly calls a variable from its parent class. For example:

```<code>class Parent:
    def __init__():
        self._randomVariable = ''
class Child(Parent):
    def__init__():
        super().__init__()
    def doSomething():
        self._randomVariable = 'Test'
</code>```

Does Chid.doSomething() technically break encapsulation for directly calling self._randomVariable in its method even if it is a child class?

I couldn't find anything that was Python specific about encapsulation but rather stuff based on Java. Is it the same idea between Java and Python?

答:
Encapsulation is not as big of a deal in Python as it is in most other languages (Java, C++, et cetera), and you really shouldn't worry about it too much. In the Python community, we have this principle that "we are all consenting adults here".

What this means is that it's on your responsibility if you go and mess around with someone else's code, but also don't prevent others from messing with your code if they really know what they're doing. For this reason, there isn't really private and protected in Python, and you shouldn't worry about them the same way you do in Java.

But as it's become clear by now, there is still some sort of privacy with underscores. So, what are they usually used for?

Single underscore prefixed variables (e.g. self._var)

These are used for both private and protected variables. Prefixing your variable with an underscore is (mostly) a convention, which simply tells the reader that "this variable is used internally by this class, and should not be accessed from the outside". Well, if your subclasses need it, they may still use it. And if you need it from outside of the class, you may still use it. But it's on your responsibility, make sure you don't break anything.

There are some other minor effects too, such as from module import * not importing underscore prefixed variables, but the convention of privacy is the main point.

Double underscore prefixed variables (e.g. self.__var)

Also known as "dunder" (double-under) variables, these are used for name mangling. The idea is that if you have a common variable name and you're afraid that subclasses might use the same variable name for their internal stuff, you can use double underscore prefix to secure your variable from being overwritten accidentally. This way your self.__var becomes self._BaseClassName__var, and your subclass's self.__var becomes self._SubClassName__var. Now they won't overlap.

And while the effect can be used to simulate other languages' private, I recommend you not to. Again, we are all consenting adults here, just mark your variable "private" with a single underscore, and I won't touch it unless I really know what I'm doing.

Body:
I am trying to understand more about the scopes of python variables.

As of now, I do not want to break or violate encapsulation on variables that are declared to be private i.e., "self._variable".

I was wondering whether if it would be breaking encapsulation if a child class directly calls a variable from its parent class. For example:

class Parent:
    def __init__():
        self._randomVariable = ''
class Child(Parent):
    def__init__():
        super().__init__()
    def doSomething():
        self._randomVariable = 'Test'

Does Chid.doSomething() technically break encapsulation for directly calling self._randomVariable in its method even if it is a child class?

I couldn't find anything that was Python specific about encapsulation but rather stuff based on Java. Is it the same idea between Java and Python?


答:
You don't have to worry about the order. Whether you obtain the values() or keySet() or entrySet() from the LinkedHashMap, the iteration order of any of them would be according to the insertion order into the LinkedHashMap.

Putting the values in a List is as simple as:

```<code>List<SomeType> grades = new ArrayList<>(grades.values());
</code>```

Of course, for that to work you have to change LinkedHashMap grades to LinkedHashMap grades<KeyType,SomeType>.

Title: How to convert LinkedHasMap Values into ArrayList/Array in right order?

Body:
You don't have to worry about the order. Whether you obtain the values() or keySet() or entrySet() from the LinkedHashMap, the iteration order of any of them would be according to the insertion order into the LinkedHashMap.

Putting the values in a List is as simple as:

List<SomeType> grades = new ArrayList<>(grades.values());

Of course, for that to work you have to change LinkedHashMap grades to LinkedHashMap grades<KeyType,SomeType>.


问:
How to save the list in to .txt?
I have to save 'Record' into text file. So I have tried to use name_error_record.write( record[0]+"   "+record[1]+"   "+record[2]+"   "+record[3]) but it doesn't work...

I have to align as 'No   Menu_name Num Total' and save it into text file. please help..

The list that I have to save is [['No.', 'Menu_name', 'Num', 'Total'], ['4', 'Smoothie_queen', '4', '12000'], ['10', 'Amorparty', '2', '4000'], ['24', 'Plane_yougurt', '14', '49000'], ['36', 'Cofe_latte', '18', '45000'], ['51', 'Cofe_latte', '16', '40000'], ['53', 'Berry_smudie', '17', '51000'], ['54', 'American_air', '4', '8000']]

and also it has to be aligned by columns as 'No    Menu name    Num   Total'.
I think I am missing something but I can't find them.. help T.T

```<code>def error_check(date):
    #========= STEP 3 ==========
    Record = []
    errormenu = []
    recordfile = open("ledger_"+date+".txt","r")
    errormenufile = open("menu.txt", "r")

    for error in errormenufile:
        menu = error.split()
        errormenu.append(menu[0])

    errormenufile.close()

    for line in recordfile:
        record = line.split()
        Record.append(record)

        Record = [x for x in Record if errormenu[0] not in x]
        Record = [x for x in Record if errormenu[1] not in x]
        Record = [x for x in Record if errormenu[2] not in x]
        Record = [x for x in Record if errormenu[3] not in x]
        Record = [x for x in Record if errormenu[4] not in x]

    name_error_record = open("ledger_"+date+"_name_error.txt","r")

    for record in Record:
        name_error_record.write( record[0]+"   "+record[1]+"   "+record[2]+"   "+record[3])

    name_error_record.close()
    #========= STEP 3 ==========
</code>```

Title: How to save the list in to .txt?

Body:
I have to save 'Record' into text file. So I have tried to use name_error_record.write( record[0]+"   "+record[1]+"   "+record[2]+"   "+record[3]) but it doesn't work...

I have to align as 'No   Menu_name Num Total' and save it into text file. please help..

The list that I have to save is [['No.', 'Menu_name', 'Num', 'Total'], ['4', 'Smoothie_queen', '4', '12000'], ['10', 'Amorparty', '2', '4000'], ['24', 'Plane_yougurt', '14', '49000'], ['36', 'Cofe_latte', '18', '45000'], ['51', 'Cofe_latte', '16', '40000'], ['53', 'Berry_smudie', '17', '51000'], ['54', 'American_air', '4', '8000']]

and also it has to be aligned by columns as 'No    Menu name    Num   Total'.
I think I am missing something but I can't find them.. help T.T

def error_check(date):
    #========= STEP 3 ==========
    Record = []
    errormenu = []
    recordfile = open("ledger_"+date+".txt","r")
    errormenufile = open("menu.txt", "r")

    for error in errormenufile:
        menu = error.split()
        errormenu.append(menu[0])

    errormenufile.close()

    for line in recordfile:
        record = line.split()
        Record.append(record)

        Record = [x for x in Record if errormenu[0] not in x]
        Record = [x for x in Record if errormenu[1] not in x]
        Record = [x for x in Record if errormenu[2] not in x]
        Record = [x for x in Record if errormenu[3] not in x]
        Record = [x for x in Record if errormenu[4] not in x]

    name_error_record = open("ledger_"+date+"_name_error.txt","r")

    for record in Record:
        name_error_record.write( record[0]+"   "+record[1]+"   "+record[2]+"   "+record[3])

    name_error_record.close()
    #========= STEP 3 ==========

Body:
l=[['No.', 'Menu_name', 'Num', 'Total'], ['4', 'Smoothie_queen', '4', '12000'], ['10', 'Amorparty', '2', '4000'], ['24', 'Plane_yougurt', '14', '49000'], ['36', 'Cofe_latte', '18', '45000'], ['51', 'Cofe_latte', '16', '40000'], ['53', 'Berry_smudie', '17', '51000'], ['54', 'American_air', '4', '8000']]
filename='' # add filenmae
with open(filename, 'w+') as file:
    for i in l:
        file.write('{} {} {} {}\n'.format(*i))


问:
Problem running ng serve command on Windows 10. This question is different and it is not duplicate
I am unable to run ng serve command on Windows 10

I have successfully installed npm and node

I am trying to install angular on Windows 10.

1- My node version is

```<code>node -v
v10.16.0
</code>```

and npm version is

```<code>npm -v
6.9.0
</code>```

After running command of angular cli which is

```<code>npm install -g @angular/cli
</code>```

I am not able to run ng serve command. It show this error

```<code>'ng' is not recognized as an internal or external command,
operable program or batch file.
</code>```

I have looked some online solutions which says to set 'PATH` but my path npm folder is empty

```<code>
C:\Users\shaha\AppData\Roaming\npm
</code>```

I have tried many times uninstallation and installation of nodejs but I am unable to run ng serve command. Please help me to solve this issue.

答:
Run the following the command to know npm default path

npm config get prefix

If the path is different than AppData/npm then change it

npm config set prefix "$APPDATA\npm"

And again run npm config get prefix to get current path then set it to Environment Variables and restart the system

You will need to log out then log back in for the change to your PATH variable to take effect.

Body:
I am unable to run ng serve command on Windows 10

I have successfully installed npm and node

I am trying to install angular on Windows 10.

1- My node version is

node -v
v10.16.0

and npm version is

npm -v
6.9.0

After running command of angular cli which is

npm install -g @angular/cli

I am not able to run ng serve command. It show this error

'ng' is not recognized as an internal or external command,
operable program or batch file.

I have looked some online solutions which says to set 'PATH` but my path npm folder is empty

C:\Users\shaha\AppData\Roaming\npm

I have tried many times uninstallation and installation of nodejs but I am unable to run ng serve command. Please help me to solve this issue.


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

Create the POCO EntityClasses for each table like this:

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

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

Create the Mappings with FluentHibernate like this:

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

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

Create the Fluent Config like this:

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

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

Do a SchemaExport to Create the Schema with:

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

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

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

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

Could someone help me?

答:
Sqlite in memory only exists for the life time of the connection. So for each new connection you need to start from the beginning.

I know two solutions for this. One is to only use a single session (and connection) for the unit tests. The other is what I did: I implemented a connection provider which always returns the same connection.

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

Create the POCO EntityClasses for each table like this:

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

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

Create the Mappings with FluentHibernate like this:

using Database.Entitites;
using FluentNHibernate.Mapping;

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

Create the Fluent Config like this:

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

            sessionFactory = Config.BuildSessionFactory();

Do a SchemaExport to Create the Schema with:

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

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

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

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

Could someone help me?


问:
ActiveRecord Query Union
I've written a couple of complex queries (at least to me) with Ruby on Rail's query interface:

```<code>watched_news_posts = Post.joins(:news => :watched).where(:watched => {:user_id => id})
watched_topic_posts = Post.joins(:post_topic_relationships => {:topic => :watched}).where(:watched => {:user_id => id})
</code>```

Both of these queries work fine by themselves.  Both return Post objects.  I would like to combine these posts into a single ActiveRelation.  Since there could be hundreds of thousands of posts at some point, this needs to be done at the database level.  If it were a MySQL query, I could simply user the UNION operator.  Does anybody know if I can do something similar with RoR's query interface?

答:
Heres how I joined SQL queries using UNION on my own ruby on rails application.

You can use the below as inspiration on your own code.

```<code>class Preference < ApplicationRecord
  scope :for, ->(object) { where(preferenceable: object) }
end
</code>```

Below is the UNION where i joined the scopes together.

```<code>  def zone_preferences
    zone = Zone.find params[:zone_id]
    zone_sql = Preference.for(zone).to_sql
    region_sql = Preference.for(zone.region).to_sql
    operator_sql = Preference.for(Operator.current).to_sql

    Preference.from("(#{zone_sql} UNION #{region_sql} UNION #{operator_sql}) AS preferences")
  end
</code>```

Title: ActiveRecord Query Union

Body:
I've written a couple of complex queries (at least to me) with Ruby on Rail's query interface:

watched_news_posts = Post.joins(:news => :watched).where(:watched => {:user_id => id})
watched_topic_posts = Post.joins(:post_topic_relationships => {:topic => :watched}).where(:watched => {:user_id => id})

Both of these queries work fine by themselves.  Both return Post objects.  I would like to combine these posts into a single ActiveRelation.  Since there could be hundreds of thousands of posts at some point, this needs to be done at the database level.  If it were a MySQL query, I could simply user the UNION operator.  Does anybody know if I can do something similar with RoR's query interface?

Body:
Heres how I joined SQL queries using UNION on my own ruby on rails application.

You can use the below as inspiration on your own code.

class Preference < ApplicationRecord
  scope :for, ->(object) { where(preferenceable: object) }
end

Below is the UNION where i joined the scopes together.

  def zone_preferences
    zone = Zone.find params[:zone_id]
    zone_sql = Preference.for(zone).to_sql
    region_sql = Preference.for(zone.region).to_sql
    operator_sql = Preference.for(Operator.current).to_sql

    Preference.from("(#{zone_sql} UNION #{region_sql} UNION #{operator_sql}) AS preferences")
  end


问:
Spring boot logbcak to file is not working on tomcat
I am running spring boot as War on tomcat with logback to console and file.

as long as i run as Java application it is fine i can see logs in console and file.
but i dont see logs printed to file when run on server.

I tried setting logger manager also, didnt work. was wondering to know if some one has faced similar issue.

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/defaults.xml" />
    <include resource="org/springframework/boot/logging/logback/file-appender.xml" />
    <property name="LOG_FILE"
     value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}/}app.log}"/>
    <property name="LOG_FILE_MAX_SIZE" value="10MB" />
    <property name="LOG_TOTAL_SIZE_CAP" value="100MB" />
    <property name="LOG_FILE_MAX_HISTORY" value="20" />
    <root level="INFO">
        <appender-ref ref="FILE" />
    </root>
</configuration>
</code>```

答:
Verify that you have the following dependency :

```<code><dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>
</code>```

or even if you have spring-boot-starter-web dependency added, logging should work.
and have the following in yml or properties file :

```<code>logging.path=logs
logging.file=${logging.path}/log.log
logging.pattern.file=%d{dd-MM-yyyy HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M - %msg%n
</code>```

and you can also have a logback.xml and use the spring default base.xml in that so that all default spring configurations apply for your logging as well :

logback.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/base.xml"/>
    <logger name="org.springframework.web" level="DEBUG"/>
</configuration>
</code>```

Body:
I am running spring boot as War on tomcat with logback to console and file.

as long as i run as Java application it is fine i can see logs in console and file.
but i dont see logs printed to file when run on server.

I tried setting logger manager also, didnt work. was wondering to know if some one has faced similar issue.

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/defaults.xml" />
    <include resource="org/springframework/boot/logging/logback/file-appender.xml" />
    <property name="LOG_FILE"
     value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}/}app.log}"/>
    <property name="LOG_FILE_MAX_SIZE" value="10MB" />
    <property name="LOG_TOTAL_SIZE_CAP" value="100MB" />
    <property name="LOG_FILE_MAX_HISTORY" value="20" />
    <root level="INFO">
        <appender-ref ref="FILE" />
    </root>
</configuration>

Body:
Verify that you have the following dependency :

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>

or even if you have spring-boot-starter-web dependency added, logging should work.
and have the following in yml or properties file :

logging.path=logs
logging.file=${logging.path}/log.log
logging.pattern.file=%d{dd-MM-yyyy HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M - %msg%n

and you can also have a logback.xml and use the spring default base.xml in that so that all default spring configurations apply for your logging as well :

logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/base.xml"/>
    <logger name="org.springframework.web" level="DEBUG"/>
</configuration>


问:
numpy slice assign to another value
Suppose I have a 1D numpy array:

```<code> arr = np.arange(10)
</code>```

Then I slice arr and assign to another variable:

```<code> arr2 = arr[5:8]
</code>```

And I want to change arr :

```<code> arr2 *= 10
</code>```

or:

```<code> arr2 = arr2 * 10
</code>```

The results are different. Why are they different?

```<code> arr
</code>```

array([ 0,  1,  2,  3,  4, 50, 60, 70,  8,  9])

```<code> arr
</code>```

array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

答:
In simplified terms, arr2 = arr[5:8] assigns a reference to the 5:7th elements of arr to a variable arr2.

Thus the operation arr2 *= 10 boils down to "multiply those elements by 10 in place", which modifies arr in place (you are performing an in-place operation, a modification, on a reference, which therefore affects the original).

However, arr2 = arr2 * 10 says "take the result of multiplying the 5:7th elements by 10, then assign it to a variable called arr2". Here, you perform an operation on a reference (not a modification), take the output (to be explicit, the operation arr2 * 10 returns a new object), and assign it to arr2, which incidentally destroys the original reference (but this part is somewhat irrelevant).

Or compare these:

```<code>arr[5:8] *= 10
arr[5:8] = arr[5:8] * 10
arr2 = arr[5:8] * 10
</code>```

The first two are equivalent. Your code is essentially a comparison between the first and the third (equivalently, the second and third). The second and third are not equal, because in your code, your earlier assignment of arr2 = arr[5:8] has nothing to do with the LHS of arr2 = arr[5:8] * 10.

Title: numpy slice assign to another value

Body:
Suppose I have a 1D numpy array:

 arr = np.arange(10)

Then I slice arr and assign to another variable:

 arr2 = arr[5:8]

And I want to change arr :

 arr2 *= 10

or:

 arr2 = arr2 * 10

The results are different. Why are they different?

 arr

array([ 0,  1,  2,  3,  4, 50, 60, 70,  8,  9])

 arr

array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

Body:
In simplified terms, arr2 = arr[5:8] assigns a reference to the 5:7th elements of arr to a variable arr2.

Thus the operation arr2 *= 10 boils down to "multiply those elements by 10 in place", which modifies arr in place (you are performing an in-place operation, a modification, on a reference, which therefore affects the original).

However, arr2 = arr2 * 10 says "take the result of multiplying the 5:7th elements by 10, then assign it to a variable called arr2". Here, you perform an operation on a reference (not a modification), take the output (to be explicit, the operation arr2 * 10 returns a new object), and assign it to arr2, which incidentally destroys the original reference (but this part is somewhat irrelevant).

Or compare these:

arr[5:8] *= 10
arr[5:8] = arr[5:8] * 10
arr2 = arr[5:8] * 10

The first two are equivalent. Your code is essentially a comparison between the first and the third (equivalently, the second and third). The second and third are not equal, because in your code, your earlier assignment of arr2 = arr[5:8] has nothing to do with the LHS of arr2 = arr[5:8] * 10.


问:
create multidimensional json array from a json in php
I have a json data. Now I want to reform it. In my json data there is a property like person_on_zone I want to make a property named person_info and store them which person under this area.

Here is my data any code. Thanks in advance

My json data

```<code>$val = [
    {
     'city':'xx',
     'zone':'yy',
     'person_on_zone':'p1'
    },
    {
     'city':'xx',
     'zone':'yy',
     'person_on_zone':'p2'
    },
    {
     'city':'xx',
     'zone':'yy',
     'person_on_zone':'p3'
    },
    {
     'city':'xx',
     'zone':'ww',
     'person_on_zone':'p1'
    },
  ]
</code>```

My expectation is

```<code>[
 {
  'city':'xx',
  'zone':'yy',
  'person_info':{
                  'person_on_zone':'p1',
                  'person_on_zone':'p2',
                  'person_on_zone':'p3',
                }
 },
 {
  'city':'xx',
  'zone':'ww',
  'person_info':{
                  'person_on_zone':'p1'
                }
 },
]
</code>```

Here I tried

```<code>foreach ($val as $v) {
    $new_array['city'] = $v['city'];
    $new_array['zone'] = $v['zone'];
    foreach ($val as $v2) {
        $new_array['person_info'] = $v['person_on_zone'];
    }
}
json_encode($new_array);
</code>```

答:
One simple foreach would do,

```<code>$result = [];
foreach ($arr as $key => $value) {
    //created unique combination of city and zone as key
    $result[$value['city'] . $value['zone']]['city']          = $value['city'];
    $result[$value['city'] . $value['zone']]['zone']          = $value['zone'];
    $result[$value['city'] . $value['zone']]['person_info'][] = ['person_on_zone' => $value['person_on_zone']];
}
echo json_encode(array_values($result));die;
</code>```

array_values — Return all the values of an array

Working demo.

Body:
I have a json data. Now I want to reform it. In my json data there is a property like person_on_zone I want to make a property named person_info and store them which person under this area.

Here is my data any code. Thanks in advance

My json data

$val = [
    {
     'city':'xx',
     'zone':'yy',
     'person_on_zone':'p1'
    },
    {
     'city':'xx',
     'zone':'yy',
     'person_on_zone':'p2'
    },
    {
     'city':'xx',
     'zone':'yy',
     'person_on_zone':'p3'
    },
    {
     'city':'xx',
     'zone':'ww',
     'person_on_zone':'p1'
    },
  ]

My expectation is

[
 {
  'city':'xx',
  'zone':'yy',
  'person_info':{
                  'person_on_zone':'p1',
                  'person_on_zone':'p2',
                  'person_on_zone':'p3',
                }
 },
 {
  'city':'xx',
  'zone':'ww',
  'person_info':{
                  'person_on_zone':'p1'
                }
 },
]

Here I tried

foreach ($val as $v) {
    $new_array['city'] = $v['city'];
    $new_array['zone'] = $v['zone'];
    foreach ($val as $v2) {
        $new_array['person_info'] = $v['person_on_zone'];
    }
}
json_encode($new_array);

Body:
One simple foreach would do,

$result = [];
foreach ($arr as $key => $value) {
    //created unique combination of city and zone as key
    $result[$value['city'] . $value['zone']]['city']          = $value['city'];
    $result[$value['city'] . $value['zone']]['zone']          = $value['zone'];
    $result[$value['city'] . $value['zone']]['person_info'][] = ['person_on_zone' => $value['person_on_zone']];
}
echo json_encode(array_values($result));die;

array_values — Return all the values of an array

Working demo.


问:
What is the problem with putting brackets("(") in a printf code
I've just started C-Programming and have a question on the following code.

```<code>#include <stdio.h>

int main(void)
{
    int num1, num2, num3;
    int result;

        printf("(num1 - num2) x (num2 + num3) x (num3 % num1) \n");
    printf("Insert 3 numbers: ");
    scanf("%d %d %d", &num1, &num2, &num3);

    result = (num1 - num2) * (num2 + num3) * (num3 % num1);
    printf("Answer: %d ", result);
    return 0;
}
</code>```

An Error occurs whenever I put the following single line of code:

```<code>  printf("(num1 - num2) x (num2 + num3) x (num3 % num1) \n");
</code>```

The reason I put this in was because I wanted to print this equation, but an error occurs whenever I put this in. The error message seems to say that there is a problem in the usage of brackets, but I don't get why putting brackets becomes a problem.

I expect the output to be,

```<code>  (num1 - num2) x (num2 + num3) x (num3 % num1)
  Insert 3 numbers:
</code>```

But the Following Error occurs:

"Debug Assertion Failed"

...

Expression: "("'n' format specifier disabled",')

答:
It's not about the parenthesis, it's about the %. For printf() format string, % character has a special meaning.

From C11, chapter §7.21.6.1

[...] The format is composed of zero or more directives: ordinary multibyte
  characters (not %), which are copied unchanged to the output stream; and conversion
  specifications, each of which results in fetching zero or more subsequent arguments,
  converting them, if applicable, according to the corresponding conversion specifier, and
  then writing the result to the output stream.

and

Each conversion specification is introduced by the character %. [...]

So, to print a % character itself, you need to put another % as the conversion specifier. From the list of conversion specifiers, (paragraph 8 in the same spec)

%    A % character is written. No argument is converted. The complete
  conversion specification shall be %%.

Body:
I've just started C-Programming and have a question on the following code.

#include <stdio.h>

int main(void)
{
    int num1, num2, num3;
    int result;

        printf("(num1 - num2) x (num2 + num3) x (num3 % num1) \n");
    printf("Insert 3 numbers: ");
    scanf("%d %d %d", &num1, &num2, &num3);

    result = (num1 - num2) * (num2 + num3) * (num3 % num1);
    printf("Answer: %d ", result);
    return 0;
}

An Error occurs whenever I put the following single line of code:

  printf("(num1 - num2) x (num2 + num3) x (num3 % num1) \n");

The reason I put this in was because I wanted to print this equation, but an error occurs whenever I put this in. The error message seems to say that there is a problem in the usage of brackets, but I don't get why putting brackets becomes a problem.

I expect the output to be,

  (num1 - num2) x (num2 + num3) x (num3 % num1)
  Insert 3 numbers:

But the Following Error occurs:

"Debug Assertion Failed"

...

Expression: "("'n' format specifier disabled",')


问:
Setting drop down value in unity with a string
Does anyone know how to set  the dropdownUI value with a string in unity?

I know how to set it up with an int like these

```<code>public DropDown dropdown;

dropdown.value = 1;
</code>```

However, what I want is to set the value with a given string.

Something like:

```<code>dropdown.value = "an Option";
</code>```

答:
We can't add string value to the dropdown value field. So if you need to show an option having the given string then use FindIndex option to find that option in the dropdown and then assign that index to the value field.</p>
```<code>dropdown.value = dropdown.options.FindIndex(option => option.text == "an Option");
</code>```

Body:
Does anyone know how to set  the dropdownUI value with a string in unity?

I know how to set it up with an int like these

public DropDown dropdown;

dropdown.value = 1;

However, what I want is to set the value with a given string.

Something like:

dropdown.value = "an Option";

Body:
We can't add string value to the dropdown value field. So if you need to show an option having the given string then use FindIndex option to find that option in the dropdown and then assign that index to the value field.

dropdown.value = dropdown.options.FindIndex(option => option.text == "an Option");