问:
How do I remove surrounding spaces from each value in multidimensional array recursively
Each string value within my $arr array contains 2 preceeding white spaces. I would like to remove these spaces using the trim() method. Furthermore, I would like to do the same for any arrays within the $arr array assuming an infinite number of arrays within arrays. I attempted to do this recursively with no success.

Although there might be a built in php method to do this for me, I am learning, and would like to know why this code block doesn't work as well as what altercation can be made to fix it.

```<code>$arr = array("  one", "  two", array("  three"));

function trimAll(&$array) {
  foreach($array as $key => $value) {
    if(gettype($value) !== "array") {
        $array[$key] = trim($value);
    } else {
        trimAll($value);
    }
  }
}

trimAll($arr);

echo $arr[0];//"one" (worked)
echo $arr[1];//"two" (worked)
echo $arr[2][0];// "  three"(didn't work)
</code>```

答:
Yes, there is a built-in PHP function which solves your problem. It is array_map()

But in your situation, you might need to do something like this:

Solution 1:

```<code>$input = array("  one", "  two", array("  three"));

function removeSpaces($object)
{
    if (is_array($object)) {
        $object = array_map('trim', $object);
    } else {
        $object = trim($object);
    }

    return $object;
}

$output = array_map('removeSpaces', $input);
</code>```

Solution 2:

```<code>$input = array("  one", "  two", array("  three"));

function array_map_recursive(callable $func, array $array) {
    return filter_var($array, \FILTER_CALLBACK, ['options' => $func]);
}

$output = array_map_recursive('trim', $input);
</code>```

Cheers.

Body:
Each string value within my $arr array contains 2 preceeding white spaces. I would like to remove these spaces using the trim() method. Furthermore, I would like to do the same for any arrays within the $arr array assuming an infinite number of arrays within arrays. I attempted to do this recursively with no success.

Although there might be a built in php method to do this for me, I am learning, and would like to know why this code block doesn't work as well as what altercation can be made to fix it.

$arr = array("  one", "  two", array("  three"));

function trimAll(&$array) {
  foreach($array as $key => $value) {
    if(gettype($value) !== "array") {
        $array[$key] = trim($value);
    } else {
        trimAll($value);
    }
  }
}

trimAll($arr);

echo $arr[0];//"one" (worked)
echo $arr[1];//"two" (worked)
echo $arr[2][0];// "  three"(didn't work)

Body:
Yes, there is a built-in PHP function which solves your problem. It is array_map()

But in your situation, you might need to do something like this:

Solution 1:

$input = array("  one", "  two", array("  three"));

function removeSpaces($object)
{
    if (is_array($object)) {
        $object = array_map('trim', $object);
    } else {
        $object = trim($object);
    }

    return $object;
}

$output = array_map('removeSpaces', $input);

Solution 2:

$input = array("  one", "  two", array("  three"));

function array_map_recursive(callable $func, array $array) {
    return filter_var($array, \FILTER_CALLBACK, ['options' => $func]);
}

$output = array_map_recursive('trim', $input);

Cheers.


来源: stackexchange

问:
UPDATE table SET with multi values
I have spent a lot of time online trying to look for an answer but no success so I decided to post the following.
I have the following tables:

```<code>TABLE_1
+------------+---------------+
| child_id   | mother_id     |
+------------+---------------+
|          1 |             4 |
|          2 |             3 |
|          3 |             2 |
|          4 |             1 |
+------------+---------------+

TABLE_2
+------------+---------------+
| child_id   | mother_id     |
+------------+---------------+
|          1 |             0 |
|          2 |             0 |
|          3 |             0 |
|          4 |             0 |
+------------+---------------+
</code>```

I would like to update the values of mother_id in my table 2 with the values of of mother_id located in my table 1.
Of course the example above could be solved doing manually:

```<code>UPDATE table2 SET mother_id = 1 where child_id = 4;
UPDATE table2 SET mother_id = 2 where child_id = 3;
UPDATE table2 SET mother_id = 3 where child_id = 2;
UPDATE table2 SET mother_id = 4 where child_id = 1;
</code>```

But let's imagine I have thousand of lines to update. Is there any way to do this using select join queries (on child_id) mixed with update in order to have only a few lines of code?

Thank you.

答:
```<code>UPDATE
 table_2 AS t2
 INNER JOIN table_1 AS t1
   ON t2.child_id = t1.child_id
SET t2.mother_id = t1.mother_id;
</code>```

You need to join the two tables based on the matching child_id and later set the values of mother_id from table_1 to that of table_2.

Here's a demo of it

ContentLicense: CC BY-SA 3.0

Title: UPDATE table SET with multi values

Body:
I have spent a lot of time online trying to look for an answer but no success so I decided to post the following.
I have the following tables:

TABLE_1
+------------+---------------+
| child_id   | mother_id     |
+------------+---------------+
|          1 |             4 |
|          2 |             3 |
|          3 |             2 |
|          4 |             1 |
+------------+---------------+

TABLE_2
+------------+---------------+
| child_id   | mother_id     |
+------------+---------------+
|          1 |             0 |
|          2 |             0 |
|          3 |             0 |
|          4 |             0 |
+------------+---------------+

I would like to update the values of mother_id in my table 2 with the values of of mother_id located in my table 1.
Of course the example above could be solved doing manually:

UPDATE table2 SET mother_id = 1 where child_id = 4;
UPDATE table2 SET mother_id = 2 where child_id = 3;
UPDATE table2 SET mother_id = 3 where child_id = 2;
UPDATE table2 SET mother_id = 4 where child_id = 1;

But let's imagine I have thousand of lines to update. Is there any way to do this using select join queries (on child_id) mixed with update in order to have only a few lines of code?

Thank you.

Body:
UPDATE
 table_2 AS t2
 INNER JOIN table_1 AS t1
   ON t2.child_id = t1.child_id
SET t2.mother_id = t1.mother_id;

You need to join the two tables based on the matching child_id and later set the values of mother_id from table_1 to that of table_2.

Here's a demo of it


问:
Get folder structure along with folder/file sizes in python
After doing my research for this specific task I found at that most of the solution given for this kind of problem either return the list of all the files or the TOTAL size of the folder/file.

What I am trying to achieve is get an output in the CSV file stating the folder structure i.e. folders - sub folders - files (optional) along with the size information for EACH.

There is no specific format for the CSV. I just need to know the tree structure with the size of the folder/sub-folder.

The reason behind this is that we are moving from physical servers to the cloud. In order to verify whether all the data was retained correctly during conversion I need to make a similar list of all SHARED DRIVES which can later be validated.

Looking forward for meaningful insights. Thanks!

答:
Edit:
Sooo, that should be what you are asking for:

```<code>import os
import csv

def sizeof_fmt(num, suffix='B'):
    for unit in ['','K','M','G','T','P','E','Z']:
        if abs(num) < 1024.0:
            return "%3.1f%s%s" % (num, unit, suffix)
        num /= 1024.0
    return "%.1f%s%s" % (num, 'Yi', suffix)

def get_size(start_path = '.'):
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(start_path):
        for f in filenames:
            fp = os.path.join(dirpath, f)
            total_size += os.path.getsize(fp)
    return sizeof_fmt(total_size)

with open("yourfilename.csv", mode="w") as dir_file:
    csv_writer = csv.writer(dir_file, delimiter=",")

    def files_and_sizes(start_path):
        dir_list = [file for file in os.listdir(start_path)]
        for file in dir_list:
            path = start_path + "\\" + file
            if os.path.isdir(path) is True:
                csv_writer.writerow([file, get_size(path)])
                files_and_sizes(start_path + "\\" + file)

    files_and_sizes(r"C:\your\path\here")
</code>```

Updated to better fit the question.

You can get all files with sizes like this:

```<code>import os

all_files_with_size = []

def files_and_sizes(start_path):
    dir_list = [file for file in os.listdir(start_path)]
    current_dir = []
    for file in dir_list:
        path = start_path + "\\" + file
        if os.path.isdir(path) is True:
            current_dir.append(files_and_sizes(path))
        else:
            current_dir.append((file, os.lstat(path).st_size))
    return current_dir
</code>```

It will return a list containing all files like (file, size) and a sublist for each directory.
I recommend appending the entries to a file, but the formatting is up to you.

Also, if you want the directory sizes as well:

```<code>if os.path.isdir(path) is True:
        current_dir.append(file, os.lstat(path).st_size)
        current_dir.append(files_and_sizes(path))
</code>```

Body:
Edit:
Sooo, that should be what you are asking for:

import os
import csv

def sizeof_fmt(num, suffix='B'):
    for unit in ['','K','M','G','T','P','E','Z']:
        if abs(num) < 1024.0:
            return "%3.1f%s%s" % (num, unit, suffix)
        num /= 1024.0
    return "%.1f%s%s" % (num, 'Yi', suffix)

def get_size(start_path = '.'):
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(start_path):
        for f in filenames:
            fp = os.path.join(dirpath, f)
            total_size += os.path.getsize(fp)
    return sizeof_fmt(total_size)

with open("yourfilename.csv", mode="w") as dir_file:
    csv_writer = csv.writer(dir_file, delimiter=",")

    def files_and_sizes(start_path):
        dir_list = [file for file in os.listdir(start_path)]
        for file in dir_list:
            path = start_path + "\\" + file
            if os.path.isdir(path) is True:
                csv_writer.writerow([file, get_size(path)])
                files_and_sizes(start_path + "\\" + file)

    files_and_sizes(r"C:\your\path\here")

Updated to better fit the question.

You can get all files with sizes like this:

import os

all_files_with_size = []

def files_and_sizes(start_path):
    dir_list = [file for file in os.listdir(start_path)]
    current_dir = []
    for file in dir_list:
        path = start_path + "\\" + file
        if os.path.isdir(path) is True:
            current_dir.append(files_and_sizes(path))
        else:
            current_dir.append((file, os.lstat(path).st_size))
    return current_dir

It will return a list containing all files like (file, size) and a sublist for each directory.
I recommend appending the entries to a file, but the formatting is up to you.

Also, if you want the directory sizes as well:

if os.path.isdir(path) is True:
        current_dir.append(file, os.lstat(path).st_size)
        current_dir.append(files_and_sizes(path))


问:
jQuery: simultaneously fadeIn and fadeOut
the following code which is called periodically by setInterval performs the following sequence:

1. fade in an image for 750 msec

2. diplay it for 6 secs

3. fade out the image for 750 msec

4. randomly select another image (function randomPic)

5. fade in for 750 msec and so on:

```<code>$("#_fadee_").fadeIn(750, function() {
    $("#_fadee_").delay(6000).fadeOut(750, randomPic);
});
</code>```

You can see the effect here. How can I get the fadeOut of the old image and the fadeIn of the new one to run simultaneously?

Thanks, Ralf

答:
If you aren't doing anything else you could do this:

```<code>$("#_fadee_").fadeIn(750, function() {
    setTimeout(function() {
        $("#_fadee_").fadeOut(750, randomPic);
        // Start fading in your other pic
    }, 6000);
});
</code>```

