问:
How to use crosstab or pivote in mysql query to get month names dynamicaly?
I have table named user_plan_dtl with the columns userid, plan description and contact date. I want count of users in each month according to plan description. And month should get selected only within a given date range.
I have database in mysql.

Below is the table user_plan_dtl

```<code>userid        contactdate  plandesc
USR001           March       ICMA
USR003           March       ICMA
USR004           April       FTDA
USR005           April       FTDA
USR006           April       FTDA
USR007           April       ICMA
USR008           April       ICMA
USR009           May         FTDA
USR002           May         FTDA
USR001           May         ICMA
</code>```

I want output like :

```<code> Count    March  April  May
 Total     2      5      3
 FTDA      0      3      2
 ICMA      2      2      1
</code>```

I have tried with below query but I am getting output for all the months.

```<code>select  d.Plandesc as AssignedUsers, max(d.January) as January,max(d.February) as February,max(d.March) as March,
max(d.April) as April ,max(d.May)as May,max(d.June)as June,
max(d.July) as July,max(d.August)as August,max(d.September) as September,
max(d.October)as October,max(d.November) as November ,max(d.December)as December from
(Select Plandesc,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='January' THEN userid END )) AS January,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='February' THEN userid END )) AS February,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='March' THEN userid END )) AS March,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='April' THEN userid END )) AS April,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='May' THEN userid END )) AS May,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='June' THEN userid END )) AS June,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='July' THEN userid END )) AS July,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='August' THEN userid END )) AS August,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='September' THEN userid END )) AS September,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='October' THEN userid END )) AS October,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='November' THEN userid END )) AS November,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='December' THEN userid END )) AS December
from user_plan_dtl
where Plandesc in ('FTDA','ICMA')
and DATE_FORMAT(contactdate, '%Y-%m-%d') >= '2017-01-01' and DATE_FORMAT(contactdate, '%Y-%m-%d') <= '2017-07-05'
group by  MONTHNAME(contactdate),Plandesc
union all
Select 'Total' as Plandesc,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='January' THEN userid END )) AS January,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='February' THEN userid END )) AS February,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='March' THEN userid END )) AS March,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='April' THEN userid END )) AS April,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='May' THEN userid END )) AS May,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='June' THEN userid END )) AS June,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='July' THEN userid END )) AS July,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='August' THEN userid END )) AS August,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='September' THEN userid END )) AS September,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='October' THEN userid END )) AS October,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='November' THEN userid END )) AS November,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='December' THEN userid END )) AS December
from user_plan_dtl
where Plandesc in ('FTDA','ICMA')
and DATE_FORMAT(contactdate, '%Y-%m-%d') >= '2017-01-01' and DATE_FORMAT(contactdate, '%Y-%m-%d') <= '2017-07-05'
group by  MONTHNAME(contactdate)
) as d group by d.Plandesc order by case when d.Plandesc = 'Total' then 0 else 1 end,d.Plandesc
</code>```

Can anyone plaese provide me the solution for this? Thanks in advance.

答:
Use CONCAT and GROUP_CONCAT to construct complex queries.

```<code>set @sql=NULL;
select group_concat(distinct concat(
  ' COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)="',c_month,
     '" THEN userid END )) AS "',c_month,'"') separator ',')
  from (select distinct contactdate as c_month from user_plan_dtl) t into @sql;
select @sql;
</code>```

(note that I've used contactdate from the data you posted here as a month, not as a date)

This will give you a string in the variable @sql:

```<code>COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)="March" THEN userid END ))
    AS "March",
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)="April" THEN userid END ))
    AS "April",
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)="May" THEN userid END ))
    AS "May"
</code>```

Then you can manipulate this string

```<code>set @sql=concat('SELECT ',@sql);
select @sql;
</code>```

and so on. (hint: create another variable for the whole statement and concatenate it with @sql). Finally you have to prepare and execute this sql statement:

```<code>PREPARE stmnt from @sql;
EXECUTE stmnt;
DEALLOCATE stmnt;
</code>```

Body:
I have table named user_plan_dtl with the columns userid, plan description and contact date. I want count of users in each month according to plan description. And month should get selected only within a given date range.
I have database in mysql.

Below is the table user_plan_dtl

userid        contactdate  plandesc
USR001           March       ICMA
USR003           March       ICMA
USR004           April       FTDA
USR005           April       FTDA
USR006           April       FTDA
USR007           April       ICMA
USR008           April       ICMA
USR009           May         FTDA
USR002           May         FTDA
USR001           May         ICMA

I want output like :

 Count    March  April  May
 Total     2      5      3
 FTDA      0      3      2
 ICMA      2      2      1

I have tried with below query but I am getting output for all the months.

select  d.Plandesc as AssignedUsers, max(d.January) as January,max(d.February) as February,max(d.March) as March,
max(d.April) as April ,max(d.May)as May,max(d.June)as June,
max(d.July) as July,max(d.August)as August,max(d.September) as September,
max(d.October)as October,max(d.November) as November ,max(d.December)as December from
(Select Plandesc,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='January' THEN userid END )) AS January,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='February' THEN userid END )) AS February,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='March' THEN userid END )) AS March,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='April' THEN userid END )) AS April,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='May' THEN userid END )) AS May,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='June' THEN userid END )) AS June,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='July' THEN userid END )) AS July,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='August' THEN userid END )) AS August,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='September' THEN userid END )) AS September,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='October' THEN userid END )) AS October,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='November' THEN userid END )) AS November,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='December' THEN userid END )) AS December
from user_plan_dtl
where Plandesc in ('FTDA','ICMA')
and DATE_FORMAT(contactdate, '%Y-%m-%d') >= '2017-01-01' and DATE_FORMAT(contactdate, '%Y-%m-%d') <= '2017-07-05'
group by  MONTHNAME(contactdate),Plandesc
union all
Select 'Total' as Plandesc,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='January' THEN userid END )) AS January,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='February' THEN userid END )) AS February,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='March' THEN userid END )) AS March,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='April' THEN userid END )) AS April,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='May' THEN userid END )) AS May,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='June' THEN userid END )) AS June,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='July' THEN userid END )) AS July,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='August' THEN userid END )) AS August,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='September' THEN userid END )) AS September,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='October' THEN userid END )) AS October,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='November' THEN userid END )) AS November,
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)='December' THEN userid END )) AS December
from user_plan_dtl
where Plandesc in ('FTDA','ICMA')
and DATE_FORMAT(contactdate, '%Y-%m-%d') >= '2017-01-01' and DATE_FORMAT(contactdate, '%Y-%m-%d') <= '2017-07-05'
group by  MONTHNAME(contactdate)
) as d group by d.Plandesc order by case when d.Plandesc = 'Total' then 0 else 1 end,d.Plandesc

Can anyone plaese provide me the solution for this? Thanks in advance.

Body:
Use CONCAT and GROUP_CONCAT to construct complex queries.

set @sql=NULL;
select group_concat(distinct concat(
  ' COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)="',c_month,
     '" THEN userid END )) AS "',c_month,'"') separator ',')
  from (select distinct contactdate as c_month from user_plan_dtl) t into @sql;
select @sql;

(note that I've used contactdate from the data you posted here as a month, not as a date)

This will give you a string in the variable @sql:

COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)="March" THEN userid END ))
    AS "March",
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)="April" THEN userid END ))
    AS "April",
COUNT(DISTINCT(CASE WHEN MONTHNAME(contactdate)="May" THEN userid END ))
    AS "May"

Then you can manipulate this string

set @sql=concat('SELECT ',@sql);
select @sql;

and so on. (hint: create another variable for the whole statement and concatenate it with @sql). Finally you have to prepare and execute this sql statement:

PREPARE stmnt from @sql;
EXECUTE stmnt;
DEALLOCATE stmnt;


来源: stackexchange

问:
static code analysis tool to Verifone terminals
Which is the best static code analysis tool to use in the verifone POS projects?
Does it have any particularity or I can use any C analysis tool like SonarQube?</p>

答:
Nope, nothing special that would prevent any standard C / C++ static analysis tool from working.  I don't know anything about SonarQube specifically, but I've used Klockwork in the past and I run ReSharper C++ currently.  In both cases, there was a bit of configuration that needed to be done for it to work properly, but in the end, it worked.

NOTE that the VeriFone terminals use ARM processors, so if your tool was built in such a way that it was specific to the x86/x64 architectures, then you may have some difficulties, but I don't think that will generally be a problem.  If I remember correctly, Klockwork stumbled on this and I had to get their tech support involved to get it configured to build for ARM... like I said, if I remember correctly--it was several years ago.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
How can i solve a first order deferential using python that has another function in it?
My problem is sort of like this
and this one combined but not quite. Anyway what im trying to do is take a double integral of a function using sympy to get the symbolic answer. The problem is that inside the derivative element and the integrals thereare 2 other functions and im not sure how to show that they are functions and not just constants. Here is what i have so far.

```<code>from sympy import *
import sympy as sp
sp.init_printing()

x=sp.Symbol('x') #a and k are constants
z=sp.Symbol('z')
k=sp.Symbol('k')
f=sp.Function('f')(x)
l=sp.Function('l')(x)

def dN(x,z):
    return -N*f*z**(a-2)

def b(x,z):
    return l*x*dN

def c(x,z):
    return z*l*x*dN

res=integrate(b,(z,k,float('inf')),(x,0,float('inf')))
sp.pprint (res)
#print(b)
</code>```

This is what im using for dN:

This is the integral im trying to preform to get eqn 12:

Any help would be much appreciated.

