问:
R merge multiple files into 1 dataframe and keep all values
I have 6 multiple files, each having only 1 column of names. I want to read all these files and combine them in 1 dataframe so that it looks like this:

```<code>file1  file2  file3  file4  file5  file6
adam   adam   adam   adam   adam   adam
Roy    NA     Roy    Roy    NA     NA
NA     Sam    Sam    NA     NA     NA
</code>```

The colnames of resulting dataframe should represent the actual file names. Let's say that the file I read were named file1.txt, file2.txt and so on..

Any help will be much appreciated.

What I've been trying so far:

```<code>multmerge = function(mypath){
+ filenames=list.files(path=mypath, full.names=TRUE, pattern = "\\.txt$")
+ datalist = lapply(filenames, function(x){read.csv(file=x,header=F)})
+ Reduce(function(x,y) {merge(x,y, all.x=T)}, datalist)}
> mymergeddata = multmerge("/Path/To/The/Folder/Having/All/Files")
> dim(mymergeddata)
[1] 11508     1
</code>```

As seen here it is combining all values (names) in one column..

答:
This is not probably the most efficient, but the function should do the trick and I'd be happy to hear about ways to improve the function as I'm a stack newbie:</p>

```<code>library(data.table); library(tidyverse)

multmerge <- function(dir) {
    # Load files and bind columns
    full_dir_filenames <- list.files(path = dir, full.names = TRUE, pattern = "\\.txt$")
    datalist <- lapply(full_dir_filenames, read_csv, col_names = FALSE) %>%
        lapply(t) %>%
        lapply(as.tibble)
    df <- bind_cols(datalist)

    # Append the column names
    file_names <- list.files(path = dir, full.names = FALSE, pattern = "\\.txt$")
    col_names <- tstrsplit(file_names, split = "[.]")[[1]]
    colnames(df) <- col_names

    df
}

multmerge()
</code>```

Body:
I have 6 multiple files, each having only 1 column of names. I want to read all these files and combine them in 1 dataframe so that it looks like this:

file1  file2  file3  file4  file5  file6
adam   adam   adam   adam   adam   adam
Roy    NA     Roy    Roy    NA     NA
NA     Sam    Sam    NA     NA     NA

The colnames of resulting dataframe should represent the actual file names. Let's say that the file I read were named file1.txt, file2.txt and so on..

Any help will be much appreciated.

What I've been trying so far:

multmerge = function(mypath){
+ filenames=list.files(path=mypath, full.names=TRUE, pattern = "\\.txt$")
+ datalist = lapply(filenames, function(x){read.csv(file=x,header=F)})
+ Reduce(function(x,y) {merge(x,y, all.x=T)}, datalist)}
> mymergeddata = multmerge("/Path/To/The/Folder/Having/All/Files")
> dim(mymergeddata)
[1] 11508     1

As seen here it is combining all values (names) in one column..

Body:
This is not probably the most efficient, but the function should do the trick and I'd be happy to hear about ways to improve the function as I'm a stack newbie:

library(data.table); library(tidyverse)

multmerge <- function(dir) {
    # Load files and bind columns
    full_dir_filenames <- list.files(path = dir, full.names = TRUE, pattern = "\\.txt$")
    datalist <- lapply(full_dir_filenames, read_csv, col_names = FALSE) %>%
        lapply(t) %>%
        lapply(as.tibble)
    df <- bind_cols(datalist)

    # Append the column names
    file_names <- list.files(path = dir, full.names = FALSE, pattern = "\\.txt$")
    col_names <- tstrsplit(file_names, split = "[.]")[[1]]
    colnames(df) <- col_names

    df
}

multmerge()


来源: stackexchange

问:
Oracle BI Publisher Failed to load XML if setting parameter and trying to view data
When I try to run this SQL with manual values everything is OK

```<code>SELECT *
FROM epayment_application
WHERE time_stamp
BETWEEN
TO_DATE('03/07/2017', 'dd/mm/yyyy')
AND
TO_DATE('05/07/2017', 'dd/mm/yyyy')
</code>```

When I replace values with parameters and try to view data

```<code>SELECT *
FROM epayment_application
WHERE time_stamp
BETWEEN
TO_DATE(:DateFrom, 'dd/mm/yyyy')
AND
TO_DATE(:DateTo, 'dd/mm/yyyy')
</code>```

It gives Failed to load XML error. Type of parameters is Date and format is also dd/mm/yyyy.

What am I doing wrong? Please help.

答:
Remove the TO_DATE from the query in BIP like this.</p>

```<code>SELECT *
FROM epayment_application
WHERE time_stamp
BETWEEN
:DateFrom
AND
:DateTo
</code>```

ContentLicense: CC BY-SA 3.0

Body:
When I try to run this SQL with manual values everything is OK

SELECT *
FROM epayment_application
WHERE time_stamp
BETWEEN
TO_DATE('03/07/2017', 'dd/mm/yyyy')
AND
TO_DATE('05/07/2017', 'dd/mm/yyyy')

When I replace values with parameters and try to view data

SELECT *
FROM epayment_application
WHERE time_stamp
BETWEEN
TO_DATE(:DateFrom, 'dd/mm/yyyy')
AND
TO_DATE(:DateTo, 'dd/mm/yyyy')

It gives Failed to load XML error. Type of parameters is Date and format is also dd/mm/yyyy.

What am I doing wrong? Please help.

Body:
Remove the TO_DATE from the query in BIP like this.

SELECT *
FROM epayment_application
WHERE time_stamp
BETWEEN
:DateFrom
AND
:DateTo


问:
AWS Codepipeline with a Codecommit targetsource repository from another account
Is it possible to create a codepipeline that has a target source of a CodeCommit Repository in another account?</p>

答: Yes, it should be possible. Follow these instructions: http://docs.aws.amazon.com/codepipeline/latest/userguide/pipelines-create-cross-account.html</p>


问:
javascript: get url path
```<code>var url = 'http://domain.com/file.php?id=1';
</code>```

or

```<code>var url = 'https://domain.us/file.php?id=1'
</code>```

or

```<code>var url = 'domain.de/file.php?id=1';
</code>```

or

```<code>var url = 'subdomain.domain.com/file.php?id=1'
</code>```

from either one of these urls I want to get only the path, in the case above:

```<code>var path = '/file.php?id=1';
</code>```

答:
this version is with regex. Try this out:</p>

```<code>var splittedURL = url.split(/\/+/g);
var path = "/"+splittedURL[splittedURL.length-1];
</code>```

ContentLicense: CC BY-SA 2.5

Title: javascript: get url path

Body:
var url = 'http://domain.com/file.php?id=1';

or

var url = 'https://domain.us/file.php?id=1'

or

var url = 'domain.de/file.php?id=1';

or

var url = 'subdomain.domain.com/file.php?id=1'

from either one of these urls I want to get only the path, in the case above:

var path = '/file.php?id=1';

Body:
this version is with regex. Try this out:

var splittedURL = url.split(/\/+/g);
var path = "/"+splittedURL[splittedURL.length-1];


问:
Using accept.js with Authorize.net AIM
We currently use Oscommerce with Authorize.net AIM enabled. We are trying to integrate accept.js.

Problem:
1. When authorize.net AIM module is enabled the form does not post to confirmation page and produces error

When AIM module is disabled then the form gets posted to confirmation page but we get "Select payment method"

We understand that atleast 1 payment method has to be enabled.

QUESTION:
1. is there are possibility of integrating accept.js with AIM?  How?
2. If AIM is disabled then how to post to confirmation page in oscommerce?

Please help.

答: Authorize.Net AIM does not support the payment nonce or one-time token generated by Accept.js. Instead you will need to use the Authorize.Net API using either XML or JSON.</p>

Title: Using accept.js with Authorize.net AIM


问:
How to fix flickering from css keyframe animation
I am trying to stagger the opacity (fade) of three boxes via an infinite keyframe animation and the animation-delay property.

I am getting some unexpected behavior, as the third box fades away, it suddenly reappears faintly ("flickers") before the animation starts again. I am experiencing this across browsers.

I would like to use pseudo elements if possible, is there a known fix for this keyframe bug?

HTML

```<code><div class="container">
   <div class="child">
   <div></div>
    </div>
</div>
</code>```

SCSS

```<code>.container {
     position: fixed;
     left: 150px;
     top: 50px;

.child {
     position: absolute;
     animation:mymove 1s infinite;

     &::before{
         display: block;
         position: absolute;
         width: 25px;
         height: 25px;
         background-color: red;
         content: "";
         right: 40px;
         animation: inherit;
         animation-delay: .15s;
    }

    div {
        width: 25px;
        height: 25px;
        background-color: red;
        animation: inherit;
        animation-delay: .30s;
     }

     &::after{
         display: block;
        position: absolute;
        width: 25px;
        height: 25px;
        background-color: red;
        content: "";
        left: 40px;
        bottom: 0px;
        animation: inherit;
        animation-delay: .45s;
       }
   }
}

 @keyframes mymove {
      0% {
      opacity: 1;
    }

      100% {
        opacity: 0;
  }
}
</code>```

JS Fiddle

答:
The reason they flicker is because you have set an animation on their parent, the child.

And since its animation doesn't have a delay, it starts before its children, but will then be overridden by them as soon as their delay has passed, hence one can see a quick flash.

The best way to avoid any future issue with this, is to remove the animation from the child

.container {
  position: fixed;
  left: 150px;
  top: 50px;
}

.container .child {
  position: absolute;
}