Alternatively, if they're both being displayed in the same area, you could fade in, and once faded in set the background image to the next image. Then, once that's faded out, set the background to the next, and so on.

ContentLicense: CC BY-SA 2.5

Body:
the following code which is called periodically by setInterval performs the following sequence:

1. fade in an image for 750 msec

2. diplay it for 6 secs

3. fade out the image for 750 msec

4. randomly select another image (function randomPic)

5. fade in for 750 msec and so on:

$("#_fadee_").fadeIn(750, function() {
    $("#_fadee_").delay(6000).fadeOut(750, randomPic);
});

You can see the effect here. How can I get the fadeOut of the old image and the fadeIn of the new one to run simultaneously?

Thanks, Ralf

Body:
If you aren't doing anything else you could do this:

$("#_fadee_").fadeIn(750, function() {
    setTimeout(function() {
        $("#_fadee_").fadeOut(750, randomPic);
        // Start fading in your other pic
    }, 6000);
});

Alternatively, if they're both being displayed in the same area, you could fade in, and once faded in set the background image to the next image. Then, once that's faded out, set the background to the next, and so on.


问:
tree.links() for D3 v4
I've been watching a tutorial on d3 but it shows some outdated code that is no longer used on v4. I was wondering what would be the updated syntax for var links = tree.links(nodes); for D3 v4?

If anybody is curious, this is the link to the tutorial.
https://www.youtube.com/watch?v=iZ6MSHA4FMU&list=PL6il2r9i3BqH9PmbOf5wA5E1wOG3FT22p&index=15

答:
You have to call links() on the hierarchy.

The changelog talks about this change:

To generate an array of {source, target} links for a given hierarchy, use node.links; this replaces tree.links and similar methods on the other layouts.

Here is a basic demo (use the console of your browser, not the Stack snippet console):

var data = {
  "name": "Eve",
  "children": [{
    "name": "Cain"
  }, {
    "name": "Seth",
    "children": [{
      "name": "Enos"
    }, {
      "name": "Noam"
    }]
  }, {
    "name": "Abel"
  }, {
    "name": "Awan",
    "children": [{
      "name": "Enoch"
    }]
  }, {
    "name": "Azura"
  }]
};

var hierarchy = d3.hierarchy(data);

var tree = d3.tree();

var links = tree(hierarchy).links();

console.log(links)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script></code>```

Title: tree.links() for D3 v4

Body:
You have to call links() on the hierarchy.

The changelog talks about this change:

To generate an array of {source, target} links for a given hierarchy, use node.links; this replaces tree.links and similar methods on the other layouts.

Here is a basic demo (use the console of your browser, not the Stack snippet console):

var data = {
  "name": "Eve",
  "children": [{
    "name": "Cain"
  }, {
    "name": "Seth",
    "children": [{
      "name": "Enos"
    }, {
      "name": "Noam"
    }]
  }, {
    "name": "Abel"
  }, {
    "name": "Awan",
    "children": [{
      "name": "Enoch"
    }]
  }, {
    "name": "Azura"
  }]
};

var hierarchy = d3.hierarchy(data);

var tree = d3.tree();

var links = tree(hierarchy).links();

console.log(links)

<script src="https://d3js.org/d3.v4.min.js"></script>


答:
There is added complexity if you really require column names that change. If you can tolerate fixed column names the pivot is simple, along these lines:

```<code>select
      dayname
    , extract(dow from utc_hour) d_of_w
    , max(case when date_part('day', utc_hour) = 0  then somecol end) hour_0
    , max(case when date_part('day', utc_hour) = 7  then somecol end) hour_7
    , max(case when date_part('day', utc_hour) = 9  then somecol end) hour_9
    , max(case when date_part('day', utc_hour) = 12 then somecol end) hour_12
    , max(case when date_part('day', utc_hour) = 14 then somecol end) hour_14
from COOLNESSTYPES
group by
      d_of_w
    , dayname
</code>```

I used Postgres to develop my example for this example using extract(hour from utc_hour) instead of the date_part() now shown above (thanks to hbomb).

```<code>|   dayname | d_of_w | hour_0 | hour_7 | hour_9 | hour_12 | hour_14 |
|-----------|--------|--------|--------|--------|---------|---------|
| Wednesday |      3 |     20 | (null) |      1 |       0 |       0 |
|    Friday |      5 | (null) | (null) |      0 |  (null) |  (null) |
|  Thursday |      4 | (null) |      1 | (null) |       0 |      58 |
</code>```

see: http://sqlfiddle.com/#!17/81cfd/2 (Postgres)

To achieve column names that change you need "dynamic sql" and to be frank it isn't clear to be if this is possible in Impala (as I don't use that product).

Title: Impala SQL build columns based on row data and populating columns with additional row data

Body:
I'm working in Impala and, while I'm fairly inexperienced in both Impala and SQL, I need to be able to build a data set that looks like the following:

|dayname  | 2017-11-08 00:00:00 | 2017-11-08 01:00:00 | ... |
|---------|---------------------+---------------------+-----|
|Wednesday| 20                  | 11                  | ... |
|---------|---------------------|---------------------|-----|
|Thursday | 287                 | 17                  | ... |
|---------|---------------------|---------------------|-----|
|...      | ...                 | ...                 | ... |
|---------|---------------------|---------------------|-----|

I am unable, due to the constraints of Impala, to use pivot, which would under normal circumstances produce the desired result.

Thus far, I have a SQL SELECT statement which looks like this:

select
dayname(date) as dayname,
utc_hour,
sum(case when (`type` IN ('Awesome')) then 1 else 0 end) as some
FROM (select *, trunc(cast(floor(date / 1000) as timestamp), "HH") as utc_hour
FROM COOLNESSTYPES
WHERE date >= 1510082633596 and month >= '2017-11'
)  a
GROUP BY utc_hour, dayname
ORDER BY utc_hour;

and returns the following data:

+-----------+---------------------+-------+
| dayname   | utc_hour            | some  |
+-----------+---------------------+-------+
| Wednesday | 2017-11-08 00:00:00 | 20    |
| Wednesday | 2017-11-08 01:00:00 | 11    |
| Wednesday | 2017-11-08 09:00:00 | 1     |
| Wednesday | 2017-11-08 11:00:00 | 40    |
| Wednesday | 2017-11-08 12:00:00 | 0     |
| Wednesday | 2017-11-08 13:00:00 | 6     |
| Wednesday | 2017-11-08 14:00:00 | 0     |
| Wednesday | 2017-11-08 16:00:00 | 2     |
| Wednesday | 2017-11-08 17:00:00 | 10    |
| Wednesday | 2017-11-08 19:00:00 | 5     |
| Thursday  | 2017-11-09 07:00:00 | 1     |
| Thursday  | 2017-11-09 12:00:00 | 0     |
| Thursday  | 2017-11-09 13:00:00 | 0     |
| Thursday  | 2017-11-09 14:00:00 | 58    |
| Friday    | 2017-11-10 09:00:00 | 0     |
| Friday    | 2017-11-10 10:00:00 | 0     |
| Friday    | 2017-11-10 16:00:00 | 0     |
+-----------+---------------------+-------+

So, how do I go about doing something like this? On Cloudera's community pages, someone recommends using unions, but I'm not really clear on how I'd label my columns as the row values from my utc_hour column. (see https://community.cloudera.com/t5/Interactive-Short-cycle-SQL/Transpose-columns-to-rows/td-p/49667 for more information on the union suggestion, if needed.)

Any help or ideas on this would be greatly appreciated. Thanks!

Body:
There is added complexity if you really require column names that change. If you can tolerate fixed column names the pivot is simple, along these lines:

select
      dayname
    , extract(dow from utc_hour) d_of_w
    , max(case when date_part('day', utc_hour) = 0  then somecol end) hour_0
    , max(case when date_part('day', utc_hour) = 7  then somecol end) hour_7
    , max(case when date_part('day', utc_hour) = 9  then somecol end) hour_9
    , max(case when date_part('day', utc_hour) = 12 then somecol end) hour_12
    , max(case when date_part('day', utc_hour) = 14 then somecol end) hour_14
from COOLNESSTYPES
group by
      d_of_w
    , dayname

I used Postgres to develop my example for this example using extract(hour from utc_hour) instead of the date_part() now shown above (thanks to hbomb).

|   dayname | d_of_w | hour_0 | hour_7 | hour_9 | hour_12 | hour_14 |
|-----------|--------|--------|--------|--------|---------|---------|
| Wednesday |      3 |     20 | (null) |      1 |       0 |       0 |
|    Friday |      5 | (null) | (null) |      0 |  (null) |  (null) |
|  Thursday |      4 | (null) |      1 | (null) |       0 |      58 |

see: http://sqlfiddle.com/#!17/81cfd/2 (Postgres)

To achieve column names that change you need "dynamic sql" and to be frank it isn't clear to be if this is possible in Impala (as I don't use that product).


问:
Trying to install Perl-Mysql DBD, mysql_config can't be found
Here's the output:

```Ian-MacBook-Pro:DBD-mysql-4.011 ianseyer$ sudo Perl Makefile.PL
Can't exec "mysql_config": No such file or directory at Makefile.PL line 76.

Cannot find the file 'mysql_config'! Your execution PATH doesn't seem
not contain the path to mysql_config. Resorting to guessed values!
Can't exec "mysql_config": No such file or directory at Makefile.PL line 454.
Can't find mysql_config. Use --mysql_config option to specify where mysql_config is located
Can't exec "mysql_config": No such file or directory at Makefile.PL line 454.
Can't find mysql_config. Use --mysql_config option to specify where mysql_config is located
Can't exec "mysql_config": No such file or directory at Makefile.PL line 454.
Can't find mysql_config. Use --mysql_config option to specify where mysql_config is located

PLEASE NOTE:

For 'make test' to run properly, you must ensure that the
database user 'root' can connect to your MySQL server
and has the proper privileges that these tests require such
as 'drop table', 'create table', 'drop procedure', 'create procedure'
as well as others.

mysql> grant all privileges on test.* to 'root'@'localhost' identified by 's3kr1t';

You can also optionally set the user to run 'make test' with:

perl Makefile.pl --testuser=username

Can't exec "mysql_config": No such file or directory at Makefile.PL line 454.
Can't find mysql_config. Use --mysql_config option to specify where mysql_config is located
Can't exec "mysql_config": No such file or directory at Makefile.PL line 454.
Can't find mysql_config. Use --mysql_config option to specify where mysql_config is located
Can't exec "mysql_config": No such file or directory at Makefile.PL line 454.
Can't find mysql_config. Use --mysql_config option to specify where mysql_config is located
Failed to determine directory of mysql.h. Use

  perl Makefile.PL --cflags=-I

to set this directory. For details see the INSTALL.html file,
section "C Compiler flags" or type

  perl Makefile.PL --help