答:
It looks like there might be some confusion between sympy functions and python functions. When you define b(x, z) that is a python function. When you refer to b in your integrate line you should supply the variables that are needed for the function, hence integrate(b(x, z)...). The same applies for dN that is called in functions b and c without args. (It should be ...*dN(x, z). In the dN function you define, you refer to N but don't define it. I would recommend that at the top you define N = sp.Function('N')(x, z). Finally, you can use sp.oo to refer to infinity rather than creating a floating point representation of the same.

Sorry I can't test it here. Hopefully these suggestions will help you get on track! :-)

Body:
My problem is sort of like this
and this one combined but not quite. Anyway what im trying to do is take a double integral of a function using sympy to get the symbolic answer. The problem is that inside the derivative element and the integrals thereare 2 other functions and im not sure how to show that they are functions and not just constants. Here is what i have so far.

from sympy import *
import sympy as sp
sp.init_printing()

x=sp.Symbol('x') #a and k are constants
z=sp.Symbol('z')
k=sp.Symbol('k')
f=sp.Function('f')(x)
l=sp.Function('l')(x)

def dN(x,z):
    return -N*f*z**(a-2)

def b(x,z):
    return l*x*dN

def c(x,z):
    return z*l*x*dN

res=integrate(b,(z,k,float('inf')),(x,0,float('inf')))
sp.pprint (res)
#print(b)

This is what im using for dN:

This is the integral im trying to preform to get eqn 12:

Any help would be much appreciated.


问:
How to make a variable globally accessible in Prestashop
I'm modifying a module in Prestashop, which has folder structure like this..

```<code>css
translations
index.php
module.php
module.tpl
</code>```

There is a variable $products that has an array of all the products. But it's only accessible to module.tpl which displays all the product on the homepage which I don't like.

I created a controller that redirects to a different page and a template/view/front/products.tpl to display all the products. But that $products variable is undefined in products.tpl file.

答:
If you have created a new controller with a new template, you need to create in this controller this variable and assign this to a template, so:

In the initContent() function of the controller you need to create the variable "$products" with the values that you need, for example:

```<code>$products = Product::getProducts($id_lang, 0, 0, 'id_product', 'DESC' );
</code>```

Then, you need to assign this php variable to a Smarty variable to show the value in the tpl file. To do this we use the method used by "@Ravinder Pal" but changing the value:

```<code>$this->context->smarty->assign('products', $products);
</code>```

And finally you can use this variable in the template that is assigned in the initContent() function with this:

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

Hope it helps you.

Body:
I'm modifying a module in Prestashop, which has folder structure like this..

css
translations
index.php
module.php
module.tpl

There is a variable $products that has an array of all the products. But it's only accessible to module.tpl which displays all the product on the homepage which I don't like.

I created a controller that redirects to a different page and a template/view/front/products.tpl to display all the products. But that $products variable is undefined in products.tpl file.

Body:
If you have created a new controller with a new template, you need to create in this controller this variable and assign this to a template, so:

In the initContent() function of the controller you need to create the variable "$products" with the values that you need, for example:

$products = Product::getProducts($id_lang, 0, 0, 'id_product', 'DESC' );

Then, you need to assign this php variable to a Smarty variable to show the value in the tpl file. To do this we use the method used by "@Ravinder Pal" but changing the value:

$this->context->smarty->assign('products', $products);

And finally you can use this variable in the template that is assigned in the initContent() function with this:

{$products}

Hope it helps you.


问:
Replace the whole announcemnt for "double tap to activate when talkback enabled
After enabling Talkback and clicking one of the elements view in my app, the announcement is reciting:

The description that I included, pauses, then it recites: "double tap to activate".

I used Accessibility delegate from the example that I found here:
https://stackoverflow.com/a/39480983/5544859

But it's only replacing the last word for me instead of the whole sentence.

For example, it's saying: Bla Bla bla. (pauses), then double tap to "custom string"

I would like to replace the whole sentence.

答: This phrase is coming from TalkBack and is not configurable by design. TalkBack is trying to provide a consistent user experience across all apps.</p>


问:
Joomla JImage & SP Simple Portfolio: Copying and rename file without manipulating it?
I have problems with Image compression in Joomla JImage with the SP Simple Portfolio Plugin, because the images are doubled in size on the hard drive compared to the original. But createThumbs() is not necessary. The pictures have already the right pixelratio and don't need any further manipulation.

Is there a way to copy the pictures, like SP does, without manipulating it? Just copying the file and rename it. Because i don't want to chance all the php Code of the plugin. This would be the easy solution. Just copying it to a directory and rename it to the right filename. JImage toFile() didn't worked because the size is doubled as well...

From original SP Simple Portfolio Code in controller/thumbs.php:

```<code>$image = new JImage($image);
$image->createThumbs($sizes, $cropratio, $path);
</code>```

答:
Did it by myself and it works like charme :). Maybe someone is interested in how to get an 1:1 image copy in the SP Portfolio:

```<code>            $resultTemp = end(explode('/',$image));
            $result = str_replace('.jpg', '', $resultTemp) ;

            $newName  = $path.'/'.$result.'_1000x750.jpg';
            copy($image , $newName);
</code>```

Instead of original code which manipulates the picture quality and size:

```<code>            $image = new JImage($image);
            $image->createThumbs($sizes, $cropratio, $path);
</code>```

Body:
I have problems with Image compression in Joomla JImage with the SP Simple Portfolio Plugin, because the images are doubled in size on the hard drive compared to the original. But createThumbs() is not necessary. The pictures have already the right pixelratio and don't need any further manipulation.

Is there a way to copy the pictures, like SP does, without manipulating it? Just copying the file and rename it. Because i don't want to chance all the php Code of the plugin. This would be the easy solution. Just copying it to a directory and rename it to the right filename. JImage toFile() didn't worked because the size is doubled as well...

From original SP Simple Portfolio Code in controller/thumbs.php:

$image = new JImage($image);
$image->createThumbs($sizes, $cropratio, $path);

Body:
Did it by myself and it works like charme :). Maybe someone is interested in how to get an 1:1 image copy in the SP Portfolio:

            $resultTemp = end(explode('/',$image));
            $result = str_replace('.jpg', '', $resultTemp) ;

            $newName  = $path.'/'.$result.'_1000x750.jpg';
            copy($image , $newName);

Instead of original code which manipulates the picture quality and size:

            $image = new JImage($image);
            $image->createThumbs($sizes, $cropratio, $path);


问:
Keras/TensorFlow: How do I transform text to use as input?
I've been reading tutorials for the last few days, but they all seem to start at the step of "I have my data from this pre-prepared data set, let's go".

What I'm trying to do is take a set of emails I've tokenized, and figure out how to get them into a model as the training and evaluation data.

Example email:

```<code>0 0 0 0 0 0 0 0 0 0 0 0 32192 6675 16943 1380 433 8767 2254 8869 8155
</code>```

I have a folder of emails (one file per email) for each spam and not spam:

```<code>/spam/
    93451.txt
    ...
/not-spam/
    112.txt
    ...
</code>```

How can I get Keras to read this data?

Alternatively, how can I generate a CSV or some other format that it wants to use to input it?

答:
There are many ways to do this, but ill try in this order:

You need to create dictionary of all the words in dataset and then assign a token for each of them. When inputing to the network you can convert it into a one-hot encoded form.

You can convert the input text by feeding it to a pretrained word embeddings model like glove or word-2-vec and obtain a embeddings vector.

You can use the one-hot vector from 1 and train your own embeddings.

Body:
I've been reading tutorials for the last few days, but they all seem to start at the step of "I have my data from this pre-prepared data set, let's go".

What I'm trying to do is take a set of emails I've tokenized, and figure out how to get them into a model as the training and evaluation data.

Example email:

0 0 0 0 0 0 0 0 0 0 0 0 32192 6675 16943 1380 433 8767 2254 8869 8155

I have a folder of emails (one file per email) for each spam and not spam:

/spam/
    93451.txt
    ...
/not-spam/
    112.txt
    ...

How can I get Keras to read this data?

Alternatively, how can I generate a CSV or some other format that it wants to use to input it?


问:
Javascript on first page load or after certain times of reloading, not reproducible with "clear caches"
I try to debugg a JavaScript error which mostly happens on the first load page

```<code>2017-06-27 10:05:12.480 /static/version1498550705/frontend/Example/default/en_US/Ves_ImageSlider/js/owl.carousel.min.js:1 Uncaught TypeError: Cannot read property 'fn' of undefined
    at /static/version1498550705/frontend/Example/default/en_US/Ves_ImageSlider/js/owl.carousel.min.js:1
    at /static/version1498550705/frontend/Example/default/en_US/Ves_ImageSlider/js/owl.carousel.min.js:1
2017-06-27 10:05:12.548 (index):285 Uncaught TypeError: owl.owlCarousel is not a function
    at HTMLDocument.<anonymous> ((index):285)
    at fire (jquery.js:3232)
    at Object.fireWith [as resolveWith] (jquery.js:3362)
    at ready (jquery.js:3582)
</code>```

This question is not so much about the error itself - it is properly to broad.

I am just asking how I can try to reproduce this bug properly to tackle it.

Clearing cache and Inkognito window does not really help to reproduce this.
But it happens more often then only sometimes.

How can I debug such a "Heisenbug" ?

EDIT: The problem might be random in around 10% probability ... when hitting F5 (no cache clear) a number of times, it happens like every third time.. Still hard to debug. Maybe a timing issue?

答:
At the end of the day, the problem was require js where two libraries were loaded, the second one depending on Jquery. I was able to fix it with a shim configuration.

See also RequireJS order of dependencies

Body:
I try to debugg a JavaScript error which mostly happens on the first load page

2017-06-27 10:05:12.480 /static/version1498550705/frontend/Example/default/en_US/Ves_ImageSlider/js/owl.carousel.min.js:1 Uncaught TypeError: Cannot read property 'fn' of undefined
    at /static/version1498550705/frontend/Example/default/en_US/Ves_ImageSlider/js/owl.carousel.min.js:1
    at /static/version1498550705/frontend/Example/default/en_US/Ves_ImageSlider/js/owl.carousel.min.js:1
2017-06-27 10:05:12.548 (index):285 Uncaught TypeError: owl.owlCarousel is not a function
    at HTMLDocument.<anonymous> ((index):285)
    at fire (jquery.js:3232)
    at Object.fireWith [as resolveWith] (jquery.js:3362)
    at ready (jquery.js:3582)

This question is not so much about the error itself - it is properly to broad.

I am just asking how I can try to reproduce this bug properly to tackle it.

Clearing cache and Inkognito window does not really help to reproduce this.
But it happens more often then only sometimes.

How can I debug such a "Heisenbug" ?

EDIT: The problem might be random in around 10% probability ... when hitting F5 (no cache clear) a number of times, it happens like every third time.. Still hard to debug. Maybe a timing issue?


问:
Background image using the background-image property not appearing so not able to get the desired display
I am new to html/css and I do not understand why my background image is not showing up over the button in the search box on the right. I want to display an image of magnifying glass over the right button in the search box?

.sbox {
  width: 297.297px;
  height: 25px;
  background-color: rgba (0, 0, 0, 0);
  font-family: Helvetica, Arial, sans-serif;
  font-size: 14px;
  font-stretch: normal;
  font-style: normal;
  font-variant-caps: normal;
  font-variant-ligatures: normal;
  font-variant-numeric: normal;
  font-weight: normal;
  cursor: auto;
  position: relative;

}