.container .child::before {
  display: block;
  position: absolute;
  width: 25px;
  height: 25px;
  background-color: red;
  content: "";
  right: 40px;
  animation: mymove 1s infinite;
  animation-delay: 0.15s;
}

.container .child div {
  width: 25px;
  height: 25px;
  background-color: red;
  animation: mymove 1s infinite;
  animation-delay: 0.3s;
}

.container .child::after {
  display: block;
  position: absolute;
  width: 25px;
  height: 25px;
  background-color: red;
  content: "";
  left: 40px;
  bottom: 0px;
  animation: mymove 1s infinite;
  animation-delay: 0.45s;
}

@keyframes mymove {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="child">
    <div></div>
  </div>
</div></code>```

Body:
I am trying to stagger the opacity (fade) of three boxes via an infinite keyframe animation and the animation-delay property.

I am getting some unexpected behavior, as the third box fades away, it suddenly reappears faintly ("flickers") before the animation starts again. I am experiencing this across browsers.

I would like to use pseudo elements if possible, is there a known fix for this keyframe bug?

HTML

SCSS

.container {
     position: fixed;
     left: 150px;
     top: 50px;

.child {
     position: absolute;
     animation:mymove 1s infinite;

     &::before{
         display: block;
         position: absolute;
         width: 25px;
         height: 25px;
         background-color: red;
         content: "";
         right: 40px;
         animation: inherit;
         animation-delay: .15s;
    }

    div {
        width: 25px;
        height: 25px;
        background-color: red;
        animation: inherit;
        animation-delay: .30s;
     }

     &::after{
         display: block;
        position: absolute;
        width: 25px;
        height: 25px;
        background-color: red;
        content: "";
        left: 40px;
        bottom: 0px;
        animation: inherit;
        animation-delay: .45s;
       }
   }
}

 @keyframes mymove {
      0% {
      opacity: 1;
    }

      100% {
        opacity: 0;
  }
}

JS Fiddle

Body:
The reason they flicker is because you have set an animation on their parent, the child.

And since its animation doesn't have a delay, it starts before its children, but will then be overridden by them as soon as their delay has passed, hence one can see a quick flash.

The best way to avoid any future issue with this, is to remove the animation from the child

.container {
  position: fixed;
  left: 150px;
  top: 50px;
}

.container .child {
  position: absolute;
}

.container .child::before {
  display: block;
  position: absolute;
  width: 25px;
  height: 25px;
  background-color: red;
  content: "";
  right: 40px;
  animation: mymove 1s infinite;
  animation-delay: 0.15s;
}

.container .child div {
  width: 25px;
  height: 25px;
  background-color: red;
  animation: mymove 1s infinite;
  animation-delay: 0.3s;
}

.container .child::after {
  display: block;
  position: absolute;
  width: 25px;
  height: 25px;
  background-color: red;
  content: "";
  left: 40px;
  bottom: 0px;
  animation: mymove 1s infinite;
  animation-delay: 0.45s;
}

@keyframes mymove {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

<div class="container">
  <div class="child">
    <div></div>
  </div>
</div>


问:
Why does START TRANSACTION doesn't affect on autocommit implicitly as it should
So this is from the docs:

To disable autocommit mode implicitly for a single series of
  statements, use the START TRANSACTION statement:

```<code>START TRANSACTION;
SELECT @A:=SUM(salary) FROM table1 WHERE type=1;
UPDATE table2 SET summary=@A WHERE type=1;
COMMIT;
</code>```

So from my understanding, unlike using BEGIN; command which shouldn't set autocommit to 0, START TRANSACTION should set it to 0.

Now if I do this (after I start a transaction):

```<code>select @@autocommit;
</code>```

I get the value of 1.

Why autocommit is still enabled even if I use START TRANSACTION command? I thought that the autocommit variable is local to a single session. Or maybe even if it says 1, it is actually set to 0 within a transaction but just can't get that info by running a SELECT @@autocommit; query?

答:
https://dev.mysql.com/doc/refman/5.7/en/commit.html says:

With START TRANSACTION, autocommit remains disabled until you end the transaction with COMMIT or ROLLBACK. The autocommit mode then reverts to its previous state.

The value of the autocommit variable is where MySQL stores the "previous state" so that it can revert to it after your transaction completes.

You can experimentally confirm that this behavior is followed. Make a change in a transaction, and then roll back the transaction.

```<code>CREATE TABLE test.MyTable (mycolumn TEXT);

START TRANSACTION;
INSERT INTO test.MyTable (mycolumn) VALUES ('Thing 1');
ROLLBACK;

SELECT * FROM test.MyTable; -- finds the row is gone
</code>```

Notice that the change you did is rolled back. If autocommit had been in effect, then rollback would never work, because each statement would commit as soon as it is executed.

Body:
So this is from the docs:

To disable autocommit mode implicitly for a single series of
  statements, use the START TRANSACTION statement:

START TRANSACTION;
SELECT @A:=SUM(salary) FROM table1 WHERE type=1;
UPDATE table2 SET summary=@A WHERE type=1;
COMMIT;

So from my understanding, unlike using BEGIN; command which shouldn't set autocommit to 0, START TRANSACTION should set it to 0.

Now if I do this (after I start a transaction):

select @@autocommit;

I get the value of 1.

Why autocommit is still enabled even if I use START TRANSACTION command? I thought that the autocommit variable is local to a single session. Or maybe even if it says 1, it is actually set to 0 within a transaction but just can't get that info by running a SELECT @@autocommit; query?

Body:
https://dev.mysql.com/doc/refman/5.7/en/commit.html says:

With START TRANSACTION, autocommit remains disabled until you end the transaction with COMMIT or ROLLBACK. The autocommit mode then reverts to its previous state.

The value of the autocommit variable is where MySQL stores the "previous state" so that it can revert to it after your transaction completes.

You can experimentally confirm that this behavior is followed. Make a change in a transaction, and then roll back the transaction.

CREATE TABLE test.MyTable (mycolumn TEXT);

START TRANSACTION;
INSERT INTO test.MyTable (mycolumn) VALUES ('Thing 1');
ROLLBACK;

SELECT * FROM test.MyTable; -- finds the row is gone

Notice that the change you did is rolled back. If autocommit had been in effect, then rollback would never work, because each statement would commit as soon as it is executed.


问:
how to sort list of names satisfying below
The answer to be in any programing language satisfying following conditions

Only the first letter of each part of the name should be capital.

All the parts of the name except the last part should be represented by only two characters.

The first character should be the first letter of the part and should be capitalized.

The second character should be . .

example:

Input:

```<code>mahatma gandhi
Mohndas KaramChand gandhi
</code>```

Output:

```<code>M. Gandhi
M. K. Gandhi
</code>```

答:
Please try if the following Java code can help you.

```<code>class Main {
    public static void main(String[] args) {
        String input = "mahatma gandhi\n" +
                "Mohndas KaramChand gandhi\nVijay singh";
        char[] chars = input.toLowerCase().toCharArray();
        boolean found = false;
        for (int i = 0; i < chars.length; i++) {
            if (Character.isWhitespace(chars[i])) {
                chars[i + 1] = Character.toUpperCase(chars[i + 1]);
            }
        }
        chars[0] = Character.toUpperCase(chars[0]);
        String output = String.valueOf(chars);
        String[] parts1 = output.split("\n");
        for (int i = 0; i < parts1.length; i++) {
            String[] names = parts1[i].split(" ");
            String[] initials = output.split(" ");
            String lastname = names[names.length - 1];
            for (int j = 0; j < names.length - 1; j++) {
                initials[j] = names[j].substring(0, 1);
                System.out.print(initials[j] + ".");
            }
            System.out.println(" " + lastname);
        }
    }
}
</code>```

Output

```<code>M. Gandhi
M.K. Gandhi
V. Singh
</code>```

You can try different versions of the input string, or change the program to read the string from a file or from the console. I hope it works for you.

Body:
The answer to be in any programing language satisfying following conditions

Only the first letter of each part of the name should be capital.

All the parts of the name except the last part should be represented by only two characters.

The first character should be the first letter of the part and should be capitalized.

The second character should be . .

example:

Input:

mahatma gandhi
Mohndas KaramChand gandhi

Output:

M. Gandhi
M. K. Gandhi

Body:
Please try if the following Java code can help you.

class Main {
    public static void main(String[] args) {
        String input = "mahatma gandhi\n" +
                "Mohndas KaramChand gandhi\nVijay singh";
        char[] chars = input.toLowerCase().toCharArray();
        boolean found = false;
        for (int i = 0; i < chars.length; i++) {
            if (Character.isWhitespace(chars[i])) {
                chars[i + 1] = Character.toUpperCase(chars[i + 1]);
            }
        }
        chars[0] = Character.toUpperCase(chars[0]);
        String output = String.valueOf(chars);
        String[] parts1 = output.split("\n");
        for (int i = 0; i < parts1.length; i++) {
            String[] names = parts1[i].split(" ");
            String[] initials = output.split(" ");
            String lastname = names[names.length - 1];
            for (int j = 0; j < names.length - 1; j++) {
                initials[j] = names[j].substring(0, 1);
                System.out.print(initials[j] + ".");
            }
            System.out.println(" " + lastname);
        }
    }
}

Output

M. Gandhi
M.K. Gandhi
V. Singh

You can try different versions of the input string, or change the program to read the string from a file or from the console. I hope it works for you.


问:
Adding Image into Webpage using AngularJS
Why does my image show up as a file logo? link below

This is how my image shows up when I add it

This is my JS for the image (AngularJS)

{
    name: 'Screw',
    price: 1,
    description: 'A small item drilled into objects',
    specs: '1 centimeter',
    images: [
                {
                    full: "1024px-Phillips_screw.jpg"
                }
            ]
}
```

<p>This is my HTML for adding the image</p>

<pre class="lang-html prettyprint-override"><code><img ng-src="{{product.images[0].full}}"/>
</code>```

答: Its passing only name of image into ng-src, you need to write whole path of image where it saved before u pass image name into curly braces.</p>

Body:
Why does my image show up as a file logo? link below

This is how my image shows up when I add it

This is my JS for the image (AngularJS)

{
    name: 'Screw',
    price: 1,
    description: 'A small item drilled into objects',
    specs: '1 centimeter',
    images: [
                {
                    full: "1024px-Phillips_screw.jpg"
                }
            ]
}

This is my HTML for adding the image


答:
In your example the id on Student is StudId and in Grades it is StuId. This may or may not be a typo, but I left it as posted.

You need to unpivot the subject+gradenumber (I use the cross apply(values... ) method to unpivot in the code below but a union all or unpivot() version would work as well), and then pivot.

Since you only want to return columns specific to each student, you use a filter on the column list generation and in the inner query of the pivot and pass that parameter to sp_executesql for the execution of the generated code.

```<code>declare @cols nvarchar(max), @sql nvarchar(max), @StuId int;
set @StuId = 2;
set @cols = stuff((
    select ', ' + quotename(sub.subName+'1')+', '+ quotename(sub.subName+'2')
    from Grades g
      inner join Student stu
        on g.StuId = stu.StudId
      inner join Subjects sub
        on g.SubId = sub.SubId
    where stu.StudId = @StuId
    order by 1
    for xml path (''), type).value('(./text())[1]','nvarchar(max)')
    ,1,2,'');
set @sql = '
    select StuName, '+ @cols +'
    from (
      select stu.StuName, u.SubName, u.Grade
      from Grades g
        inner join Student stu
          on g.StuId = stu.StudId
        inner join Subjects sub
          on g.SubId = sub.SubId
        cross apply (values
            (sub.SubName+''1'', g.Grade1)
          , (sub.SubName+''2'', g.Grade2)
          )u (SubName,Grade)
      where stu.StudId = @StuId
      ) as t
    pivot (sum(Grade) for SubName in (' + @cols +')) p';

select CodeGenerated = @sql;
exec sp_executesql @sql ,N'@StuId int', @StuId;
</code>```

rextester demo: http://rextester.com/DCLY81531

returns CodeGenerated:

```<code>select StuName, [English1], [English2], [Math1], [Math2], [Physics1], [Physics2]
    from (
      select stu.StuName, u.SubName, u.Grade
      from Grades g
        inner join Student stu
          on g.StuId = stu.StudId
        inner join Subjects sub
          on g.SubId = sub.SubId
        cross apply (values
            (sub.SubName+'1', g.Grade1)
          , (sub.SubName+'2', g.Grade2)
          )u (SubName,Grade)
      where stu.StudId = @StuId
      ) as t
    pivot (sum(Grade) for SubName in ([English1], [English2], [Math1], [Math2], [Physics1], [Physics2])) p
</code>```

for @StuId = 2 returns:

```<code>+---------------+----------+----------+-------+-------+----------+----------+
|    StuName    | English1 | English2 | Math1 | Math2 | Physics1 | Physics2 |
+---------------+----------+----------+-------+-------+----------+----------+
| Leroy Jenkins |        8 |        4 |     7 |     9 |        6 |       10 |
+---------------+----------+----------+-------+-------+----------+----------+
</code>```

for @StuId = 1 returns:

```<code>+------------+----------+----------+---------+---------+
|  StuName   | English1 | English2 | French1 | French2 |
+------------+----------+----------+---------+---------+
| Marco Polo |       10 |        6 |       9 |       7 |
+------------+----------+----------+---------+---------+
</code>```

Title: T-SQL Dynamic Pivot on different and multiple columns

Body:
Table Student:

Studid      StuName
=========================
1           'Marco Polo'
2           'Leroy Jenkins'

Table Subjects:

Subid      SubName
===================
1           English
2           French
3           German
4           Math
5           Physics

Table Grades

Stuid      Subid          Grade1            Grade2
==================================================
1           1                10               6
1           2                9                7
2           1                8                4
2           4                7                9
2           5                6                10

I would like to achieve 2 tables:
Table1:

StuName      English 1      English 2      French 1       French 2
==================================================================
'Marco Polo'     10             6              9              7

Table1:

StuName      English 1      English 2      Math 1       Math 2      Physics 1       Physics 2
==================================================================
'Leroy Jenkins'    8             4              7              9    6              10

Body:
In your example the id on Student is StudId and in Grades it is StuId. This may or may not be a typo, but I left it as posted.

You need to unpivot the subject+gradenumber (I use the cross apply(values... ) method to unpivot in the code below but a union all or unpivot() version would work as well), and then pivot.

Since you only want to return columns specific to each student, you use a filter on the column list generation and in the inner query of the pivot and pass that parameter to sp_executesql for the execution of the generated code.

declare @cols nvarchar(max), @sql nvarchar(max), @StuId int;
set @StuId = 2;
set @cols = stuff((
    select ', ' + quotename(sub.subName+'1')+', '+ quotename(sub.subName+'2')
    from Grades g
      inner join Student stu
        on g.StuId = stu.StudId
      inner join Subjects sub
        on g.SubId = sub.SubId
    where stu.StudId = @StuId
    order by 1
    for xml path (''), type).value('(./text())[1]','nvarchar(max)')
    ,1,2,'');
set @sql = '
    select StuName, '+ @cols +'
    from (
      select stu.StuName, u.SubName, u.Grade
      from Grades g
        inner join Student stu
          on g.StuId = stu.StudId
        inner join Subjects sub
          on g.SubId = sub.SubId
        cross apply (values
            (sub.SubName+''1'', g.Grade1)
          , (sub.SubName+''2'', g.Grade2)
          )u (SubName,Grade)
      where stu.StudId = @StuId
      ) as t
    pivot (sum(Grade) for SubName in (' + @cols +')) p';

select CodeGenerated = @sql;
exec sp_executesql @sql ,N'@StuId int', @StuId;

rextester demo: http://rextester.com/DCLY81531

returns CodeGenerated:

select StuName, [English1], [English2], [Math1], [Math2], [Physics1], [Physics2]
    from (
      select stu.StuName, u.SubName, u.Grade
      from Grades g
        inner join Student stu
          on g.StuId = stu.StudId
        inner join Subjects sub
          on g.SubId = sub.SubId
        cross apply (values
            (sub.SubName+'1', g.Grade1)
          , (sub.SubName+'2', g.Grade2)
          )u (SubName,Grade)
      where stu.StudId = @StuId
      ) as t
    pivot (sum(Grade) for SubName in ([English1], [English2], [Math1], [Math2], [Physics1], [Physics2])) p

for @StuId = 2 returns:

+---------------+----------+----------+-------+-------+----------+----------+
|    StuName    | English1 | English2 | Math1 | Math2 | Physics1 | Physics2 |
+---------------+----------+----------+-------+-------+----------+----------+
| Leroy Jenkins |        8 |        4 |     7 |     9 |        6 |       10 |
+---------------+----------+----------+-------+-------+----------+----------+

for @StuId = 1 returns:

+------------+----------+----------+---------+---------+
|  StuName   | English1 | English2 | French1 | French2 |
+------------+----------+----------+---------+---------+
| Marco Polo |       10 |        6 |       9 |       7 |
+------------+----------+----------+---------+---------+


问:
Where do I put SQL in my code when using notepad?
Lets say I have some code where I will be using just javascript, html, and css. I would create an outline like this.

```<code><!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script  type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
</head>
<style>

</style>
<script>

</script>
<body>
    <button>Create a new table</button>
</body>
</html>
</code>```

But what I want is when the user clicks a button it can create a table using SQL. My question is do I put that code in the script tags() or create separate tags for the SQL part?

答: You cannot execute SQL from an HTML file. That requires server side processing with PHP, Ruby, Python, etc.</p>

Body:
Lets say I have some code where I will be using just javascript, html, and css. I would create an outline like this.

<!DOCTYPE html>

    <button>Create a new table</button>

But what I want is when the user clicks a button it can create a table using SQL. My question is do I put that code in the script tags() or create separate tags for the SQL part?


问:
TensorFlow: Train model on a custom image dataset
I am interested in training and evaluating a convolutional neural net model on my own set of images. I want to use the tf.layers module for my model definition, along with a tf.learn.Estimator object to train and evaluate the model using the fit() and evaluate() methods, respectively.

Here is the tutorial that I have been following, which is helpful for showcasing the tf.layers module and the tf.learn.Estimator class. However, the dataset that it uses (MNIST) is simply imported and loaded (as NumPy arrays). See the following main function from the tutorial script:

```<code>def main(unused_argv):
  # Load training and eval data
  mnist = learn.datasets.load_dataset("mnist")
  train_data = mnist.train.images  # Returns np.array
  train_labels = np.asarray(mnist.train.labels, dtype=np.int32)
  eval_data = mnist.test.images  # Returns np.array
  eval_labels = np.asarray(mnist.test.labels, dtype=np.int32)

  # Create the Estimator
  mnist_classifier = learn.Estimator(
      model_fn=cnn_model_fn, model_dir="/tmp/mnist_convnet_model")

  # Set up logging for predictions
  # Log the values in the "Softmax" tensor with label "probabilities"
  tensors_to_log = {"probabilities": "softmax_tensor"}
  logging_hook = tf.train.LoggingTensorHook(
      tensors=tensors_to_log, every_n_iter=50)

  # Train the model
  mnist_classifier.fit(
      x=train_data,
      y=train_labels,
      batch_size=100,
      steps=20000,
      monitors=[logging_hook])

  # Configure the accuracy metric for evaluation
  metrics = {
      "accuracy":
          learn.MetricSpec(
              metric_fn=tf.metrics.accuracy, prediction_key="classes"),
  }

  # Evaluate the model and print results
  eval_results = mnist_classifier.evaluate(
      x=eval_data, y=eval_labels, metrics=metrics)
  print(eval_results)
</code>```

Full code here

I have my own images, which I have in both jpg format within a certain directory structure:

```<code>data
    train
        classA
            1.jpg
            2.jpg
            ...
        classB
            3.jpg
            4.jpg
            ...
        ...
    validate
        classA
            5.jpg
            6.jpg
            ...
        classB
            ...
        ...
</code>```

And I have also converted my image directories into TFRecord format, with one TFRecord file for train and one for validation. I followed this tutorial, which uses the build_image_data.py script from the Inception model that comes with TensorFlow as a blackbox that outputs these TFRecord files. I admit that I may have put the cart before the horse a bit by creating these, but I thought that perhaps there was a way to use these as inputs to the tf.learn.Estimator's fit() and evaluate() methods.

Questions

How can I format my jpg (or TFRecord) data so that I can use them as inputs to the Estimator object's functions?

I'm assuming I have to convert my images and labels to NumPy arrays, as it shows in the code above, however, it is not clear how the mnist.train.images and mnist.train.validation are formatted.

Does anyone have any experience with converting jpg files and labels to NumPy arrays that this Estimator class expects as inputs?

Any help would be greatly appreciated.

答:
The file that you have referenced, cnn_mnist.py, and specifically the following function mnist_classifier.fit, requires Numpy arrays as input for x and y. Therefore, I will address your second and third questions as TFRecords may not be easily incorporated into the referenced code.

however, it is not clear how the mnist.train.images and mnist.train.validation are formatted

mnist.train.images is a Numpy array with shape (55000, 784), where 55000 is the number of images and 784 is the dimension of each flattened image (28 x 28). mnist.validation.images is also a Numpy array with shape (5000, 784).

Does anyone have any experience with converting jpg files and labels to NumPy arrays that this Estimator class expects as inputs?

The following code reads in one JPEG image as a three-dimensional Numpy array:

```<code>    from scipy.misc import imread
    filename = '1.jpg'
    np_1 = imread(filename)
</code>```

I assume all of these images are the same size or that you are able to resize them to the same size, considering that you have already generated TFRecords files from this dataset. All that is left to do is flatten the image, read in the other images iteratively and flatten them, and then vertically stack all the images. This object can be fed into the Estimator function.

Below is code to flatten and vertically stack two three-dimensional Numpy arrays:

```<code>    import numpy as np
    np_1_2 = np.vstack((np_1.flatten(), np_2.flatten()))
</code>```

Body:
I am interested in training and evaluating a convolutional neural net model on my own set of images. I want to use the tf.layers module for my model definition, along with a tf.learn.Estimator object to train and evaluate the model using the fit() and evaluate() methods, respectively.

Here is the tutorial that I have been following, which is helpful for showcasing the tf.layers module and the tf.learn.Estimator class. However, the dataset that it uses (MNIST) is simply imported and loaded (as NumPy arrays). See the following main function from the tutorial script:

def main(unused_argv):
  # Load training and eval data
  mnist = learn.datasets.load_dataset("mnist")
  train_data = mnist.train.images  # Returns np.array
  train_labels = np.asarray(mnist.train.labels, dtype=np.int32)
  eval_data = mnist.test.images  # Returns np.array
  eval_labels = np.asarray(mnist.test.labels, dtype=np.int32)

  # Create the Estimator
  mnist_classifier = learn.Estimator(
      model_fn=cnn_model_fn, model_dir="/tmp/mnist_convnet_model")

  # Set up logging for predictions
  # Log the values in the "Softmax" tensor with label "probabilities"
  tensors_to_log = {"probabilities": "softmax_tensor"}
  logging_hook = tf.train.LoggingTensorHook(
      tensors=tensors_to_log, every_n_iter=50)

  # Train the model
  mnist_classifier.fit(
      x=train_data,
      y=train_labels,
      batch_size=100,
      steps=20000,
      monitors=[logging_hook])

  # Configure the accuracy metric for evaluation
  metrics = {
      "accuracy":
          learn.MetricSpec(
              metric_fn=tf.metrics.accuracy, prediction_key="classes"),
  }

  # Evaluate the model and print results
  eval_results = mnist_classifier.evaluate(
      x=eval_data, y=eval_labels, metrics=metrics)
  print(eval_results)

Full code here

I have my own images, which I have in both jpg format within a certain directory structure:

data
    train
        classA
            1.jpg
            2.jpg
            ...
        classB
            3.jpg
            4.jpg
            ...
        ...
    validate
        classA
            5.jpg
            6.jpg
            ...
        classB
            ...
        ...

And I have also converted my image directories into TFRecord format, with one TFRecord file for train and one for validation. I followed this tutorial, which uses the build_image_data.py script from the Inception model that comes with TensorFlow as a blackbox that outputs these TFRecord files. I admit that I may have put the cart before the horse a bit by creating these, but I thought that perhaps there was a way to use these as inputs to the tf.learn.Estimator's fit() and evaluate() methods.

Questions

How can I format my jpg (or TFRecord) data so that I can use them as inputs to the Estimator object's functions?

I'm assuming I have to convert my images and labels to NumPy arrays, as it shows in the code above, however, it is not clear how the mnist.train.images and mnist.train.validation are formatted.

Does anyone have any experience with converting jpg files and labels to NumPy arrays that this Estimator class expects as inputs?

Any help would be greatly appreciated.

Body:
The file that you have referenced, cnn_mnist.py, and specifically the following function mnist_classifier.fit, requires Numpy arrays as input for x and y. Therefore, I will address your second and third questions as TFRecords may not be easily incorporated into the referenced code.

however, it is not clear how the mnist.train.images and mnist.train.validation are formatted

mnist.train.images is a Numpy array with shape (55000, 784), where 55000 is the number of images and 784 is the dimension of each flattened image (28 x 28). mnist.validation.images is also a Numpy array with shape (5000, 784).

Does anyone have any experience with converting jpg files and labels to NumPy arrays that this Estimator class expects as inputs?

The following code reads in one JPEG image as a three-dimensional Numpy array:

    from scipy.misc import imread
    filename = '1.jpg'
    np_1 = imread(filename)

I assume all of these images are the same size or that you are able to resize them to the same size, considering that you have already generated TFRecords files from this dataset. All that is left to do is flatten the image, read in the other images iteratively and flatten them, and then vertically stack all the images. This object can be fed into the Estimator function.

Below is code to flatten and vertically stack two three-dimensional Numpy arrays:

    import numpy as np
    np_1_2 = np.vstack((np_1.flatten(), np_2.flatten()))


问:
Issue with mysql node js
I have recently installed MySQL on my Ubuntu 16.04. And I have successfully been able to use commands in the command prompt to create tables, and do commands like

```<code>select * from articles
</code>```

However, the issue appears when I run code from a .js file from node.js. The command line just freezes afterwards. In the picture below, the terminal on the right is the one calling the select.js file with node, while the one on the left is manually calling select * from articles:

Interestingly enough, when I use the insert.js file, the same thing happens in the terminal on the right BUT the line is inserted (which I can verify manually with the terminal on the left).

QUESTION:
Why might the terminal on the right not finish executing and in the case of the select * from articles not display the content inside the articles table?

答:
Please use the result variable in the callback as well which gives you the exact response of query.

It should be like this

```<code>var query = connection.query(<sql query>, function (err, res){
    console.log(err);
    console.log(result);
});
</code>```

Title: Issue with mysql node js

Body:
I have recently installed MySQL on my Ubuntu 16.04. And I have successfully been able to use commands in the command prompt to create tables, and do commands like

select * from articles

However, the issue appears when I run code from a .js file from node.js. The command line just freezes afterwards. In the picture below, the terminal on the right is the one calling the select.js file with node, while the one on the left is manually calling select * from articles:

Interestingly enough, when I use the insert.js file, the same thing happens in the terminal on the right BUT the line is inserted (which I can verify manually with the terminal on the left).

QUESTION:
Why might the terminal on the right not finish executing and in the case of the select * from articles not display the content inside the articles table?

Body:
Please use the result variable in the callback as well which gives you the exact response of query.

It should be like this

var query = connection.query(<sql query>, function (err, res){
    console.log(err);
    console.log(result);
});


问:
configure TLS certificate authroity in arangojs
I created my own certificate authority to generate TLSv1.2 certificates for my development environment.
My CA has a root cert, an intermediate cert signed by the root and a number of "leaf" certificates signed by the intermediate cert. I use one of this leaf certificates for securely connectin to the arangodb server.
The arangod process seems to be running fine because I can successfully access the web interface to interact with the database, after installing the root/intermediate certs in the browser.

Troubles start when I try to connect my nodejs API server to the database using the arangojs javascript driver as explained in https://github.com/arangodb/arangojs#new-database where I found:

If you need to support self-signed HTTPS certificates, you may have to add your certificates to the agentOptions, e.g.:

```<code>agentOptions: {
  ca: [
    fs.readFileSync('.ssl/sub.class1.server.ca.pem'),
    fs.readFileSync('.ssl/ca.pem')
  ]
}
</code>```

The agentOption configuration works when using self-signed certificates and:

```<code>agentOptions: {
  ca: [
    fs.readFileSync('db.crt.pem')
  ]
}
</code>```

but fails when using my own CA-signed certificate and:

```<code>agentOptions: {
  ca: [
    fs.readFileSync('interm.crt.pem')
  ]
}
</code>```

I also tried several other ca settings like:
1. passing [root, interm] certs buffers
2. passing [interm, root] certs buffers (exchanged order)
3. passing [root+interm] cert buffer (single concatenated file)
4. passing [interm+root] cert buffer (as above, exchanged order)
but none of this seems to work. I always get a very long error message from arangojs in which, quite at the beginning, I see UNABLE_TO_VERIFY_LEAF_SIGNATURE

By looking it up I found references to node-ssl-root-cas npm module but since I'm using my own CA I don't see why I would want to use that (I also tried and didn't work either).

My issue seems to be similar to https://github.com/arangodb/arangojs/issues/39 but the solution seems to be 1:1 in sync with the documentation above and it still didn't work.

In the end I think this is just a subtle configuration problem of the agantOptions in arangojs. Can someone point me to the right config?

答:
I finally managed to establish a secured TLS connection by using:

```<code>agentOptions: {
  ca: [
    fs.readFileSync('interm_root.crt.pem')
  ]
}
</code>```

where interm_root.crt.pem is the concatenation of intermediate and root certificates, that is obtained as:

cat interm.crt.pem root.crt.pem > interm_root.crt.pem

For some reason I didn't get the concatenation right in the rush of my first round of tests.

Hope this can help other arangojs users anyway

Body:
I created my own certificate authority to generate TLSv1.2 certificates for my development environment.
My CA has a root cert, an intermediate cert signed by the root and a number of "leaf" certificates signed by the intermediate cert. I use one of this leaf certificates for securely connectin to the arangodb server.
The arangod process seems to be running fine because I can successfully access the web interface to interact with the database, after installing the root/intermediate certs in the browser.

Troubles start when I try to connect my nodejs API server to the database using the arangojs javascript driver as explained in https://github.com/arangodb/arangojs#new-database where I found:

If you need to support self-signed HTTPS certificates, you may have to add your certificates to the agentOptions, e.g.:

agentOptions: {
  ca: [
    fs.readFileSync('.ssl/sub.class1.server.ca.pem'),
    fs.readFileSync('.ssl/ca.pem')
  ]
}

The agentOption configuration works when using self-signed certificates and:

agentOptions: {
  ca: [
    fs.readFileSync('db.crt.pem')
  ]
}

but fails when using my own CA-signed certificate and:

agentOptions: {
  ca: [
    fs.readFileSync('interm.crt.pem')
  ]
}

I also tried several other ca settings like:
1. passing [root, interm] certs buffers
2. passing [interm, root] certs buffers (exchanged order)
3. passing [root+interm] cert buffer (single concatenated file)
4. passing [interm+root] cert buffer (as above, exchanged order)
but none of this seems to work. I always get a very long error message from arangojs in which, quite at the beginning, I see UNABLE_TO_VERIFY_LEAF_SIGNATURE

By looking it up I found references to node-ssl-root-cas npm module but since I'm using my own CA I don't see why I would want to use that (I also tried and didn't work either).

My issue seems to be similar to https://github.com/arangodb/arangojs/issues/39 but the solution seems to be 1:1 in sync with the documentation above and it still didn't work.

In the end I think this is just a subtle configuration problem of the agantOptions in arangojs. Can someone point me to the right config?

Body:
I finally managed to establish a secured TLS connection by using:

agentOptions: {
  ca: [
    fs.readFileSync('interm_root.crt.pem')
  ]
}

where interm_root.crt.pem is the concatenation of intermediate and root certificates, that is obtained as:

cat interm.crt.pem root.crt.pem > interm_root.crt.pem

For some reason I didn't get the concatenation right in the rush of my first round of tests.

Hope this can help other arangojs users anyway


问:
Ruby - Filtering array of hashes based on another array
I am trying to filter an array of hashes based on another array. What's the best way to accomplish this? Here are the 2 brutes I've right now:

```<code>x=[1,2,3]
y = [{dis:4,as:"hi"},{dis:2,as:"li"}]

1) aa = []
x.each do |a|
  qq = y.select{|k,v| k[:dis]==a}
  aa+=qq unless qq.empty?
