问:
Create prediction grid from dplyr piping
I'm hoping someone out there has a solution for using some form of expand.grid in piping using dplyr. I am doing some modeling where I have a few different groups (or Types below) and the groups have different ranges for x & y data. Once I run a gam on the data I am interested in creating a plot for the predictions, but I only want to predict values over the range that each value occupies, not the whole range of the data set.

I already have a working example posted below, but I'm wondering if there is a way to get around using a loop and complete my task.

Cheers

```<code>require(ggplot2)
require(dplyr)

# Create some data
df  = data.frame(Type = rep(c("A","B"), each = 100),
                 x = c(rnorm(100, 0, 1), rnorm(100, 2, 1)),
                 y = c(rnorm(100, 0, 1), rnorm(100, 2, 1)))

# and if you want to check out the data
ggplot(df,aes(x,y,col=Type)) + geom_point() + stat_ellipse()

# OK so I have no issue extracting the minimum and maximum values
# for each type
df_summ = df %>%
  group_by(Type) %>%
  summarize(xmin = min(x),
            xmax = max(x),
            ymin = min(y),
            ymax = max(y))
df_summ

# and I can create a loop and use the expand.grid function to get my
# desired output
test = NULL
for(ii in c("A","B")){
  df1 = df_summ[df_summ$Type == ii,]
  x = seq(df1$xmin, df1$xmax, length.out = 10)
  y = seq(df1$ymin, df1$ymax, length.out = 10)
  coords = expand.grid(x = x, y = y)
  coords$Type = ii
  test = rbind(test, coords)
}

ggplot(test, aes(x,y,col = Type)) + geom_point()
</code>```

But what I would really like to do is find a way to bypass the loop
and try and get the same output straight from my piping operator.
I've tried a few combinations using the do() function but to no effect,
and the one posted below is just one of many, many failed attempts

```<code>df %>%
  group_by(Type) %>%
  summarize(xmin = min(x),
            xmax = max(x),
            ymin = min(y),
            ymax = max(y)) %>%
  do(data.frame(x = seq(xmin, xmax, length.out = 10),
                y = seq(ymin, ymax, length.out = 10)))

# this last line returns an error
# Error in is.finite(from) :
#   default method not implemented for type 'closure'
</code>```

答:
Using the data_grid function from the modelr package, here's one way to do it:

```<code>library(dplyr)
library(modelr)

df %>%
   group_by(Type) %>%
   data_grid(x, y) %>%
ggplot(aes(x,y, color = Type)) + geom_point()
</code>```

This approach generates for each value of x and each value of y in each group a row containing the pair x and y. So each x-y pair in the resulting dataframe is based only on values of x and y that actually appear in the data.

Body:
I'm hoping someone out there has a solution for using some form of expand.grid in piping using dplyr. I am doing some modeling where I have a few different groups (or Types below) and the groups have different ranges for x & y data. Once I run a gam on the data I am interested in creating a plot for the predictions, but I only want to predict values over the range that each value occupies, not the whole range of the data set.

I already have a working example posted below, but I'm wondering if there is a way to get around using a loop and complete my task.

Cheers

require(ggplot2)
require(dplyr)

# Create some data
df  = data.frame(Type = rep(c("A","B"), each = 100),
                 x = c(rnorm(100, 0, 1), rnorm(100, 2, 1)),
                 y = c(rnorm(100, 0, 1), rnorm(100, 2, 1)))

# and if you want to check out the data
ggplot(df,aes(x,y,col=Type)) + geom_point() + stat_ellipse()

# OK so I have no issue extracting the minimum and maximum values
# for each type
df_summ = df %>%
  group_by(Type) %>%
  summarize(xmin = min(x),
            xmax = max(x),
            ymin = min(y),
            ymax = max(y))
df_summ

# and I can create a loop and use the expand.grid function to get my
# desired output
test = NULL
for(ii in c("A","B")){
  df1 = df_summ[df_summ$Type == ii,]
  x = seq(df1$xmin, df1$xmax, length.out = 10)
  y = seq(df1$ymin, df1$ymax, length.out = 10)
  coords = expand.grid(x = x, y = y)
  coords$Type = ii
  test = rbind(test, coords)
}

ggplot(test, aes(x,y,col = Type)) + geom_point()

But what I would really like to do is find a way to bypass the loop
and try and get the same output straight from my piping operator.
I've tried a few combinations using the do() function but to no effect,
and the one posted below is just one of many, many failed attempts

df %>%
  group_by(Type) %>%
  summarize(xmin = min(x),
            xmax = max(x),
            ymin = min(y),
            ymax = max(y)) %>%
  do(data.frame(x = seq(xmin, xmax, length.out = 10),
                y = seq(ymin, ymax, length.out = 10)))

# this last line returns an error
# Error in is.finite(from) :
#   default method not implemented for type 'closure'

Body:
Using the data_grid function from the modelr package, here's one way to do it:

library(dplyr)
library(modelr)

df %>%
   group_by(Type) %>%
   data_grid(x, y) %>%
ggplot(aes(x,y, color = Type)) + geom_point()

This approach generates for each value of x and each value of y in each group a row containing the pair x and y. So each x-y pair in the resulting dataframe is based only on values of x and y that actually appear in the data.


来源: stackexchange

问:
R: Sum columns based on match table, merging column names
I have a data frame like this (where the letters are column names):

```<code>a   b   c   B   C   A
1   2   3   6   7   8
1   2   3   6   7   8
1   2   3   6   7   8
1   2   3   6   7   8
</code>```

And I would like to sum the columns based on this match table:

```<code>a   A
b   B
c   C
</code>```

While also merging the column names, so that the result would be:

```<code>a/A b/B c/C
9   8   10
9   8   10
9   8   10
9   8   10
</code>```

Please keep in mind that the solution need to be applicable to large data frames, so I cannot be specifying the new column names manually.

Thanks a lot!

答:
Here is one way of doing it...</p>

```<code>df <- data.frame(a=c(1,1,1,1),b=c(2,2,2,2),c=c(3,3,3,3),B=c(6,6,6,6),C=c(7,7,7,7),A=c(8,8,8,8))
matchtab <- data.frame(V1=c("a","b","c"),V2=c("A","B","C"),stringsAsFactors = FALSE)

df2 <- do.call(cbind,lapply(seq_len(nrow(matchtab)),function(i)
                           data.frame(df[,matchtab$V1[i]]+df[,matchtab$V2[i]])))
names(df2) <- paste0(matchtab$V1,"/",matchtab$V2)

df2
  a/A b/B c/C
1   9   8  10
2   9   8  10
3   9   8  10
4   9   8  10
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a data frame like this (where the letters are column names):

a   b   c   B   C   A
1   2   3   6   7   8
1   2   3   6   7   8
1   2   3   6   7   8
1   2   3   6   7   8

And I would like to sum the columns based on this match table:

a   A
b   B
c   C

While also merging the column names, so that the result would be:

a/A b/B c/C
9   8   10
9   8   10
9   8   10
9   8   10

Please keep in mind that the solution need to be applicable to large data frames, so I cannot be specifying the new column names manually.

Thanks a lot!

Body:
Here is one way of doing it...

df <- data.frame(a=c(1,1,1,1),b=c(2,2,2,2),c=c(3,3,3,3),B=c(6,6,6,6),C=c(7,7,7,7),A=c(8,8,8,8))
matchtab <- data.frame(V1=c("a","b","c"),V2=c("A","B","C"),stringsAsFactors = FALSE)

df2 <- do.call(cbind,lapply(seq_len(nrow(matchtab)),function(i)
                           data.frame(df[,matchtab$V1[i]]+df[,matchtab$V2[i]])))
names(df2) <- paste0(matchtab$V1,"/",matchtab$V2)

df2
  a/A b/B c/C
1   9   8  10
2   9   8  10
3   9   8  10
4   9   8  10


问:
How can I place a dot before the last three digits in a terminal output
What is the best way to place a dot after the last three dots in a terminal output?

I want to get from this: 10902MB/88%

to this: 10.902MB/88%

Currently I have this command for that:

```<code>df -m /dev/sda8 | grep -Eo '[0-9]*  [0-9]*%'| sed 's/  */MB\//g'
</code>```

Edit

The output of `df -m /dev/sda8 is

```<code>Filesystem     1M-blocks  Used Available Use% Mounted on
/dev/sda8          90349 74910     10828  88% /
</code>```

I need only the Available and Use% values.

Body:
What is the best way to place a dot after the last three dots in a terminal output?

I want to get from this: 10902MB/88%

to this: 10.902MB/88%

Currently I have this command for that:

df -m /dev/sda8 | grep -Eo '[0-9]*  [0-9]*%'| sed 's/  */MB\//g'

Edit