.fb {
  background: url("../img/mag.png") no-repeat 0 0;
  background-size: 50px 50px;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

  <head>
    <link rel="stylesheet" href="css/facebook.css">
  </head>

  <body>
    <button value="1" class="tools" aria-label="Search" type="submit">
  <i class=fb></i>
</button>
    <input type="text" class="sbox" placeholder="Search " arial-label="Search" />
  </body>

</html></code>```

答:
Based on the question, I feel that you want to display an image in search box on the right. If so, please apply background image to class 'sbox' and the image position should be 'right 0'. The class 'sbox' will look as below:

```<code>.sbox {
  width: 297.297px;
  height: 25px;
  background-color: rgba (0, 0, 0, 0);
  font-family: Helvetica, Arial, sans-serif;
  font-size: 14px;
  font-stretch: normal;
  font-style: normal;
  font-variant-caps: normal;
  font-variant-ligatures: normal;
  font-variant-numeric: normal;
  font-weight:`enter code here` normal;
  cursor: auto;
  position: relative;
  top: -26px;
  background: url("../img/mag.png") no-repeat right 0;
}
</code>```

And if you want the image (magnifying glass) to the button on the right, the code is as follows:

```<code>.fb {
background: url("../img/mag.png") no-repeat right 0;
width:15px;
height:14px;
display:inline-block;
float:right;
  }
</code>```

Body:
I am new to html/css and I do not understand why my background image is not showing up over the button in the search box on the right. I want to display an image of magnifying glass over the right button in the search box?

.sbox {
  width: 297.297px;
  height: 25px;
  background-color: rgba (0, 0, 0, 0);
  font-family: Helvetica, Arial, sans-serif;
  font-size: 14px;
  font-stretch: normal;
  font-style: normal;
  font-variant-caps: normal;
  font-variant-ligatures: normal;
  font-variant-numeric: normal;
  font-weight: normal;
  cursor: auto;
  position: relative;

}

.fb {
  background: url("../img/mag.png") no-repeat 0 0;
  background-size: 50px 50px;
  }

<!DOCTYPE html>

    <link rel="stylesheet" href="css/facebook.css">

    <button value="1" class="tools" aria-label="Search" type="submit">

</button>
    <input type="text" class="sbox" placeholder="Search " arial-label="Search" />

Body:
Based on the question, I feel that you want to display an image in search box on the right. If so, please apply background image to class 'sbox' and the image position should be 'right 0'. The class 'sbox' will look as below:

.sbox {
  width: 297.297px;
  height: 25px;
  background-color: rgba (0, 0, 0, 0);
  font-family: Helvetica, Arial, sans-serif;
  font-size: 14px;
  font-stretch: normal;
  font-style: normal;
  font-variant-caps: normal;
  font-variant-ligatures: normal;
  font-variant-numeric: normal;
  font-weight:`enter code here` normal;
  cursor: auto;
  position: relative;
  top: -26px;
  background: url("../img/mag.png") no-repeat right 0;
}

And if you want the image (magnifying glass) to the button on the right, the code is as follows:

.fb {
background: url("../img/mag.png") no-repeat right 0;
width:15px;
height:14px;
display:inline-block;
float:right;
  }


问:
Capture Slow Output from Method
I have a slow running utility method that logs one line of output at a time. I need to be able to output each of those lines and then read them from other locations in code. I have attempted using Tasks and Streams similar to the code below:

```<code>public static Task SlowOutput(Stream output)
{
    Task result = new Task(() =>
    {
        using(StreamWriter sw = new StreamWriter(output))
        {
            for(var i = 0; i < int.MaxValue; i++)
            {
                sw.WriteLine(i.ToString());
                System.Threading.Thread.Sleep(1000);
            }
        }
    }
}
</code>```

And then called like this:

```<code>MemoryStream ms = new MemoryStream();
var t = SlowOutput(ms);
using (var sr = new StreamReader(ms))
{
    while (!t.IsCompleted)
    {
        Console.WriteLine(sr.ReadLine())
    }
}
</code>```

But of course, sr.ReadLine() is always empty because as soon as the method's sw.WriteLine() is called, it changes the position of the underlying stream to the end.

What I'm trying to do is pipe the output of the stream by maybe queueing up the characters that the method outputs and then consuming them from outside the method.  Streams don't seem to be the way to go.

Is there a generally accepted way to do this?

答:
What I would do is switch to a BlockingCollection<String>.

```<code>public static Task SlowOutput(BlockingCollection<string> output)
{
    return Task.Run(() =>
    {
        for(var i = 0; i < int.MaxValue; i++)
        {
            output.Add(i);
            System.Threading.Thread.Sleep(1000);
        }
        output.CompleteAdding();
    }
}
</code>```

consumed by

```<code>var bc = BlockingCollection<string>();
SlowOutput(bc);
foreach(var line in bc.GetConsumingEnumerable()) //Blocks till a item is added to the collection. Leaves the foreach loop after CompleteAdding() is called and there are no more items to be processed.
{
    Console.WriteLine(line)
}
</code>```

Title: Capture Slow Output from Method

Body:
I have a slow running utility method that logs one line of output at a time. I need to be able to output each of those lines and then read them from other locations in code. I have attempted using Tasks and Streams similar to the code below:

public static Task SlowOutput(Stream output)
{
    Task result = new Task(() =>
    {
        using(StreamWriter sw = new StreamWriter(output))
        {
            for(var i = 0; i < int.MaxValue; i++)
            {
                sw.WriteLine(i.ToString());
                System.Threading.Thread.Sleep(1000);
            }
        }
    }
}

And then called like this:

MemoryStream ms = new MemoryStream();
var t = SlowOutput(ms);
using (var sr = new StreamReader(ms))
{
    while (!t.IsCompleted)
    {
        Console.WriteLine(sr.ReadLine())
    }
}

But of course, sr.ReadLine() is always empty because as soon as the method's sw.WriteLine() is called, it changes the position of the underlying stream to the end.

What I'm trying to do is pipe the output of the stream by maybe queueing up the characters that the method outputs and then consuming them from outside the method.  Streams don't seem to be the way to go.

Is there a generally accepted way to do this?

Body:
What I would do is switch to a BlockingCollection<String>.

public static Task SlowOutput(BlockingCollection<string> output)
{
    return Task.Run(() =>
    {
        for(var i = 0; i < int.MaxValue; i++)
        {
            output.Add(i);
            System.Threading.Thread.Sleep(1000);
        }
        output.CompleteAdding();
    }
}

consumed by

var bc = BlockingCollection<string>();
SlowOutput(bc);
foreach(var line in bc.GetConsumingEnumerable()) //Blocks till a item is added to the collection. Leaves the foreach loop after CompleteAdding() is called and there are no more items to be processed.
{
    Console.WriteLine(line)
}


问:
How to find the minimum set of vertices in a Directed Graph such that all other vertices can be reached
Given a directed graph, I need to find the minimum set of vertices from which all other vertices can be reached.

So the result of the function should be the smallest number of vertices, from which all other vertices can be reached by following the directed edges.

The largest result possible would be if there were no edges, so all nodes would be returned.

If there are cycles in the graph, for each cycle, one node is selected. It does not matter which one, but it should be consistent if the algorithm is run again.

I am not sure that there is an existing algorithm for this? If so does it have a name? I have tried doing my research and the closest thing seems to be finding a mother vertex
If it is that algorithm, could the actual algorithm be elaborated as the answer given in that link is kind of vague.

Given I have to implement this in javascript, the preference would be a .js library or javascript example code.

答:
[EDIT #2: As Jason Orendorff mentions in a comment, finding the feedback vertex set is overkill and will produce a vertex set larger than necessary in general.  kyun's answer is (or will be, when he/she adds in the important info in the comments) the right way to do it.]

[EDIT: I had the two steps round the wrong way...  Now we should guarantee minimality.]

Call all of the vertices with in-degree zero Z.  No vertex in Z can be reached by any other vertex, so it must be included in the final set.

Using a depth-first (or breadth-first) traversal, trace out all the vertices reachable from each vertex in Z and delete them -- these are the vertices already "covered" by Z.

The graph now consists purely of directed cycles.  Find a feedback vertex set F which gives you a smallest-possible set of vertices whose removal would break every cycle in the graph.  Unfortunately as that Wikipedia link shows, this problem is NP-hard for directed graphs.

The set of vertices you're looking for is Z+F.

ContentLicense: CC BY-SA 2.5


问:
xpages register a anonymous user to names.nsf with login name and email
Case: Create a web application to register user through the Name.nsf on the server.

userA

userB

means there have 2 database related.

First database: Anonymous(web) allow to key in there information through the database.

Second database: Names.nsf

First database with "full" access user must be allow to create a user in the names nsf or create an email address for user!

Question

Do i just need to link the names.nsf in server view ($VIMPeopleByLastName) and create document of those web-user?

答: It's been along time since I did things with the NAB (exchange, exchange everywhere) however if I recall this is pretty straightforward.... Previously, via an xpage, I got the user to fill out a username and a few details, then when you submit, call a lotuScript agent that goes off and create's the account in the NAB? I believe it used to check user didnt exist already, set the htttpPassword field, the change date to now, username, company, email address etc - The agent can be run with the rights of a user who has access to write to the NAB also. It then creates the account, generates a password, and used to email a link where the user would then go to set their own password</p>


问:
Creating winforms base controls
We have several winforms applications we want to restyle and make consistent (styling wise).  We want to create some base classes for some of the windows controls such as buttons and toolstrip.  All my base classes intend to do is specify the specific styling we wish to apply.  This works the first time I bring into my form but later on if I wish to update a property it doesn't apply it back to the forms that previously already have pulled it in.  Anyway to get this to work?  Here's an example, lets say I want to create a base class for a toolstrip.  All I want to do is set the backcolor to green (I really want to set more properties but this is to demo my issue).  So I create a class library called BaseControls and create a class called BaseToolStrip and set the backcolor to green in its constructor.

```<code>public class BaseToolStrip : ToolStrip
{
  public BaseToolStrip()
  {
    BackColor = Color.Green;
  }
}
</code>```

Now if I create a demo project and add an instance of BaseToolStrip to the form it works.  It creates a green toolstrip.  Later if I decided I want my base toolstrip to have a backcolor of red if I update the constructor in my BaseToolStrip class and set the BackColor = Color.Red and run my solution the color is still green.  It appears that once I've brought that control in it set backcolor = green.  So even though in my base class I set backcolor = red in my form that instantiates it still has backcolor = green.  Any way to override all instances and set backcolor equal to the color specified in my BaseToolStrip class?

答:
Your problem is that the WinForms designer is saving the current value in InitializeComponent() in any designer that uses that control.

That happens after your ctor runs and replaces your value.

You can prevent that by overriding / shadowing the property and adding [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] (you'll need to reopen & resave all designers that use it to remove the property).

Title: Creating winforms base controls

Body:
We have several winforms applications we want to restyle and make consistent (styling wise).  We want to create some base classes for some of the windows controls such as buttons and toolstrip.  All my base classes intend to do is specify the specific styling we wish to apply.  This works the first time I bring into my form but later on if I wish to update a property it doesn't apply it back to the forms that previously already have pulled it in.  Anyway to get this to work?  Here's an example, lets say I want to create a base class for a toolstrip.  All I want to do is set the backcolor to green (I really want to set more properties but this is to demo my issue).  So I create a class library called BaseControls and create a class called BaseToolStrip and set the backcolor to green in its constructor.

public class BaseToolStrip : ToolStrip
{
  public BaseToolStrip()
  {
    BackColor = Color.Green;
  }
}

Now if I create a demo project and add an instance of BaseToolStrip to the form it works.  It creates a green toolstrip.  Later if I decided I want my base toolstrip to have a backcolor of red if I update the constructor in my BaseToolStrip class and set the BackColor = Color.Red and run my solution the color is still green.  It appears that once I've brought that control in it set backcolor = green.  So even though in my base class I set backcolor = red in my form that instantiates it still has backcolor = green.  Any way to override all instances and set backcolor equal to the color specified in my BaseToolStrip class?


问:
What event handler to use for ComboBox Item Selected (Selected Item not necessarily changed)
Goal: issue an event when items in a combobox drop down list is selected.

Problem: Using "SelectionChanged", however, if the user choose the same item as the item is currently being selected then the selection is not changed and therefore this event will not be triggered.

Question: What other event handler(or other ways) I may use to issue an event regardless of the selected item is changed or not as long as the mouse clicked on that item and that item is being selected.

(Clarification: Problem is how to trigger "something" when the same item is being selected again. No duplicates in the drop down list. Scenario: first time select item 1,close drop down. And then again, open drop down box and select item 1 when some function are triggered.)

Solution: for now there seems to be no straight-forward solution to do this. But according to each individual project, there can be ways to work around it. (Please update if there are indeed good ways to do this). Thanks.

答:
I hope that you will find helpfull the following trick.

You can bind both the events

```<code>combobox.SelectionChanged += OnSelectionChanged;
combobox.DropDownOpened += OnDropDownOpened;
</code>```

And force selected item to null inside the OnDropDownOpened

```<code>private void OnDropDownOpened(object sender, EventArgs e)
{
    combobox.SelectedItem = null;
}
</code>```

And do what you need with the item inside the OnSelectionChanged.
The OnSelectionChanged will be raised every time you will open the combobox, but you can check if SelectedItem is null inside the method and skip the command

```<code>private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (combobox.SelectedItem != null)
        {
           //Do something with the selected item
        }
    }
</code>```

Body:
I hope that you will find helpfull the following trick.

You can bind both the events

combobox.SelectionChanged += OnSelectionChanged;
combobox.DropDownOpened += OnDropDownOpened;

And force selected item to null inside the OnDropDownOpened

private void OnDropDownOpened(object sender, EventArgs e)
{
    combobox.SelectedItem = null;
}

And do what you need with the item inside the OnSelectionChanged.
The OnSelectionChanged will be raised every time you will open the combobox, but you can check if SelectedItem is null inside the method and skip the command

private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (combobox.SelectedItem != null)
        {
           //Do something with the selected item
        }
    }


问:
awk command fails with command substitution
Running this command fails:

```<code>$(printf "awk '{%sprint}'" $(tail -n +2 file.txt | cut -f2 | sort | uniq | awk 'BEGIN{a=1}{printf "gsub(\"%s\",%i);", $1,a++}')) file.txt
</code>```

It gives the following error:

```<code>awk: '
awk: ^ invalid char ''' in expression
</code>```

However, if I run the substituted command, I get this:

```<code>awk '{gsub("ACB",1);gsub("ASW",2);gsub("BEB",3);gsub("CDX",4);gsub("CEU",5);gsub("CHB",6);gsub("CHS",7);gsub("CLM",8);gsub("ESN",9);gsub("FIN",10);gsub("GBR",11);gsub("GIH",12);gsub("GWD",13);gsub("IBS",14);gsub("ITU",15);gsub("JPT",16);gsub("KHV",17);gsub("LWK",18);gsub("MSL",19);gsub("MXL",20);gsub("PEL",21);gsub("PJL",22);gsub("PUR",23);gsub("STU",24);gsub("TSI",25);gsub("YRI",26);print}'
</code>```

which I can run like so:

```<code>awk '{gsub("ACB",1);gsub("ASW",2);gsub("BEB",3);gsub("CDX",4);gsub("CEU",5);gsub("CHB",6);gsub("CHS",7);gsub("CLM",8);gsub("ESN",9);gsub("FIN",10);gsub("GBR",11);gsub("GIH",12);gsub("GWD",13);gsub("IBS",14);gsub("ITU",15);gsub("JPT",16);gsub("KHV",17);gsub("LWK",18);gsub("MSL",19);gsub("MXL",20);gsub("PEL",21);gsub("PJL",22);gsub("PUR",23);gsub("STU",24);gsub("TSI",25);gsub("YRI",26);print}' file.txt
</code>```

And it works perfectly. What am I doing wrong?

@ChrisLear gave me a working solution, but I still don't quite understand what the command solution is doing. Here's the working code:

```<code>$(printf "awk {%sprint}" $(tail -n +2 file.txt | cut -f2 | sort | uniq | awk 'BEGIN{a=1}{printf "gsub(\"%s\",%i);", $1,a++}')) file.txt
</code>```

The single quotes around {%sprint} are removed. Why do those single quotes break the command substitution?

edit: changed backtick to $(...) notation. Also added solution I don't understand.

答:
It looks like you're trying to take a bunch of unique 2nd fields from a file starting at line 2 and map those to numbers based on their alphabetic ordering, then apply the change to the same file. If so then with GNU awk for sorted_in and inplace editing that'd be:

```<code>awk -i inplace '
NR==FNR {
    if (NR>1) {
        map[$2]
    }
    next
}
FNR==1 {
    PROCINFO["sorted_in"] = "@ind_str_asc"
    for (str in map) {
        map[str] = ++i
    }
}
{
    $2 = map[$2]
    print
}
' file.txt
</code>```

If that's not what you need then edit your question to show concise, testable sample input and expected output.

Body:
Running this command fails:

$(printf "awk '{%sprint}'" $(tail -n +2 file.txt | cut -f2 | sort | uniq | awk 'BEGIN{a=1}{printf "gsub(\"%s\",%i);", $1,a++}')) file.txt

It gives the following error:

awk: '
awk: ^ invalid char ''' in expression

However, if I run the substituted command, I get this:

awk '{gsub("ACB",1);gsub("ASW",2);gsub("BEB",3);gsub("CDX",4);gsub("CEU",5);gsub("CHB",6);gsub("CHS",7);gsub("CLM",8);gsub("ESN",9);gsub("FIN",10);gsub("GBR",11);gsub("GIH",12);gsub("GWD",13);gsub("IBS",14);gsub("ITU",15);gsub("JPT",16);gsub("KHV",17);gsub("LWK",18);gsub("MSL",19);gsub("MXL",20);gsub("PEL",21);gsub("PJL",22);gsub("PUR",23);gsub("STU",24);gsub("TSI",25);gsub("YRI",26);print}'

which I can run like so:

awk '{gsub("ACB",1);gsub("ASW",2);gsub("BEB",3);gsub("CDX",4);gsub("CEU",5);gsub("CHB",6);gsub("CHS",7);gsub("CLM",8);gsub("ESN",9);gsub("FIN",10);gsub("GBR",11);gsub("GIH",12);gsub("GWD",13);gsub("IBS",14);gsub("ITU",15);gsub("JPT",16);gsub("KHV",17);gsub("LWK",18);gsub("MSL",19);gsub("MXL",20);gsub("PEL",21);gsub("PJL",22);gsub("PUR",23);gsub("STU",24);gsub("TSI",25);gsub("YRI",26);print}' file.txt

And it works perfectly. What am I doing wrong?

@ChrisLear gave me a working solution, but I still don't quite understand what the command solution is doing. Here's the working code:

$(printf "awk {%sprint}" $(tail -n +2 file.txt | cut -f2 | sort | uniq | awk 'BEGIN{a=1}{printf "gsub(\"%s\",%i);", $1,a++}')) file.txt

The single quotes around {%sprint} are removed. Why do those single quotes break the command substitution?

edit: changed backtick to $(...) notation. Also added solution I don't understand.

Body:
It looks like you're trying to take a bunch of unique 2nd fields from a file starting at line 2 and map those to numbers based on their alphabetic ordering, then apply the change to the same file. If so then with GNU awk for sorted_in and inplace editing that'd be:

awk -i inplace '
NR==FNR {
    if (NR>1) {
        map[$2]
    }
    next
}
FNR==1 {
    PROCINFO["sorted_in"] = "@ind_str_asc"
    for (str in map) {
        map[str] = ++i
    }
}
{
    $2 = map[$2]
    print
}
' file.txt

If that's not what you need then edit your question to show concise, testable sample input and expected output.


问:
Node child processes: how to intercept signals like SIGINT
In my Node app, I'm hooking on the SIGINT signal in order to gracefully stop (using pm2, but this is not relevant here).

My app also execs/spawns a couple of child processes.

I am able to hook on SIGINT to intercept it and perform graceful stop, however my child processes are passed through the same signal, and thus, instantly killed.

How can I intercept the SIGINT signal on my child processes?

A sample of what I'm doing:

```<code>const child = child_process.spawn('sleep', ['10000000']);
console.log(`Child pid: ${child.pid}`);

child.on('exit', (code, signal) => { console.log('Exit', code, signal); });

process.on('SIGINT', () => {
    console.log("Intercepting SIGINT");
});
</code>```

答:
By default, child processes created by child_process.spawn() have the same process group as the parent, unless they were called with the {detached:true} option.

The upshot is that this script will behave differently in different environments:

// spawn-test.js
const { spawn } = require('child_process');
const one = spawn('sleep', ['101']);
const two = spawn('sleep', ['102'], {detached: true});
two.unref();
process.on('SIGINT', function () {
  console.log('just ignore SIGINT');
});
```

<p>On interactive shells, a SIGINT from Ctl-C is sent to the whole group by default, so the non-detached child will get the SIGINT and exit:</p>

<pre class="lang-sh prettyprint-override"><code>you@bash $ node spawn-test.js
^Cjust ignore SIGINT
# the parent process continues here, let's check children in another window:
you@bash [another-terminal-window] $ ps aux | grep sleep
... sleep 102
# note that sleep 101 is not running anymore
# because it recieved the SIGINT from the Ctl-C on parent
</code>```

...but calls to kill(2) can just signal your parent process, so children stay alive:

you@bash $ node spawn-test.js & echo $?
[2] 1234
you@bash [another-terminal-window] $ kill -SIGINT 1234
you@bash [another-terminal-window] $ ps aux | grep sleep
... sleep 101
... sleep 102
# both are still running
```

<p>However, pm2 is a whole other beast. Even if you try the above techniques, it kills the whole process tree, including your detached process, even with a long <code>--kill-timeout</code>:</p>

<pre class="lang-sh prettyprint-override"><code># Test pm2 stop
you@bash $ pm2 start spawn-test.js --kill-timeout 3600
you@bash $ pm2 stop spawn-test
you@bash $ ps aux | grep sleep
# both are dead

# Test pm3 reload
you@bash $ pm2 start spawn-test.js --kill-timeout 3600
you@bash $ pm2 reload spawn-test
you@bash $ ps aux | grep sleep
# both have different PIDs and were therefore killed and restarted
</code>```

This seems like a bug in pm2.

I've gotten around similar problems by using the init system (systemd in my case) rather than pm2, since this allows for greater control over signal handling.

On systemd, signals are sent to the whole group by default, but you can use KillMode=mixed to have the signal sent to the parent process only, but still SIGKILL child processes if they run beyond the timeout.

My systemd unit files look like this:

```<code>[Unit]
Description=node server with long-running children example

[Service]
Type=simple
Restart=always
RestartSec=30
TimeoutStopSec=3600
KillMode=mixed
ExecStart=/usr/local/bin/node /path/to/your/server.js

[Install]
WantedBy=multi-user.target
</code>```

Body:
In my Node app, I'm hooking on the SIGINT signal in order to gracefully stop (using pm2, but this is not relevant here).

My app also execs/spawns a couple of child processes.

I am able to hook on SIGINT to intercept it and perform graceful stop, however my child processes are passed through the same signal, and thus, instantly killed.

How can I intercept the SIGINT signal on my child processes?

A sample of what I'm doing:

const child = child_process.spawn('sleep', ['10000000']);
console.log(`Child pid: ${child.pid}`);

child.on('exit', (code, signal) => { console.log('Exit', code, signal); });

process.on('SIGINT', () => {
    console.log("Intercepting SIGINT");
});

Body:
By default, child processes created by child_process.spawn() have the same process group as the parent, unless they were called with the {detached:true} option.

The upshot is that this script will behave differently in different environments:

// spawn-test.js
const { spawn } = require('child_process');
const one = spawn('sleep', ['101']);
const two = spawn('sleep', ['102'], {detached: true});
two.unref();
process.on('SIGINT', function () {
  console.log('just ignore SIGINT');
});

On interactive shells, a SIGINT from Ctl-C is sent to the whole group by default, so the non-detached child will get the SIGINT and exit:

you@bash $ node spawn-test.js
^Cjust ignore SIGINT
# the parent process continues here, let's check children in another window:
you@bash [another-terminal-window] $ ps aux | grep sleep
... sleep 102
# note that sleep 101 is not running anymore
# because it recieved the SIGINT from the Ctl-C on parent

...but calls to kill(2) can just signal your parent process, so children stay alive:

you@bash $ node spawn-test.js & echo $?
[2] 1234
you@bash [another-terminal-window] $ kill -SIGINT 1234
you@bash [another-terminal-window] $ ps aux | grep sleep
... sleep 101
... sleep 102
# both are still running

However, pm2 is a whole other beast. Even if you try the above techniques, it kills the whole process tree, including your detached process, even with a long --kill-timeout:

# Test pm2 stop
you@bash $ pm2 start spawn-test.js --kill-timeout 3600
you@bash $ pm2 stop spawn-test
you@bash $ ps aux | grep sleep
# both are dead

# Test pm3 reload
you@bash $ pm2 start spawn-test.js --kill-timeout 3600
you@bash $ pm2 reload spawn-test
you@bash $ ps aux | grep sleep
# both have different PIDs and were therefore killed and restarted

This seems like a bug in pm2.

I've gotten around similar problems by using the init system (systemd in my case) rather than pm2, since this allows for greater control over signal handling.

On systemd, signals are sent to the whole group by default, but you can use KillMode=mixed to have the signal sent to the parent process only, but still SIGKILL child processes if they run beyond the timeout.

My systemd unit files look like this:

[Unit]
Description=node server with long-running children example

[Service]
Type=simple
Restart=always
RestartSec=30
TimeoutStopSec=3600
KillMode=mixed
ExecStart=/usr/local/bin/node /path/to/your/server.js

[Install]
WantedBy=multi-user.target


问:
PHP performance question
Wondering which would be better for performance. The site will be viewed by people that are logged in and people that are not. The site is almost the same for the users that are logged in except they have more privledges. So I am wondering what would be more efficient.

//OPTION ONE

```<code>if(isLoggedIn()){
Write the whole web site plus the content the logged in user can access
}
else {
Write the whole website again, minus the content the logged in users can access.
}

//OPTION TWO
Write the website content and inset the login function wherever i need to restrict the access, so the function would be called a few different times.
</code>```

I am wondering if it would be better for performance using option one because the function would first be checked once, and wouldn't need to be checked again, if the user is logged in the first chunk would be loaded, if the user is not logged in, it would ignore the first chunk and load the second chunk.

答:
Both.

You don't want to check isLoggedIn() everytime (especially if it's going to hit the database) because that will be slow. But you don't want to have 2 versions of HTML either because it's unmaintainable.

Check it once at the top and set a variable (or use a session variable and check that). Then in the HTML use if statements against the variable to determine what to show. For example:

PHP:

```<code>$logged_in = false;
if(isLoggedIn() ) {
     $logged_in = true;
}
</code>```

HTML:

```<code><?php if($logged_in) { ?>
<div>
     Super-secret needs a login stuff
</div>
<?php } else { ?>
<div>
     Sorry! You have to login to see this cool stuff
</div>
<?php } ?>
</code>```

Title: PHP performance question

Body:
Wondering which would be better for performance. The site will be viewed by people that are logged in and people that are not. The site is almost the same for the users that are logged in except they have more privledges. So I am wondering what would be more efficient.

//OPTION ONE

if(isLoggedIn()){
Write the whole web site plus the content the logged in user can access
}
else {
Write the whole website again, minus the content the logged in users can access.
}

//OPTION TWO
Write the website content and inset the login function wherever i need to restrict the access, so the function would be called a few different times.

I am wondering if it would be better for performance using option one because the function would first be checked once, and wouldn't need to be checked again, if the user is logged in the first chunk would be loaded, if the user is not logged in, it would ignore the first chunk and load the second chunk.

Body:
Both.

You don't want to check isLoggedIn() everytime (especially if it's going to hit the database) because that will be slow. But you don't want to have 2 versions of HTML either because it's unmaintainable.