end

2) q = []
y.each do |k,v|
  x.each do |ele|
    if k[:dis]==ele
      q << {dis: ele,as: k[:as]}
    end
  end
end
</code>```

Here's the output I'm intending:

[{dis:2,as:"li"}]

答:
You can delete the nonconforming elements of y in place with  with .keep_if

```<code>> y.keep_if { |h| x.include? h[:dis] }
</code>```

Or reverse the logic with .delete_if:

```<code>> y.delete_if { |h| !x.include? h[:dis] }
</code>```

All produce:

```<code>> y
=> [{:dis=>2, :as=>"li"}]
</code>```

Body:
I am trying to filter an array of hashes based on another array. What's the best way to accomplish this? Here are the 2 brutes I've right now:

x=[1,2,3]
y = [{dis:4,as:"hi"},{dis:2,as:"li"}]

1) aa = []
x.each do |a|
  qq = y.select{|k,v| k[:dis]==a}
  aa+=qq unless qq.empty?
end

2) q = []
y.each do |k,v|
  x.each do |ele|
    if k[:dis]==ele
      q << {dis: ele,as: k[:as]}
    end
  end
end

Here's the output I'm intending:

[{dis:2,as:"li"}]

Body:
You can delete the nonconforming elements of y in place with  with .keep_if

> y.keep_if { |h| x.include? h[:dis] }

Or reverse the logic with .delete_if:

> y.delete_if { |h| !x.include? h[:dis] }

All produce:

> y
=> [{:dis=>2, :as=>"li"}]


问:
ruby on rails - validation in nested class shows the error screen on failing
I currently have a problem with a simple validation.
On saving my model this validation is ran.

A user has multiple questions, questions have multiple answers

This validates statement is part of my joined table class

```<code>validates :answers, length: { maximum: 6 }
</code>```

The answer will be the one updated, so I ask the question to validate itself

```<code>validates_associated :user_question
</code>```

This validation is failed correctly when the number of answers selected exceeds 6.
However, instead of returning to my form. It shows me a big error message stating that the validation has failed.

I would like to display these problems on the form so the user knows what's wrong.

Other validation errors for the form are displaying as intended. It's just this nested attribute that is causing problems for some reason.

This is the error that is being shown

```<code>ActiveRecord::RecordInvalid