```

I've researched the issue and tried making a symlink to no avail.

Do I have to compile this myself?

答:
Find the script mysql_config.pl under your MySQL directory, and run Makefile.PL like:

```<code>perl Makefile.PL --mysql_config=/path/to/mysql-5.x.y.zzz/bin/mysql_config.pl
</code>```

Body:
Here's the output:

Ian-MacBook-Pro:DBD-mysql-4.011 ianseyer$ sudo Perl Makefile.PL
Can't exec "mysql_config": No such file or directory at Makefile.PL line 76.

Cannot find the file 'mysql_config'! Your execution PATH doesn't seem
not contain the path to mysql_config. Resorting to guessed values!
Can't exec "mysql_config": No such file or directory at Makefile.PL line 454.
Can't find mysql_config. Use --mysql_config option to specify where mysql_config is located
Can't exec "mysql_config": No such file or directory at Makefile.PL line 454.
Can't find mysql_config. Use --mysql_config option to specify where mysql_config is located
Can't exec "mysql_config": No such file or directory at Makefile.PL line 454.
Can't find mysql_config. Use --mysql_config option to specify where mysql_config is located

PLEASE NOTE:

For 'make test' to run properly, you must ensure that the
database user 'root' can connect to your MySQL server
and has the proper privileges that these tests require such
as 'drop table', 'create table', 'drop procedure', 'create procedure'
as well as others.

mysql> grant all privileges on test.* to 'root'@'localhost' identified by 's3kr1t';

You can also optionally set the user to run 'make test' with:

perl Makefile.pl --testuser=username

Can't exec "mysql_config": No such file or directory at Makefile.PL line 454.
Can't find mysql_config. Use --mysql_config option to specify where mysql_config is located
Can't exec "mysql_config": No such file or directory at Makefile.PL line 454.
Can't find mysql_config. Use --mysql_config option to specify where mysql_config is located
Can't exec "mysql_config": No such file or directory at Makefile.PL line 454.
Can't find mysql_config. Use --mysql_config option to specify where mysql_config is located
Failed to determine directory of mysql.h. Use

  perl Makefile.PL --cflags=-I

to set this directory. For details see the INSTALL.html file,
section "C Compiler flags" or type

  perl Makefile.PL --help

I've researched the issue and tried making a symlink to no avail.

Do I have to compile this myself?

Body:
Find the script mysql_config.pl under your MySQL directory, and run Makefile.PL like:

perl Makefile.PL --mysql_config=/path/to/mysql-5.x.y.zzz/bin/mysql_config.pl


问:
Azure deployment: A route named 'HelpPage_Default' is already in the route collection. Route names must be unique. Parameter name: name
When I run locally the website runs fine. But when deployed on Microsoft Azure , it is throwing the above error occurs.

I already tried deleting the .DLL Files from bin folder and obj folder, but the problem still exist.

Stack Trace:

```<code>[ArgumentException: A route named 'HelpPage_Default' is already in the route collection. Route names must be unique.
Parameter name: name]
   System.Web.Routing.RouteCollection.Add(String name, RouteBase item) +3213863
   System.Web.Mvc.RouteCollectionExtensions.MapRoute(RouteCollection routes, String name, String url, Object defaults, Object constraints, String[] namespaces) +203
   System.Web.Mvc.AreaRegistrationContext.MapRoute(String name, String url, Object defaults, Object constraints, String[] namespaces) +56
   Makewayy.Areas.HelpPage.HelpPageAreaRegistration.RegisterArea(AreaRegistrationContext context) +87
   System.Web.Mvc.AreaRegistration.CreateContextAndRegister(RouteCollection routes, Object state) +104
   System.Web.Mvc.AreaRegistration.RegisterAllAreas(RouteCollection routes, IBuildManager buildManager, Object state) +190
   System.Web.Mvc.AreaRegistration.RegisterAllAreas(Object state) +34
   Makewayy.WebApiApplication.Application_Start() +12

[HttpException (0x80004005): A route named 'HelpPage_Default' is already in the route collection. Route names must be unique.
Parameter name: name]
   System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +10104513
   System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +118
   System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +173
   System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +336
   System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +296

[HttpException (0x80004005): A route named 'HelpPage_Default' is already in the route collection. Route names must be unique.
Parameter name: name]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +10085804
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +95
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context)
</code>```

Route Configuration:-

```<code>public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}
</code>```

AreaRegistration -

```<code>namespace Makewayy.Areas.HelpPage
{
    public class HelpPageAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
            get
            {
                return "HelpPage";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "HelpPage_Default",
                "Help/{action}/{apiId}",
                new { controller = "Help", action = "Index", apiId = UrlParameter.Optional });

            HelpPageConfig.Register(GlobalConfiguration.Configuration);
        }
    }
}
</code>```

答:
A route named 'HelpPage_Default' is already in the route collection. Route names must be unique.

Per my understanding, you need to make sure that you have not defined the route named HelpPage_Default no more than once. Also, you need to check your code and make sure that AreaRegistration.RegisterAllAreas(); could only be called once.

Moreover, please make sure your application could work on your local side. And before publishing it to azure website, you could use kudu and empty the web content under D:\home\site\wwwroot, then redeploy your application.

ContentLicense: CC BY-SA 4.0

Body:
When I run locally the website runs fine. But when deployed on Microsoft Azure , it is throwing the above error occurs.

I already tried deleting the .DLL Files from bin folder and obj folder, but the problem still exist.

Stack Trace:

[ArgumentException: A route named 'HelpPage_Default' is already in the route collection. Route names must be unique.
Parameter name: name]
   System.Web.Routing.RouteCollection.Add(String name, RouteBase item) +3213863
   System.Web.Mvc.RouteCollectionExtensions.MapRoute(RouteCollection routes, String name, String url, Object defaults, Object constraints, String[] namespaces) +203
   System.Web.Mvc.AreaRegistrationContext.MapRoute(String name, String url, Object defaults, Object constraints, String[] namespaces) +56
   Makewayy.Areas.HelpPage.HelpPageAreaRegistration.RegisterArea(AreaRegistrationContext context) +87
   System.Web.Mvc.AreaRegistration.CreateContextAndRegister(RouteCollection routes, Object state) +104
   System.Web.Mvc.AreaRegistration.RegisterAllAreas(RouteCollection routes, IBuildManager buildManager, Object state) +190
   System.Web.Mvc.AreaRegistration.RegisterAllAreas(Object state) +34
   Makewayy.WebApiApplication.Application_Start() +12

[HttpException (0x80004005): A route named 'HelpPage_Default' is already in the route collection. Route names must be unique.
Parameter name: name]
   System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +10104513
   System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +118
   System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +173
   System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +336
   System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +296

[HttpException (0x80004005): A route named 'HelpPage_Default' is already in the route collection. Route names must be unique.
Parameter name: name]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +10085804
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +95
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context)

Route Configuration:-

public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

AreaRegistration -

namespace Makewayy.Areas.HelpPage
{
    public class HelpPageAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
            get
            {
                return "HelpPage";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "HelpPage_Default",
                "Help/{action}/{apiId}",
                new { controller = "Help", action = "Index", apiId = UrlParameter.Optional });

            HelpPageConfig.Register(GlobalConfiguration.Configuration);
        }
    }
}


问:
Angular: composite ControlValueAccessor to implement nested form
Composition of ControlValueAccessor to implement nested form is introduced in an Angular Connect 2017 presentation.

https://docs.google.com/presentation/d/e/2PACX-1vTS20UdnMGqA3ecrv7ww_7CDKQM8VgdH2tbHl94aXgEsYQ2cyjq62ydU3e3ZF_BaQ64kMyQa0INe2oI/pub?slide=id.g293d7d2b9d_1_1532

In this presentation, the speaker showed a way to implement custom form control which have multiple value (not only single string value but has two string field, like street and city). I want to implement it but I'm stuck. Sample app is here, does anybody know what should I correct?

https://stackblitz.com/edit/angular-h2ehwx

parent component

```<code>@Component({
  selector: 'my-app',
  template: `
    <h1>Form</h1>
    <form [formGroup]="form" (ngSubmit)="onSubmit(form.value)" novalidate>
      <label>name</label>
      <input formControlName="name">
      <app-address-form formControlName="address"></app-address-form>
      <button>submit</button>
    </form>
  `,
})
export class AppComponent  {
  @Input() name: string;
  submitData = '';
  form: FormGroup;

  constructor(private fb: FormBuilder) {
    this.form = fb.group({
      name: 'foo bar',
      address: fb.group({
        city: 'baz',
        town: 'qux',
      })
    });
  }

  onSubmit(v: any) {
    console.log(v);
  }
}
</code>```

nested form component

```<code>@Component({
  selector: 'app-address-form',
  template: `
    <div [formGroup]="form">
      <label>city</label>
      <input formControlName="city" (blur)="onTouched()">
      <label>town</label>
      <input formControlName="town" (blur)="onTouched()">
    </div>
  `,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      multi: true,
      useExisting: forwardRef(() => AddressFormComponent)
    }
  ]
})
export class AddressFormComponent implements ControlValueAccessor {
  form: FormGroup;

  onTouched: () => void = () => {};

  writeValue(v: any) {
    this.form.setValue(v, { emitEvent: false });
  }

  registerOnChange(fn: (v: any) => void) {
    this.form.valueChanges.subscribe(fn);
  }

  setDisabledState(disabled: boolean) {
    disabled ? this.form.disable() : this.form.enable();
  }

  registerOnTouched(fn: () => void) {
    this.onTouched = fn;
  }
}
</code>```

and error message I got

```<code>ERROR TypeError: Cannot read property 'setValue' of undefined
at AddressFormComponent.writeValue (address-form.component.ts:32)
at setUpControl (shared.js:47)
at FormGroupDirective.addControl (form_group_directive.js:125)
at FormControlName._setUpControl (form_control_name.js:201)
at FormControlName.ngOnChanges (form_control_name.js:114)
at checkAndUpdateDirectiveInline (provider.js:249)
at checkAndUpdateNodeInline (view.js:472)
at checkAndUpdateNode (view.js:415)
at debugCheckAndUpdateNode (services.js:504)
at debugCheckDirectivesFn (services.js:445)
</code>```

I think FormGroup instance should be injected to nested form component somehow...

答:
Couple issues, on your AppComponent change your FormBuilder to:

```<code>this.form = fb.group({
  name: 'foo bar',
  address: fb.control({ //Not using FormGroup
    city: 'baz',
    town: 'qux',
  })
});
</code>```

On your AddressFormComponent you need to initialize your FormGroup like so:

```<code>form: FormGroup = new FormGroup({
    city: new FormControl,
    town: new FormControl
});
</code>```

Here's the fork of your sample: https://stackblitz.com/edit/angular-np38bi

Body:
Composition of ControlValueAccessor to implement nested form is introduced in an Angular Connect 2017 presentation.

https://docs.google.com/presentation/d/e/2PACX-1vTS20UdnMGqA3ecrv7ww_7CDKQM8VgdH2tbHl94aXgEsYQ2cyjq62ydU3e3ZF_BaQ64kMyQa0INe2oI/pub?slide=id.g293d7d2b9d_1_1532

In this presentation, the speaker showed a way to implement custom form control which have multiple value (not only single string value but has two string field, like street and city). I want to implement it but I'm stuck. Sample app is here, does anybody know what should I correct?

https://stackblitz.com/edit/angular-h2ehwx

parent component

@Component({
  selector: 'my-app',
  template: `