Check it once at the top and set a variable (or use a session variable and check that). Then in the HTML use if statements against the variable to determine what to show. For example:

PHP:

$logged_in = false;
if(isLoggedIn() ) {
     $logged_in = true;
}

HTML:

<?php if($logged_in) { ?>
<div>
     Super-secret needs a login stuff
</div>
<?php } else { ?>
<div>
     Sorry! You have to login to see this cool stuff
</div>
<?php } ?>


问:
javascript foreach find and update
Let say I have an array of tree type data

```<code>[ { 'id': 1, 'name': 'root', 'parent_id': 1 },
  { 'id': 2, 'name': 'level 1', 'parent_id': 1 },
  { 'id': 3, 'name': 'level 2', 'parent_id': 1 },
  { 'id': 4, 'name': 'level 2.1', 'parent_id': 3 } ]
</code>```

is it possible to update the array to

```<code>[ { 'id': 1, 'name': 'root', 'parent_id': 1, 'parent_name': 'root' },
  { 'id': 2, 'name': 'level 1', 'parent_id': 1, 'parent_name': 'root' },
  { 'id': 3, 'name': 'level 2', 'parent_id': 1, 'parent_name': 'root' },
  { 'id': 4, 'name': 'level 2.1', 'parent_id': 3, 'parent_name': 'level 2' } ]
</code>```