Validation failed: User question is invalid
</code>```

On the following line: @user.attributes=(user_params)

That's indeed the moment when it validates (I think), but it is too abstracted to see what is wrong with the validation exactly (If there is anything wrong).

Any help is appreciated.

答:
how about if add this custom validation, this inside your question.rb (class)</p>

```<code>validate :maximum_six_answer

private

def maximum_six_answer
  if answers.size > 6
    errors.add :base, "sorry maximum six answers"
  end
end
</code>```

Body:
I currently have a problem with a simple validation.
On saving my model this validation is ran.

A user has multiple questions, questions have multiple answers

This validates statement is part of my joined table class

validates :answers, length: { maximum: 6 }

The answer will be the one updated, so I ask the question to validate itself

validates_associated :user_question

This validation is failed correctly when the number of answers selected exceeds 6.
However, instead of returning to my form. It shows me a big error message stating that the validation has failed.

I would like to display these problems on the form so the user knows what's wrong.

Other validation errors for the form are displaying as intended. It's just this nested attribute that is causing problems for some reason.

This is the error that is being shown

ActiveRecord::RecordInvalid

Validation failed: User question is invalid

On the following line: @user.attributes=(user_params)

That's indeed the moment when it validates (I think), but it is too abstracted to see what is wrong with the validation exactly (If there is anything wrong).

Any help is appreciated.

Body:
how about if add this custom validation, this inside your question.rb (class)

validate :maximum_six_answer

private

def maximum_six_answer
  if answers.size > 6
    errors.add :base, "sorry maximum six answers"
  end
end


问:
Speed up lmer function in R
I would like to share some of my thoughts when trying to improve the model fitting time of a linear mixed effects model  in R using the lme4 package.

Dataset Size: The dataset consists, approximately, of 400.000 rows and 32 columns. Unfortunately, no information can be shared about the nature of the data.

Assumptions and Checks: It is assumed that the response variable comes from a Normal distribution. Prior to the model fitting process, variables were tested for collinearity and multicollinearity using correlation tables and the alias function provided in R.

Continuous variables were scaled in order to help convergence.

Model Structure: The model equation contains 31 fixed effects (including intercept) and 30 random effects (intercept is not included). Random effects are randomized for a specific factor variable that has 2700 levels. The covariance structure is Variance Components as it is assumed that there is independency between random effects.

Model equation example:

lmer(Response ~ 1 + Var1 + Var2 + ... + Var30 + (Var1-1| Group) + (Var2-1| Group) + ... + (Var30-1| Group), data=data, REML=TRUE)

Model was fitted successfully, however, it took about 3,1 hours to provide results. The same model in SAS took a few seconds. There is available literature on the web on how to reduce time by using the non-linear optimization algorithm nloptwrap and turnining off the time consuming derivative calculation that is performed after the optmization is finished calc.derivs = FALSE:

https://cran.r-project.org/web/packages/lme4/vignettes/lmerperf.html

Time was reduced by 78%.

Question: Is there any other alternative way to reduce the model fitting time by defining the lmer parameter inputs accordingly? There is so much difference between R and SAS in terms of model fitting time.

Any suggestion is appreciated.

答:
We have implemented random intercepts regression assuming compound symmetry in the R package Rfast. The command is rint.reg. It is 30+ times faster than the corresponding lme4 function. I do not know if this helps, but just in case.

https://cran.r-project.org/web/packages/Rfast/index.html

Title: Speed up lmer function in R


问:
Windows error LNK1179
I compiled an exe on windows VS 2005, a c++ program that link to other libs of mine.
It compiled and suddenly it doesn't with an error of LNK1170 COMDAT "

I can't understand what happened and how to solve the problem.

Thanks

答: I started again the IDE and also reboot the machine and it didn't help. I managed to solve it after I clean and comiple again (not recompile option) 2 libs of mine. I don't understand why it helped but it succeeded to lnik the project.</p>

Title: Windows error LNK1179


问:
How to keep track of virtual memory used when running Python code?
I have a Python package I am benchmarking for virtual memory used.

At the moment, this isn't very precise. I submit the script e.g.

```<code>python script1.py
</code>```

and look at the time and resources used in order to execute.

Is there some package/method to find out where my RAM bottlenecks are? I'm thinking of a tool like

```<code>ram_used python script1.py
</code>```

that would keep track of how much RAM is used.

Does such a thing exist?

答:
Yes, there is - It's called memory_profiler. Once you've gone through and added the @profile decorator to the functions you would like to profile, you can use;

```<code>python -m memory_profiler example.py
</code>```

Body:
I have a Python package I am benchmarking for virtual memory used.

At the moment, this isn't very precise. I submit the script e.g.

python script1.py

and look at the time and resources used in order to execute.

Is there some package/method to find out where my RAM bottlenecks are? I'm thinking of a tool like

ram_used python script1.py

that would keep track of how much RAM is used.

Does such a thing exist?

Body:
Yes, there is - It's called memory_profiler. Once you've gone through and added the @profile decorator to the functions you would like to profile, you can use;

python -m memory_profiler example.py


问:
NSPredicate query for a Realm object
Could someone please help me construct a realm query to search for a video(s) of a particular entryid value, for extra points a second query that would find both videos by their entryids ?

Thank you!

```<code>Video {
    nid = 1;
    video_title = OK;
    video_description = Description {
        value = Description;
    };

    video_kaltura = Kaltura {
        entryid = 0_abababa3;
        mediatype = 1;
    };
}