Form

    <form [formGroup]="form" (ngSubmit)="onSubmit(form.value)" novalidate>
      name
      <input formControlName="name">
      <app-address-form formControlName="address"></app-address-form>
      <button>submit</button>
    </form>
  `,
})
export class AppComponent  {
  @Input() name: string;
  submitData = '';
  form: FormGroup;

  constructor(private fb: FormBuilder) {
    this.form = fb.group({
      name: 'foo bar',
      address: fb.group({
        city: 'baz',
        town: 'qux',
      })
    });
  }

  onSubmit(v: any) {
    console.log(v);
  }
}

nested form component

@Component({
  selector: 'app-address-form',
  template: `

      city
      <input formControlName="city" (blur)="onTouched()">
      town
      <input formControlName="town" (blur)="onTouched()">

  `,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      multi: true,
      useExisting: forwardRef(() => AddressFormComponent)
    }
  ]
})
export class AddressFormComponent implements ControlValueAccessor {
  form: FormGroup;

  onTouched: () => void = () => {};

  writeValue(v: any) {
    this.form.setValue(v, { emitEvent: false });
  }

  registerOnChange(fn: (v: any) => void) {
    this.form.valueChanges.subscribe(fn);
  }

  setDisabledState(disabled: boolean) {
    disabled ? this.form.disable() : this.form.enable();
  }

  registerOnTouched(fn: () => void) {
    this.onTouched = fn;
  }
}

and error message I got

ERROR TypeError: Cannot read property 'setValue' of undefined
at AddressFormComponent.writeValue (address-form.component.ts:32)
at setUpControl (shared.js:47)
at FormGroupDirective.addControl (form_group_directive.js:125)
at FormControlName._setUpControl (form_control_name.js:201)
at FormControlName.ngOnChanges (form_control_name.js:114)
at checkAndUpdateDirectiveInline (provider.js:249)
at checkAndUpdateNodeInline (view.js:472)
at checkAndUpdateNode (view.js:415)
at debugCheckAndUpdateNode (services.js:504)
at debugCheckDirectivesFn (services.js:445)

I think FormGroup instance should be injected to nested form component somehow...

Body:
Couple issues, on your AppComponent change your FormBuilder to:

this.form = fb.group({
  name: 'foo bar',
  address: fb.control({ //Not using FormGroup
    city: 'baz',
    town: 'qux',
  })
});

On your AddressFormComponent you need to initialize your FormGroup like so:

form: FormGroup = new FormGroup({
    city: new FormControl,
    town: new FormControl
});

Here's the fork of your sample: https://stackblitz.com/edit/angular-np38bi


问:
Checking values in a class list
Basically, I have a class for the Player of a game

```<code>class Player:
    def __init__(self,inventory,hp):
        self.inventory = []
        self.hp = 20
    ...
    ...

P = Player()
</code>```

And I simply want to check for an item in the inventory (where items are each a class as well)

```<code>class Book():
    def __init__(self,name,description):
        ...
        ...
</code>```

Then do this.

```<code>if Book() in P.inventory:
    print("You have a book.")
else:
    print("You don't have a book.")
</code>```

The problem I'm having is that even if the Book() object is in the player's inventory, it reads the if statement as false and runs the else statement.

I'm thinking I could try to use a for loop like so

```<code>for i in P.inventory:
    counter = 0
    if i == Book():
        print("You have a book.")
        counter = 1
if counter == 0:
    print("You don't have a book.")
</code>```

but I'm hoping I won't have to use that much code for such a simple task.

答:
You'll have to check the object type of the items in the inventory to see if they are of class Book()

```<code>for o in P.inventory:
    if isinstance(o, Book()):
        print("You have a book.")
        break
else:
    print("You don't have a book.")
</code>```

Notice that the else statement is part of the for statement, not the if statement

Title: Checking values in a class list

Body:
Basically, I have a class for the Player of a game

class Player:
    def __init__(self,inventory,hp):
        self.inventory = []
        self.hp = 20
    ...
    ...

P = Player()

And I simply want to check for an item in the inventory (where items are each a class as well)

class Book():
    def __init__(self,name,description):
        ...
        ...

Then do this.

if Book() in P.inventory:
    print("You have a book.")
else:
    print("You don't have a book.")

The problem I'm having is that even if the Book() object is in the player's inventory, it reads the if statement as false and runs the else statement.

I'm thinking I could try to use a for loop like so

for i in P.inventory:
    counter = 0
    if i == Book():
        print("You have a book.")
        counter = 1
if counter == 0:
    print("You don't have a book.")

but I'm hoping I won't have to use that much code for such a simple task.

Body:
You'll have to check the object type of the items in the inventory to see if they are of class Book()

for o in P.inventory:
    if isinstance(o, Book()):
        print("You have a book.")
        break
else:
    print("You don't have a book.")

Notice that the else statement is part of the for statement, not the if statement


问:
Low-latency video streaming from c++ opencv application in WINDOWS
There are quite a lot of questions on the topic, but most of them involve the use of undesired protocols - HTML5, WebRTC, etc.

Basically, the problem can formulated as follows: how do I stream my own cv::Mat images over either RTSP or MJPEG [AFAIK it is better for realtime streaming] streams in Windows? Nearly everything I can find relies on the OS being Linux, and is just not applicable to the project.

FFMPEG's pipelining sort of worked, but the delay was about 10 seconds. Could take it down to 3-4 seconds using some -incomprehensibly-long-parameter-list-that-ffmpeg-team-loves-so-much, but it is not enough, because the project under consideration is a surveillance app with active user controlling the camera, so I need to be as close to realtime as possible.

Another issue is that the solution should not eat the whole amount of cores, because they are already overloaded with object tracking algorithms.

Thanks for help in advance!

EDIT:
ffmpeg -re -an -f mjpeg -i http://..addr.../video.mjpg -vcodec libx264 -tune zerolatency -f rtp rtp://127.0.0.1:1234 -sdp_file stream.sdp - command I used to retranslate the stream directly without any preprocessing, and it yielded about 4 seconds of delay on a localhost.

答:
First you have to find out from where your latency is coming from.

There are basic 4 sources of latency:

Video Capture

Encoding

Transmission

Decoding (Player)

Since you are measuring from localhost, we could consider transmission as 0 seconds. If your video resolution and frame rate are not gargantuan, decoding times would also be close to zero.

We now should focus on the first 2 itens: Capture and Encoding.

The "problem" here is that libx264 is a software encoder. So, it uses CPU power AND needs the data in the main memory, not in the GPU memory where the image is first created.

So, when FFMPEG captures a frame it has to pass the layers of the OS from video memory to main memory.

Unfortunately you wont get any better results than 3 or 2 seconds if you use libx264.

I suggest you take a look on the Nvidia Capture solution.
https://developer.nvidia.com/capture-sdk

If you are using a capable GPU you can than capture and encode each frame from the backbuffer or intra frame buffer directly in the GPU. You can than use ffmpeg to send it as you please.


问:
What are the most common/uncommon error messages one encounters in Objective-C and what causes them?
I've been trying to maintain a list of all the error messages I ever encounter while developing and their common causes and fixes. What are the common (and the not so common) error messages you encountered and how did you fix them?  </p>

答:
In general I find objective-c exception and error messages tO be self-explanatory. I think you would be better served by learning to use the debugger with breakpoints on objective-c exceptions to locate the specific line causing a crash than by trying to compile a list of recipies for resolving common errors.

That said the one non-obvious error I see as a frequent point of confusion is "unrecognized selector foo: sent to BarClass". While the reason why that is an error should be clear answering how that happened can be harder and I see two common causes:

An app is attempting to call a subclass' method on an instance of a super class. Often a result of developers failing to change the class of objects in IB.

An object has been over-released or otherwise referenced after being deallocated. If a new instance of some other class now occupies that memory address the app with hit an "unrecognized selector" exception rather than a "BAD_ACCESS".


问:
Thymeleaf does not Serialize the object
I had trying to display a bootstrap modal when i click a row with the extra data
but when y try to print the object , it does not work:

```<code><table id="datatable" class="table table-striped table-bordered">
    <thead>
    <tr>
        <th># Factura</th>
        <th>Cliente</th>
        <th>Fecha</th>
        <th>Accion</th>
    </tr>
    </thead>

    <tbody>
    <tr th:each="bill : ${bills}">
        <td th:text="${bill.bill_id}"></td>
        <td th:text="${bill.client.name}"></td>
        <td th:text="${bill.date}"></td>
        <td>
            <a class="btn btn-info btn-xs open-modal" data-whatever="[[{$bill}]]" data-toggle="modal" data-target="#billModal">Ver Detalles</a>
        </td>
    </tr>
    </tbody>
</table>
</code>```

so, i dont know how to that bill object and send it to the modal, i have tried many ways.And it only serialize when i put with th:text or th:value

Title: Thymeleaf does not Serialize the object

Body:
I had trying to display a bootstrap modal when i click a row with the extra data
but when y try to print the object , it does not work:

        # Factura
        Cliente
        Fecha
        Accion

            Ver Detalles

so, i dont know how to that bill object and send it to the modal, i have tried many ways.And it only serialize when i put with th:text or th:value

Body: th:attr="data-whatever=${bill}"


问:
Return a dictionary with keys that are the first letter of a word and lists of those words?
I want to write a function that takes a list of words and keys and outputs those keys as dictionary keys with any words starting with that letter attached.
How could this be achieved using simple python 3 code?

eg. takes (['apples', 'apple', 'bananna', 'fan'], 'fad')

returns {'a' : ['apple', 'apples'], 'f' : ['fan']}

so far i have tried:

```<code>def dictionary(words, char_keys)
char_keys = remove_duplicates(char_keys)
ret = {}
keys_in_dict = []
words = sorted(words)
for word in words:
    if word[0] in char_keys and word[0] not in keys_in_dict:
        ret[word[0]] = word
        keys_in_dict.append(word[0])
    elif word[0] in keys_in_dict:
        ret[word[0]] += (word)
return ret
</code>```

This gives kinda the right output but it the output is in a single string rather than a list of strings.(the def is not indented properly i know)

答:
If the input is a list of strings, you can check if the char is in the dict, if yes, append the word, otherwise add a list with the word:

```<code>def dictionary(inpt):
    result = {}
    for word in inpt:
        char = word[0]
        if char in result:
            result[char].append(word)
        else:
            result[char] = [word]
    return result
</code>```

The modern way to do this is to use a collections.defaultdict with list as argument.

```<code>def dictionary(inpt):
    result = defaultdict(list)
    for word in inpt:
        result[word[0]].append(word)
    return result