using lodash forEach and find?

```<code>_.forEach(arr, function (o) {
  let item = _.find(arr, {'id': o.parent_id})
  o.parent_name = item.name
})
</code>```

my problem is inside the function of forEach, it has no idea what arr is, I got it working replacing the forEach with a plain for loop.

```<code>for (i = 0; i < arr.length; i++) {
  let item = _.find(arr, {'id': arr[i].parent_id})
  arr[i].parent_name = item.name
}
</code>```

So wondering if there're any more elegant way to accomplish this

答:
Try reading the documentation on _.forEach.

The iteratee is invoked with three arguments: (value, index|key, collection).

You need to setup your forEach like so:

```<code>_.forEach(arr, function (o, idx, arr) {
      let item = _.find(arr, {'id': o.parent_id})
      o.parent_name = item.name
});
</code>```

Title: javascript foreach find and update

Body:
Let say I have an array of tree type data

[ { 'id': 1, 'name': 'root', 'parent_id': 1 },
  { 'id': 2, 'name': 'level 1', 'parent_id': 1 },
  { 'id': 3, 'name': 'level 2', 'parent_id': 1 },
  { 'id': 4, 'name': 'level 2.1', 'parent_id': 3 } ]

is it possible to update the array to

[ { 'id': 1, 'name': 'root', 'parent_id': 1, 'parent_name': 'root' },
  { 'id': 2, 'name': 'level 1', 'parent_id': 1, 'parent_name': 'root' },
  { 'id': 3, 'name': 'level 2', 'parent_id': 1, 'parent_name': 'root' },
  { 'id': 4, 'name': 'level 2.1', 'parent_id': 3, 'parent_name': 'level 2' } ]

using lodash forEach and find?

_.forEach(arr, function (o) {
  let item = _.find(arr, {'id': o.parent_id})
  o.parent_name = item.name
})

my problem is inside the function of forEach, it has no idea what arr is, I got it working replacing the forEach with a plain for loop.

for (i = 0; i < arr.length; i++) {
  let item = _.find(arr, {'id': arr[i].parent_id})
  arr[i].parent_name = item.name
}

So wondering if there're any more elegant way to accomplish this

Body:
Try reading the documentation on _.forEach.

The iteratee is invoked with three arguments: (value, index|key, collection).

You need to setup your forEach like so:

_.forEach(arr, function (o, idx, arr) {
      let item = _.find(arr, {'id': o.parent_id})
      o.parent_name = item.name
});


问:
Uploading new products with multiple variant options
I am trying to upload products via ruby (not with rails). I have uploaded 100 + products via API, although I cannot upload a product with more than one option value. Even if I assign three option values, it will not populate the other two.

Here is the script:

```<code>require 'shopify_api'
require 'open-uri'
require 'json'

begin_time = Time.now

shop_url  = "*https*(yes I know the * are their)://-YouWish-:-I'dShareNakedPics-@dev-tactical.myshopify.com/admin/products.json"
include ShopifyAPI

ShopifyAPI::Base.site ="*https*://-YouWish-:-I'dShareNakedPics-@dev-tactical.myshopify.com/admin/"

raw_product_data = JSON.parse(open('omg.json') {|f| f.read }.force_encoding('UTF-8'))
raw_product_data_size = raw_product_data.size

puts '========================================================================='
puts "#{raw_product_data_size} seconds till explosion. assistance
needed..."
puts '-------------------------------------------------------------------------'
single_product_begin_time = Time.now

# Create new product
new_product = ShopifyAPI::Product.new
new_product.title = "Variants Suck"
new_product.body_html = "So"
new_product.product_type = "Much"
new_product.vendor = "Please"
new_product.tags = "Help"

new_product.variants = [
     {
      "option1" => "This One Works",
      "option2" => "Lost Cause",
      "option3" => "/wrist",
      "postion" => "1",
      "price" => "10.00",
      "sku" => "12345",
      "inventory_management" => "shopify",
    }   ]
 new_product.images = [
    {
      src: "https://cdn.shopify.com/s/files/1/0750/0067/files/Pro-Tapes.jpg?11603036243532110652"
    }   ]

  new_product.save

  creation_time = Time.now - single_product_begin_time

puts '-------------------------------------------------------------------------'
puts "Sorry About the mess babe, atleast it only took #{begin_time - Time.now} minutes."
puts '========================================================================='
</code>```

I am testing this on a dev shop, but I am attempting to rebuild something previously built on magento, where I can have people convert my csv data entry to json, then array/hash the data.

Please don't link me to the (shopify)/API info. I have read it. I don't understand the formatting of it. If I were to shopify-cli console, and paste the api example in irb, it won't execute properly. I am sure I am just lacking the required knowledge of working with APIs, although if you can help me just slightly it would be much appreciated.

答:
I used @bknights code as a reference and got my code to work in ruby. You just have to set the option names on the product level first:

```<code>new_product = ShopifyAPI::Product.new
new_product.options = [{"name" => "Size"}, {"name" => "Color"}]
</code>```

Then adding variants work:

```<code>new_product.variants = [
    {
      "option1" => "S",
      "option2" => "Black",
      "position" => "1",
      "price" => "10.00"
    },
    {
      "option1" => "M",
      "option2" => "Black",
      "position" => "1",
      "price" => "10.00"
    }
]
new_product.save
</code>```