Video {
    nid = 2;
    video_title = OK;
    video_description = Description {
        value = Description;
    };
    video_kaltura = Kaltura {
        entryid = 0_cdcdcdc3;
        mediatype = 1;
    };
}
</code>```

I've tried things like:

```<code>NSPredicate *pred = [NSPredicate predicateWithFormat:@"video_kaltura['entryid'] CONTAINS[c] '0_abababa3'"];
RLMResults *test = [Video objectsWithPredicate:pred];
</code>```

and their variations to no avail.

答:
NSPredicate uses key paths to traverse properties (object.someProperty.otherProperty).

Based on your example data, you'd want a predicate like video_kalutra.entryid == '0_abababa3'.

Title: NSPredicate query for a Realm object

Body:
Could someone please help me construct a realm query to search for a video(s) of a particular entryid value, for extra points a second query that would find both videos by their entryids ?

Thank you!

Video {
    nid = 1;
    video_title = OK;
    video_description = Description {
        value = Description;
    };

    video_kaltura = Kaltura {
        entryid = 0_abababa3;
        mediatype = 1;
    };
}

Video {
    nid = 2;
    video_title = OK;
    video_description = Description {
        value = Description;
    };
    video_kaltura = Kaltura {
        entryid = 0_cdcdcdc3;
        mediatype = 1;
    };
}

I've tried things like:

NSPredicate *pred = [NSPredicate predicateWithFormat:@"video_kaltura['entryid'] CONTAINS[c] '0_abababa3'"];
RLMResults *test = [Video objectsWithPredicate:pred];

and their variations to no avail.


问:
TensorFlow FailedPreconditionError when using variables from the tf.metric module
I tried to add some additional measurements to my training code for a CNN by utilising the functions from the tf.metrics submodule, such as tf.metrics.accuracy(y_labels, y_predicted) and equivalents for precision or recall. This is done in contrast to most of their tutorials where they suggest the convoluted:

```<code>accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
</code>```

Whereas my implementation replaces this line with:

```<code>accuracy = tf.metrics.accuracy(y_labels, y_predicted)
</code>```

Now, even though I do the sess.run(tf.initialize_all_variables()) within my with tf.Session() as sess: block, I still get the following error when trying to use tf.metrics.accuracy function:

```<code>FailedPreconditionError (see above for traceback): Attempting to use uninitialized value performance/accuracy/count
 [[Node: performance/accuracy/count/read = Identity[T=DT_FLOAT, _class=["loc:@performance/accuracy/count"], _device="/job:localhost/replica:0/task:0/cpu:0"](performance/accuracy/count)]]