</code>```

Body:
I want to write a function that takes a list of words and keys and outputs those keys as dictionary keys with any words starting with that letter attached.
How could this be achieved using simple python 3 code?

eg. takes (['apples', 'apple', 'bananna', 'fan'], 'fad')

returns {'a' : ['apple', 'apples'], 'f' : ['fan']}

so far i have tried:

def dictionary(words, char_keys)
char_keys = remove_duplicates(char_keys)
ret = {}
keys_in_dict = []
words = sorted(words)
for word in words:
    if word[0] in char_keys and word[0] not in keys_in_dict:
        ret[word[0]] = word
        keys_in_dict.append(word[0])
    elif word[0] in keys_in_dict:
        ret[word[0]] += (word)
return ret

This gives kinda the right output but it the output is in a single string rather than a list of strings.(the def is not indented properly i know)

Body:
If the input is a list of strings, you can check if the char is in the dict, if yes, append the word, otherwise add a list with the word:

def dictionary(inpt):
    result = {}
    for word in inpt:
        char = word[0]
        if char in result:
            result[char].append(word)
        else:
            result[char] = [word]
    return result

The modern way to do this is to use a collections.defaultdict with list as argument.

def dictionary(inpt):
    result = defaultdict(list)
    for word in inpt:
        result[word[0]].append(word)
    return result


问:
Regular expression for alpahbet,underscore,hyphen,apostrophe only
I want a regular expression that accept only alphabets,hyphen,apostrophe,underscore.
I tried

```<code>/^[ A-Za-z-_']*$/
</code>```

but its not working. Please help.

答:
You can use the following (in Java):

```<code>String acceptHyphenApostropheUnderscoreRegEx = "^(\\p{Alpha}*+((['_-]+)\\p{Alpha})?)*+$";
</code>```

If you want to have spaces and @ also (as some have given above) try:

```<code>String acceptHyphenApostropheUnderscoreRegEx = "^(\\p{Alpha}*+((\\s|['@_-]+)\\p{Alpha})?)*+$";
</code>```

Body:
I want a regular expression that accept only alphabets,hyphen,apostrophe,underscore.
I tried

/^[ A-Za-z-_']*$/

but its not working. Please help.

Body:
You can use the following (in Java):

String acceptHyphenApostropheUnderscoreRegEx = "^(\\p{Alpha}*+((['_-]+)\\p{Alpha})?)*+$";

If you want to have spaces and @ also (as some have given above) try:

String acceptHyphenApostropheUnderscoreRegEx = "^(\\p{Alpha}*+((\\s|['@_-]+)\\p{Alpha})?)*+$";


问:
Laravel foreach array on view
Hello I have array like this, can you help me how to foreach to view.

array(2) {
  [0]=>
  string(1) "2"
  [1]=>
  string(2) "19"
}

答:
If you have an array like this:

```<code>$array = ["2", "19"];
</code>```

You can view it using the blade template engine like so:

```<code>@foreach($array as $item)
  {{$item}}
@endforeach
</code>```

If you just want to access it in normal PHP though it would be like:

```<code>foreach($array as $item) {
  echo $item;
  // or whatever you want to do with the information here
}
</code>```

Is this what you are trying to do?

Title: Laravel foreach array on view

Body:
If you have an array like this:

$array = ["2", "19"];

You can view it using the blade template engine like so:

@foreach($array as $item)
  {{$item}}
@endforeach

If you just want to access it in normal PHP though it would be like:

foreach($array as $item) {
  echo $item;
  // or whatever you want to do with the information here
}

Is this what you are trying to do?


问:
Populate variable from a JSON Result in ASP.NET MVC
I don't know if this is a basic stuff but I'm a having a hard time on populating a variable from a JSON result. I can't just find a right keyword on it.

What I want to do is populate this variable.

Js File

```<code>var opts = [
 { key: 1, label: 'High' },
 { key: 2, label: 'Normal' },
 { key: 3, label: 'Low' }
];
</code>```

Layer

```<code>public IEnumerable<DropdownModel> ToLayerLevel()
    {
        List<DropdownModel> data = new List<DropdownModel>();
        using (SqlConnection con = new SqlConnection(Conn.MyConn()))
        {
            SqlCommand com = new SqlCommand("SELECT id, desc FROM PriorityLevel", con);
            con.Open();
            SqlDataReader reader = com.ExecuteReader();
            while (reader.Read())
            {
                DropdownModel value = new DropdownModel();
                value.key = reader.GetInt32(0);
                value.label = reader.GetString(1);
                data.Add(value);
            }
        }
        return data;
    }
</code>```

Controller

```<code>public JsonResult ddlToLayerLevel()
    {
        DropdownLayers ddl = new DropdownLayers();
        var data = ddl.ToLayerLevel();
        return Json(data, JsonRequestBehavior.AllowGet);
    }
</code>```

答:
You can make an ajax call to the server action method where it will return the data you need

```<code>public JsonResult ddlToLayerLevel()
{
    var ddl = new DropdownLayers();
    var data = ddl.ToLayerLevel().ToList();
    return Json(data, JsonRequestBehavior.AllowGet);
}
</code>```

This will return an array of items with key and label properties, in JSON format

```<code>[{"key":1,"label":"High"},{"key":2,"label":"Normal"},{"key":3,"label":"Low"}]
</code>```

Now you can call this action method using ajax . Here is a sample using jQuery $.get method.

```<code>var url="/YourControllerName/ddlToLayerLevel";
$.get(url).done(function(resultArray) {
                // resultArray is an array of items.
                //  Use it inside this callback method scope
             var opts=resultArray;
             console.log(opts);
          });
</code>```

To avoid 404 Not found errors, when making ajax call's from external js files, you may use the Url.Action method to generate the correct relative path in your view file(where you can execute C# methods like Url.Action) and use that in your external js file.

For example, you can do like this in your razor view file

```<code><script>
    var myProject= myProject|| {};
    myProject.layerLevelUrl ="@Url.Action("ddlToLayerLevel","YourControllerName")";
</script>
<script src="pathToYourExternalJsFile.js"></script>
</code>```

Now in your external js file you can use it like

```<code>$.get(myProject.layerLevelUrl)
 .done(function(resultArray) {
     // resultArray is an array of items. Use it inside this callback method
     var opts=resultArray;
     console.log(JSON.stringify(opts));
 });
</code>```

Body:
I don't know if this is a basic stuff but I'm a having a hard time on populating a variable from a JSON result. I can't just find a right keyword on it.

What I want to do is populate this variable.

Js File

var opts = [
 { key: 1, label: 'High' },
 { key: 2, label: 'Normal' },
 { key: 3, label: 'Low' }
];

Layer

public IEnumerable<DropdownModel> ToLayerLevel()
    {
        List<DropdownModel> data = new List<DropdownModel>();
        using (SqlConnection con = new SqlConnection(Conn.MyConn()))
        {
            SqlCommand com = new SqlCommand("SELECT id, desc FROM PriorityLevel", con);
            con.Open();
            SqlDataReader reader = com.ExecuteReader();
            while (reader.Read())
            {
                DropdownModel value = new DropdownModel();
                value.key = reader.GetInt32(0);
                value.label = reader.GetString(1);
                data.Add(value);
            }
        }
        return data;
    }

Controller

public JsonResult ddlToLayerLevel()
    {
        DropdownLayers ddl = new DropdownLayers();
        var data = ddl.ToLayerLevel();
        return Json(data, JsonRequestBehavior.AllowGet);
    }

Body:
You can make an ajax call to the server action method where it will return the data you need

public JsonResult ddlToLayerLevel()
{
    var ddl = new DropdownLayers();
    var data = ddl.ToLayerLevel().ToList();
    return Json(data, JsonRequestBehavior.AllowGet);
}

This will return an array of items with key and label properties, in JSON format

[{"key":1,"label":"High"},{"key":2,"label":"Normal"},{"key":3,"label":"Low"}]

Now you can call this action method using ajax . Here is a sample using jQuery $.get method.

var url="/YourControllerName/ddlToLayerLevel";
$.get(url).done(function(resultArray) {
                // resultArray is an array of items.
                //  Use it inside this callback method scope
             var opts=resultArray;
             console.log(opts);
          });

To avoid 404 Not found errors, when making ajax call's from external js files, you may use the Url.Action method to generate the correct relative path in your view file(where you can execute C# methods like Url.Action) and use that in your external js file.

For example, you can do like this in your razor view file

<script>
    var myProject= myProject|| {};
    myProject.layerLevelUrl ="@Url.Action("ddlToLayerLevel","YourControllerName")";
</script>
<script src="pathToYourExternalJsFile.js"></script>

Now in your external js file you can use it like

$.get(myProject.layerLevelUrl)
 .done(function(resultArray) {
     // resultArray is an array of items. Use it inside this callback method
     var opts=resultArray;
     console.log(JSON.stringify(opts));
 });


问:
Compatibility of shadowdomv1 on firefox
I'm trying to use ShadowDomv1 (with https://github.com/webcomponents/webcomponentsjs and https://github.com/webcomponents/shadycss) but it's not working.

The ShadowDom by itself works, but the css is not encapsulated (as we can see with the h2 css rule).

It works as intended on Chrome and Safari (but they both support ShadowDomv1 natively).

Am I missing something or is it impossible ?

Here the jsbin : http://jsbin.com/maqohoxowu/edit?html,output

And the code :

```<code><script type="text/javascript" src="https://rawgithub.com/webcomponents/webcomponentsjs/master/webcomponents-hi-sd-ce.js"></script>
<style type="text/css">
    h2 {
        color: red;
        border-bottom: 1px black dotted;
    }
</style>
<h2>h2 red and dotted</h2>

<my-element>
</my-element>

<template id="myElementTemplate">
    <style scope="my-element">
        h2 {color: blue}
    </style>
    <div>
        <h2>h2 blue and not dotted !</h2> <!-- Should not be dotted because of the encapsulation -->
    </div>
</template>

<script type="text/javascript">
    ShadyCSS.prepareTemplate(myElementTemplate, 'my-element');

    class MyElement extends HTMLElement {
        connectedCallback() {
            ShadyCSS.styleElement(this);

            if (!this.shadowRoot) {
                this.attachShadow({mode: 'open'});
                this.shadowRoot.appendChild(document.importNode(myElementTemplate.content, true));
            }
            ShadyCSS.styleElement(this);
        }
    }

    customElements.define("my-element", MyElement);
</script>
</code>```

答:
The polyfill can not emulate the encapsulation of CSS that is handled natively by true ShadowDOM.

Instead, if you plan to use both then avoid using simple CSS selectors. Instead try using a CSS naming pattern like BEM: http://getbem.com/introduction/

This will allow your CSS to work, most of the time, in either true ShadowDOM and in ShadyDOM.

Title: Compatibility of shadowdomv1 on firefox

Body:
I'm trying to use ShadowDomv1 (with https://github.com/webcomponents/webcomponentsjs and https://github.com/webcomponents/shadycss) but it's not working.

The ShadowDom by itself works, but the css is not encapsulated (as we can see with the h2 css rule).

It works as intended on Chrome and Safari (but they both support ShadowDomv1 natively).

Am I missing something or is it impossible ?

Here the jsbin : http://jsbin.com/maqohoxowu/edit?html,output

And the code :

h2 red and dotted

<my-element>
</my-element>

<template id="myElementTemplate">

h2 blue and not dotted !

</template>


问:
How can I query a TFS Build Definition custom defined variable within a PowerShell Build Step
In my TFS Build Definition I want to create a custom variable within the Variables Tab. This variable I want to name MyVariable.

In my Build Definition I have a PowerShell script step.
In this powershell script (PS1) I want to query the value of the variable.

How can I do this?

The following things I tried, but these do not work:

```<code>Write-Host "MyVariable: $Env:MyVariable"
Write-Host "MyVariable: $MyVariable
</code>```

答:
Manu is right, the PowerShell script format is incorrect.

Please try:

```<code>Write-Host "MyVariable:" $Env:MyVariable
</code>```

Body:
In my TFS Build Definition I want to create a custom variable within the Variables Tab. This variable I want to name MyVariable.

In my Build Definition I have a PowerShell script step.
In this powershell script (PS1) I want to query the value of the variable.

How can I do this?

The following things I tried, but these do not work:

Write-Host "MyVariable: $Env:MyVariable"
Write-Host "MyVariable: $MyVariable

Body:
Manu is right, the PowerShell script format is incorrect.

Please try:

Write-Host "MyVariable:" $Env:MyVariable


问:
How can I read user input from the console?
I want to get a number from the user, and then multiply that number with Pi. my attempt at this is below. But a contains gibberish. For example, if I insert 22, then a contains 50. What am I doing wrong? I don't get any compiler errors.

```<code>double a,b;
a = Console.Read();
b = a * Math.PI;
Console.WriteLine(b);
</code>```

答:
Sometime in the future .NET4.6</p>

```<code>//for Double
double inputValues = double.Parse(Console.ReadLine());

//for Int
int inputValues = int.Parse(Console.ReadLine());
</code>```

Body:
I want to get a number from the user, and then multiply that number with Pi. my attempt at this is below. But a contains gibberish. For example, if I insert 22, then a contains 50. What am I doing wrong? I don't get any compiler errors.

double a,b;
a = Console.Read();
b = a * Math.PI;
Console.WriteLine(b);

Body:
Sometime in the future .NET4.6

//for Double
double inputValues = double.Parse(Console.ReadLine());

//for Int
int inputValues = int.Parse(Console.ReadLine());


问:
Promise resolves before forEach loop completes
I'm building my first CRUD (library) application and recently learned about promises as a means to avoid deeply-nested callbacks. I'm attempting to seed my DB with some data each time the server starts, but I seem to be missing something conceptually.

I have four objects in a bookData array that I want to iterate over and save to the DB using Mongoose:

function seedBooks() {
    return new Promise(function(resolve,reject){
        bookData.forEach(function(seed){
            Book.create(seed, function(err, newBook){
                if(err) {
                    reject(err);
                }
            });
        });
        resolve();
    });
}```
</div>
</div>
</p>

<p>This function is one of a few that I am attempting to chain together, which is why I'm using promises. But I'm finding that <code>seedBooks()</code> resolves with anywhere between 1 and 4 of the sample books created,  </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function seedDB() {
    removeAllBooks()
    .then(function(){
        return removeAllUsers();
    })
    .then(function(){
        return seedUsers();
    })
    .then(function(){
        return seedBooks();
    })
    .then(function(){
        return seedBookInstances();
    });
}</code>```

Am I understanding or using promises & resolve incorrectly? Any help is appreciated. Thanks!

答:
Edit: The below explains why your code is not working and advice for, in general, how to convert non-promise code to promises. Since Mongoose produces promises, however, you should be using those instead of using new Promise. See Olegzandr's answer regarding that.

The promise is resolving immediately because you are calling resolve() immediately.

The rule of thumb when converting non-promises to promises is to promisify the smallest part of the non-promise code. In this case, it means promisifying the code to save a single item. If you do that, the collect place to call resolve() becomes clear:

```<code>function seedBook(seed) {
    return new Promise(function (resolve, reject) {
        Book.create(seed, function (err, newBook) {
            if (err) { reject(err); } else { resolve(newBook); }
        });
    });
}

function seedBooks() {
    return Promise.all(bookData.map(seedBook));
}
</code>```

This also has the benefit of allowing you to access the returned newBooks, should you want to.

Body:
I'm building my first CRUD (library) application and recently learned about promises as a means to avoid deeply-nested callbacks. I'm attempting to seed my DB with some data each time the server starts, but I seem to be missing something conceptually.

I have four objects in a bookData array that I want to iterate over and save to the DB using Mongoose:

function seedBooks() {
    return new Promise(function(resolve,reject){
        bookData.forEach(function(seed){
            Book.create(seed, function(err, newBook){
                if(err) {
                    reject(err);
                }
            });
        });
        resolve();
    });
}

This function is one of a few that I am attempting to chain together, which is why I'm using promises. But I'm finding that seedBooks() resolves with anywhere between 1 and 4 of the sample books created,

function seedDB() {
    removeAllBooks()
    .then(function(){
        return removeAllUsers();
    })
    .then(function(){
        return seedUsers();
    })
    .then(function(){
        return seedBooks();
    })
    .then(function(){
        return seedBookInstances();
    });
}

Am I understanding or using promises & resolve incorrectly? Any help is appreciated. Thanks!

Body:
Edit: The below explains why your code is not working and advice for, in general, how to convert non-promise code to promises. Since Mongoose produces promises, however, you should be using those instead of using new Promise. See Olegzandr's answer regarding that.

The promise is resolving immediately because you are calling resolve() immediately.

The rule of thumb when converting non-promises to promises is to promisify the smallest part of the non-promise code. In this case, it means promisifying the code to save a single item. If you do that, the collect place to call resolve() becomes clear:

function seedBook(seed) {
    return new Promise(function (resolve, reject) {
        Book.create(seed, function (err, newBook) {
            if (err) { reject(err); } else { resolve(newBook); }
        });
    });
}

function seedBooks() {
    return Promise.all(bookData.map(seedBook));
}

This also has the benefit of allowing you to access the returned newBooks, should you want to.


问:
Connecting multiple javascript elements together with data-attributes (JSFiddle included)
I have a javascript function that works when I only have one element on the page, but with multiple items I don't know how to pair each item to its corresponding image.

In this JSFiddle, what I currently have is laid out. When you hover over "link 3" it is behaving properly, the image is supposed to appear under the mouse while hovering over the link. But when I hover over the other links, they don't know which item to make visible.

I can pass unique slugs to any of the items in the links. Does anyone know the best way to properly connect each item?

https://jsfiddle.net/xw2Lvvj7/

var $img = $('.image');
$img.hide();
$('.hidden-overlay').mousemove(function(e) {
  $img.stop(1, 1).fadeIn();
  $('.image').offset({
    top: e.pageY - ($img.outerHeight() / 2),
    left: e.pageX - ($img.outerWidth() / 2)
  });
}).mouseleave(function() {
  $img.fadeOut();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  padding: 90px;
}

.link {
  background: red;
  position: relative;
  z-index: 1;
}

.image {
  background-size: cover;
  height: 90px;
  width: 90px;
  position: absolute;
  z-index: 2;
}

.hidden-overlay {
  position: absolute;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
  z-index: 3
}</code>```

        link 1

        link 2

        link 3

```

答:
You can find each of their .image classes parents to something like this:

var $img = $('.image');
$img.hide();
$('.hidden-overlay').mousemove(function(e) {

  // Find the [.image] classes inside the [.link] parent classes for every .hidden-overlay
  var oImageHover = $(this).parents('.link').find('.image');
  oImageHover.stop(1, 1).fadeIn();
  oImageHover.offset({
    top: e.pageY - (oImageHover.outerHeight() / 2),
    left: e.pageX - (oImageHover.outerWidth() / 2)
  });
}).mouseleave(function() {
  // The same thing as well when the element was out of focus
  var oImageLeave = $(this).parents('.link').find('.image');
  oImageLeave.fadeOut();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  padding: 90px;
}

.link {
  background: red;
  position: relative;
  z-index: 1;
}

.image {
  background-size: cover;
  height: 90px;
  width: 90px;
  position: absolute;
  z-index: 2;
}

.hidden-overlay {
  position: absolute;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
  z-index: 3
}</code>```

    link 1

    link 2

    link 3

  ```

Hope this helps for your case

Body:
I have a javascript function that works when I only have one element on the page, but with multiple items I don't know how to pair each item to its corresponding image.

In this JSFiddle, what I currently have is laid out. When you hover over "link 3" it is behaving properly, the image is supposed to appear under the mouse while hovering over the link. But when I hover over the other links, they don't know which item to make visible.

I can pass unique slugs to any of the items in the links. Does anyone know the best way to properly connect each item?

https://jsfiddle.net/xw2Lvvj7/

var $img = $('.image');
$img.hide();
$('.hidden-overlay').mousemove(function(e) {
  $img.stop(1, 1).fadeIn();
  $('.image').offset({
    top: e.pageY - ($img.outerHeight() / 2),
    left: e.pageX - ($img.outerWidth() / 2)
  });
}).mouseleave(function() {
  $img.fadeOut();
});

body {
  padding: 90px;
}

.link {
  background: red;
  position: relative;
  z-index: 1;
}

.image {
  background-size: cover;
  height: 90px;
  width: 90px;
  position: absolute;
  z-index: 2;
}

.hidden-overlay {
  position: absolute;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
  z-index: 3
}

        link 1

        link 2

        link 3

Body:
You can find each of their .image classes parents to something like this:

var $img = $('.image');
$img.hide();
$('.hidden-overlay').mousemove(function(e) {

  // Find the [.image] classes inside the [.link] parent classes for every .hidden-overlay
  var oImageHover = $(this).parents('.link').find('.image');
  oImageHover.stop(1, 1).fadeIn();
  oImageHover.offset({
    top: e.pageY - (oImageHover.outerHeight() / 2),
    left: e.pageX - (oImageHover.outerWidth() / 2)
  });
}).mouseleave(function() {
  // The same thing as well when the element was out of focus
  var oImageLeave = $(this).parents('.link').find('.image');
  oImageLeave.fadeOut();
});

body {
  padding: 90px;
}

.link {
  background: red;
  position: relative;
  z-index: 1;
}

.image {
  background-size: cover;
  height: 90px;
  width: 90px;
  position: absolute;
  z-index: 2;
}

.hidden-overlay {
  position: absolute;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
  z-index: 3
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <a class="link" data-slug="1">
    link 1
    <div class="image" style="background-image: url('http://via.placeholder.com/350x150');" data-slug="1"></div>
    <div class="hidden-overlay" data-slug="1"></div>
  </a>
  <br>
  <br>
  <br>
  <br>
  <a class="link" data-slug="2">
    link 2
    <div class="image" style="background-image: url('http://via.placeholder.com/450x450');" data-slug="2"></div>
    <div class="hidden-overlay" data-slug="2"></div>
  </a>
  <br>
  <br>
  <br>
  <br>
  <a class="link" data-slug="3">
    link 3
    <div class="image" style="background-image: url('http://via.placeholder.com/100x100');" data-slug="3"></div>
    <div class="hidden-overlay" data-slug="3"></div>
  </a>

  <body>

Hope this helps for your case


问:
Fill available space without overflowing
I am trying to create a desktop application user interface with html and what i want to achieve is having a fixed header and footer with content filling the remaining (whatever) space the window is. Been trying to use flex but not quite understand how it works with almost all of my trials ending up with an overflow.

Fiddle
http://jsfiddle.net/4dxperkp/

```<code>section {
  display: flex;
  flex-flow: column;
}

header {
  background: tomato;
}

div {
  background: gold;

  height: 100vh;
}

footer {
  background: tomato;
}
</code>```

I also came accross -webkit-fill-available but it end up causing an overflow as well.

答:
Use CSS's calc() function in min-height using javascript (for dynamic height calculations) like:

```<code>var heightHeader = $('header').height();
var heightFooter = $('footer').height();
var mainHeight = heightHeader + heightFooter;
var divHeight = 'calc(100vh - ' + mainHeight + 'px)';

$('.main-content').css('min-height', divHeight);
</code>```

Have a look at the updated Fiddle.

Hope this helps!

Body:
I am trying to create a desktop application user interface with html and what i want to achieve is having a fixed header and footer with content filling the remaining (whatever) space the window is. Been trying to use flex but not quite understand how it works with almost all of my trials ending up with an overflow.

Fiddle
http://jsfiddle.net/4dxperkp/

section {
  display: flex;
  flex-flow: column;
}

header {
  background: tomato;
}

div {
  background: gold;

  height: 100vh;
}

footer {
  background: tomato;
}

I also came accross -webkit-fill-available but it end up causing an overflow as well.

Body:
Use CSS's calc() function in min-height using javascript (for dynamic height calculations) like:

var heightHeader = $('header').height();
var heightFooter = $('footer').height();
var mainHeight = heightHeader + heightFooter;
var divHeight = 'calc(100vh - ' + mainHeight + 'px)';

$('.main-content').css('min-height', divHeight);

Have a look at the updated Fiddle.

Hope this helps!


问:
Best method to authenticate that a user is actually a college student using gmail API in iOS?
When I type in a .edu address into gmail.com it automatically takes me the CAS page for that specific university. Does anyone know how I can direct the user to that specific CAS page for the university given that he or she gives me the school that they go to in my Android or iOS application?

I need to authenticate that a student is actually in a university in my app, so this is the method I am thinking to use. Is there any other better way?

答:
A user possessing an email address on a university's domain is certainly a good indication that they have an affiliation with the school. If you're using Google's SSO service, you can let the service do the authentication (which in Google's case, means using their account chooser) and then block any accounts that don't come from approved domains.

A similar approach, albeit with potentially more flexibility, would be to use a service like Firebase and create your own username/password based authentication system. With Firebase, this isn't hard to do, and you'd be able to restrict sign-ups by using the email verification system. Part of your validation could be a check to make sure the email address used is on an approved domain.

Docs:

https://firebase.google.com/docs/auth/android/password-auth


问:
Dispose C# DLL marked for COM interop
I created a vanilla C# dll and marked it for COM inter op. The dll is a plain user form with no functionality as this is an experiment.

I registered the DLL and opened active x test container and instantiated my COM object. It shows up in the test container and i can view the exposed methods of the control - these are the default methods and not created by me.

i then exit from the active x test container and i noticed that test container was still lurking around in task manager and that i had to kill the process manually. This leads me to believe that the test container still holds a reference to my C# dll exposed for com inter op.

The default dispose method in the designer.cs is

```<code> protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);

   }