Body:
I am trying to upload products via ruby (not with rails). I have uploaded 100 + products via API, although I cannot upload a product with more than one option value. Even if I assign three option values, it will not populate the other two.

Here is the script:

require 'shopify_api'
require 'open-uri'
require 'json'

begin_time = Time.now

shop_url  = "*https*(yes I know the * are their)://-YouWish-:-I'dShareNakedPics-@dev-tactical.myshopify.com/admin/products.json"
include ShopifyAPI

ShopifyAPI::Base.site ="*https*://-YouWish-:-I'dShareNakedPics-@dev-tactical.myshopify.com/admin/"

raw_product_data = JSON.parse(open('omg.json') {|f| f.read }.force_encoding('UTF-8'))
raw_product_data_size = raw_product_data.size

puts '========================================================================='
puts "#{raw_product_data_size} seconds till explosion. assistance
needed..."
puts '-------------------------------------------------------------------------'
single_product_begin_time = Time.now

# Create new product
new_product = ShopifyAPI::Product.new
new_product.title = "Variants Suck"
new_product.body_html = "So"
new_product.product_type = "Much"
new_product.vendor = "Please"
new_product.tags = "Help"

new_product.variants = [
     {
      "option1" => "This One Works",
      "option2" => "Lost Cause",
      "option3" => "/wrist",
      "postion" => "1",
      "price" => "10.00",
      "sku" => "12345",
      "inventory_management" => "shopify",
    }   ]
 new_product.images = [
    {
      src: "https://cdn.shopify.com/s/files/1/0750/0067/files/Pro-Tapes.jpg?11603036243532110652"
    }   ]

  new_product.save

  creation_time = Time.now - single_product_begin_time

puts '-------------------------------------------------------------------------'
puts "Sorry About the mess babe, atleast it only took #{begin_time - Time.now} minutes."
puts '========================================================================='

I am testing this on a dev shop, but I am attempting to rebuild something previously built on magento, where I can have people convert my csv data entry to json, then array/hash the data.

Please don't link me to the (shopify)/API info. I have read it. I don't understand the formatting of it. If I were to shopify-cli console, and paste the api example in irb, it won't execute properly. I am sure I am just lacking the required knowledge of working with APIs, although if you can help me just slightly it would be much appreciated.

Body:
I used @bknights code as a reference and got my code to work in ruby. You just have to set the option names on the product level first:

new_product = ShopifyAPI::Product.new
new_product.options = [{"name" => "Size"}, {"name" => "Color"}]

Then adding variants work:

new_product.variants = [
    {
      "option1" => "S",
      "option2" => "Black",
      "position" => "1",
      "price" => "10.00"
    },
    {
      "option1" => "M",
      "option2" => "Black",
      "position" => "1",
      "price" => "10.00"
    }
]
new_product.save