The output of `df -m /dev/sda8 is

Filesystem     1M-blocks  Used Available Use% Mounted on
/dev/sda8          90349 74910     10828  88% /

I need only the Available and Use% values.

Body:
echo 10902MB/88% | awk '{gsub(/[0-9][0-9][0-9]MB\//, ".&")} 1'

or

df -m /dev/sda8 | awk '{gsub(/[0-9][0-9][0-9]MB\//, ".&")} 1'


问:
How can I set the location of a stylesheet with jQuery?
How can I set the location of a stylesheet with jQuery?</p>

答:
You can manipulate the  element in much the same way that you can elements inside the  tag:

```<code>$("head>link[href$=mystyle.css]").remove();
$('<link rel="stylesheet" href="/css/anotherstyle.css"/>').appendTo("head");
</code>```

This removes the mystyle.css <link> tag and insert a new <link> tag with /css/anotherstyle.css at the end of the  element.

ContentLicense: CC BY-SA 2.5

Body:
You can manipulate the <head> element in much the same way that you can elements inside the <body> tag:

$("head>link[href$=mystyle.css]").remove();
$('<link rel="stylesheet" href="/css/anotherstyle.css"/>').appendTo("head");

This removes the mystyle.css <link> tag and insert a new <link> tag with /css/anotherstyle.css at the end of the <head> element.


问:
You have an error in your SQL syntax- PHP
I am trying to update my table row but can't get success.

here is error that coming.

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Current_date = '2017-03-30', Content = 'This is first notification te' at line 2

here is my code

```<code>if(!empty($_FILES) || isset($_FILES['Details_file'])){
    $filetmp = $_FILES["Details_file"]["tmp_name"];
    $filename = $_FILES["Details_file"]["name"];
    $filetype = $_FILES["Details_file"]["type"];
    $filepath = "notification/".$filename;

    move_uploaded_file($filetmp, $filepath);

    echo $_POST['post_date'];
    $stmt = $con1->prepare("UPDATE notification SET
        Current_date = '".$_POST['post_date']."',
        Content = '".$_POST['Content']."',
        File_name= '".$filename."',
        File_path ='".$filepath."',
        Apply_link = '".$_POST['apply_now']."',
        Last_date = '".$_POST['Last_date']."'
        WHERE id = '".$_POST['fetch_id']."'") or die(mysqli_error($con1));

    $stmt->execute();
    $stmt->close();
}
</code>```

any one can tell me what is problem with my code here.

答: Current_date is a reserved keyword in mySQL, so in order to use it as a name of the column, you would need to enclose it in backticks.

Body:
I am trying to update my table row but can't get success.

here is error that coming.

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Current_date = '2017-03-30', Content = 'This is first notification te' at line 2

here is my code

if(!empty($_FILES) || isset($_FILES['Details_file'])){
    $filetmp = $_FILES["Details_file"]["tmp_name"];
    $filename = $_FILES["Details_file"]["name"];
    $filetype = $_FILES["Details_file"]["type"];
    $filepath = "notification/".$filename;

    move_uploaded_file($filetmp, $filepath);

    echo $_POST['post_date'];
    $stmt = $con1->prepare("UPDATE notification SET
        Current_date = '".$_POST['post_date']."',
        Content = '".$_POST['Content']."',
        File_name= '".$filename."',
        File_path ='".$filepath."',
        Apply_link = '".$_POST['apply_now']."',
        Last_date = '".$_POST['Last_date']."'
        WHERE id = '".$_POST['fetch_id']."'") or die(mysqli_error($con1));

    $stmt->execute();
    $stmt->close();
}

any one can tell me what is problem with my code here.


问:
MySQL Query with while loop
So, I need to make MySQL query where I select data according to time.

```<code>1| SET @t = 1490894826;
2| SELECT id
3| FROM table
4| WHERE status=1 AND
5| fav>500 AND
6| time BETWEEN @t-86400 AND @t
7| LIMIT 10
</code>```

My question is, I need 10 rows from this query, but if it gives me 7 rows(for example), how can I set my query to do it again and again while number of selected rows is not 10 or time is bigger than 1480531730, and every next time @t variable needs to be substracted by 86400. Sorry for my english, take a look how I did it using PHP just to show you what I really want and I hope it will be more clearly.

```<code>$time=1490894826;
do{
   $query = $db->query("SELECT * FROM table WHERE status=1 AND fav>500 AND time BETWEEN ? AND ? LIMIT 10",[$time-86400,$time]);
   $time=$time-86400;
}while($query->rowCount()!=10||$time>1480531730);
</code>```

Thank you

答:
Try this:

```<code>SET @t = 1490894826;
SELECT id FROM table WHERE status=1 AND fav>500 AND
time <= @t
ORDER BY time DESC LIMIT 10
</code>```

This will sort by descending time, and give you the 10 most recent rows which have time <= @t. It is a very good idea to have an index on time, or (status,fav,time) to speed it up.

Title: MySQL Query with while loop

Body:
So, I need to make MySQL query where I select data according to time.

1| SET @t = 1490894826;
2| SELECT id
3| FROM table
4| WHERE status=1 AND
5| fav>500 AND
6| time BETWEEN @t-86400 AND @t
7| LIMIT 10

My question is, I need 10 rows from this query, but if it gives me 7 rows(for example), how can I set my query to do it again and again while number of selected rows is not 10 or time is bigger than 1480531730, and every next time @t variable needs to be substracted by 86400. Sorry for my english, take a look how I did it using PHP just to show you what I really want and I hope it will be more clearly.

$time=1490894826;
do{
   $query = $db->query("SELECT * FROM table WHERE status=1 AND fav>500 AND time BETWEEN ? AND ? LIMIT 10",[$time-86400,$time]);
   $time=$time-86400;
}while($query->rowCount()!=10||$time>1480531730);

Thank you

Body:
Try this:

SET @t = 1490894826;
SELECT id FROM table WHERE status=1 AND fav>500 AND
time <= @t
ORDER BY time DESC LIMIT 10

This will sort by descending time, and give you the 10 most recent rows which have time <= @t. It is a very good idea to have an index on time, or (status,fav,time) to speed it up.


问:
How to assign back data frame columns using dplyr
I need to modify some columns in data frame using dplyr. For example,

```<code>select(mtcars,hp:am)+99
</code>```

How can I assign back to the data frame mtcars?

```<code>mtcars[,4:9]=select(mtcars,hp:am)+99
</code>```

would work, but it uses absolute index 4:9, and I want to avoid that (which is why I am using dplyr : operation.)

答:
You cold borrow some of the logic from the subset() command to get a list of variable indices

```<code>varindex <- function(x, select) {
    if (missing(select))
        TRUE
    else {
        nl <- as.list(seq_along(x))
        names(nl) <- names(x)
        eval(substitute(select), nl, parent.frame())
    }
}
</code>```

And then use that for updating your data.frame

```<code>cols <- varindex(mtcars, hp:am)
mtcars[,cols] <- mtcars[,cols]+99
</code>```

If you want to stick with dplyr, the correct function to use is mutate(), not select(). Use

```<code>mutate_at(mtcars, vars(hp:am), function(x) x+99)
</code>```

Body:
I need to modify some columns in data frame using dplyr. For example,

select(mtcars,hp:am)+99

How can I assign back to the data frame mtcars?

mtcars[,4:9]=select(mtcars,hp:am)+99

would work, but it uses absolute index 4:9, and I want to avoid that (which is why I am using dplyr : operation.)

Body:
You cold borrow some of the logic from the subset() command to get a list of variable indices

varindex <- function(x, select) {
    if (missing(select))
        TRUE
    else {
        nl <- as.list(seq_along(x))
        names(nl) <- names(x)
        eval(substitute(select), nl, parent.frame())
    }
}

And then use that for updating your data.frame

cols <- varindex(mtcars, hp:am)
mtcars[,cols] <- mtcars[,cols]+99

If you want to stick with dplyr, the correct function to use is mutate(), not select(). Use

mutate_at(mtcars, vars(hp:am), function(x) x+99)


问:
ffmpeg making gif from serially numbered images
my files are named :

```<code>file1.png
file2.png
file3.png
....
file11.png
...
file123.png
...
file200.png
</code>```

now I want to make a gif of these images. I tired with

```<code>ffmpeg -framerate 10  -pattern_type glob -i 'file*.png' -c:v libx264 -pix_fmt yuv420p growth.avi
</code>```

but it does not work properly. What am i doing wrong?

答:
Convert to gif.

```<code>cd /home/user/Pictures && convert -delay 20 -loop 0 *.png result.gif
</code>```

Based upon your output to video format (.avi), you can use the commands directly in console to output to video format

```<code>ffmpeg -f image2 -pattern_type glob -framerate 12 -i 'file*.png' -s 420x360 output.avi

ffmpeg -framerate 29 -i file%d.png output.avi
</code>```

If you want to concat from file, first create file and give the location of the pictures. You can define duration in the file

Eg. Create imageList.txt in your picture folder. Put the location of picture like this.

```<code>file 'file4.png'
duration 2
file 'file5.png'
duration 2
file 'file6.png'
duration 3
file 'file7.png'
duration 2
file 'file8.png'
</code>```

In console,

```<code>ffmpeg -f concat -i imageList.txt -vsync vfr -pix_fmt yuv420p asf.avi
</code>```

Body:
my files are named :

file1.png
file2.png
file3.png
....
file11.png
...
file123.png
...
file200.png

now I want to make a gif of these images. I tired with

ffmpeg -framerate 10  -pattern_type glob -i 'file*.png' -c:v libx264 -pix_fmt yuv420p growth.avi

but it does not work properly. What am i doing wrong?

Body:
Convert to gif.

cd /home/user/Pictures && convert -delay 20 -loop 0 *.png result.gif

Based upon your output to video format (.avi), you can use the commands directly in console to output to video format

ffmpeg -f image2 -pattern_type glob -framerate 12 -i 'file*.png' -s 420x360 output.avi

ffmpeg -framerate 29 -i file%d.png output.avi

If you want to concat from file, first create file and give the location of the pictures. You can define duration in the file

Eg. Create imageList.txt in your picture folder. Put the location of picture like this.

file 'file4.png'
duration 2
file 'file5.png'
duration 2
file 'file6.png'
duration 3
file 'file7.png'
duration 2
file 'file8.png'

In console,

ffmpeg -f concat -i imageList.txt -vsync vfr -pix_fmt yuv420p asf.avi


问:
How to pass subscribed value to another Component?
I have a problem to pass a subscribed value to another component.

Structur:

```<code>app/
---elements/
------navigation.component.ts
---pages/
------login/
----------login.component.ts
</code>```

login.component.ts

```<code>isAuthenticated: any = false;

  onSignin() {
    this.authService.signinUser(this.myForm.value)
      .subscribe(
        data => {
          this.isAuthenticated = data;
        });
  }
</code>```

this.isAuthenticated is true if the login was successful.

What is the best way to send the data of isAuthenticated to the navigation.component.ts?

navigation.component.ts

```<code>isAuthenticated: any = false;

  constructor (private authService: AuthService, private router: Router) {
    this.authService.isAuthenticated()
      .subscribe(data => {
        this.isAuthenticated = data;
      });
  }
</code>```

Added:
auth.service.ts

```<code>isAuthenticated() {

      if (this.currentUser != null) {

        const token = this.currentUser.token;

        const body = JSON.stringify({token: token});
        return this.http.post('https://test.com/src/v13n22214', body)
          .map((response: Response) => {
            const authResponse = response.json().response;
            if (authResponse) {
              return true;
            } else {
              return false;
            }
          });
      }
</code>```

答:
You should save the value in the service then you can get it in another component, since you already injected the service</p>

```<code> constructor (private authService: AuthService, private router: Router) {
    this.isAuthenticated = this.authService.isAuthenticated();
 }
</code>```

Body:
I have a problem to pass a subscribed value to another component.

Structur:

app/
---elements/
------navigation.component.ts
---pages/
------login/
----------login.component.ts

login.component.ts

isAuthenticated: any = false;

  onSignin() {
    this.authService.signinUser(this.myForm.value)
      .subscribe(
        data => {
          this.isAuthenticated = data;
        });
  }

this.isAuthenticated is true if the login was successful.

What is the best way to send the data of isAuthenticated to the navigation.component.ts?

navigation.component.ts

isAuthenticated: any = false;

  constructor (private authService: AuthService, private router: Router) {
    this.authService.isAuthenticated()
      .subscribe(data => {
        this.isAuthenticated = data;
      });
  }

Added:
auth.service.ts

isAuthenticated() {

      if (this.currentUser != null) {

        const token = this.currentUser.token;

        const body = JSON.stringify({token: token});
        return this.http.post('https://test.com/src/v13n22214', body)
          .map((response: Response) => {
            const authResponse = response.json().response;
            if (authResponse) {
              return true;
            } else {
              return false;
            }
          });
      }

Body:
You should save the value in the service then you can get it in another component, since you already injected the service

 constructor (private authService: AuthService, private router: Router) {
    this.isAuthenticated = this.authService.isAuthenticated();
 }


问:
UITestControlNotAvailableException: The control is not available or not valid
I have written such code:

```<code>int timeOut = 300000; //milliseconds
string _displayTextProp = "DisplayText";

WpfText screenResult = MainWindow.UITableStatusControlCustom.ScreenResultLabelValue;

screenResult.WaitForControlExist(timeOut);
screenResult.WaitForControlPropertyNotEqual(_displayTextProp, null, timeOut);
screenResult.WaitForControlPropertyNotEqual(_displayTextProp, "0", timeOut);// (1)
</code>```

In this (1) method I have gotten exception UITestControlNotAvailableException

Test method  threw exception:
Microsoft.VisualStudio.TestTools.UITest.Extension.UITestControlNotAvailableException: The control is not available or not valid. ---> System.Runtime.InteropServices.COMException: Exception from HRESULT: 0x80042002
              at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
   at System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(Int32 errorCode)
   at MS.Internal.Automation.UiaCoreApi.CheckError(Int32 hr)
   at MS.Internal.Automation.UiaCoreApi.UiaGetPropertyValue(SafeNodeHandle hnode, Int32 propertyId, Object& value)
   at System.Windows.Automation.AutomationElement.GetCurrentPropertyValue(AutomationProperty property, Boolean ignoreDefaultValue)
   at System.Windows.Automation.AutomationElement.GetCurrentPropertyValue(AutomationProperty property)
   at Microsoft.VisualStudio.TestTools.UITest.Extension.Uia.UiaUtility.GetAutomationPropertyValue[T](AutomationElement element, AutomationProperty property)
 --- End of inner exception stack trace ---
    at Microsoft.VisualStudio.TestTools.UITest.Extension.Uia.UiaUtility.MapAndThrowException(SystemException e, IUITechnologyElement element)
   at Microsoft.VisualStudio.TestTools.UITest.Extension.Uia.UiaUtility.GetAutomationPropertyValue[T](AutomationElement element, AutomationProperty property)
   at Microsoft.VisualStudio.TestTools.UITest.Extension.Uia.UiaElement.GetAutomationPropertyValue[T](AutomationProperty automationProperty)
   at Microsoft.VisualStudio.TestTools.UITest.Extension.Uia.UiaElement.GetRequestedState(AccessibleStates requestedState)
   at Microsoft.VisualStudio.TestTools.UITest.Extension.UITechnologyElement.IsState(IUITechnologyElement element, AccessibleStates state)
   at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.EnsureValid(Boolean waitForReady, Boolean refetch)
   at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.GetPropertyValue(String propertyName)
   at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.GetProperty(String propertyName)
   at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.<>c_DisplayClass4.<WaitForControlPropertyNotEqual>b_3(UITestControl ctrl)
   at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.WaitForCondition[T](T conditionContext, Predicate1 conditionEvaluator, Int32 millisecondsTimeout)
   at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.WaitForControlCondition(Predicate1 conditionEvaluator, Int32 millisecondsTimeout)
   at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.WaitForControlPropertyNotEqual(String propertyName, Object propertyValue, Int32 millisecondsTimeout)

What is reason can be such behaviour?

Thank you for advance!

答:
As per this link:

This exception is thrown when the UI test framework attempts to access a UI element that is no longer available or cannot be accessed.  So you may have disposed of an item, or not have access to the element any longer and are now trying to access it.  Potentially you've failed to initialize one of the AutomationElements?

Body:
I have written such code:

int timeOut = 300000; //milliseconds
string _displayTextProp = "DisplayText";

WpfText screenResult = MainWindow.UITableStatusControlCustom.ScreenResultLabelValue;

screenResult.WaitForControlExist(timeOut);
screenResult.WaitForControlPropertyNotEqual(_displayTextProp, null, timeOut);
screenResult.WaitForControlPropertyNotEqual(_displayTextProp, "0", timeOut);// (1)

In this (1) method I have gotten exception UITestControlNotAvailableException

Test method  threw exception:
Microsoft.VisualStudio.TestTools.UITest.Extension.UITestControlNotAvailableException: The control is not available or not valid. ---> System.Runtime.InteropServices.COMException: Exception from HRESULT: 0x80042002
              at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
   at System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(Int32 errorCode)
   at MS.Internal.Automation.UiaCoreApi.CheckError(Int32 hr)
   at MS.Internal.Automation.UiaCoreApi.UiaGetPropertyValue(SafeNodeHandle hnode, Int32 propertyId, Object& value)
   at System.Windows.Automation.AutomationElement.GetCurrentPropertyValue(AutomationProperty property, Boolean ignoreDefaultValue)
   at System.Windows.Automation.AutomationElement.GetCurrentPropertyValue(AutomationProperty property)
   at Microsoft.VisualStudio.TestTools.UITest.Extension.Uia.UiaUtility.GetAutomationPropertyValue[T](AutomationElement element, AutomationProperty property)
 --- End of inner exception stack trace ---
    at Microsoft.VisualStudio.TestTools.UITest.Extension.Uia.UiaUtility.MapAndThrowException(SystemException e, IUITechnologyElement element)
   at Microsoft.VisualStudio.TestTools.UITest.Extension.Uia.UiaUtility.GetAutomationPropertyValue[T](AutomationElement element, AutomationProperty property)
   at Microsoft.VisualStudio.TestTools.UITest.Extension.Uia.UiaElement.GetAutomationPropertyValue[T](AutomationProperty automationProperty)
   at Microsoft.VisualStudio.TestTools.UITest.Extension.Uia.UiaElement.GetRequestedState(AccessibleStates requestedState)
   at Microsoft.VisualStudio.TestTools.UITest.Extension.UITechnologyElement.IsState(IUITechnologyElement element, AccessibleStates state)
   at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.EnsureValid(Boolean waitForReady, Boolean refetch)
   at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.GetPropertyValue(String propertyName)
   at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.GetProperty(String propertyName)
   at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.<>c_DisplayClass4.<WaitForControlPropertyNotEqual>b_3(UITestControl ctrl)
   at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.WaitForCondition[T](T conditionContext, Predicate1 conditionEvaluator, Int32 millisecondsTimeout)
   at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.WaitForControlCondition(Predicate1 conditionEvaluator, Int32 millisecondsTimeout)
   at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.WaitForControlPropertyNotEqual(String propertyName, Object propertyValue, Int32 millisecondsTimeout)

What is reason can be such behaviour?

Thank you for advance!


答:
Something like this?

```<code>df <- data.frame(a = rep(1, 5), b = rep(2, 5), c = rep(3, 5),
                 A = rep(8, 5), C = rep(7, 5), B = rep(6, 5))

df.names <- data.frame(First = c("a", "b", "c"), Second =  c("A", "B", "C"))

apply(df.names, MAR = 1, FUN = function(mynames, mydf) rowSums(df[,colnames(df) %in% mynames]), mydf = df)
</code>```

Gives,

```<code>     [,1] [,2] [,3]
[1,]    9    8   10
[2,]    9    8   10
[3,]    9    8   10
[4,]    9    8   10
[5,]    9    8   10
</code>```

Title: R: Sum columns based on match table, merging column names

Body:
Something like this?

df <- data.frame(a = rep(1, 5), b = rep(2, 5), c = rep(3, 5),
                 A = rep(8, 5), C = rep(7, 5), B = rep(6, 5))

df.names <- data.frame(First = c("a", "b", "c"), Second =  c("A", "B", "C"))

apply(df.names, MAR = 1, FUN = function(mynames, mydf) rowSums(df[,colnames(df) %in% mynames]), mydf = df)

Gives,

     [,1] [,2] [,3]
[1,]    9    8   10
[2,]    9    8   10
[3,]    9    8   10
[4,]    9    8   10
[5,]    9    8   10


问:
Calling copy constructor during operator overloading for different operators
This is a relatively simple code which contains an overloaded assignment operator and a multiplication operator. I've returned an object by value for both the operators. What's bugging me is that when I use the assignment operator, the copy constructor is always called while for the multiplication operator, copy constructors are never called.

```<code>#include<iostream>
using namespace std;
class foo {
public:
  int x;
  foo() {x=1;}
  foo(int a){x=a;}
  foo(const foo &p){
    cout<<"CC:\tCopying from:  "<<p.x<<'\t'<<&p<<"\tTo:  "<<this<<endl;
  }
  foo operator=(const foo &r){
      cout<<"Assgn:\t"<<"Assigning from:  "<<r.x<<'\t'<<&r
          <<"\tTo:  "<<this->x<<'\t'<<this<<endl;
      return *this;
  }
  foo operator*(const foo &r){
      cout<<"Product:\t"<<"Multiplying from:  "<<r.x<<'\t'<<&r
          <<"\tTo:  "<<this->x<<'\t'<<this<<endl;
      return foo(x*r.x);
  }
};

int main() {
  foo x(1),y(2);
  foo z=x=y;
  foo a=x*y;
  x.x=1; y.x=2;
  x*y*z;
  x=y=z;
  cout<<"X: "<<&x<<endl<<"Y: "<<&y<<endl<<"Z: "<<&z<<endl;
}
</code>```

Here's the output:

```<code>Assgn:  Assigning from:  2  0x7fff2cddbf70  To:  1  0x7fff2cddbf78
CC: Copying from:  1    0x7fff2cddbf78  To:  0x7fff2cddbf68
Product:    Multiplying from:  2    0x7fff2cddbf70  To:  1  0x7fff2cddbf78
Product:    Multiplying from:  2    0x7fff2cddbf70  To:  1  0x7fff2cddbf78
Product:    Multiplying from:  7618584  0x7fff2cddbf68  To:  2  0x7fff2cddbf58
Assgn:  Assigning from:  7618584    0x7fff2cddbf68  To:  2  0x7fff2cddbf70
CC: Copying from:  2    0x7fff2cddbf70  To:  0x7fff2cddbf48
Assgn:  Assigning from:  3  0x7fff2cddbf48  To:  1  0x7fff2cddbf78
CC: Copying from:  1    0x7fff2cddbf78  To:  0x7fff2cddbf40
X: 0x7fff2cddbf78
Y: 0x7fff2cddbf70
Z: 0x7fff2cddbf68
</code>```

The basic thing is, copy constructors are never being called when the multiplication operator is used (not even when i have a statement like foo 'a = x * y'). But while returning the value of 'a = b', copy constructor is called.

I know that compiler optimisation makes some changes in the output and that's why CC is not invoked when I declare a variable like z = x = y or z = x * y. But again, why is CC called when returning x=y when it can directly compute z like in the case of z = x * y? Is there any specific reason for this? Like, assignment operators are treated differently, or that since I return *this in assignment operator, it's different from the case in multiplication operator wherein I return a temporary variable ( this should be unlikely because ASFAIK, the compiler isn't be able to differentiate variables of local and global scope).

答:
One of my assumptions while trying to reach an answer was wrong.

I tried the same thing but just changed the assignment operator definition just a bit so that I first stored the value in a local variable and then returned it. And in this case, no copy constructor was called.

This means that the compiler can and does differentiate between variables of different scopes. Since the code which I posted in the question returns a non-local variable, copy-constructor is called.

I am guessing the same thing would happen (ie CC would be called) when I call the assignment operator from a different function outside the class. Even better yet, it would be interesting to see what happens when CC is called from within a different member function in the same class (although it would probably be the same).

Body:
This is a relatively simple code which contains an overloaded assignment operator and a multiplication operator. I've returned an object by value for both the operators. What's bugging me is that when I use the assignment operator, the copy constructor is always called while for the multiplication operator, copy constructors are never called.

#include<iostream>
using namespace std;
class foo {
public:
  int x;
  foo() {x=1;}
  foo(int a){x=a;}
  foo(const foo &p){
    cout<<"CC:\tCopying from:  "<<p.x<<'\t'<<&p<<"\tTo:  "<<this<<endl;
  }
  foo operator=(const foo &r){
      cout<<"Assgn:\t"<<"Assigning from:  "<<r.x<<'\t'<<&r
          <<"\tTo:  "<<this->x<<'\t'<<this<<endl;
      return *this;
  }
  foo operator*(const foo &r){
      cout<<"Product:\t"<<"Multiplying from:  "<<r.x<<'\t'<<&r
          <<"\tTo:  "<<this->x<<'\t'<<this<<endl;
      return foo(x*r.x);
  }
};

int main() {
  foo x(1),y(2);
  foo z=x=y;
  foo a=x*y;
  x.x=1; y.x=2;
  x*y*z;
  x=y=z;
  cout<<"X: "<<&x<<endl<<"Y: "<<&y<<endl<<"Z: "<<&z<<endl;
}

Here's the output:

Assgn:  Assigning from:  2  0x7fff2cddbf70  To:  1  0x7fff2cddbf78
CC: Copying from:  1    0x7fff2cddbf78  To:  0x7fff2cddbf68
Product:    Multiplying from:  2    0x7fff2cddbf70  To:  1  0x7fff2cddbf78
Product:    Multiplying from:  2    0x7fff2cddbf70  To:  1  0x7fff2cddbf78
Product:    Multiplying from:  7618584  0x7fff2cddbf68  To:  2  0x7fff2cddbf58
Assgn:  Assigning from:  7618584    0x7fff2cddbf68  To:  2  0x7fff2cddbf70
CC: Copying from:  2    0x7fff2cddbf70  To:  0x7fff2cddbf48
Assgn:  Assigning from:  3  0x7fff2cddbf48  To:  1  0x7fff2cddbf78
CC: Copying from:  1    0x7fff2cddbf78  To:  0x7fff2cddbf40
X: 0x7fff2cddbf78
Y: 0x7fff2cddbf70
Z: 0x7fff2cddbf68

The basic thing is, copy constructors are never being called when the multiplication operator is used (not even when i have a statement like foo 'a = x * y'). But while returning the value of 'a = b', copy constructor is called.

I know that compiler optimisation makes some changes in the output and that's why CC is not invoked when I declare a variable like z = x = y or z = x * y. But again, why is CC called when returning x=y when it can directly compute z like in the case of z = x * y? Is there any specific reason for this? Like, assignment operators are treated differently, or that since I return *this in assignment operator, it's different from the case in multiplication operator wherein I return a temporary variable ( this should be unlikely because ASFAIK, the compiler isn't be able to differentiate variables of local and global scope).


问:
set backlight time
Is there any way to change backlight turn off TIME using programming(Preferred  c# or vb.net other c++ can be used too)? I guess, may be it is changed using registry info or API.

Manually, it is done by:

Setting > Backlight (Battery Power and External Power)

Thank you

答:
::SystemParametersInfo does it.
Specify uiAction parameter to SPI_SETBATTERYIDLETIMEOUT to adjust "battery timeout" and/or SPI_SETEXTERNALIDLETIMEOUT for "AC timeout".

See detailed information on msdn.

Title: set backlight time


问:
Two divs: the first one is floated and the position of the second one depends on its width, why?
I have two divs. The first one is width: 50% and the second on is width: 80%. When I set float: left to the first one, the text of the second one is placed on the right of the first one. That's ok, it is what I expect. See the code here:

floated div

second div
```
</div>
</div>
</p>

<p><strong>The doubt</strong>: if I set <code>width: 30%</code> to the second div. The div is placed below the first one, why? Check the snippet:</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-html lang-html prettyprint-override"><code>      <div style="float: left; width: 50%; background: orange">floated div</div>
      <div style="width: 30%; background: red">second div</div> </code>```

答:
Not sure what you are trying to do with the snippet, but I would just add a clear between the 2 div's.

floated div

second div
```

Body:
I have two divs. The first one is width: 50% and the second on is width: 80%. When I set float: left to the first one, the text of the second one is placed on the right of the first one. That's ok, it is what I expect. See the code here:

floated div

second div

The doubt: if I set width: 30% to the second div. The div is placed below the first one, why? Check the snippet:

floated div

second div

Body:
Not sure what you are trying to do with the snippet, but I would just add a clear between the 2 div's.

<div style="float: left; width: 50%; background: orange">floated div</div>
<div style="clear: both;"></div>
<div style="width: 80%; background: red">second div</div>


问:
php find a specify word in a specific column from stored proc sql server
I'm kind of new in php and i'm searching a way to get some words from a specific column that i get from a sql server stored proc. These 'words' will me to use them as style for my css

Example :
Column HTML_CODE has sometime 'bold', 'green' or something else. Sometime they are in the same column, not always in the same order. I don't know how to use them in my loop. See what i has until now :

```<code>    $result = sqlsrv_query($conn, $sql);
while ($row = sqlsrv_fetch_array($result))
{
    //print_r( $row );  // debug code
    if ($row['HTML_CODE'] == 'BOLD(), Green()'){
        $couleur='green';
        $font= 'bold';
    }
    else {
        $couleur='black';
        $font= 'normal';
    }
?>
                            <tbody>
                                <tr>
                                    <?php echo "<tr style=\"font-weight:$font; color:$couleur;\">"; ?>
                                    <td><?php echo ($row['Nom']); ?></td>
                                    <td><?php echo ($row['Quantite']); ?></td>
                                    <td><?php echo ($row['Montant']); if (is_numeric($row['Montant'])) {
                                      echo ' $';
                                    }?></td>
                                    <td><?php echo ($row['#GL']); ?></td>
                                    <td><?php echo ($row['Debit']); if (is_numeric($row['Debit'])) {
                                      echo ' $';
                                    } ?></td>
                                    <td><?php echo ($row['Credit']); if (is_numeric($row['Credit'])) {
                                      echo ' $';
                                    }?></td>
                                </tr>
                            </tbody>
</code>```

答: if( strstr($row['HTML_CODE'], "BOLD()")){ $font= 'bold'; } </p>

Body:
I'm kind of new in php and i'm searching a way to get some words from a specific column that i get from a sql server stored proc. These 'words' will me to use them as style for my css

Example :
Column HTML_CODE has sometime 'bold', 'green' or something else. Sometime they are in the same column, not always in the same order. I don't know how to use them in my loop. See what i has until now :

    $result = sqlsrv_query($conn, $sql);
while ($row = sqlsrv_fetch_array($result))
{
    //print_r( $row );  // debug code
    if ($row['HTML_CODE'] == 'BOLD(), Green()'){
        $couleur='green';
        $font= 'bold';
    }
    else {
        $couleur='black';
        $font= 'normal';
    }
?>

                                    <?php echo "
"; ?>
                                    <?php echo ($row['Nom']); ?>
                                    <?php echo ($row['Quantite']); ?>
                                    <?php echo ($row['Montant']); if (is_numeric($row['Montant'])) {
                                      echo ' $';
                                    }?>
                                    <?php echo ($row['#GL']); ?>
                                    <?php echo ($row['Debit']); if (is_numeric($row['Debit'])) {
                                      echo ' $';
                                    } ?>
                                    <?php echo ($row['Credit']); if (is_numeric($row['Credit'])) {
                                      echo ' $';
                                    }?>


问:
Pandas column contents as index
I am trying to set a new pandas column using an existing pandas columns as set of indices to separate list, but I keep getting the following error:

```<code>TypeError: list indices must be integers or slices, not Series
</code>```

See code below:

```<code>import pandas as pd

monthvalues=[1,4,9,16,25,36,49,64,81,100,121,144]

df=pd.DataFrame([1,4,7,9], columns=['month'])

df['value']=monthvalues[df['month']-1]
</code>```

Expected result

```<code>    "month" "value"
0   1       1
1   4       16
2   7       49
3   9       81
</code>```

Note that this is just an example, I'm not actually trying to square the month digit in reality.

答:
It's because df['month'] returns a Pandas Series, not a list as I suspect you expect (although it still wouldn't work if it were a list).

I'm not sure if there's a neater way, but try this:

```<code>df['value'] = [monthvalues[x] for x in df['month']-1]
</code>```

Title: Pandas column contents as index

Body:
I am trying to set a new pandas column using an existing pandas columns as set of indices to separate list, but I keep getting the following error:

TypeError: list indices must be integers or slices, not Series

See code below:

import pandas as pd

monthvalues=[1,4,9,16,25,36,49,64,81,100,121,144]

df=pd.DataFrame([1,4,7,9], columns=['month'])

df['value']=monthvalues[df['month']-1]

Expected result

    "month" "value"
0   1       1
1   4       16
2   7       49
3   9       81

Note that this is just an example, I'm not actually trying to square the month digit in reality.

Body:
It's because df['month'] returns a Pandas Series, not a list as I suspect you expect (although it still wouldn't work if it were a list).

I'm not sure if there's a neater way, but try this:

df['value'] = [monthvalues[x] for x in df['month']-1]


问:
Hide div if value is undefined or blank (Angularjs)
I have the following. If i do a console.log($scope.variable), i get 2 values of it at different times on the console.

It shows undefined and '' at the console.

I want to hide a div on basis of this value. I do the following

```<code><div ng-hide="$scope.variable== undefined || $scope.variable = ''>
  Hide this section
</div>
</code>```

It should be able to hide the section since the values are either undefined and '' at all cases. However the div still shows at the UI. Am i missing any constraint or not putting the condition check properly ?

答:
```<code><div ng-show="variable != null"></div>
</code>```

or

```<code><div ng-hide="variable == null>
  Hide this section
</div>
</code>```

You could use ng-if in this case, which would result in better performance,

```<code> <div ng-if="variable == null">
      Hide this section
 </div>
</code>```

Body:
I have the following. If i do a console.log($scope.variable), i get 2 values of it at different times on the console.

It shows undefined and '' at the console.

I want to hide a div on basis of this value. I do the following

  Hide this section

It should be able to hide the section since the values are either undefined and '' at all cases. However the div still shows at the UI. Am i missing any constraint or not putting the condition check properly ?

Body:
<div ng-show="variable != null"></div>

or

<div ng-hide="variable == null>
  Hide this section
</div>

You could use ng-if in this case, which would result in better performance,

 <div ng-if="variable == null">
      Hide this section
 </div>


问:
Comparing brier score for Azure ML classifier
I'm trying to compare the brier score for two classifiers in Azure ML studio:

```<code>import pandas as pd
import numpy as np
from sklearn.metrics import brier_score_loss

def azureml_main(dataframe1, dataframe2):
    colnames_1 = dataframe1.columns
    y_true_1 = np.array(dataframe1[colnames_1[1]])
    y_prob_1 = np.array(dataframe1[colnames_1[-1]])
    brier_score_1 = brier_score_loss(y_true_1, y_prob_1)

    colnames_2 = dataframe2.columns
    y_true_2 = np.array(dataframe2[colnames_2[1]])
    y_prob_2 = np.array(dataframe2[colnames_2[-1]])
    brier_score_2 = brier_score_loss(y_true_2, y_prob_2)

    data = {'brier_score': [brier_score_1, brier_score_2]}
    result = pd.DataFrame(data, columns=['brier_score'])

    return result
</code>```

My problem is that the script only outputs a value in the first row with the brier score of the first dataset. The second row is empty. This is how I have connected the script:

答:
I turned out that the problem was caused by a few NaN values in the second dataframe.
Adding dataframe2 = dataframe2.dropna() to the top of the script solved the problem.

Body:
I'm trying to compare the brier score for two classifiers in Azure ML studio:

import pandas as pd
import numpy as np
from sklearn.metrics import brier_score_loss

def azureml_main(dataframe1, dataframe2):
    colnames_1 = dataframe1.columns
    y_true_1 = np.array(dataframe1[colnames_1[1]])
    y_prob_1 = np.array(dataframe1[colnames_1[-1]])
    brier_score_1 = brier_score_loss(y_true_1, y_prob_1)

    colnames_2 = dataframe2.columns
    y_true_2 = np.array(dataframe2[colnames_2[1]])
    y_prob_2 = np.array(dataframe2[colnames_2[-1]])
    brier_score_2 = brier_score_loss(y_true_2, y_prob_2)

    data = {'brier_score': [brier_score_1, brier_score_2]}
    result = pd.DataFrame(data, columns=['brier_score'])

    return result

My problem is that the script only outputs a value in the first row with the brier score of the first dataset. The second row is empty. This is how I have connected the script:


问:
unable to access controller functions in command line or console application
I am preparing a console application and making a connection to database using container of entity manager. This works fine. Code is below

```<code>protected function execute(InputInterface $input, OutputInterface $output)
{
    // get Doctrine
    $this->em = $this->getContainer()->get('doctrine.orm.entity_manager');
    // find all disc that are not treated by Manager in last week i.e sysdate - 6
    $pendingApprovals = $this->em->getRepository('GMRestBundle:TDtlsDisc')->getPendingManagerAppoval();
    // for each unapproved disc, start sending emails

    $repository = $this->em->getRepository('GMRestBundle:TDtlsDisc');
    $emailReminder = new SubmitDisclosureController();
    foreach($pendingApprovals as $labManagerReview) {
        $tDtlsDiscEntity = $repository->findByDiscId($labManagerReview['DISC_ID']);
        $emailReminder->sendMailToLabManager($tDtlsDiscEntity);
    }
}
</code>```

Now, the issue is it is giving error when I call thsi $emailReminder->sendMailToLabManager($tDtlsDiscEntity); which will in turn makes a connection of orm and get some data from database. This sendMailToLabManager is in SubmitDisclosureController and the code is below.

```<code>public function sendMailToLabManager($tDtlsDiscEntity)
{
    $repository = $this->getDoctrine()->getRepository('GMRestBundle:TXrefDiscSso');
    $entityRepository = $this->getDoctrine()->getRepository('GMRestBundle:TDtlsEntity');
    $discId = $tDtlsDiscEntity->getDiscId();
.......
</code>```

In console application, I am no able to use any controller which access DB by making another connection to doctrine object. Same controller if I called through another action controller in web, it works well.

```<code> Error: Call to a member function has() on null
</code>```

I see this above error message now.

答:
You should create a service which provides the function instead of using the controller. After that you have to insert the EntityManager via dependency injection in to the the service.

If your command extends ContainerAwareCommand you can use $this->get() inside your command to retrieve the service you have defined before.

Body:
I am preparing a console application and making a connection to database using container of entity manager. This works fine. Code is below

protected function execute(InputInterface $input, OutputInterface $output)
{
    // get Doctrine
    $this->em = $this->getContainer()->get('doctrine.orm.entity_manager');
    // find all disc that are not treated by Manager in last week i.e sysdate - 6
    $pendingApprovals = $this->em->getRepository('GMRestBundle:TDtlsDisc')->getPendingManagerAppoval();
    // for each unapproved disc, start sending emails

    $repository = $this->em->getRepository('GMRestBundle:TDtlsDisc');
    $emailReminder = new SubmitDisclosureController();
    foreach($pendingApprovals as $labManagerReview) {
        $tDtlsDiscEntity = $repository->findByDiscId($labManagerReview['DISC_ID']);
        $emailReminder->sendMailToLabManager($tDtlsDiscEntity);
    }
}

Now, the issue is it is giving error when I call thsi $emailReminder->sendMailToLabManager($tDtlsDiscEntity); which will in turn makes a connection of orm and get some data from database. This sendMailToLabManager is in SubmitDisclosureController and the code is below.

public function sendMailToLabManager($tDtlsDiscEntity)
{
    $repository = $this->getDoctrine()->getRepository('GMRestBundle:TXrefDiscSso');
    $entityRepository = $this->getDoctrine()->getRepository('GMRestBundle:TDtlsEntity');
    $discId = $tDtlsDiscEntity->getDiscId();
.......

In console application, I am no able to use any controller which access DB by making another connection to doctrine object. Same controller if I called through another action controller in web, it works well.

 Error: Call to a member function has() on null

I see this above error message now.


答:
I would suggest that you do something like this:

```<code>SET @t = 1490894826;
SELECT id
FROM table
WHERE status = 1 AND fav > 500 AND
      time <= @t
ORDER BY time DESC
LIMIT 10;
</code>```

That is, remove the BETWEEN and just take the 10 most recent times.

Title: MySQL Query with while loop

Body:
So, I need to make MySQL query where I select data according to time.

1| SET @t = 1490894826;
2| SELECT id
3| FROM table
4| WHERE status=1 AND
5| fav>500 AND
6| time BETWEEN @t-86400 AND @t
7| LIMIT 10

My question is, I need 10 rows from this query, but if it gives me 7 rows(for example), how can I set my query to do it again and again while number of selected rows is not 10 or time is bigger than 1480531730, and every next time @t variable needs to be substracted by 86400. Sorry for my english, take a look how I did it using PHP just to show you what I really want and I hope it will be more clearly.

$time=1490894826;
do{
   $query = $db->query("SELECT * FROM table WHERE status=1 AND fav>500 AND time BETWEEN ? AND ? LIMIT 10",[$time-86400,$time]);
   $time=$time-86400;
}while($query->rowCount()!=10||$time>1480531730);

Thank you

Body:
I would suggest that you do something like this:

SET @t = 1490894826;
SELECT id
FROM table
WHERE status = 1 AND fav > 500 AND
      time <= @t
ORDER BY time DESC
LIMIT 10;

That is, remove the BETWEEN and just take the 10 most recent times.


问:
How to create shapes on a JFreeChart line chart?
I would like to have shapes (small squares) that mark data points in the line chart that I am creating with ChartFactory.createLineChart().

It should look something like this (this image was not created with JFreeChart):

I have followed the description here, however, they don't appear for me. This is what the output from my JFreeChart software looks like:

My code is:

```<code>JFreeChart lineChart = ChartFactory.createLineChart(...);
CategoryPlot plot = (CategoryPlot) lineChart.getPlot();
plot.getRenderer().setBaseShape(
    new Rectangle2D.Double(-20.0, -20.0, 40.0, 40.0));
</code>```

I also tried using setSeriesShape instead of setBaseShape for all the series I'm plotting, it didn't make any difference either.

What am I doing wrong?

答:
Given a reference to the renderer,

```<code>LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();
</code>```

Invoke setBaseShapesVisible() to enable the shapes provided by your chosen DrawingSupplier.

```<code>renderer.setBaseShapesVisible(true);
</code>```

To change the appearance, pass a custom Shape to setSeriesShape() for the desired series.

```<code>renderer.setSeriesShape(0, new Ellipse2D.Double(-3d, -3d, 6d, 6d));
</code>```

Body:
I would like to have shapes (small squares) that mark data points in the line chart that I am creating with ChartFactory.createLineChart().

It should look something like this (this image was not created with JFreeChart):

I have followed the description here, however, they don't appear for me. This is what the output from my JFreeChart software looks like:

My code is:

JFreeChart lineChart = ChartFactory.createLineChart(...);
CategoryPlot plot = (CategoryPlot) lineChart.getPlot();
plot.getRenderer().setBaseShape(
    new Rectangle2D.Double(-20.0, -20.0, 40.0, 40.0));

I also tried using setSeriesShape instead of setBaseShape for all the series I'm plotting, it didn't make any difference either.

What am I doing wrong?

Body:
Given a reference to the renderer,

LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();

Invoke setBaseShapesVisible() to enable the shapes provided by your chosen DrawingSupplier.

renderer.setBaseShapesVisible(true);

To change the appearance, pass a custom Shape to setSeriesShape() for the desired series.

renderer.setSeriesShape(0, new Ellipse2D.Double(-3d, -3d, 6d, 6d));


问:
Problem with max SQL function
I have this code in PHP

```<code>$max="SELECT MAX(num) FROM info";
$maxquery= mysql_query($max) or die (died);
while($row = mysql_fetch_array($maxquery)){
    echo "The max num is ". $row['num']."this is it";
}
$maxnum= mysql_fetch_array($maxquery);
echo "<br>".$maxnum."hh";
</code>```

then the output be:

The max num is this is it

hh

Why didn't the query get the max number?

The table is called info and it has these fields, ID, num, title, description, and answer.

After editing:

I tried my query in MySQL and it works fine!

"SELECT MAX(num) FROM info"

and this is my complete code if it can help:

```<code><?php
    $answer=$_GET["answerbox"];
    $ID=$_GET["TheID"];

    $host="localhost";
    $username="root";
    $password="";
    $db_name="game";
    mysql_connect("$host","$username","$password")or die("cannot connect");
    mysql_select_db("$db_name")or die("cannot select DB");

    $max="SELECT MAX(num) FROM info";
    $maxquery= mysql_query($max) or die (died);
    while($row = mysql_fetch_array($maxquery)) {
        echo "The max num is ". $row['num']."this is it";
    }

    $maxnum= mysql_fetch_array($maxquery);
    $sql="SELECT * FROM info  WHERE ID=".$ID;
    $query = mysql_query($sql) or die(errorquery);
    $row = mysql_fetch_array($query);
    $trueanswer = $row['Answer'];
    $num=$row['num'];
    if ($num<$maxnum)
    {
        $numto= $num +1 ;
        echo "<br>".$maxnum."hh";
    }
?>
</code>```

答:
The column you are looking for in the result set is NOT called num. Try print_r($row); to see what the array indices are, or give it an alias, e.g.</p>

```<code>$max="SELECT MAX(num) AS max_num FROM info";
...
   echo "The max num is ". $row['max_num']
</code>```

Title: Problem with max SQL function

Body:
I have this code in PHP

$max="SELECT MAX(num) FROM info";
$maxquery= mysql_query($max) or die (died);
while($row = mysql_fetch_array($maxquery)){
    echo "The max num is ". $row['num']."this is it";
}
$maxnum= mysql_fetch_array($maxquery);
echo "
".$maxnum."hh";

then the output be:

The max num is this is it

hh

Why didn't the query get the max number?

The table is called info and it has these fields, ID, num, title, description, and answer.

After editing:

I tried my query in MySQL and it works fine!

"SELECT MAX(num) FROM info"

and this is my complete code if it can help:

<?php
    $answer=$_GET["answerbox"];
    $ID=$_GET["TheID"];

    $host="localhost";
    $username="root";
    $password="";
    $db_name="game";
    mysql_connect("$host","$username","$password")or die("cannot connect");
    mysql_select_db("$db_name")or die("cannot select DB");

    $max="SELECT MAX(num) FROM info";
    $maxquery= mysql_query($max) or die (died);
    while($row = mysql_fetch_array($maxquery)) {
        echo "The max num is ". $row['num']."this is it";
    }

    $maxnum= mysql_fetch_array($maxquery);
    $sql="SELECT * FROM info  WHERE ID=".$ID;
    $query = mysql_query($sql) or die(errorquery);
    $row = mysql_fetch_array($query);
    $trueanswer = $row['Answer'];
    $num=$row['num'];
    if ($num<$maxnum)
    {
        $numto= $num +1 ;
        echo "
".$maxnum."hh";
    }
?>

Body:
The column you are looking for in the result set is NOT called num. Try print_r($row); to see what the array indices are, or give it an alias, e.g.

$max="SELECT MAX(num) AS max_num FROM info";
...
   echo "The max num is ". $row['max_num']


问:
wxpython button with stock icon but no text
I am using wxPython and would like to create a button with a stock icon and no text. If I do

```<code>wx.Button(self,wx.ID_ADD)
</code>```

I get a button with a plus sign icon and the word 'Add' beside it.

How can I get a button with only the icon ?

答:
At first glance, it looks like wx.BU_NOTEXT could work for this, but it actually doesn't because wxWidgets supposes that if this style is used, then the button is supposed to have a bitmap explicitly associated with it.

So the simplest fix is to actually do set this bitmap by calling btn->SetBitmapLabel(wxArtProvider::GetBitmap(wxART_PLUS, wxART_MENU)) (this is C++, but should be easily translatable to Python too). If you do it like this, you don't need to use wxID_ADD as the button ID any more, but if you still want to keep using this ID, then you also need to use wxBU_NOTEXT to get rid of the stock text.

And, unlike stock buttons, which intentionally conform to the standard platform look and so may show the icon or not depending on the platform, this code will work the same everywhere.

Body:
I am using wxPython and would like to create a button with a stock icon and no text. If I do

wx.Button(self,wx.ID_ADD)

I get a button with a plus sign icon and the word 'Add' beside it.

How can I get a button with only the icon ?


问:
Declaring Maps with typescript
```<code>private itemsMap: Map<Array<string>,string> = new Map([
    [['shp'], 'Shapefile'],
    [['doc', 'docx'], 'Microsoft Word']
]);
</code>```

Typescript doesn't like this, it gives me: "Argument of type '(string | string[])[][]' is not assignable to parameter of type 'Iterable<[{},{}]>"

This is a valid way to declare a "Map literal" though.  Is there a way to do this that isn't going to cause an issue?

答:
What TypeScript version are using?  This appears to work correctly with the current TypeScript version (currently 2.2.x).

See this playground

Title: Declaring Maps with typescript

Body:
private itemsMap: Map<Array<string>,string> = new Map([
    [['shp'], 'Shapefile'],
    [['doc', 'docx'], 'Microsoft Word']
]);

Typescript doesn't like this, it gives me: "Argument of type '(string | string[])[][]' is not assignable to parameter of type 'Iterable<[{},{}]>"

This is a valid way to declare a "Map literal" though.  Is there a way to do this that isn't going to cause an issue?


问:
How do I return focus to an element when the entire page changes?
I have a complicated setup. My application is driven by a set of "rules" which dictate what the user interface is. The UI is rendered by looping through the rules and creating the individual dropdowns. Initially, everything renders properly. However, once a user makes a change to the UI, other rules may be affected. In my application, an api call is made, which then returns a modified set of rules. In the attached plunker, I've simplified things such that only the new set of rules is applied, which causes the page to re-render. The problem is that my users would like to be able to tab between all of the entries on the page and make changes. However, once the page is re-rendered, the currently selected page element is now gone nothing has the focus. I've tried to put the focus back on the proper element by tracking a common Id, but to no avail.

Using either of these doesn't seem to work.

var el = document.getElementById(focusId);
el.focus();
angular.element(el).focus();

I've also tried using the autofocus attribute on the dropdown that I want to have focus, but that didn't work either. I'm using angularjs 1.2. Any ideas are appreciated.

http://plnkr.co/edit/ND9PKqULIOlixWR4XChN?p=preview

答:
If you want to assign auto focus dynamically to a element on the DOM from angular you can use this:

```<code>var myEl = angular.element(document.querySelector('select'));
myEl.attr('autofocus',"attr val");
</code>```

You can also pass in an id like: angular.element(document.querySelector('#focusId'));

You can look here for a prior answer which may be of some more help!

-Cheers!

Body:
If you want to assign auto focus dynamically to a element on the DOM from angular you can use this:

var myEl = angular.element(document.querySelector('select'));
myEl.attr('autofocus',"attr val");

You can also pass in an id like: angular.element(document.querySelector('#focusId'));

You can look here for a prior answer which may be of some more help!

-Cheers!


问:
Implementation of scheme vector-set
I am trying to understand how vector-set! is implemented. It looks to me like vector-set! is a special form - much like set! is. When I look at examples using vector-set! I see the following, desirable behavior (in guile).

```<code>(define test (lambda (v i) (vector-set! v i 0)))
(define v (make-vector 5 1))
v
$1 = #(1 1 1 1 1)
(test v 0)
v
$2 = #(0 1 1 1 1)
</code>```

I can also do this (in guile)

```<code>(define test (lambda (v i) (vector-set! (eval v (interaction-environment)) i 0)))
(test (quote v) 3)
v
$21 = #(0 1 1 0 1)
</code>```

Contrasting to the set! behavior:

```<code>(define a 1)
(define test2 (lambda b (begin (set! b 0) b)))
(test2 (quote a))
$26 = 0
a
$27 = 1
</code>```

In this case, to my understanding the set! changes b to 0 (and not the 'evaluated" b (which should be a). The eval trick from above does not work here.

My question is: How is vector-set! implemented compared to set! (or set-variable-value!). Does vector-set! peak at it's first argument? Or something else? I have tried to look at some of scheme implementations but extracting the gist from the code is tricky. Perhaps someone has an explanation or a link to some (sicp style) scheme implementation.

答:
In "some SICP-style Scheme implementation", where vector-set! would be handled by eval-vector-mutation, it could be

```<code>(define (eval-vector-mutation exp env)
    ; exp = (vector-set! vec idx val)
  (let ((vec (eval (vector-mutation-vec exp) env))
        (idx (eval (vector-mutation-idx exp) env))
        (val (eval (vector-mutation-val exp) env)))
    (begin
      (set-car! (cddr (drop vec idx)) val)  ; srfi-1 drop
      vec)))
</code>```

and make-vector handled by

```<code>(define (eval-vector-creation exp env)
    ; exp = (make-vector cnt val)
  (let ((cnt (eval (vector-creation-cnt exp) env))
        (val (eval (vector-creation-val exp) env)))
    (cons 'vector                           ; tagged list
      (cons cnt                             ; vector size
        (make-list cnt val)))))             ; srfi-1 make-list
</code>```

Here vectors are represented by tagged lists in the underlying Scheme implementation (not the Scheme being defined), and its mutation primitives, like set-car!, are used to manipulate them. If your implementation language were C, say, you'd just use C arrays as your vectors representation, or perhaps a structure coupling an array with the additional pertinent info, like its size ,etc.

Title: Implementation of scheme vector-set

Body:
I am trying to understand how vector-set! is implemented. It looks to me like vector-set! is a special form - much like set! is. When I look at examples using vector-set! I see the following, desirable behavior (in guile).

(define test (lambda (v i) (vector-set! v i 0)))
(define v (make-vector 5 1))
v
$1 = #(1 1 1 1 1)
(test v 0)
v
$2 = #(0 1 1 1 1)

I can also do this (in guile)

(define test (lambda (v i) (vector-set! (eval v (interaction-environment)) i 0)))
(test (quote v) 3)
v
$21 = #(0 1 1 0 1)

Contrasting to the set! behavior:

(define a 1)
(define test2 (lambda b (begin (set! b 0) b)))
(test2 (quote a))
$26 = 0
a
$27 = 1

In this case, to my understanding the set! changes b to 0 (and not the 'evaluated" b (which should be a). The eval trick from above does not work here.

My question is: How is vector-set! implemented compared to set! (or set-variable-value!). Does vector-set! peak at it's first argument? Or something else? I have tried to look at some of scheme implementations but extracting the gist from the code is tricky. Perhaps someone has an explanation or a link to some (sicp style) scheme implementation.

Body:
In "some SICP-style Scheme implementation", where vector-set! would be handled by eval-vector-mutation, it could be

(define (eval-vector-mutation exp env)
    ; exp = (vector-set! vec idx val)
  (let ((vec (eval (vector-mutation-vec exp) env))
        (idx (eval (vector-mutation-idx exp) env))
        (val (eval (vector-mutation-val exp) env)))
    (begin
      (set-car! (cddr (drop vec idx)) val)  ; srfi-1 drop
      vec)))

and make-vector handled by

(define (eval-vector-creation exp env)
    ; exp = (make-vector cnt val)
  (let ((cnt (eval (vector-creation-cnt exp) env))
        (val (eval (vector-creation-val exp) env)))
    (cons 'vector                           ; tagged list
      (cons cnt                             ; vector size
        (make-list cnt val)))))             ; srfi-1 make-list

Here vectors are represented by tagged lists in the underlying Scheme implementation (not the Scheme being defined), and its mutation primitives, like set-car!, are used to manipulate them. If your implementation language were C, say, you'd just use C arrays as your vectors representation, or perhaps a structure coupling an array with the additional pertinent info, like its size ,etc.


问:
What is the fastest way to open a form from a form?
What is the fast and effective way to open Form2 from Form1?

I work in WinCE (limited memory and CPU power) so this becomes important.

答:
If you want the form be open quicker in terms of user responsiveness AND you can handle the memory overhead you might consider "preloading" the form.  Instantiate the form in the start up procedure of your app and cache the form in a global variable (or make it a singleton and create an instance).  This increases app start up time but gives you improved responsiveness when you later show the form.  If the form has a lot of controls calling show then hide against the form in start up will also preload the forms controls, further reducing the time it takes to subsequently display the form.

This is not usualy recommended on the full .net framework!

OwnerDisplayName: Gold

LastEditorDisplayName: Rich B

OwnerDisplayName: Christopher Edwards


答:
You could also take a look at the DatePeriod class:

```<code>$period = new DatePeriod(
     new DateTime('2010-10-01'),
     new DateInterval('P1D'),
     new DateTime('2010-10-05')
);
</code>```

Which should get you an array with DateTime objects.

To iterate

```<code>foreach ($period as $key => $value) {
    //$value->format('Y-m-d')
}
</code>```

Title: PHP: Return all dates between two dates in an array

Body:
Expected Input:

getDatesFromRange( '2010-10-01', '2010-10-05' );

Expected Output:

Array( '2010-10-01', '2010-10-02', '2010-10-03', '2010-10-04', '2010-10-05' )

Body:
You could also take a look at the DatePeriod class:

$period = new DatePeriod(
     new DateTime('2010-10-01'),
     new DateInterval('P1D'),
     new DateTime('2010-10-05')
);

Which should get you an array with DateTime objects.

To iterate

foreach ($period as $key => $value) {
    //$value->format('Y-m-d')
}


问:
Msg 156, Levl 15, State 1, Line 1 Incorrect syntax near keyword 'top'
This section of my code is failing. I cannot figure out why I am receiving this message.  Can anyone please look it over and see if you see anything that looks wrong?

Thanks so much!!!

```<code>    declare @ReportOrder int
    declare @numrows int
    declare @Section varchar(30)
    declare @Dept_Op varchar(5)
    declare @Dept varchar(30)
    declare @SDept_Op varchar(5)
    declare @SDept varchar(30)
    declare @Class_Op varchar(5)
    declare @Class varchar(30)
    declare @Over_POS Int
    declare @year int
    declare @week int
    declare @Perc_To_Total float
    declare @Perc_Remaining float
    declare @LS smalldatetime
    declare @LYCARD_2NC smalldatetime

    declare @sql nvarchar(4000)

    select @year = datepart(yy,getdate())
    select @year = @year - 1
    select @week = staging.dbo.fn_Calendar_Week(getdate())
    select @LS = staging.dbo.fn_Last_Saturday(getdate())
    select @lyCARD_2NC = dateadd(yy,-1,@LS)

    Truncate table ReportData.dbo.rpt_Holiday_Top_Selling_Report_2NC
    Truncate table Staging.dbo.tmp_Top10_2NC

    declare cur cursor for select ReportOrder, numrows, Section, Dept_Op,              Dept, SDept_Op, SDept, Class_Op, Class, Over_POS
    from Reference.dbo.Holiday_Top_Selling_Config_new
    order by ReportOrder

    open cur
    fetch next from cur into @ReportOrder, @numrows, @Section, @Dept_Op,     @Dept, @SDept_Op, @SDept, @Class_Op, @Class, @Over_POS

    while @@Fetch_Status = 0
    begin

    select @sql = 'insert into    Reportdata.dbo.rpt_Holiday_Top_Selling_Report_2NC '
    select @sql = @sql + 'select top ' + cast(@numrows as char(2)) + ' '
    select @sql = @sql + cast(@ReportOrder as char(3)) + ' as PrintOrder,'
    select @sql = @sql + '''' + @Section + '''' + ' as Section,'
    select @sql = @sql + ' row_Number() over (order by t1.wtd_dollars desc) as Rank, '
    select @sql = @sql + ' t1.ISBN as TY_ISBN, '
    select @sql = @sql + ' t1.title as TY_Title, '
    select @sql = @sql + ' t1.Author as TY_Author, '
    select @sql = @sql + ' t1.Dept as TY_Dept_Num, '
    select @sql = @sql + ' t1.SDept as TY_SDept_Num, '
    select @sql = @sql + ' t1.Class as TY_Class_Num, '
    select @sql = @sql + ' t1.display_min, '
    select @sql = @sql + ' t1.Class_Name as TY_Class, '
    select @sql = @sql + ' t1.wtd_Dollars as TY_SLS$, '
    select @sql = @sql + ' t1.wtd_Units as TY_SLSU, '
    select @sql = @sql + ' 0 as Discount, '
    select @sql = @sql + ' t1.OnHand_2NC as OnHand, '
    select @sql = @sql + ' isnull(t1.Qty_OnOrder,0) as OnOrder, '
    select @sql = @sql + ' 0 as Proj, '
    select @sql = @sql + ' NULL as NNTC, '
    select @sql = @sql + ' NULL as LY_ISBN, '
    select @sql = @sql + ' NULL as LY_Title, '
    select @sql = @sql + ' NULL as LY_Author, '
    select @sql = @sql + ' NULL as LY_Dept_Num, '
    select @sql = @sql + ' NULL as LY_SDept_Num, '
    select @sql = @sql + ' NULL as LY_Class_Num, '
    select @sql = @sql + ' NULL as LY_On_Hand, '
    select @sql = @sql + ' NULL as LY_Class, '
    select @sql = @sql + ' NULL as LY_SLS$, '
    select @sql = @sql + ' NULL as LY_SLSU, '
    select @sql = @sql + ' NULL as Forecast_Thru, '
    select @sql = @sql + ' NULL as Week_42, '
    select @sql = @sql + ' NULL as Week_43, '
    select @sql = @sql + ' NULL as Week_44, '
    select @sql = @sql + ' NULL as Week_45, '
    select @sql = @sql + ' NULL as Week_46, '
    select @sql = @sql + ' NULL as Week_47, '
    select @sql = @sql + ' NULL as Week_48, '
    select @sql = @sql + ' NULL as Week_49 '
    select @sql = @sql + ' from dssdata.dbo.CARD_2NC t1'
    select @sql = @sql + ' where t1.dept ' + @Dept_Op + ' ' + @Dept
    select @sql = @sql + ' and t1.SDept ' + @SDept_Op + ' ' + @SDept
    select @sql = @sql + ' and t1.Class ' + @Class_Op + ' ' + @Class

    if @Over_POS > 0
        select @sql = @sql + ' and t1.Retail > ' + cast(@Over_POS as char(3)) + ' '
        select @sql = @sql + ' order by wtd_Dollars desc '

    EXEC sp_executesql @sql

    select @sql = 'insert into Staging.dbo.tmp_Top10_2NC'
    select @sql = @sql + 'select top ' + cast(@numrows as char(3)) + ' '
    select @sql = @sql + 'row_Number() over (order by t1.LYWeek1dollars desc) as LYRank, '
    select @sql = @sql + 't1.ISBN as ISBN, '
    select @sql = @sql + 't1.Title as Title, '
    select @sql = @sql + 't1.Author, '
    select @sql = @sql + 't1.Dept, '
    select @sql = @sql + 't1.SDept, '
    select @sql = @sql + 't1.Class, '
    select @sql = @sql + 't1.OnHand_2NC, '
    select @sql = @sql + 't1.Class_Name, '
    select @sql = @sql + 't1.LYWeek1Dollars as Sls$, '
    select @sql = @sql + 't1.LYWeek1Units as SlsU '
    select @sql = @sql + 'from  dssdata.dbo.CARD_2NC t1 '
    select @sql = @sql + ' where t1.dept ' + @Dept_Op + ' ' + @Dept
    select @sql = @sql + ' and t1.SDept ' + @SDept_Op + ' ' + @SDept
    select @sql = @sql + ' and t1.Class ' + @Class_Op + ' ' + @Class

    if @Over_POS > 0
        select @sql = @sql + ' and t1.retail > ' + cast(@Over_POS as char(3)) + ' '
        select @sql = @sql + ' order by LYWeek1Dollars desc '

    EXEC sp_executesql @sql

    select @sql = 'update ReportData.dbo.rpt_Holiday_Top_Selling_Report_2NC '
    select @sql = @sql + 'Set   LY_Title = Title, '
    select @sql = @sql + 'LY_ISBN = ISBN, '
    select @sql = @sql + 'NNTC = (Proj + (TY_SLSU * 3)) - (ReportData.dbo.rpt_Holiday_Top_Selling_Report_2NC.onHand + OnOrder), '
    select @sql = @sql + 'LY_Author = Author, '
    select @sql = @sql + 'LY_Dept_Num = Dept_Num, '
    select @sql = @sql + 'LY_SDept_Num = SDept_Num, '
    select @sql = @sql + 'LY_Class_Num = Class_Num, '
    select @sql = @sql + 'LY_OnHand = Staging.dbo.tmp_Top10_2NC.OnHand, '
    select @sql = @sql + 'LY_Class = Class, '
    select @sql = @sql + 'LY_SLS$ = SLS$, '
    select @sql = @sql + 'LY_SLSU = SLSU '
    select @sql = @sql + 'from  Staging.dbo.tmp_Top10_2NC'
    select @sql = @sql + 'where Staging.dbo.tmp_Top10_2NC.LYRank = Rank '
    select @sql = @sql + 'and Section = ' + '''' + @Section + ''''

    EXEC sp_executesql @sql

    truncate table Staging.dbo.tmp_Top10_NEW

    fetch next from cur into @ReportOrder, @numrows, @Section, @Dept_Op,      @Dept, @SDept_Op, @SDept, @Class_Op, @Class, @Over_POS
   end

   close cur
   deallocate cur
</code>```

答:
Missing a space at the end of

select @sql = 'insert into Staging.dbo.tmp_Top10_2NC'

```<code>select @sql = 'insert into Staging.dbo.tmp_Top10_2NC '
select @sql = @sql + 'select top ' + cast(@numrows as char(3)) + ' '
</code>```

Body:
This section of my code is failing. I cannot figure out why I am receiving this message.  Can anyone please look it over and see if you see anything that looks wrong?

Thanks so much!!!

    declare @ReportOrder int
    declare @numrows int
    declare @Section varchar(30)
    declare @Dept_Op varchar(5)
    declare @Dept varchar(30)
    declare @SDept_Op varchar(5)
    declare @SDept varchar(30)
    declare @Class_Op varchar(5)
    declare @Class varchar(30)
    declare @Over_POS Int
    declare @year int
    declare @week int
    declare @Perc_To_Total float
    declare @Perc_Remaining float
    declare @LS smalldatetime
    declare @LYCARD_2NC smalldatetime

    declare @sql nvarchar(4000)

    select @year = datepart(yy,getdate())
    select @year = @year - 1
    select @week = staging.dbo.fn_Calendar_Week(getdate())
    select @LS = staging.dbo.fn_Last_Saturday(getdate())
    select @lyCARD_2NC = dateadd(yy,-1,@LS)

    Truncate table ReportData.dbo.rpt_Holiday_Top_Selling_Report_2NC
    Truncate table Staging.dbo.tmp_Top10_2NC

    declare cur cursor for select ReportOrder, numrows, Section, Dept_Op,              Dept, SDept_Op, SDept, Class_Op, Class, Over_POS
    from Reference.dbo.Holiday_Top_Selling_Config_new
    order by ReportOrder

    open cur
    fetch next from cur into @ReportOrder, @numrows, @Section, @Dept_Op,     @Dept, @SDept_Op, @SDept, @Class_Op, @Class, @Over_POS

    while @@Fetch_Status = 0
    begin

    select @sql = 'insert into    Reportdata.dbo.rpt_Holiday_Top_Selling_Report_2NC '
    select @sql = @sql + 'select top ' + cast(@numrows as char(2)) + ' '
    select @sql = @sql + cast(@ReportOrder as char(3)) + ' as PrintOrder,'
    select @sql = @sql + '''' + @Section + '''' + ' as Section,'
    select @sql = @sql + ' row_Number() over (order by t1.wtd_dollars desc) as Rank, '
    select @sql = @sql + ' t1.ISBN as TY_ISBN, '
    select @sql = @sql + ' t1.title as TY_Title, '
    select @sql = @sql + ' t1.Author as TY_Author, '
    select @sql = @sql + ' t1.Dept as TY_Dept_Num, '
    select @sql = @sql + ' t1.SDept as TY_SDept_Num, '
    select @sql = @sql + ' t1.Class as TY_Class_Num, '
    select @sql = @sql + ' t1.display_min, '
    select @sql = @sql + ' t1.Class_Name as TY_Class, '
    select @sql = @sql + ' t1.wtd_Dollars as TY_SLS$, '
    select @sql = @sql + ' t1.wtd_Units as TY_SLSU, '
    select @sql = @sql + ' 0 as Discount, '
    select @sql = @sql + ' t1.OnHand_2NC as OnHand, '
    select @sql = @sql + ' isnull(t1.Qty_OnOrder,0) as OnOrder, '
    select @sql = @sql + ' 0 as Proj, '
    select @sql = @sql + ' NULL as NNTC, '
    select @sql = @sql + ' NULL as LY_ISBN, '
    select @sql = @sql + ' NULL as LY_Title, '
    select @sql = @sql + ' NULL as LY_Author, '
    select @sql = @sql + ' NULL as LY_Dept_Num, '
    select @sql = @sql + ' NULL as LY_SDept_Num, '
    select @sql = @sql + ' NULL as LY_Class_Num, '
    select @sql = @sql + ' NULL as LY_On_Hand, '
    select @sql = @sql + ' NULL as LY_Class, '
    select @sql = @sql + ' NULL as LY_SLS$, '
    select @sql = @sql + ' NULL as LY_SLSU, '
    select @sql = @sql + ' NULL as Forecast_Thru, '
    select @sql = @sql + ' NULL as Week_42, '
    select @sql = @sql + ' NULL as Week_43, '
    select @sql = @sql + ' NULL as Week_44, '
    select @sql = @sql + ' NULL as Week_45, '
    select @sql = @sql + ' NULL as Week_46, '
    select @sql = @sql + ' NULL as Week_47, '
    select @sql = @sql + ' NULL as Week_48, '
    select @sql = @sql + ' NULL as Week_49 '
    select @sql = @sql + ' from dssdata.dbo.CARD_2NC t1'
    select @sql = @sql + ' where t1.dept ' + @Dept_Op + ' ' + @Dept
    select @sql = @sql + ' and t1.SDept ' + @SDept_Op + ' ' + @SDept
    select @sql = @sql + ' and t1.Class ' + @Class_Op + ' ' + @Class

    if @Over_POS > 0
        select @sql = @sql + ' and t1.Retail > ' + cast(@Over_POS as char(3)) + ' '
        select @sql = @sql + ' order by wtd_Dollars desc '

    EXEC sp_executesql @sql

    select @sql = 'insert into Staging.dbo.tmp_Top10_2NC'
    select @sql = @sql + 'select top ' + cast(@numrows as char(3)) + ' '
    select @sql = @sql + 'row_Number() over (order by t1.LYWeek1dollars desc) as LYRank, '
    select @sql = @sql + 't1.ISBN as ISBN, '
    select @sql = @sql + 't1.Title as Title, '
    select @sql = @sql + 't1.Author, '
    select @sql = @sql + 't1.Dept, '
    select @sql = @sql + 't1.SDept, '
    select @sql = @sql + 't1.Class, '
    select @sql = @sql + 't1.OnHand_2NC, '
    select @sql = @sql + 't1.Class_Name, '
    select @sql = @sql + 't1.LYWeek1Dollars as Sls$, '
    select @sql = @sql + 't1.LYWeek1Units as SlsU '
    select @sql = @sql + 'from  dssdata.dbo.CARD_2NC t1 '
    select @sql = @sql + ' where t1.dept ' + @Dept_Op + ' ' + @Dept
    select @sql = @sql + ' and t1.SDept ' + @SDept_Op + ' ' + @SDept
    select @sql = @sql + ' and t1.Class ' + @Class_Op + ' ' + @Class

    if @Over_POS > 0
        select @sql = @sql + ' and t1.retail > ' + cast(@Over_POS as char(3)) + ' '
        select @sql = @sql + ' order by LYWeek1Dollars desc '

    EXEC sp_executesql @sql

    select @sql = 'update ReportData.dbo.rpt_Holiday_Top_Selling_Report_2NC '
    select @sql = @sql + 'Set   LY_Title = Title, '
    select @sql = @sql + 'LY_ISBN = ISBN, '
    select @sql = @sql + 'NNTC = (Proj + (TY_SLSU * 3)) - (ReportData.dbo.rpt_Holiday_Top_Selling_Report_2NC.onHand + OnOrder), '
    select @sql = @sql + 'LY_Author = Author, '
    select @sql = @sql + 'LY_Dept_Num = Dept_Num, '
    select @sql = @sql + 'LY_SDept_Num = SDept_Num, '
    select @sql = @sql + 'LY_Class_Num = Class_Num, '
    select @sql = @sql + 'LY_OnHand = Staging.dbo.tmp_Top10_2NC.OnHand, '
    select @sql = @sql + 'LY_Class = Class, '
    select @sql = @sql + 'LY_SLS$ = SLS$, '
    select @sql = @sql + 'LY_SLSU = SLSU '
    select @sql = @sql + 'from  Staging.dbo.tmp_Top10_2NC'
    select @sql = @sql + 'where Staging.dbo.tmp_Top10_2NC.LYRank = Rank '
    select @sql = @sql + 'and Section = ' + '''' + @Section + ''''

    EXEC sp_executesql @sql

    truncate table Staging.dbo.tmp_Top10_NEW

    fetch next from cur into @ReportOrder, @numrows, @Section, @Dept_Op,      @Dept, @SDept_Op, @SDept, @Class_Op, @Class, @Over_POS
   end

   close cur
   deallocate cur

Body:
Missing a space at the end of

select @sql = 'insert into Staging.dbo.tmp_Top10_2NC'

select @sql = 'insert into Staging.dbo.tmp_Top10_2NC '
select @sql = @sql + 'select top ' + cast(@numrows as char(3)) + ' '


问:
How can an array be grouped by two properties?
Ex:

```<code>const arr = [{
  group: 1,
  question: {
    templateId: 100
  }
}, {
  group: 2,
  question: {
    templateId: 200
  }
}, {
  group: 1,
  question: {
    templateId: 100
  }
}, {
  group: 1,
  question: {
    templateId: 300
  }
}];
</code>```

Expected Result: const result = groupBy(arr, 'group', 'question.templateId');

```<code>const result = [
  [{
    group: 1,
    question: {
      templateId: 100
    }
  }, {
    group: 1,
    question: {
      templateId: 100
    }
  }],
  [{
    group: 1,
    question: {
      templateId: 300
    }
  }],
  [{
    group: 2,
    question: {
      templateId: 200
    }
  }]
];
</code>```

So far: I am able to group the result by a single property using Array.prototype.reduce().

function groupBy(arr, key) {
  return [...arr.reduce((accumulator, currentValue) => {
    const propVal = currentValue[key],
      group = accumulator.get(propVal) || [];
    group.push(currentValue);
    return accumulator.set(propVal, group);
  }, new Map()).values()];
}

const arr = [{
  group: 1,
  question: {
    templateId: 100
  }
}, {
  group: 2,
  question: {
    templateId: 200
  }
}, {
  group: 1,
  question: {
    templateId: 100
  }
}, {
  group: 1,
  question: {
    templateId: 300
  }
}];

const result = groupBy(arr, 'group');

console.log(result);```

答:
@Bergi's answer is great if you can hard-code the inputs.

If you want to use string inputs instead, you can use the sort() method, and walk the objects as needed.

This solution will handle any number of arguments:

function groupBy(arr) {
  var arg = arguments;

  return arr.sort((a, b) => {
    var i, key, aval, bval;

    for(i = 1 ; i < arguments.length ; i++) {
      key = arguments[i].split('.');
      aval = a[key[0]];
      bval = b[key[0]];
      key.shift();
      while(key.length) {  //walk the objects
        aval = aval[key[0]];
        bval = bval[key[0]];
        key.shift();
      };
      if     (aval < bval) return -1;
      else if(aval > bval) return  1;
    }
    return 0;
  });
}

const arr = [{
  group: 1,
  question: {
    templateId: 100
  }
}, {
  group: 2,
  question: {
    templateId: 200
  }
}, {
  group: 1,
  question: {
    templateId: 100
  }
}, {
  group: 1,
  question: {
    templateId: 300
  }
}];

const result = groupBy(arr, 'group', 'question.templateId');

console.log(result);```

Body:
Ex:

const arr = [{
  group: 1,
  question: {
    templateId: 100
  }
}, {
  group: 2,
  question: {
    templateId: 200
  }
}, {
  group: 1,
  question: {
    templateId: 100
  }
}, {
  group: 1,
  question: {
    templateId: 300
  }
}];

Expected Result: const result = groupBy(arr, 'group', 'question.templateId');

const result = [
  [{
    group: 1,
    question: {
      templateId: 100
    }
  }, {
    group: 1,
    question: {
      templateId: 100
    }
  }],
  [{
    group: 1,
    question: {
      templateId: 300
    }
  }],
  [{
    group: 2,
    question: {
      templateId: 200
    }
  }]
];

So far: I am able to group the result by a single property using Array.prototype.reduce().

function groupBy(arr, key) {
  return [...arr.reduce((accumulator, currentValue) => {
    const propVal = currentValue[key],
      group = accumulator.get(propVal) || [];
    group.push(currentValue);
    return accumulator.set(propVal, group);
  }, new Map()).values()];
}

const arr = [{
  group: 1,
  question: {
    templateId: 100
  }
}, {
  group: 2,
  question: {
    templateId: 200
  }
}, {
  group: 1,
  question: {
    templateId: 100
  }
}, {
  group: 1,
  question: {
    templateId: 300
  }
}];

const result = groupBy(arr, 'group');

console.log(result);


问:
Is it not possible to stringify an Error using JSON.stringify?

Reproducing the problem

I'm running into an issue when trying to pass error messages around using web sockets. I can replicate the issue I am facing using JSON.stringify to cater to a wider audience:

// node v0.10.15
> var error = new Error('simple error message');
    undefined

> error
    [Error: simple error message]

> Object.getOwnPropertyNames(error);
    [ 'stack', 'arguments', 'type', 'message' ]

> JSON.stringify(error);
    '{}'
```

<p>The problem is that I end up with an empty object.</p>

<h2>What I've tried</h2>

<p><strong>Browsers</strong></p>

<p>I first tried leaving node.js and running it in various browsers. Chrome version 28 gives me the same result, and interestingly enough, Firefox at least makes an attempt but left out the message:</p>

<pre class="lang-js prettyprint-override"><code>>>> JSON.stringify(error); // Firebug, Firefox 23
{"fileName":"debug eval code","lineNumber":1,"stack":"@debug eval code:1\n"}
</code>```

Replacer function

I then looked at the Error.prototype. It shows that the prototype contains methods such as toString and toSource. Knowing that functions can't be stringified, I included a replacer function when calling JSON.stringify to remove all functions, but then realized that it too had some weird behavior:

var error = new Error('simple error message');
JSON.stringify(error, function(key, value) {
    console.log(key === ''); // true (?)
    console.log(value === error); // true (?)
});
```

<p>It doesn't seem to loop over the object as it normally would, and therefore I can't check if the key is a function and ignore it.</p>

<h2>The Question</h2>

<p>Is there any way to stringify native Error messages with <code>JSON.stringify</code>? If not, why does this behavior occur?</p>

<h3>Methods of getting around this</h3>

<ul>
<li>Stick with simple string-based error messages, or create personal error objects and don't rely on the native Error object.</li>
<li>Pull properties: <code>JSON.stringify({ message: error.message, stack: error.stack })</code></li>
</ul>

<h3>Updates</h3>

<p>@Ray Toal Suggested in a comment that I take a look at the property descriptors. It is clear now why it does not work:</p>

<pre class="lang-js prettyprint-override"><code>var error = new Error('simple error message');
var propertyNames = Object.getOwnPropertyNames(error);
var descriptor;
for (var property, i = 0, len = propertyNames.length; i < len; ++i) {
    property = propertyNames[i];
    descriptor = Object.getOwnPropertyDescriptor(error, property);
    console.log(property, descriptor);
}
</code>```

Output:

stack { get: [Function],
  set: [Function],
  enumerable: false,
  configurable: true }
arguments { value: undefined,
  writable: true,
  enumerable: false,
  configurable: true }
type { value: undefined,
  writable: true,
  enumerable: false,
  configurable: true }
message { value: 'simple error message',
  writable: true,
  enumerable: false,
  configurable: true }
```

Key: enumerable: false.

Accepted answer provides a workaround for this problem.

答:
None of the answers above seemed to properly serialize properties which are on the prototype of Error (because getOwnPropertyNames() does not include inherited properties). I was also not able to redefine the properties like one of the answers suggested.

This is the solution I came up with - it uses lodash but you could replace lodash with generic versions of those functions.

```<code> function recursivePropertyFinder(obj){
    if( obj === Object.prototype){
        return {};
    }else{
        return _.reduce(Object.getOwnPropertyNames(obj),
            function copy(result, value, key) {
                if( !_.isFunction(obj[value])){
                    if( _.isObject(obj[value])){
                        result[value] = recursivePropertyFinder(obj[value]);
                    }else{
                        result[value] = obj[value];
                    }
                }
                return result;
            }, recursivePropertyFinder(Object.getPrototypeOf(obj)));
    }
}

Error.prototype.toJSON = function(){
    return recursivePropertyFinder(this);
}
</code>```

Here's the test I did in Chrome:

```<code>var myError = Error('hello');
myError.causedBy = Error('error2');
myError.causedBy.causedBy = Error('error3');
myError.causedBy.causedBy.displayed = true;
JSON.stringify(myError);

{"name":"Error","message":"hello","stack":"Error: hello\n    at <anonymous>:66:15","causedBy":{"name":"Error","message":"error2","stack":"Error: error2\n    at <anonymous>:67:20","causedBy":{"name":"Error","message":"error3","stack":"Error: error3\n    at <anonymous>:68:29","displayed":true}}}
</code>```

Body:
Reproducing the problem

I'm running into an issue when trying to pass error messages around using web sockets. I can replicate the issue I am facing using JSON.stringify to cater to a wider audience:

// node v0.10.15
> var error = new Error('simple error message');
    undefined

> error
    [Error: simple error message]

> Object.getOwnPropertyNames(error);
    [ 'stack', 'arguments', 'type', 'message' ]

> JSON.stringify(error);
    '{}'

The problem is that I end up with an empty object.

What I've tried

Browsers

I first tried leaving node.js and running it in various browsers. Chrome version 28 gives me the same result, and interestingly enough, Firefox at least makes an attempt but left out the message:

>>> JSON.stringify(error); // Firebug, Firefox 23
{"fileName":"debug eval code","lineNumber":1,"stack":"@debug eval code:1\n"}

Replacer function

I then looked at the Error.prototype. It shows that the prototype contains methods such as toString and toSource. Knowing that functions can't be stringified, I included a replacer function when calling JSON.stringify to remove all functions, but then realized that it too had some weird behavior:

var error = new Error('simple error message');
JSON.stringify(error, function(key, value) {
    console.log(key === ''); // true (?)
    console.log(value === error); // true (?)
});

It doesn't seem to loop over the object as it normally would, and therefore I can't check if the key is a function and ignore it.

The Question

Is there any way to stringify native Error messages with JSON.stringify? If not, why does this behavior occur?

Methods of getting around this

Stick with simple string-based error messages, or create personal error objects and don't rely on the native Error object.

Pull properties: JSON.stringify({ message: error.message, stack: error.stack })

Updates

@Ray Toal Suggested in a comment that I take a look at the property descriptors. It is clear now why it does not work:

var error = new Error('simple error message');
var propertyNames = Object.getOwnPropertyNames(error);
var descriptor;
for (var property, i = 0, len = propertyNames.length; i < len; ++i) {
    property = propertyNames[i];
    descriptor = Object.getOwnPropertyDescriptor(error, property);
    console.log(property, descriptor);
}

Output:

stack { get: [Function],
  set: [Function],
  enumerable: false,
  configurable: true }
arguments { value: undefined,
  writable: true,
  enumerable: false,
  configurable: true }
type { value: undefined,
  writable: true,
  enumerable: false,
  configurable: true }
message { value: 'simple error message',
  writable: true,
  enumerable: false,
  configurable: true }

Key: enumerable: false.

Accepted answer provides a workaround for this problem.

Body:
None of the answers above seemed to properly serialize properties which are on the prototype of Error (because getOwnPropertyNames() does not include inherited properties). I was also not able to redefine the properties like one of the answers suggested.

This is the solution I came up with - it uses lodash but you could replace lodash with generic versions of those functions.

 function recursivePropertyFinder(obj){
    if( obj === Object.prototype){
        return {};
    }else{
        return _.reduce(Object.getOwnPropertyNames(obj),
            function copy(result, value, key) {
                if( !_.isFunction(obj[value])){
                    if( _.isObject(obj[value])){
                        result[value] = recursivePropertyFinder(obj[value]);
                    }else{
                        result[value] = obj[value];
                    }
                }
                return result;
            }, recursivePropertyFinder(Object.getPrototypeOf(obj)));
    }
}

Error.prototype.toJSON = function(){
    return recursivePropertyFinder(this);
}

Here's the test I did in Chrome:

var myError = Error('hello');
myError.causedBy = Error('error2');
myError.causedBy.causedBy = Error('error3');
myError.causedBy.causedBy.displayed = true;
JSON.stringify(myError);

{"name":"Error","message":"hello","stack":"Error: hello\n    at <anonymous>:66:15","causedBy":{"name":"Error","message":"error2","stack":"Error: error2\n    at <anonymous>:67:20","causedBy":{"name":"Error","message":"error3","stack":"Error: error3\n    at <anonymous>:68:29","displayed":true}}}


问:
Conditional mutating with dplyr for only some rows
I use ifelse with mutate to conditionally change variable names within a column. For example:

```<code>mutate(df, thiscol = ifelse((new == "oldname"), "newname", NA)
</code>```

But I would like to change it so that instead of variables that don't fit the conditions turning into NA, they just stay as they were.

答: mutate(df, thiscol = ifelse(new == "oldname", "newname", thiscol))

Body:
I use ifelse with mutate to conditionally change variable names within a column. For example:

mutate(df, thiscol = ifelse((new == "oldname"), "newname", NA)

But I would like to change it so that instead of variables that don't fit the conditions turning into NA, they just stay as they were.

ContentLicense: CC BY-SA 4.0


问:
Random Access in Array
I was reading this, advantages of java, where it states that random access is an advantage of arrays in java. I do not understand how can accessing a random element of an array is an advantage. Shouldn't it be a disadvantage?

Why is java allowing to access elements of an array randomly, if the data is stored continuously, shouldn't the data be accessed in an orderly manner?

答:
Depends on your use, if you want to access data again, i recommend to see Maps ou HashMaps using , it's the most simple way to work.

If you want to sort an array you can use Arrays.sort(...);

Title: Random Access in Array


问:
Can the NOT operator work on multiple conditions present in parenthesis?
I run following query in MySQL :

```<code>SELECT * FROM Customers
WHERE NOT Country='Germany' AND NOT Country='USA';
</code>```

It returned me exactly the correct expected result.

After that I run following query :

```<code>SELECT * FROM Customers
WHERE NOT (Country='Germany' AND Country='USA');
</code>```

This time it returned me all the records present in the table(result-set of the query SELECT * FROM Customers;)

I'm not understanding why the NOT operator is not working in second query with parenthesis?

You can go to this link and check :

```<code>https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_where_not_and
</code>```

答:
```<code>SELECT * FROM Customers
WHERE NOT (Country='Germany' AND Country='USA');
</code>```

What this is really saying is does this record not equal to both at the same time.  You couldn't have one row where you had the following as a positive:

```<code>(Country='Germany' AND Country='USA')
</code>```

You would get the results you are looking for with the following:

```<code>Where Country not in ('Germany', 'USA')
</code>```

Body:
I run following query in MySQL :

SELECT * FROM Customers
WHERE NOT Country='Germany' AND NOT Country='USA';

It returned me exactly the correct expected result.

After that I run following query :

SELECT * FROM Customers
WHERE NOT (Country='Germany' AND Country='USA');

This time it returned me all the records present in the table(result-set of the query SELECT * FROM Customers;)

I'm not understanding why the NOT operator is not working in second query with parenthesis?

You can go to this link and check :

https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_where_not_and

Body:
SELECT * FROM Customers
WHERE NOT (Country='Germany' AND Country='USA');

What this is really saying is does this record not equal to both at the same time.  You couldn't have one row where you had the following as a positive:

(Country='Germany' AND Country='USA')

You would get the results you are looking for with the following:

Where Country not in ('Germany', 'USA')


问:
C# folders and sub folders
How to do this:

Check if folder upload exists (if nor then create it) ~/ uploads

Check if subfolder with username exists ~/uploads/folder with username

It as to check for each case individually because I could add a new user to the system and of course the folder uploads alredy exists, just need to create a sub folder with username

答:
```<code>string userName = ""; // Substitute with logic for obtaining username
string folder = ResolveUrl( "~/Uploads" );

folder = System.IO.Path.Combine( folder, userName );

if ( !System.IO.Directory.Exists( folder ) )
    System.IO.Directory.CreateDirectory( folder );
</code>```

Title: C# folders and sub folders