</code>```

When i used the test container with Quick time, it invoked quick time as expected and when i closed the test container it disposed correctly and did not leave a footprint in the task manager.

The question - is there a specific thing that i must do in my dispose method? Also, this may not be relevant, but when i create a test project and it launches my c# control and i click on the close button, it closes my test form but the test application ins still running in debug mode - the run button is disabled.

答:
You could try:

```<code>public void IDisposable.Dispose()
{
   System.Runtime.InteropServices.Marshal.ReleaseComObject(this);
}
</code>```

Typically you do this when consuming COM objects from within .net, not sure about the other way. But it can't hurt to try. Let me know how it worked out;-)

Edit:

You can also try and supress finalization:

GC.SuppressFinalize(this);

Title: Dispose C# DLL marked for COM interop

Body:
I created a vanilla C# dll and marked it for COM inter op. The dll is a plain user form with no functionality as this is an experiment.

I registered the DLL and opened active x test container and instantiated my COM object. It shows up in the test container and i can view the exposed methods of the control - these are the default methods and not created by me.

i then exit from the active x test container and i noticed that test container was still lurking around in task manager and that i had to kill the process manually. This leads me to believe that the test container still holds a reference to my C# dll exposed for com inter op.

The default dispose method in the designer.cs is

 protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);

   }

When i used the test container with Quick time, it invoked quick time as expected and when i closed the test container it disposed correctly and did not leave a footprint in the task manager.

The question - is there a specific thing that i must do in my dispose method? Also, this may not be relevant, but when i create a test project and it launches my c# control and i click on the close button, it closes my test form but the test application ins still running in debug mode - the run button is disabled.

Body:
You could try:

public void IDisposable.Dispose()
{
   System.Runtime.InteropServices.Marshal.ReleaseComObject(this);
}

Typically you do this when consuming COM objects from within .net, not sure about the other way. But it can't hurt to try. Let me know how it worked out;-)

Edit:

You can also try and supress finalization:

GC.SuppressFinalize(this);

OwnerDisplayName: Josh

LastEditorDisplayName: Josh


问:
p-datatable rowStyleClass doesn't style every row
I'm using
, and the method in my component looks like this:

```<code>  newRowFormat(rowData, rowIndex) {
    return('newRow');
  }