问:
Updating Bokeh Plot in JS
I am developing in Javascript to render a table using a DataTables (Table plug-in for jQuery). I am also using Bootstrap Multiselect (https://github.com/davidstutz/bootstrap-multiselect) to filter the table. I would like to re-render my BokehJS plot everytime the table is re-drawn. I have hooked up the correct calls but I am also calling Bokeh.Plotting.show to re-render the graph. This forces me to remove the last created div to avoid multiple graphs plotted. I am new to the JS side of Bokeh and wanted to understand if there is a cleaner method to update the plot in JS?

```<code>    var eventFired = function ( type ) {
    //var n = $('#demo_info')[0];
    //n.innerHTML += '<div>'+type+' event - '+new Date().getTime()+'</div>';
    //n.scrollTop = n.scrollHeight;

    var plt = Bokeh.Plotting;

    // set up some data
    var M = 25;
    var xx = [];
    var yy = [];
    var colors = [];
    var radii = [];
    for (var y = 0; y <= M; y += 4) {
        for (var x = 0; x <= M; x += 4) {
            xx.push(x * (Math.random() +0.5));
            yy.push(y * (Math.random() +0.5));
            colors.push(plt.color(50+8*x, 30+8*y, 150));
            radii.push(Math.random() * 0.4 + 1.7)
        }
    }

    // create a data source
    var source = new Bokeh.ColumnDataSource({
        data: { x: xx, y: yy, radius: radii, colors: colors }
    });

    // make the plot and add some tools
    var tools = "pan,crosshair,wheel_zoom,box_zoom,reset,save";
    var p = plt.figure({ title: type+' event - '+new Date().getTime(),
                        height: 300,
                        width: 300,
                        tools: tools });

    // call the circle glyph method to add some circle glyphs
    var circles = p.circle({ field: "x" }, { field: "y" }, {
        source: source,
        radius: radii,
        fill_color: colors,
        fill_alpha: 0.6,
        line_color: null
    });

    //remove old plot on update conditions
    $('.bk-root').remove();

    // Show the plot, appending it to the end of the current
    // section of the document we are in.

    Bokeh.Plotting.show(p, document.getElementById('myplot'));
    //To Do: add in transition to improve the UI appearance
}
</code>```

And here is the the datatable setting up the call back to the BokehJS script.

```<code></script>
      $('#table').DataTable({
    responsive: {
        details: {
            display: $.fn.dataTable.Responsive.display.modal( {
                header: function ( row ) {
                    var data = row.data();
                    return 'Details for '+data[0]+' '+data[1];
                }
            } ),
            renderer: $.fn.dataTable.Responsive.renderer.tableAll( {
                tableClass: 'table'
            } )
        }
    },
    paginate: false,
    info: false,
    paging: true,
    autoWidth: true,
    dom: '<"dt-buttons">Bf<"clear">lirtp',
    "buttons": [ 'copy', 'csv', 'excel' ],
  }).on( 'draw.dt',   function () { eventFired( 'Draw' ); } );
</code>```

Lastly, is there a good method to update the plot via a transition effect to improve the appearance of the re-plotting?

答:
I eventually figured out all of the components in the process in a modified use case compared to the one shown above. In my present approach I needed to utilize my source data and emit a 'change' trigger.

```<code>source.data.factors = [my new factor list]
source.trigger('change');
</code>```

The new factor list based on the jQuery datatable can be obtained as followed.

```<code>$('mytable').DataTable().columns(0, {search: 'applied'}).data()[0]
</code>```

Also in my use case I am working with a categorical axis. In my specific use case, my factors will dynamically change upon redraw of the graph. This can be achieved using the plot's attributes.

```<code>p.attributes.x_range.factors = [ my new factor list from my updated source data]
</code>```

There is also no need to remove the old plot, and the added plus is the redraw is very fast for my simple plots.

Title: Updating Bokeh Plot in JS

Body:
I am developing in Javascript to render a table using a DataTables (Table plug-in for jQuery). I am also using Bootstrap Multiselect (https://github.com/davidstutz/bootstrap-multiselect) to filter the table. I would like to re-render my BokehJS plot everytime the table is re-drawn. I have hooked up the correct calls but I am also calling Bokeh.Plotting.show to re-render the graph. This forces me to remove the last created div to avoid multiple graphs plotted. I am new to the JS side of Bokeh and wanted to understand if there is a cleaner method to update the plot in JS?

    var eventFired = function ( type ) {
    //var n = $('#demo_info')[0];
    //n.innerHTML += '
'+type+' event - '+new Date().getTime()+'
';
    //n.scrollTop = n.scrollHeight;

    var plt = Bokeh.Plotting;

    // set up some data
    var M = 25;
    var xx = [];
    var yy = [];
    var colors = [];
    var radii = [];
    for (var y = 0; y <= M; y += 4) {
        for (var x = 0; x <= M; x += 4) {
            xx.push(x * (Math.random() +0.5));
            yy.push(y * (Math.random() +0.5));
            colors.push(plt.color(50+8*x, 30+8*y, 150));
            radii.push(Math.random() * 0.4 + 1.7)
        }
    }

    // create a data source
    var source = new Bokeh.ColumnDataSource({
        data: { x: xx, y: yy, radius: radii, colors: colors }
    });

    // make the plot and add some tools
    var tools = "pan,crosshair,wheel_zoom,box_zoom,reset,save";
    var p = plt.figure({ title: type+' event - '+new Date().getTime(),
                        height: 300,
                        width: 300,
                        tools: tools });

    // call the circle glyph method to add some circle glyphs
    var circles = p.circle({ field: "x" }, { field: "y" }, {
        source: source,
        radius: radii,
        fill_color: colors,
        fill_alpha: 0.6,
        line_color: null
    });

    //remove old plot on update conditions
    $('.bk-root').remove();

    // Show the plot, appending it to the end of the current
    // section of the document we are in.

    Bokeh.Plotting.show(p, document.getElementById('myplot'));
    //To Do: add in transition to improve the UI appearance
}

And here is the the datatable setting up the call back to the BokehJS script.

</script>
      $('#table').DataTable({
    responsive: {
        details: {
            display: $.fn.dataTable.Responsive.display.modal( {
                header: function ( row ) {
                    var data = row.data();
                    return 'Details for '+data[0]+' '+data[1];
                }
            } ),
            renderer: $.fn.dataTable.Responsive.renderer.tableAll( {
                tableClass: 'table'
            } )
        }
    },
    paginate: false,
    info: false,
    paging: true,
    autoWidth: true,
    dom: '<"dt-buttons">Bf<"clear">lirtp',
    "buttons": [ 'copy', 'csv', 'excel' ],
  }).on( 'draw.dt',   function () { eventFired( 'Draw' ); } );

Lastly, is there a good method to update the plot via a transition effect to improve the appearance of the re-plotting?

Body:
I eventually figured out all of the components in the process in a modified use case compared to the one shown above. In my present approach I needed to utilize my source data and emit a 'change' trigger.

source.data.factors = [my new factor list]
source.trigger('change');

The new factor list based on the jQuery datatable can be obtained as followed.

$('mytable').DataTable().columns(0, {search: 'applied'}).data()[0]

Also in my use case I am working with a categorical axis. In my specific use case, my factors will dynamically change upon redraw of the graph. This can be achieved using the plot's attributes.

p.attributes.x_range.factors = [ my new factor list from my updated source data]

There is also no need to remove the old plot, and the added plus is the redraw is very fast for my simple plots.


问:
SQL ORACLE need assistance-
SQL>

```<code>CREATE TABLE Loan(
    Loan_ID NUMBER (5)
    CONSTRAINT  pk_Loan primary key,
    Start_Date DATE NOT NULL,
    End_Date DATE NOT NULL,
    Copy_ID NUMBER(5),
    CONSTRAINT fk_Copy_ID references Copy (Copy_ID),
    customer_ID NUMBER(5),
    CONSTRAINT fk_customer_ID references Customers (Customer_ID),
   Evaluation NUMBER(1) NOT NULL,
   check (Evaluation>=0 and Evaluation<=5>);
CONSTRAINT fk_Copy_ID references Copy (Copy_ID),
                                  *
</code>```

ERROR at line 7:
ORA-00907: missing right parenthesis

答:
Try this please: </p>

```<code>CREATE TABLE Loan(
    Loan_ID NUMBER (5)
    CONSTRAINT  pk_Loan primary key,
    Start_Date DATE NOT NULL,
    End_Date DATE NOT NULL,
    Copy_ID NUMBER(5),
    customer_ID NUMBER(5),
    Evaluation NUMBER(1) NOT NULL,
    CONSTRAINT fk_Copy_ID foreign key (copy_id) references Copy (Copy_ID),
    CONSTRAINT fk_customer_ID foreign key (customer_id) references Customers (Customer_ID),
    constraint chk_evaluation check (Evaluation>=0 and evaluation<=5) );
</code>```

Title: SQL ORACLE need assistance-

Body:
SQL>

CREATE TABLE Loan(
    Loan_ID NUMBER (5)
    CONSTRAINT  pk_Loan primary key,
    Start_Date DATE NOT NULL,
    End_Date DATE NOT NULL,
    Copy_ID NUMBER(5),
    CONSTRAINT fk_Copy_ID references Copy (Copy_ID),
    customer_ID NUMBER(5),
    CONSTRAINT fk_customer_ID references Customers (Customer_ID),
   Evaluation NUMBER(1) NOT NULL,
   check (Evaluation>=0 and Evaluation<=5>);
CONSTRAINT fk_Copy_ID references Copy (Copy_ID),
                                  *

ERROR at line 7:
ORA-00907: missing right parenthesis

Body:
Try this please:

CREATE TABLE Loan(
    Loan_ID NUMBER (5)
    CONSTRAINT  pk_Loan primary key,
    Start_Date DATE NOT NULL,
    End_Date DATE NOT NULL,
    Copy_ID NUMBER(5),
    customer_ID NUMBER(5),
    Evaluation NUMBER(1) NOT NULL,
    CONSTRAINT fk_Copy_ID foreign key (copy_id) references Copy (Copy_ID),
    CONSTRAINT fk_customer_ID foreign key (customer_id) references Customers (Customer_ID),
    constraint chk_evaluation check (Evaluation>=0 and evaluation<=5) );


问:
Copy-item Files in Folders and subfolders in the same directory structure of source server using PowerShell
I am struggling really hard to get this below script worked to copy the files in folders and sub folders in the proper structure (As the source server).

Lets say, there are folders mentioned below:

Main Folder: File aaa, File bbb

Sub Folder a: File 1, File 2, File 3

Sub Folder b: File 4, File 5, File 6

Script used:

```<code>Get-ChildItem -Path \\Server1\Test -recurse | ForEach-Object {
Copy-Item -LiteralPath $_.FullName -Destination \\server2\test |
Get-Acl -Path $_.FullName | Set-Acl -Path "\\server2\test\$(Split-Path -Path $_.FullName -Leaf)"

}
</code>```

Output:
File aaa, File bbb

Sub Folder a (Empty Folder)

Sub Folder b (Empty Folder)

File 1, File 2, File 3, File 4, File 5, File 6.

I want the files to get copied to their respective folders (Like the source folders). Any further help is highly appreciated.

答:
If you want to mirror same content from source to destination, try following one.

```<code>function CopyFilesToFolder ($fromFolder, $toFolder) {
    $childItems = Get-ChildItem $fromFolder
    $childItems | ForEach-Object {
         Copy-Item -Path $_.FullName -Destination $toFolder -Recurse -Force
    }
}
</code>```

Test:

```<code>CopyFilesToFolder "C:\temp\q" "c:\temp\w"
</code>```

Body:
I am struggling really hard to get this below script worked to copy the files in folders and sub folders in the proper structure (As the source server).

Lets say, there are folders mentioned below:

Main Folder: File aaa, File bbb

Sub Folder a: File 1, File 2, File 3

Sub Folder b: File 4, File 5, File 6

Script used:

Get-ChildItem -Path \\Server1\Test -recurse | ForEach-Object {
Copy-Item -LiteralPath $_.FullName -Destination \\server2\test |
Get-Acl -Path $_.FullName | Set-Acl -Path "\\server2\test\$(Split-Path -Path $_.FullName -Leaf)"

}

Output:
File aaa, File bbb

Sub Folder a (Empty Folder)

Sub Folder b (Empty Folder)

File 1, File 2, File 3, File 4, File 5, File 6.

I want the files to get copied to their respective folders (Like the source folders). Any further help is highly appreciated.

Body:
If you want to mirror same content from source to destination, try following one.

function CopyFilesToFolder ($fromFolder, $toFolder) {
    $childItems = Get-ChildItem $fromFolder
    $childItems | ForEach-Object {
         Copy-Item -Path $_.FullName -Destination $toFolder -Recurse -Force
    }
}

Test:

CopyFilesToFolder "C:\temp\q" "c:\temp\w"


问:
Making the Android emulator run faster
The Android emulator is a bit sluggish. For some devices, like the Motorola Droid and the Nexus One, the app runs faster in the actual device than the emulator. This is a problem when testing games and visual effects.

How do you make the emulator run as fast as possible? I've been toying with its parameters but haven't found a configuration that shows a noticeable improvement yet.

答:
I think it is because clr virtual machine uses cpu directly without code opcode translation.
It may be optimization for clr application or may be windows mobile/window phone 7 started on INTEL proccessor.
Android platform based on linux and theoretically you can start android on virtual machine in i686 environment. In this case virtual machines such as vmware could execute some opcodes direcly. But this option will be allowed only if you write on the Java. Because the Java interpret their byte-code or precompile it before execution.
see:
http://www.taranfx.com/how-to-run-google-android-in-virtualbox-vmware-on-netbooks</p>

Title: Making the Android emulator run faster


问:
Control tint of individual particles
I'm creating dustclouds for a toy, using the CC Particle World and with Textured QuadPolygon, containing a bitmap.

However, the structure of the individual clouds are quite indistinguishable from each other. Is there a way to create a random tint-expression within two RGB-codes - or perhaps another way - to make the individual clouds to be a bit more visible?

答: I used a PNG dustcloud instead of the JPEG-one which had a Luma Inverted Matte to create transparency - looks much better now.</p>

Title: Control tint of individual particles


问:
UISearchController search bar overlap first cell when active
I am using UISearchController to search for data in my tableview. I am not using table view controller. I would like to hide the navigation bar when my search bar is active therefore I set self.searchController.hidesNavigationBarDuringPresentation = YES; to yes.

However when I do this and want to search, my active search bar covers part of the first cell. the covered part has same height as status bar.

I tried other articles and questions similar to this one but nothing helped me to solve it. Then I started to play with the table view header size. I did this

```<code> -(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

  return 20.0f;
}
</code>```

The result was that when I tapped search bar an started to search problem was not there anymore.

However when the search bar is not active there was a gab between searchbar and first cell

Any ideas how to fix this issue?

Edit: after adding self.automaticallyAdjustsScrollViewInsets = false;

答:
Not the best solution but just to workaround.

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
  return searchController.isActive ? 20.0f : 0.0f;
}

Body:
I am using UISearchController to search for data in my tableview. I am not using table view controller. I would like to hide the navigation bar when my search bar is active therefore I set self.searchController.hidesNavigationBarDuringPresentation = YES; to yes.

However when I do this and want to search, my active search bar covers part of the first cell. the covered part has same height as status bar.

I tried other articles and questions similar to this one but nothing helped me to solve it. Then I started to play with the table view header size. I did this

 -(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

  return 20.0f;
}

The result was that when I tapped search bar an started to search problem was not there anymore.

However when the search bar is not active there was a gab between searchbar and first cell

Any ideas how to fix this issue?

Edit: after adding self.automaticallyAdjustsScrollViewInsets = false;


问:
ImportError : cannot import name '_win32stdio'
I am working with Scrapy framework to scrap out data from website, but getting the following error in command prompt:

ImportError: cannot import name '_win32stdio'

Traceback is attached as a screenshot.

Kindly revert if require directory structure of my program's directory.

答:
I have gone through the same. I have resolved by updating the twisted package

pip install --upgrade twisted

 or

pip uninstall twisted and pip install twisted


问:
Construct a static lookup
Say I have a giant list of definitions that are used to lookup values that an object can default to given a "type number". This type number is unique, and points to data that the object will be set to when initialized with it.

My usual go-to is to have a static property that will return a new Dictionary with each get. E.g.

```<code>public static Dictionary<long, Tuple<string,DefaultValue>> Defaults
{
   get { return new Dictionary<long, DefaultValue>()
         {
            { 123, new DefaultValue("Name of default 1", 12312, 23544, ...)},
            { 456, new DefaultValue("Name of default 2", 36734, 74367, ...)},
            ...
         }
   }
}
</code>```

This works, and the lookup list will likely never be large enough for this to noticeably impact performance or memory usage, but being somewhat stingy on performance I don't like the idea of having a new Dictionary instantiated every time it is referenced. I would much rather it be completely hard-coded into memory.

How would this be solved in a professional way? I feel like the way I am doing it above is incredibly sloppy.

答:
If the lookup table is small and your goal is to increase the performance of the lookup operation then you can also consider using a function with a switch statement instead of a lookup dictionary.

See this answer for more information: https://stackoverflow.com/a/11617459/1709981

Title: Construct a static lookup

Body:
Say I have a giant list of definitions that are used to lookup values that an object can default to given a "type number". This type number is unique, and points to data that the object will be set to when initialized with it.

My usual go-to is to have a static property that will return a new Dictionary with each get. E.g.

public static Dictionary<long, Tuple<string,DefaultValue>> Defaults
{
   get { return new Dictionary<long, DefaultValue>()
         {
            { 123, new DefaultValue("Name of default 1", 12312, 23544, ...)},
            { 456, new DefaultValue("Name of default 2", 36734, 74367, ...)},
            ...
         }
   }
}

This works, and the lookup list will likely never be large enough for this to noticeably impact performance or memory usage, but being somewhat stingy on performance I don't like the idea of having a new Dictionary instantiated every time it is referenced. I would much rather it be completely hard-coded into memory.

How would this be solved in a professional way? I feel like the way I am doing it above is incredibly sloppy.


答:
To remove a dollar sign (or any character) from the front of a string, do</p>

```<code>var withoutDollarSign = withDollarSign.substr(1)
</code>```

Title: String slicing in javascript

Body:
export class Prices{
value : string;
}

const PRICES : Prices[] =[
{value :'$10,000'},{value :'$20,000'},{value :'$30,000'},{value
:'$40,000'},{value :'$50,000'},
{value :'$60,000'},{value :'$70,000'},{value :'$80,000'},{value
:'$90,000'},{value :'$100,000'},
{value :'$125,000'},{value :'$150,000'},{value :'$175,000'},{value
:'$200,000'},{value :'$225,000'},
{value :'$250,000'},{value :'$275,000'},{value :'$300,000'},{value
:'$325,000'},{value :'$350,000'},
{value :'$375,000'},{value :'$400,000'},{value :'$425,000'},{value
:'$450,000'},{value :'$475,000'},
{value :'$500,000'},{value :'$525,000'},{value :'$550,000'},{value
:'$575,000'},{value :'$600,000'}]

export class ConstantProperty implements OnInit{
prices=PRICES;
selectedPriceMin : Prices;
}

I am selecting the price from a drop down menu in html,
Now I want to slice that selected price in order to remove dollar sign.

Body:
To remove a dollar sign (or any character) from the front of a string, do

var withoutDollarSign = withDollarSign.substr(1)


问:
Selenium use without testing?
As I know Selenium use as a web UI functional testing tool.Is there any tool that I can use instead of selenium.I mean I do not want to test the web site.But I want to use functionalities like Selenium.Can I do that using selenium or is there any tool that I can use for this?

thanxx

答:
It sounds like you want a loop which accesses the web site getting / checking the currency conversion at set intervals.

The tool to use for this is Selenium RC.

See Selenium RC : Importing a script from Selenium IDE for an example.

This is using Netbeans / JUnit as a wrapper.

Then you just need an assert and throw an exception when the answer is not what you are looking for.

Selenium RC allows you to write Java code so it is trivial to have loops / checks / waits / timeouts etc.

Because it is JUnit you can take it outside of Netbeans if you want and simply run from a command line.

Another solution would be to use something like Fiddler to analyze what exactly is being sent to the web site and then code that using the standard Java HTTP POST / GET functionality e.g. Sending a POST Request Using a URL

Title: Selenium use without testing?


问:
How to add a udf who's parameter is a table name
I want to add a udf to calcite. The udf's parameter is a table name, and it will return a varchar value. Are there any sample for this? Thanks.

My test sql is:

```<code>SELECT MYTEST22(a), MYTEST(a), MYTEST1(a), COUNT(*)
FROM alisis.table1
WHERE a=max_dt(alisis.table1)
GROUP BY MYTEST22(a),MYTEST(a),MYTEST1(a)
</code>```

max_dt is the function I want to add.

答:
I don't know what your want to do, could you make a clear explanation?

No function can accept table as parameter, the parameters must have certain type, String, Int or others. So constants and columns can be used as parameters. If your meaning is the table name as a parameter, the sql should be as follows:

```<code>SELECT MYTEST22(a), MYTEST(a), MYTEST1(a), COUNT(*)
FROM alisis.table1
WHERE a=max_dt('alisis.table1')
GROUP BY MYTEST22(a),MYTEST(a),MYTEST1(a)
</code>```

As I known, all functions Calcite (version is 1.11) supported are defined at SqlStdOperatorTable. If you want to support other functions, you can implement a class that extends SqlStdOperatorTable, for example:

```<code>public class TestOperatorTable extends SqlStdOperatorTable {
  private static volatile TestOperatorTable instance;
  public static TestOperatorTable instance() {
    if (instance == null) {
      synchronized(TestOperatorTable.class) {
        if (instance == null) {
          instance = new TestOperatorTable();
          // Use reflection to register the expressions stored in public fields.
          instance.init();
        }
      }
    }
    return instance;
  }

  /** Follow add your functions */
  public static SqlFunction LTRIM = new SqlTrimFunction("LTRIM");
}
</code>```

SqlTrimFunction as follows:

```<code>public class SqlTrimFunction extends SqlFunction {
  public SqlTrimFunction(String funcName) {
    super(
      funcName,
      SqlKind.OTHER_FUNCTION,
      ReturnTypes.VARCHAR_2000,  // return type is String
      InferTypes.FIRST_KNOWN,
      OperandTypes.STRING,       // parameter type is String
      SqlFunctionCategory.STRING
    );
  }
}
</code>```

When you create a SqlValidator, for example SqlValidatorImpl, you should use TestOperatorTable as its first parameter.

Body:
I want to add a udf to calcite. The udf's parameter is a table name, and it will return a varchar value. Are there any sample for this? Thanks.

My test sql is:

SELECT MYTEST22(a), MYTEST(a), MYTEST1(a), COUNT(*)
FROM alisis.table1
WHERE a=max_dt(alisis.table1)
GROUP BY MYTEST22(a),MYTEST(a),MYTEST1(a)

max_dt is the function I want to add.

Body:
I don't know what your want to do, could you make a clear explanation?

No function can accept table as parameter, the parameters must have certain type, String, Int or others. So constants and columns can be used as parameters. If your meaning is the table name as a parameter, the sql should be as follows:

SELECT MYTEST22(a), MYTEST(a), MYTEST1(a), COUNT(*)
FROM alisis.table1
WHERE a=max_dt('alisis.table1')
GROUP BY MYTEST22(a),MYTEST(a),MYTEST1(a)

As I known, all functions Calcite (version is 1.11) supported are defined at SqlStdOperatorTable. If you want to support other functions, you can implement a class that extends SqlStdOperatorTable, for example:

public class TestOperatorTable extends SqlStdOperatorTable {
  private static volatile TestOperatorTable instance;
  public static TestOperatorTable instance() {
    if (instance == null) {
      synchronized(TestOperatorTable.class) {
        if (instance == null) {
          instance = new TestOperatorTable();
          // Use reflection to register the expressions stored in public fields.
          instance.init();
        }
      }
    }
    return instance;
  }

  /** Follow add your functions */
  public static SqlFunction LTRIM = new SqlTrimFunction("LTRIM");
}

SqlTrimFunction as follows:

public class SqlTrimFunction extends SqlFunction {
  public SqlTrimFunction(String funcName) {
    super(
      funcName,
      SqlKind.OTHER_FUNCTION,
      ReturnTypes.VARCHAR_2000,  // return type is String
      InferTypes.FIRST_KNOWN,
      OperandTypes.STRING,       // parameter type is String
      SqlFunctionCategory.STRING
    );
  }
}

When you create a SqlValidator, for example SqlValidatorImpl, you should use TestOperatorTable as its first parameter.


问:
How do I add validation to the form in my React component?
My Contact page form is as follows,

<form name="contactform" onSubmit={this.contactSubmit.bind(this)}>

    <fieldset>
      <input ref="name" type="text" size="30" placeholder="Name"/>

      <input refs="email" type="text" size="30" placeholder="Email"/>

      <input refs="phone" type="text" size="30" placeholder="Phone"/>

      <input refs="address" type="text" size="30" placeholder="Address"/>

    </fieldset>

    <fieldset>
      <textarea refs="message" cols="40" rows="20"
                className="comments" placeholder="Message"/>
    </fieldset>

    <fieldset>
      <button className="btn btn-lg pro" id="submit"
              value="Submit">Send Message</button>
    </fieldset>

</form>
```

Need to add validation for all fields. Can anyone help me to add validation in this react form?

答:
I've taken your code and adapted it with library react-form-with-constraints: https://codepen.io/tkrotoff/pen/LLraZp

const {
  FormWithConstraints,
  FieldFeedbacks,
  FieldFeedback
} = ReactFormWithConstraints;

class Form extends React.Component {
  handleChange = e => {
    this.form.validateFields(e.target);
  }

  contactSubmit = e => {
    e.preventDefault();

    this.form.validateFields();

    if (!this.form.isValid()) {
      console.log('form is invalid: do not submit');
    } else {
      console.log('form is valid: submit');
    }
  }

  render() {
    return (
      <FormWithConstraints
        ref={form => this.form = form}
        onSubmit={this.contactSubmit}
        noValidate>

          <input name="name" size="30" placeholder="Name"
                 required onChange={this.handleChange}
                 className="form-control" />
          <FieldFeedbacks for="name">
            <FieldFeedback when="*" />
          </FieldFeedbacks>

          <input type="email" name="email" size="30" placeholder="Email"
                 required onChange={this.handleChange}
                 className="form-control" />
          <FieldFeedbacks for="email">
            <FieldFeedback when="*" />
          </FieldFeedbacks>

          <input name="phone" size="30" placeholder="Phone"
                 required onChange={this.handleChange}
                 className="form-control" />
          <FieldFeedbacks for="phone">
            <FieldFeedback when="*" />
          </FieldFeedbacks>

          <input name="address" size="30" placeholder="Address"
                 required onChange={this.handleChange}
                 className="form-control" />
          <FieldFeedbacks for="address">
            <FieldFeedback when="*" />
          </FieldFeedbacks>

          <textarea name="comments" cols="40" rows="20" placeholder="Message"
                    required minLength={5} maxLength={50}
                    onChange={this.handleChange}
                    className="form-control" />
          <FieldFeedbacks for="comments">
            <FieldFeedback when="*" />
          </FieldFeedbacks>

          <button className="btn btn-lg btn-primary">Send Message</button>

      </FormWithConstraints>
    );
  }
}
```

Screenshot:

This is a quick hack. For a proper demo, check  https://github.com/tkrotoff/react-form-with-constraints#examples

Body:
My Contact page form is as follows,

<form name="contactform" onSubmit={this.contactSubmit.bind(this)}>

    <fieldset>
      <input ref="name" type="text" size="30" placeholder="Name"/>

      <input refs="email" type="text" size="30" placeholder="Email"/>

      <input refs="phone" type="text" size="30" placeholder="Phone"/>

      <input refs="address" type="text" size="30" placeholder="Address"/>

    </fieldset>

    <fieldset>
      <textarea refs="message" cols="40" rows="20"
                className="comments" placeholder="Message"/>
    </fieldset>

    <fieldset>
      <button className="btn btn-lg pro" id="submit"
              value="Submit">Send Message</button>
    </fieldset>

</form>

Need to add validation for all fields. Can anyone help me to add validation in this react form?

Body:
I've taken your code and adapted it with library react-form-with-constraints: https://codepen.io/tkrotoff/pen/LLraZp

const {
  FormWithConstraints,
  FieldFeedbacks,
  FieldFeedback
} = ReactFormWithConstraints;

class Form extends React.Component {
  handleChange = e => {
    this.form.validateFields(e.target);
  }

  contactSubmit = e => {
    e.preventDefault();

    this.form.validateFields();

    if (!this.form.isValid()) {
      console.log('form is invalid: do not submit');
    } else {
      console.log('form is valid: submit');
    }
  }

  render() {
    return (
      <FormWithConstraints
        ref={form => this.form = form}
        onSubmit={this.contactSubmit}
        noValidate>

        <div className="col-md-6">
          <input name="name" size="30" placeholder="Name"
                 required onChange={this.handleChange}
                 className="form-control" />
          <FieldFeedbacks for="name">
            <FieldFeedback when="*" />
          </FieldFeedbacks>

          <input type="email" name="email" size="30" placeholder="Email"
                 required onChange={this.handleChange}
                 className="form-control" />
          <FieldFeedbacks for="email">
            <FieldFeedback when="*" />
          </FieldFeedbacks>

          <input name="phone" size="30" placeholder="Phone"
                 required onChange={this.handleChange}
                 className="form-control" />
          <FieldFeedbacks for="phone">
            <FieldFeedback when="*" />
          </FieldFeedbacks>

          <input name="address" size="30" placeholder="Address"
                 required onChange={this.handleChange}
                 className="form-control" />
          <FieldFeedbacks for="address">
            <FieldFeedback when="*" />
          </FieldFeedbacks>
        </div>

        <div className="col-md-6">
          <textarea name="comments" cols="40" rows="20" placeholder="Message"
                    required minLength={5} maxLength={50}
                    onChange={this.handleChange}
                    className="form-control" />
          <FieldFeedbacks for="comments">
            <FieldFeedback when="*" />
          </FieldFeedbacks>
        </div>

        <div className="col-md-12">
          <button className="btn btn-lg btn-primary">Send Message</button>
        </div>
      </FormWithConstraints>
    );
  }
}

Screenshot:

This is a quick hack. For a proper demo, check  https://github.com/tkrotoff/react-form-with-constraints#examples