</code>```

Most notably, replacing the accuracy = tf.metrics.accuracy(y_labels, y_predicted) line with accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) fixes the problem, however, I would like to implement other metrics such as precision, recall, etc. without doing it by hand.

答:
sess.run(tf.initialize_all_variables()) is deprecated.

Use sess.run(tf.global_variables_initializer()) instead to resolve your issue.

Reference

According to doc of tf.initialize_all_variables,

THIS FUNCTION IS DEPRECATED. It will be removed after 2017-03-02. Instructions for updating: Use tf.global_variables_initializer instead.

Body:
I tried to add some additional measurements to my training code for a CNN by utilising the functions from the tf.metrics submodule, such as tf.metrics.accuracy(y_labels, y_predicted) and equivalents for precision or recall. This is done in contrast to most of their tutorials where they suggest the convoluted:

accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

Whereas my implementation replaces this line with:

accuracy = tf.metrics.accuracy(y_labels, y_predicted)

Now, even though I do the sess.run(tf.initialize_all_variables()) within my with tf.Session() as sess: block, I still get the following error when trying to use tf.metrics.accuracy function:

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value performance/accuracy/count
 [[Node: performance/accuracy/count/read = Identity[T=DT_FLOAT, _class=["loc:@performance/accuracy/count"], _device="/job:localhost/replica:0/task:0/cpu:0"](performance/accuracy/count)]]

Most notably, replacing the accuracy = tf.metrics.accuracy(y_labels, y_predicted) line with accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) fixes the problem, however, I would like to implement other metrics such as precision, recall, etc. without doing it by hand.


问:
Jackson's readEntity is serializing my Exceptions into java.lang.Throwable instead of the correct Error exception
In my code I have an Exception that extends IllegalArgumentException:

```<code>public class InvalidDataSourceException extends IllegalArgumentException {
  public InvalidDataSourceException(String message, Throwable cause) {
    super(message, cause);
  }
}
</code>```

And in my Jersey REST web service, all errors are wrapped with a class RESTError so that
all rest services can throw this same exception:

```<code>public class RESTError extends Throwable {
    public RESTError(Throwable cause) {
        super(cause);
    }
}
</code>```

So when the InvalidDataSourceException occurs, it is thrown as the cause of a RESTError:

```<code>throw new RESTError(invalidDataSourceException);
</code>```

We have registered a serializer for Throwable object:

```<code>public class ThrowableSerializer extends JsonSerializer<Throwable> {

  @Override
  public void serialize(Throwable value, JsonGenerator jgen,
      SerializerProvider provider) throws IOException, JsonProcessingException {
    jgen.writeStartObject();
    jgen.writeStringField("class", value.getClass().getCanonicalName());
    jgen.writeStringField("message", value.getMessage());
    jgen.writeObjectField("stackTrace", value.getStackTrace());
    jgen.writeStringField("stackTraceAsString", Throwables.getStackTraceAsString(value));
    jgen.writeObjectField("cause", value.getCause());
    jgen.writeEndObject();

  }
}
</code>```

Below is a unit test, in which I attempt to write the RESTError to string, then re-serialize:

```<code>public class TestJsonSerializationOfExceptions {
  private static final Logger log = LoggerFactory.getLogger(TestJsonSerializationOfExceptions.class);

  @Test
  public void testBasic() throws Exception {
    ObjectMapper objectMapper = ObjectMapperFactory.create();
    try {
      throw new InvalidDataSourceException("test msg");
    } catch (Throwable t) {
      RESTError restError = new RESTError(Response.Status.INTERNAL_SERVER_ERROR, Errors.General, t);
      String str = objectMapper.writeValueAsString(restError); // It is correct here!
      log.info("Rest error when serialized: {}", str);
      restError = objectMapper.readValue(str, RESTError.class);
      Assert.assertEquals(restError.getCause().getClass(), InvalidDataSourceException.class);
    }
  }
}
</code>```

When I do this, the Exception cause is serialized to java.lang.Throwable, instead of my custom InvalidDataSourceException. It down-casted it. Thus the unit test fails. Why is that?

答:
Look at Throwable javadoc.

When you extend Throwable and pass another one to constructor, it is passed to private Throwable cause property. And then this is the only information about type. So during deserialization Java only knows that there is property cause with a type Throwable and has no information if it was InvalidDataSourceException or whatever else.

EDIT: Now it looks like missing deserializer issue

Body:
In my code I have an Exception that extends IllegalArgumentException:

public class InvalidDataSourceException extends IllegalArgumentException {
  public InvalidDataSourceException(String message, Throwable cause) {
    super(message, cause);
  }
}

And in my Jersey REST web service, all errors are wrapped with a class RESTError so that
all rest services can throw this same exception:

public class RESTError extends Throwable {
    public RESTError(Throwable cause) {
        super(cause);
    }
}

So when the InvalidDataSourceException occurs, it is thrown as the cause of a RESTError:

throw new RESTError(invalidDataSourceException);

We have registered a serializer for Throwable object:

public class ThrowableSerializer extends JsonSerializer<Throwable> {

  @Override
  public void serialize(Throwable value, JsonGenerator jgen,
      SerializerProvider provider) throws IOException, JsonProcessingException {
    jgen.writeStartObject();
    jgen.writeStringField("class", value.getClass().getCanonicalName());
    jgen.writeStringField("message", value.getMessage());
    jgen.writeObjectField("stackTrace", value.getStackTrace());
    jgen.writeStringField("stackTraceAsString", Throwables.getStackTraceAsString(value));
    jgen.writeObjectField("cause", value.getCause());
    jgen.writeEndObject();

  }
}

Below is a unit test, in which I attempt to write the RESTError to string, then re-serialize:

public class TestJsonSerializationOfExceptions {
  private static final Logger log = LoggerFactory.getLogger(TestJsonSerializationOfExceptions.class);

  @Test
  public void testBasic() throws Exception {
    ObjectMapper objectMapper = ObjectMapperFactory.create();
    try {
      throw new InvalidDataSourceException("test msg");
    } catch (Throwable t) {
      RESTError restError = new RESTError(Response.Status.INTERNAL_SERVER_ERROR, Errors.General, t);
      String str = objectMapper.writeValueAsString(restError); // It is correct here!
      log.info("Rest error when serialized: {}", str);
      restError = objectMapper.readValue(str, RESTError.class);
      Assert.assertEquals(restError.getCause().getClass(), InvalidDataSourceException.class);
    }
  }
}

When I do this, the Exception cause is serialized to java.lang.Throwable, instead of my custom InvalidDataSourceException. It down-casted it. Thus the unit test fails. Why is that?


问:
Installing TensorFlow examples in EC2 Instance
I am currently running on Amazon EC2 instance and am trying to run the following code in a Jupyter Notebook (Python 2.7):

```<code>from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/")
images, labels = mnist.train.images, mnist.train.labels
images = images.reshape((55000,28,28))
np.savez_compressed("MNIST_data/train", images=images, labels=labels)
</code>```

However, I get the following error:

```<code>---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-4-de596f1c663d> in <module>()
      1