</code>```

And in the component CSS, that class newRow looks like this:

```<code>:host /deep/ .newRow {
  background-color: gold;
}
</code>```

The result is that every other row of the table is being colored gold, when every row should have that class applied to it.  Long story, but I want the class applied to every single row, not every other row.

Ideas?

答:
Well, the solution (at least for now) turned out to be to use the forbidden !important rule:

```<code>:host /deep/ .newRow {
  background-color: gold!important;
}
</code>```

Don't really like it (or understand why it works), but it works.  Trying to override PrimeNG styles is requiring me to use :host /deep/ as well as !important in this case.

Body:
I'm using
, and the method in my component looks like this:

  newRowFormat(rowData, rowIndex) {
    return('newRow');
  }

And in the component CSS, that class newRow looks like this:

:host /deep/ .newRow {
  background-color: gold;
}

The result is that every other row of the table is being colored gold, when every row should have that class applied to it.  Long story, but I want the class applied to every single row, not every other row.

Ideas?

Body:
Well, the solution (at least for now) turned out to be to use the forbidden !important rule:

:host /deep/ .newRow {
  background-color: gold!important;
}

Don't really like it (or understand why it works), but it works.  Trying to override PrimeNG styles is requiring me to use :host /deep/ as well as !important in this case.


问:
What is the best way to check if a tuple has any empty/None values in Python?
What is the best/most efficient way to check if all tuple values? Do I need to iterate over all tuple items and check or is there some even better way?

For example:

```<code>t1 = (1, 2, 'abc')
t2 = ('', 2, 3)
t3 = (0.0, 3, 5)
t4 = (4, 3, None)
</code>```

Checking these tuples, every tuple except t1, should return True, meaning there is so called empty value.

P.S. there is this question: Test if tuple contains only None values with Python, but is it only about None values

答:
An answer using all has been provided:

```<code>not all(t1)
</code>```

However in a case like t3, this will return True, because one of the values is 0:

```<code>t3 = (0.0, 3, 5)
</code>```

The 'all' built-in keyword checks if all values of a given iterable are values that evaluate to a negative boolean (False). 0, 0.0, '' and None all evaluate to False.

If you only want to test for None (as the title of the question suggests), this works:

```<code>any(map(lambda x: x is None, t3))
</code>```

This returns True if any of the elements of t3 is None, or False if none of them are.

Body:
What is the best/most efficient way to check if all tuple values? Do I need to iterate over all tuple items and check or is there some even better way?

For example:

t1 = (1, 2, 'abc')
t2 = ('', 2, 3)
t3 = (0.0, 3, 5)
t4 = (4, 3, None)

Checking these tuples, every tuple except t1, should return True, meaning there is so called empty value.

P.S. there is this question: Test if tuple contains only None values with Python, but is it only about None values

Body:
An answer using all has been provided:

not all(t1)

However in a case like t3, this will return True, because one of the values is 0:

t3 = (0.0, 3, 5)

The 'all' built-in keyword checks if all values of a given iterable are values that evaluate to a negative boolean (False). 0, 0.0, '' and None all evaluate to False.

If you only want to test for None (as the title of the question suggests), this works:

any(map(lambda x: x is None, t3))

This returns True if any of the elements of t3 is None, or False if none of them are.


问:
Passing values to MySQL IN operation in PDO prepared statement?
I have a form field that is returning a comma-delimited string that I want to pass in to a PHP PDO MySQL query IN operation, but the IN operation requires that the values be comma-delimited (as opposed to my string of delimited values).

How do I do this?

```<code>$values = $_POST['values']; # '10,5,4,3' (string)
$query = "SELECT * FROM table WHERE id IN (:values)";
$data = array( ':values' => $values );
</code>```

答:
PDO alone cannot bind arrays to a :parameter. You need a helper function for that.

Also in your example, the literal string '10,5,4,3' would be received as one value. Parameter binding will turn it into .. id IN ('10,5,4,3') and not into a list comparison.

The workaround in your case would be to fall back on using dynamic SQL and escaping.

```<code>$values = preg_replace('/[^\d,]/', "", $_POST['values']);
$query = "SELECT * FROM table WHERE id IN ($values)";
</code>```

I'm personally using a wrapper/helper function which has a special syntax for arrays (but you don't actually have one to begin with, so it would be a double workaround):

```<code>db("SELECT * FROM table WHERE id IN (??)", explode(",",$values));
</code>```

Body:
I have a form field that is returning a comma-delimited string that I want to pass in to a PHP PDO MySQL query IN operation, but the IN operation requires that the values be comma-delimited (as opposed to my string of delimited values).

How do I do this?

$values = $_POST['values']; # '10,5,4,3' (string)
$query = "SELECT * FROM table WHERE id IN (:values)";
$data = array( ':values' => $values );

Body:
PDO alone cannot bind arrays to a :parameter. You need a helper function for that.

Also in your example, the literal string '10,5,4,3' would be received as one value. Parameter binding will turn it into .. id IN ('10,5,4,3') and not into a list comparison.

The workaround in your case would be to fall back on using dynamic SQL and escaping.

$values = preg_replace('/[^\d,]/', "", $_POST['values']);
$query = "SELECT * FROM table WHERE id IN ($values)";

I'm personally using a wrapper/helper function which has a special syntax for arrays (but you don't actually have one to begin with, so it would be a double workaround):

db("SELECT * FROM table WHERE id IN (??)", explode(",",$values));


问:
Simple custom sorting function for jQuery DataTables
Numeric sorting is not working on my dataset. So I made a custom sorting that converts whole string into number then sorts based on that, but for some reasons its not working. What am i missing here?

```<code>$.fn.dataTableExt.oSort["test-desc"] = function (x, y)
{

         x = parseInt(x);
        y = parseInt(y);

        if ( x < y)
        {
            return 1;
        }

        return 0;

};

$.fn.dataTableExt.oSort["test-asc"] = function (x, y)
{

    x = parseInt(x);
    y = parseInt(y);

    if ( x > y)
    {
        return 1;
    }

    return 0;

}

$('table').DataTable({
    "pageLength": 300,
    "bLengthChange": false,
    "columnDefs": [
    { "type": "test", targets: 3 }
    ]
});
</code>```

Both ascending and descending are not working properly. I have checked these functions are being called and properly converting strings to numeric instances.

答:
jQuery DataTable sort function doesn't return 1 and 0. Instead they return 1 and -1. So modifying the sort function made them work perfectly.</p>

```<code>    $.fn.dataTableExt.oSort["test-desc"] = function (x, y)
    {

        x = parseInt(x);
        y = parseInt(y);

        if ( x > y)
        {
            return -1;
        }

        return 1;

    };

    $.fn.dataTableExt.oSort["test-asc"] = function (x, y)
    {

        x = parseInt(x);
        y = parseInt(y);

        if ( x > y)
        {
            return 1;
        }

        return -1;
    }
</code>```

Body:
Numeric sorting is not working on my dataset. So I made a custom sorting that converts whole string into number then sorts based on that, but for some reasons its not working. What am i missing here?

$.fn.dataTableExt.oSort["test-desc"] = function (x, y)
{

         x = parseInt(x);
        y = parseInt(y);

        if ( x < y)
        {
            return 1;
        }

        return 0;

};

$.fn.dataTableExt.oSort["test-asc"] = function (x, y)
{

    x = parseInt(x);
    y = parseInt(y);

    if ( x > y)
    {
        return 1;
    }

    return 0;

}

$('table').DataTable({
    "pageLength": 300,
    "bLengthChange": false,
    "columnDefs": [
    { "type": "test", targets: 3 }
    ]
});

Both ascending and descending are not working properly. I have checked these functions are being called and properly converting strings to numeric instances.

Body:
jQuery DataTable sort function doesn't return 1 and 0. Instead they return 1 and -1. So modifying the sort function made them work perfectly.

    $.fn.dataTableExt.oSort["test-desc"] = function (x, y)
    {

        x = parseInt(x);
        y = parseInt(y);

        if ( x > y)
        {
            return -1;
        }

        return 1;

    };

    $.fn.dataTableExt.oSort["test-asc"] = function (x, y)
    {

        x = parseInt(x);
        y = parseInt(y);

        if ( x > y)
        {
            return 1;
        }

        return -1;
    }


问:
Use FFMPEG to record a RTSP stream to a local file
I'm looking for a snippet (C/ObjC) in which an up-to-date version of FFMPEG is used to capture a RTSP or RTP stream and save it as a .mp4 file onto the device (with a start/stop record button)

Almost all snippets are are out-dated. I would like to use FFMPEG/Libav v3.2-v3.4

I'm using IJKPlayer to display the streams, which works nicely, but there's no record functionality included.

Any suggestions? Thanks!

答:
You can use a ffmpeg call from a command line. Ffmpeg syntax is very straight forward.

```<code>ffmpeg [global_options] {[input_file_options] -i input_url} ... {[output_file_options] output_url} ...
</code>```

So, if you don´t need to reencode or decode your RTPS video stream, you can simply run:

```<code>ffmpeg -i rtsp://your_stream_url your_file_name.format
</code>```

Where format could be avi, mp4, flv or others, ffmpeg you automatic package your stream to the output file.

More information here.

https://www.ffmpeg.org/ffmpeg.html

Body:
You can use a ffmpeg call from a command line. Ffmpeg syntax is very straight forward.

ffmpeg [global_options] {[input_file_options] -i input_url} ... {[output_file_options] output_url} ...

So, if you don´t need to reencode or decode your RTPS video stream, you can simply run:

ffmpeg -i rtsp://your_stream_url your_file_name.format

Where format could be avi, mp4, flv or others, ffmpeg you automatic package your stream to the output file.

More information here.

https://www.ffmpeg.org/ffmpeg.html


问:
Thymeleaf does not Serialize the object
I had trying to display a bootstrap modal when i click a row with the extra data
but when y try to print the object , it does not work:

```<code><table id="datatable" class="table table-striped table-bordered">
    <thead>
    <tr>
        <th># Factura</th>
        <th>Cliente</th>
        <th>Fecha</th>
        <th>Accion</th>
    </tr>
    </thead>

    <tbody>
    <tr th:each="bill : ${bills}">
        <td th:text="${bill.bill_id}"></td>
        <td th:text="${bill.client.name}"></td>
        <td th:text="${bill.date}"></td>
        <td>
            <a class="btn btn-info btn-xs open-modal" data-whatever="[[{$bill}]]" data-toggle="modal" data-target="#billModal">Ver Detalles</a>
        </td>
    </tr>
    </tbody>
</table>
</code>```

so, i dont know how to that bill object and send it to the modal, i have tried many ways.And it only serialize when i put with th:text or th:value

答:
At least in Thymeleaf 2.x, you need to use the th:attr directive to populate arbitrary attribute values (like data-whatever).

For example

```<code>th:attr="data-whatever=${bill}"
</code>```

In Thymeleaf 3, you may be able to use inlined attributes. I haven't used it yet and the documentation does not make it clear if it's safe for attribute values.

See http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#setting-attribute-values

According to the docs, you may even be able to use the default attribute processor

```<code>th:data-whatever="${bill}"
</code>```

Title: Thymeleaf does not Serialize the object

Body:
I had trying to display a bootstrap modal when i click a row with the extra data
but when y try to print the object , it does not work:

        # Factura
        Cliente
        Fecha
        Accion

            Ver Detalles

so, i dont know how to that bill object and send it to the modal, i have tried many ways.And it only serialize when i put with th:text or th:value

Body:
At least in Thymeleaf 2.x, you need to use the th:attr directive to populate arbitrary attribute values (like data-whatever).

For example

th:attr="data-whatever=${bill}"

In Thymeleaf 3, you may be able to use inlined attributes. I haven't used it yet and the documentation does not make it clear if it's safe for attribute values.

See http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#setting-attribute-values

According to the docs, you may even be able to use the default attribute processor

th:data-whatever="${bill}"


问:
CAML Query with NotIncludes Fails when using Contains
I have the following CAML query which works perfectly:

```<code>var emergencyCAML = "<View><Query><Where><And><Contains><FieldRef Name='Project_x0020_Members'/><Value Type='Note'>" + searchTerms[0] + "</Value></Contains><Contains><FieldRef Name='Project_x0020_Members'/><Value Type='Note'>" + searchTerms[1] + "</Value></Contains></And></Where><OrderBy><FieldRef Name='Title' Ascending='TRUE' /></OrderBy></Query></View>";
</code>```

However,
When I add the notIncludes it doesn't bring any results.

```<code>var emergencyCAML = "<View><Query><Where><And><Contains><FieldRef Name='Project_x0020_Members'/><Value Type='Note'>" + searchTerms[0] + "</Value></Contains><Contains><FieldRef Name='Project_x0020_Members'/><Value Type='Note'>" + searchTerms[1] + "</Value></Contains><NotIncludes><FieldRef Name = 'Hidden' LookupId='True'/><Value Type = 'Lookup'>" + _spPageContextInfo.userId + "</Value><XML /></NotIncludes></And></Where><OrderBy><FieldRef Name='Title' Ascending='TRUE' /></OrderBy></Query></View>";
</code>```

答:
Each  element can only contain two child elements. Your version with the not includes violates that.  Try fixing it by wrapping the  in another  tag to ensure the first And only has two direct child elements. Like this:

```<code><View>
<Query>
    <Where>
        <And>
            <And>
                <Contains><FieldRef Name='Project_x0020_Members'/><Value Type='Note'>" + searchTerms[0] + "</Value></Contains>
                <Contains><FieldRef Name='Project_x0020_Members'/><Value Type='Note'>" + searchTerms[1] + "</Value></Contains>
            </And>
            <NotIncludes><FieldRef Name = 'Hidden' LookupId='True'/><Value Type = 'Lookup'>" + _spPageContextInfo.userId + "</Value><XML /></NotIncludes>
        </And>
    </Where>
    <OrderBy><FieldRef Name='Title' Ascending='TRUE' /></OrderBy>
</Query>
</View>
</code>```

More info: https://msdn.microsoft.com/en-us/library/office/ms196939.aspx

Remarks
  This element can be nested inside other And and Or elements. The server supports unlimited complicated queries. However, any given And element can have only two conjuncts; that is, only two child elements. If you need to conjoin three or more conditions, you must nest the And elements, as demonstrated by the third example in the following section.

Body:
I have the following CAML query which works perfectly:

var emergencyCAML = "<View><Query><Where><And><Contains><FieldRef Name='Project_x0020_Members'/><Value Type='Note'>" + searchTerms[0] + "</Value></Contains><Contains><FieldRef Name='Project_x0020_Members'/><Value Type='Note'>" + searchTerms[1] + "</Value></Contains></And></Where><OrderBy><FieldRef Name='Title' Ascending='TRUE' /></OrderBy></Query></View>";

However,
When I add the notIncludes it doesn't bring any results.

var emergencyCAML = "<View><Query><Where><And><Contains><FieldRef Name='Project_x0020_Members'/><Value Type='Note'>" + searchTerms[0] + "</Value></Contains><Contains><FieldRef Name='Project_x0020_Members'/><Value Type='Note'>" + searchTerms[1] + "</Value></Contains><NotIncludes><FieldRef Name = 'Hidden' LookupId='True'/><Value Type = 'Lookup'>" + _spPageContextInfo.userId + "</Value><XML /></NotIncludes></And></Where><OrderBy><FieldRef Name='Title' Ascending='TRUE' /></OrderBy></Query></View>";

Body:
Each  element can only contain two child elements. Your version with the not includes violates that.  Try fixing it by wrapping the  in another  tag to ensure the first And only has two direct child elements. Like this:

<View>
<Query>
    <Where>
        <And>
            <And>
                <Contains><FieldRef Name='Project_x0020_Members'/><Value Type='Note'>" + searchTerms[0] + "</Value></Contains>
                <Contains><FieldRef Name='Project_x0020_Members'/><Value Type='Note'>" + searchTerms[1] + "</Value></Contains>
            </And>
            <NotIncludes><FieldRef Name = 'Hidden' LookupId='True'/><Value Type = 'Lookup'>" + _spPageContextInfo.userId + "</Value><XML /></NotIncludes>
        </And>
    </Where>
    <OrderBy><FieldRef Name='Title' Ascending='TRUE' /></OrderBy>
</Query>
</View>

More info: https://msdn.microsoft.com/en-us/library/office/ms196939.aspx

Remarks
  This element can be nested inside other And and Or elements. The server supports unlimited complicated queries. However, any given And element can have only two conjuncts; that is, only two child elements. If you need to conjoin three or more conditions, you must nest the And elements, as demonstrated by the third example in the following section.