----> 2 from tensorflow.examples.tutorials.mnist import input_data
      3 mnist = input_data.read_data_sets("MNIST_data/")
      4 images, labels = mnist.train.images, mnist.train.labels
      5 images = images.reshape((55000,28,28))

ImportError: No module named tensorflow.examples.tutorials.mnist
</code>```

Up until now, I have not had to install any libraries in order to get TensorFlow code to work (and I'm not exactly sure why I haven't needed to install anything).  How do I install this example set?

答:
Hm, the following,

```<code>from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data", one_hot=True)
</code>```

should work, I just double-checked. Maybe you have a very old TensorFlow version installed? You can check the version via

```<code>import tensorflow as tf
tf.__version__
</code>```

I don't remember when input_data was added to tensorflow.examples.tutorials.mnist but it should work with either Tf 1.1 and 1.2

Body:
I am currently running on Amazon EC2 instance and am trying to run the following code in a Jupyter Notebook (Python 2.7):

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/")
images, labels = mnist.train.images, mnist.train.labels
images = images.reshape((55000,28,28))
np.savez_compressed("MNIST_data/train", images=images, labels=labels)

However, I get the following error:

---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-4-de596f1c663d> in <module>()
      1
----> 2 from tensorflow.examples.tutorials.mnist import input_data
      3 mnist = input_data.read_data_sets("MNIST_data/")
      4 images, labels = mnist.train.images, mnist.train.labels
      5 images = images.reshape((55000,28,28))

ImportError: No module named tensorflow.examples.tutorials.mnist

Up until now, I have not had to install any libraries in order to get TensorFlow code to work (and I'm not exactly sure why I haven't needed to install anything).  How do I install this example set?

Body:
Hm, the following,

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data", one_hot=True)

should work, I just double-checked. Maybe you have a very old TensorFlow version installed? You can check the version via

import tensorflow as tf
tf.__version__

I don't remember when input_data was added to tensorflow.examples.tutorials.mnist but it should work with either Tf 1.1 and 1.2


问:
Keras LSTM Shape for Pandas DataFrame
I'm playing around with machine learning and trying to follow along with some examples but am stuck trying to get my data into a Keras LSTM layer.

I have some stock ticker data in a Pandas DataFrame which is resampled at 15 minute intervals with ohlc and a load of other metrics for each row.

My code is below. df is my DataFrame:

```<code>x = df.iloc[:, :-1].values
y = df.iloc[:, -1:].values

dimof_input = x.shape[1]
dimof_output = len(set(y.flat))

model = Sequential()
model.add(LSTM(4, input_dim=dimof_input, return_sequences=True))
model.compile(loss='mse', optimizer='rmsprop')

model.fit(x, y, nb_epoch=1, batch_size=1, verbose=2)
</code>```

When I try and fit I get:

```<code>Error when checking input: expected lstm_16_input to have 3 dimensions,
but got array with shape (33, 100)
</code>```

I've copied this from examples elsewhere. I can't quite see how to get the correct shape of data into this model. Can anyone help?

Thanks loads.

答:
Input shapes

3D tensor with shape (batch_size, timesteps, input_dim), (Optional) 2D tensors with shape (batch_size, output_dim). (from there).

And you specified input_dim=dimof_input. Model expects 3D tensor as input, but got 2D. If you give a reference to the tutorial that is being implemented I probably will be able to say more about causes of the problem.

You could try reshape your input data as following:

```<code>x = x.reshape(x.shape[0], 1, x.shape[1])
</code>```

Also, some information about input data of Keras LSTM layer input data could be found here.

Title: Keras LSTM Shape for Pandas DataFrame

Body:
I'm playing around with machine learning and trying to follow along with some examples but am stuck trying to get my data into a Keras LSTM layer.

I have some stock ticker data in a Pandas DataFrame which is resampled at 15 minute intervals with ohlc and a load of other metrics for each row.

My code is below. df is my DataFrame:

x = df.iloc[:, :-1].values
y = df.iloc[:, -1:].values

dimof_input = x.shape[1]
dimof_output = len(set(y.flat))

model = Sequential()
model.add(LSTM(4, input_dim=dimof_input, return_sequences=True))
model.compile(loss='mse', optimizer='rmsprop')

model.fit(x, y, nb_epoch=1, batch_size=1, verbose=2)

When I try and fit I get:

Error when checking input: expected lstm_16_input to have 3 dimensions,
but got array with shape (33, 100)

I've copied this from examples elsewhere. I can't quite see how to get the correct shape of data into this model. Can anyone help?

Thanks loads.

Body:
Input shapes

3D tensor with shape (batch_size, timesteps, input_dim), (Optional) 2D tensors with shape (batch_size, output_dim). (from there).

And you specified input_dim=dimof_input. Model expects 3D tensor as input, but got 2D. If you give a reference to the tutorial that is being implemented I probably will be able to say more about causes of the problem.

You could try reshape your input data as following:

x = x.reshape(x.shape[0], 1, x.shape[1])

Also, some information about input data of Keras LSTM layer input data could be found here.


问:
collision detection using bounding boxes slowing aframe down
Hi I recently made a component for collision detection among primitive and non primitive shapes. I was using bounding box collision provided in three.js.. its working fine but when I am using it for custom objects its slowing the entire experience down... kindly look into my component and tell me whats the issue...

```<code>AFRAME.registerComponent('manual-body', {
          matchingElements: function(attribute){
            var matchingElements = [];
            var allElements = document.getElementsByTagName('*');
            for (var i = 0, n = allElements.length; i < n; i++){
              if (allElements[i].getAttribute(attribute) !== null){
                // Element exists with attribute. Add to array.
                matchingElements.push(allElements[i]);
              }
            }
            return matchingElements;
          },
          tick: function(){
            var elements=this.matchingElements('manual-body');
            for(var i=0;i<elements.length;i++){
              if(this.el.id==elements[i].id){
                continue;
              }
              firstBB = new THREE.Box3().setFromObject(elements[i].object3D);
              secondBB = new THREE.Box3().setFromObject(this.el.object3D);
              var collision = firstBB.intersectsBox(secondBB);
              if(collision){
                this.el.emit('collision', {elSource: this.el,elTarget:elements[i]});
              }
            }
          }
        });
</code>```

What do you think might be the cause of the lag? is it the collision logic inside the tick function or is it something else.....

Thanks

答:
The method THREE.Box3().setFromObject works by looping over every vertex in a model to determine the bounding box. This is too much work to run every frame in your tick for complex models.

You may want to check out aframe-extras sphere-collider component for efficient, approximate collisions

Body:
Hi I recently made a component for collision detection among primitive and non primitive shapes. I was using bounding box collision provided in three.js.. its working fine but when I am using it for custom objects its slowing the entire experience down... kindly look into my component and tell me whats the issue...

AFRAME.registerComponent('manual-body', {
          matchingElements: function(attribute){
            var matchingElements = [];
            var allElements = document.getElementsByTagName('*');
            for (var i = 0, n = allElements.length; i < n; i++){
              if (allElements[i].getAttribute(attribute) !== null){
                // Element exists with attribute. Add to array.
                matchingElements.push(allElements[i]);
              }
            }
            return matchingElements;
          },
          tick: function(){
            var elements=this.matchingElements('manual-body');
            for(var i=0;i<elements.length;i++){
              if(this.el.id==elements[i].id){
                continue;
              }
              firstBB = new THREE.Box3().setFromObject(elements[i].object3D);
              secondBB = new THREE.Box3().setFromObject(this.el.object3D);
              var collision = firstBB.intersectsBox(secondBB);
              if(collision){
                this.el.emit('collision', {elSource: this.el,elTarget:elements[i]});
              }
            }
          }
        });

What do you think might be the cause of the lag? is it the collision logic inside the tick function or is it something else.....

Thanks


问:
groupMembershipClaims - getting membership information
I am trying to make AAD to provide group information. I have changed manifest file of my Web App:

```<code>"groupMembershipClaims": "SecurityGroup"
</code>```

I would expect my Identity to contain membership information, but it dosent. I have tried following:

```<code>ClaimsIdentity claimsId = ClaimsPrincipal.Current.Identity as ClaimsIdentity;
var rr = claimsId2.FindFirst("groups");
var rr2 = claimsId2.Claims.ToList();
</code>```

But both are empty. Do you need to do more than changing the manifest file?

答: As we figured out in the comments, it required a sign out and sign in to refresh the claims from Azure AD.</p>

Body:
I am trying to make AAD to provide group information. I have changed manifest file of my Web App:

"groupMembershipClaims": "SecurityGroup"

I would expect my Identity to contain membership information, but it dosent. I have tried following:

ClaimsIdentity claimsId = ClaimsPrincipal.Current.Identity as ClaimsIdentity;
var rr = claimsId2.FindFirst("groups");
var rr2 = claimsId2.Claims.ToList();

But both are empty. Do you need to do more than changing the manifest file?


问:
NodeJS: how to create a flag
I am struggling how to create a flag in nodejs. Please refer to small code below to get my idea

```<code>var isLogged = "no"

function login(){
    this.isLogged = "yes"
}

function sendText(){
    if(this.isLogged == "yes"){
      console.log("Hello World")
    }
}
</code>```

In nodeJS, variable seems not to support this. Please advice me how to do it. Thanks

答:
no windows object in node use variable indexing. like this.

var isLogged = 'no'

function login() {
  isLogged = "yes"
}

function sendText() {
  if (isLogged == "yes") {
    console.log("Hello World")
  }
}

console.log(isLogged);
login()
sendText();
console.log(isLogged);```

Title: NodeJS: how to create a flag

Body:
I am struggling how to create a flag in nodejs. Please refer to small code below to get my idea

var isLogged = "no"

function login(){
    this.isLogged = "yes"
}

function sendText(){
    if(this.isLogged == "yes"){
      console.log("Hello World")
    }
}

In nodeJS, variable seems not to support this. Please advice me how to do it. Thanks


问:
Change a variable name in all places in Python
I have written a code in Python3 using the IDE Wing, but I want to change a variable name, e.g., var_1, to var_2 in all places in my file. In MATLAB, when you change a variable name in one place, by Shift+Enter it is automatically done for all other occurrences of that variable in the file. Is there any similar way to do it in Python?

答:
In WingIDE you have the option via the Refactor Menu to do Rename Symbol.

This does an intelligent replace, and also takes care of distinguishing global variable from class attributes with the same name.


问:
Identify all possible combinations of a variable, including if values are missing in R
I'm curious about the total number of ways people could have completed a training in a 'choose your own adventure format'

For example, there are 10 different levels to the training in total (i.e., level 1, 2 ... 10). People can complete 1:10; 10:1; 1,2,3,5,10; 2,1,3,5,4,6,7,9,8,10; or any combination of the levels using all, some, or none of the levels before taking their exit test.

I'm hoping to find a way to make these combinations into a categorical variable because I'm wondering if sequence matters in the users likelihood of passing the exit test.

I'd like to know how to do this in R, but if anyone has other creative solutions to offer regarding better ways to use sequence as a variable, I'm all ears for that too.

Thanks!

答:
You could use combn inside Map and unlist afterwards to get a list of all combinations.

```<code>res <- Map(combn, 10, 1:10, simplify = FALSE)
unlist(res, recursive = FALSE)
</code>```

Body:
You could use combn inside Map and unlist afterwards to get a list of all combinations.

res <- Map(combn, 10, 1:10, simplify = FALSE)
unlist(res, recursive = FALSE)


问:
creating a method to return a range of random values
Consider the following code. The basic idea is to return a comma separated list of 20 numbers any of which can be a value between 0 and the max allowed value. On each pass through the loop the potential max value allowed for the next value in the list reduces by whatever last random value picked was.

So it works... but it sucks. The problem being it's always going to produce output like this:

"22,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"

"17,3,3,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"

"23,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"

How could it be modified to allow for a more even distribution of values across the range?

```<code>    public static string RandomRangeOfValuesMaker(int total)
    {
        var remainingTotal = total + 1;

        const int numberOfValues = 20;

        var rand = new Random();

        var builder = new StringBuilder();

        for (var i = 1; i < numberOfValues + 1; i++)
        {
            var currentRandomNumber = rand.Next(remainingTotal);

            remainingTotal = remainingTotal - currentRandomNumber;

            builder.Append(currentRandomNumber + ",");
        }

        var rangeOfValues = builder.ToString().Remove(builder.ToString().Length - 1);

        return rangeOfValues;
    }
</code>```

答:
If you want a sequence of random integers that add up to a particular sum, the easiest thing is to first pick a sequence of random integers in the range [0, sum], sort them, then return the differences:

```<code>public static IEnumerable<int> GetSequenceWithSum( Random rand, int count, int sum )
{
    // Get a list of count-1 random numbers in the range [0, sum] in ascending order.
    // This partitions the range [0, sum] into count different bins of random size.
    var partition = Enumerable.Range( 0, count - 1 )
                              .Select( _ => rand.Next( 0, sum + 1 ) )
                              .OrderBy( x => x );

    // Yield the size of each partition in the range.
    int previous = 0;
    foreach( int value in partition )
    {
        yield return value - previous;
        previous = value;
    }

    yield return sum - previous;
}
</code>```

I can't say precisely what distribution this gives you, but it will give you one that looks "even".

The simplest way to understand why this works is to think of it this way:

Say you want a bunch of sticks of random length, but when you glue the sticks together you want their lengths to add up to some specific length.

One way to accomplish this is to start with a stick of the length you want and to cut it randomly into the number of pieces you want.  That way the sum of the lengths of each of the pieces is the length of the piece you started with.

This code "cuts" the stick by first picking random numbers which represent the locations at which we'll cut the big stick.  It then puts the cut positions in order so we know which cuts are next to each other.  Then all it has to do is subtract consecutive cuts to get the lengths of the stick pieces.

Body:
Consider the following code. The basic idea is to return a comma separated list of 20 numbers any of which can be a value between 0 and the max allowed value. On each pass through the loop the potential max value allowed for the next value in the list reduces by whatever last random value picked was.

So it works... but it sucks. The problem being it's always going to produce output like this:

"22,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"

"17,3,3,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"

"23,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"

How could it be modified to allow for a more even distribution of values across the range?

    public static string RandomRangeOfValuesMaker(int total)
    {
        var remainingTotal = total + 1;

        const int numberOfValues = 20;

        var rand = new Random();

        var builder = new StringBuilder();

        for (var i = 1; i < numberOfValues + 1; i++)
        {
            var currentRandomNumber = rand.Next(remainingTotal);

            remainingTotal = remainingTotal - currentRandomNumber;

            builder.Append(currentRandomNumber + ",");
        }

        var rangeOfValues = builder.ToString().Remove(builder.ToString().Length - 1);

        return rangeOfValues;
    }

Body:
If you want a sequence of random integers that add up to a particular sum, the easiest thing is to first pick a sequence of random integers in the range [0, sum], sort them, then return the differences:

public static IEnumerable<int> GetSequenceWithSum( Random rand, int count, int sum )
{
    // Get a list of count-1 random numbers in the range [0, sum] in ascending order.
    // This partitions the range [0, sum] into count different bins of random size.
    var partition = Enumerable.Range( 0, count - 1 )
                              .Select( _ => rand.Next( 0, sum + 1 ) )
                              .OrderBy( x => x );

    // Yield the size of each partition in the range.
    int previous = 0;
    foreach( int value in partition )
    {
        yield return value - previous;
        previous = value;
    }

    yield return sum - previous;
}

I can't say precisely what distribution this gives you, but it will give you one that looks "even".

The simplest way to understand why this works is to think of it this way:

Say you want a bunch of sticks of random length, but when you glue the sticks together you want their lengths to add up to some specific length.

One way to accomplish this is to start with a stick of the length you want and to cut it randomly into the number of pieces you want.  That way the sum of the lengths of each of the pieces is the length of the piece you started with.

This code "cuts" the stick by first picking random numbers which represent the locations at which we'll cut the big stick.  It then puts the cut positions in order so we know which cuts are next to each other.  Then all it has to do is subtract consecutive cuts to get the lengths of the stick pieces.