问:
Batch - for loop parameter order
I was trying to use tokens in a for loop to separate a CSV file in my batch file. Here's the code snippet:

for /f "tokens=1-31* delims=," %%a in ("!revamped!") do (
  echo %%a
  echo %%b
  ...
  echo %%y
  echo %%z
      rem what parameter should I use next?
)
```

After using %%a all the way to %%z, I have no idea which parameter should I use next.

Question: What is the order of using parameters after using all %%a to %%z  in a for loop?

答:
As others already pointed out in comments, for /F is limited to 31 tokens. There are the following work-arounds:

Use nested for /F loops, like this (50 tokens are used here):

for /F "tokens=1-25* delims=," %%A in ("!revamped!") do (
    for /F "tokens=1-25* delims=," %%a in ("%%Z") do (
        echo token # 01: "%%A"
        echo token # 25: "%%Y"
        echo token # 26: "%%a"
        echo token # 50: "%%y"
        echo remaining tokens: "%%z"
    )
)
```</li>
<li><p>Use a standard <code>for</code> loop loop to gain a practically unlimited number of tokens:</p>

<pre class="lang-cmd prettyprint-override"><code>for /F "tokens=*" %%A in ("!revamped!") do (
    set /A "INDEX=0" & rem // (reset index number)
    set "LINE=%%A"
    rem /* In the following, every delimiter `,` is replaced by `" "`;
    rem    the entire line string is enclosed within `""`; hence
    rem    the result is a list of space-sepatated quoted tokens,
    rem    which can easily be handled by a standard `for` loop;
    rem    the surrounding quotes are later removed by the `~` modifier;
    rem    regard that the line string must not contain `*` or `?`: */
    for %%a in ("!LINE:,=" "!") do (
        set /A "INDEX+=1" & rem // (build index just for demonstration)
        echo token # !INDEX!: "%%~a"
    )
)
</code>```

Title: Batch - for loop parameter order

Body:
I was trying to use tokens in a for loop to separate a CSV file in my batch file. Here's the code snippet:

for /f "tokens=1-31* delims=," %%a in ("!revamped!") do (
  echo %%a
  echo %%b
  ...
  echo %%y
  echo %%z
      rem what parameter should I use next?
)

After using %%a all the way to %%z, I have no idea which parameter should I use next.

Question: What is the order of using parameters after using all %%a to %%z  in a for loop?

Body:
As others already pointed out in comments, for /F is limited to 31 tokens. There are the following work-arounds:

Use nested for /F loops, like this (50 tokens are used here):

for /F "tokens=1-25* delims=," %%A in ("!revamped!") do (
    for /F "tokens=1-25* delims=," %%a in ("%%Z") do (
        echo token # 01: "%%A"
        echo token # 25: "%%Y"
        echo token # 26: "%%a"
        echo token # 50: "%%y"
        echo remaining tokens: "%%z"
    )
)

Use a standard for loop loop to gain a practically unlimited number of tokens:

for /F "tokens=*" %%A in ("!revamped!") do (
    set /A "INDEX=0" & rem // (reset index number)
    set "LINE=%%A"
    rem /* In the following, every delimiter `,` is replaced by `" "`;
    rem    the entire line string is enclosed within `""`; hence
    rem    the result is a list of space-sepatated quoted tokens,
    rem    which can easily be handled by a standard `for` loop;
    rem    the surrounding quotes are later removed by the `~` modifier;
    rem    regard that the line string must not contain `*` or `?`: */
    for %%a in ("!LINE:,=" "!") do (
        set /A "INDEX+=1" & rem // (build index just for demonstration)
        echo token # !INDEX!: "%%~a"
    )
)


来源: stackexchange

问:
Spring boot RestController won't work with classes which implements an interface
I'm trying to implement a Springboot REST api. and the class where I have defined the @RestController doesn't seem to be working. I have a class called MyService where it implements all the abstract methods. I have added the @RestController annotation on top of the class declaration and added the @RequestMapping annotation for the method that I need to call from the rest call. But this doesn't work. I tried this with a class which does not implement any interface and that works fine.

Here is the code

```<code>package com.my.service;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyService implements MyServiceInterface{

    @Override
    @RequestMapping("/age")
    public String Age() {
        return  "24";
    }
}
</code>```

the code of MyServiceInterface

```<code>public interface MyServiceInterface {
    public String Age();
}
</code>```

And the error I'm getting from postman is

```<code>{"timestamp":1489688505136,"status":404,"error":"Not Found","message":"No message available","path":"/age"}
</code>```

答:
Found it! it seems like adding @Override is the reason i managed it to get it working by adding @RequestMapping("/age") for a non overriding method.
like</p>

```<code>@RequestMapping("/age")
public String Age() {
    return  "24";
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to implement a Springboot REST api. and the class where I have defined the @RestController doesn't seem to be working. I have a class called MyService where it implements all the abstract methods. I have added the @RestController annotation on top of the class declaration and added the @RequestMapping annotation for the method that I need to call from the rest call. But this doesn't work. I tried this with a class which does not implement any interface and that works fine.

Here is the code

package com.my.service;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyService implements MyServiceInterface{

    @Override
    @RequestMapping("/age")
    public String Age() {
        return  "24";
    }
}

the code of MyServiceInterface

public interface MyServiceInterface {
    public String Age();
}

And the error I'm getting from postman is

{"timestamp":1489688505136,"status":404,"error":"Not Found","message":"No message available","path":"/age"}

Body:
Found it! it seems like adding @Override is the reason i managed it to get it working by adding @RequestMapping("/age") for a non overriding method.
like

@RequestMapping("/age")
public String Age() {
    return  "24";
}


问:
dplyr mutate rowwise max of range of columns
I can use the following to return the maximum of 2 columns

```<code>newiris<-iris %>%
 rowwise() %>%
 mutate(mak=max(Sepal.Width,Petal.Length))
</code>```

What I want to do is find that maximum across a range of columns so I don't have to name each one like this

```<code>newiris<-iris %>%
 rowwise() %>%
 mutate(mak=max(Sepal.Width:Petal.Length))
</code>```

Any ideas?

答:
It seems like @akrun's answer only addresses the cases when you can type in the names of all the variables, whether that's using mutate directly with mutate(pmax_value=pmax(var1, var2)) or when using lazy evaluation with mutate_ and interp via mutate_(interp(~pmax(v1, v2), v1=as.name(var1), v2=as.name(var2)).

I can see two ways to do this if you want to use the colon syntax Sepal.Length:Petal.Width or if you happen to have a vector with the column names.

The first is more elegant. You tidy the data and take the maximum among the values when grouped:

```<code>data(iris)
library(dplyr)
library(tidyr)

iris_id = iris %>% mutate(id=1:nrow(.))
iris_id %>%
  gather('attribute', 'value', Sepal.Length:Petal.Width) %>%
  group_by(id) %>%
  summarize(max_attribute=max(value)) %>%
  right_join(iris_id, by='id') %>%
  head(3)
## # A tibble: 3 × 7
##      id max_attribute Sepal.Length Sepal.Width Petal.Length Petal.Width Species
##   <int>         <dbl>        <dbl>       <dbl>        <dbl>       <dbl>  <fctr>
## 1     1           5.1          5.1         3.5          1.4         0.2  setosa
## 2     2           4.9          4.9         3.0          1.4         0.2  setosa
## 3     3           4.7          4.7         3.2          1.3         0.2  setosa
</code>```

The harder way is to use an interpolated formula. This is good if you have a character vector with the names of the variables to be max'ed over or if you the table is too tall/wide for it to be tidied.

```<code># Make a character vector of the names of the columns we want to take the
# maximum over
target_columns = iris %>% select(-Species) %>% names
## [1] "Sepal.Length" "Sepal.Width"  "Petal.Length" "Petal.Width"

# Make a vector of dummy variables that will take the place of the real
# column names inside the interpolated formula
dummy_vars = sapply(1:length(target_columns), function(i) sprintf('x%i', i))
## [1] "x1" "x2" "x3" "x4"

# Paste those variables together to make the argument of the pmax in the
# interpolated formula
dummy_vars_string = paste0(dummy_vars, collapse=',')
## [1] "x1,x2,x3,x4"

# Make a named list that maps the dummy variable names (e.g., x1) to the
# real variable names (e.g., Sepal.Length)
dummy_vars_list = lapply(target_columns, as.name) %>% setNames(dummy_vars)
## $x1
## Sepal.Length
##
## $x2
## Sepal.Width
##
## $x3
## Petal.Length
##
## $x4
## Petal.Width

# Make a pmax formula using the dummy variables
max_formula = as.formula(paste0(c('~pmax(', dummy_vars_string, ')'), collapse=''))
## ~pmax(x1, x2, x3, x4)

# Interpolate the formula using the named variables
library(lazyeval)
iris %>%
  mutate_(max_attribute=interp(max_formula, .values=dummy_vars_list)) %>%
  head(3)
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species max_attribute
## 1          5.1         3.5          1.4         0.2  setosa           5.1
## 2          4.9         3.0          1.4         0.2  setosa           4.9
## 3          4.7         3.2          1.3         0.2  setosa           4.7
</code>```

Body:
I can use the following to return the maximum of 2 columns

newiris<-iris %>%
 rowwise() %>%
 mutate(mak=max(Sepal.Width,Petal.Length))

What I want to do is find that maximum across a range of columns so I don't have to name each one like this

newiris<-iris %>%
 rowwise() %>%
 mutate(mak=max(Sepal.Width:Petal.Length))

Any ideas?

Body:
It seems like @akrun's answer only addresses the cases when you can type in the names of all the variables, whether that's using mutate directly with mutate(pmax_value=pmax(var1, var2)) or when using lazy evaluation with mutate_ and interp via mutate_(interp(~pmax(v1, v2), v1=as.name(var1), v2=as.name(var2)).

I can see two ways to do this if you want to use the colon syntax Sepal.Length:Petal.Width or if you happen to have a vector with the column names.

The first is more elegant. You tidy the data and take the maximum among the values when grouped:

data(iris)
library(dplyr)
library(tidyr)

iris_id = iris %>% mutate(id=1:nrow(.))
iris_id %>%
  gather('attribute', 'value', Sepal.Length:Petal.Width) %>%
  group_by(id) %>%
  summarize(max_attribute=max(value)) %>%
  right_join(iris_id, by='id') %>%
  head(3)
## # A tibble: 3 × 7
##      id max_attribute Sepal.Length Sepal.Width Petal.Length Petal.Width Species
##   <int>         <dbl>        <dbl>       <dbl>        <dbl>       <dbl>  <fctr>
## 1     1           5.1          5.1         3.5          1.4         0.2  setosa
## 2     2           4.9          4.9         3.0          1.4         0.2  setosa
## 3     3           4.7          4.7         3.2          1.3         0.2  setosa

The harder way is to use an interpolated formula. This is good if you have a character vector with the names of the variables to be max'ed over or if you the table is too tall/wide for it to be tidied.

# Make a character vector of the names of the columns we want to take the
# maximum over
target_columns = iris %>% select(-Species) %>% names
## [1] "Sepal.Length" "Sepal.Width"  "Petal.Length" "Petal.Width"

# Make a vector of dummy variables that will take the place of the real
# column names inside the interpolated formula
dummy_vars = sapply(1:length(target_columns), function(i) sprintf('x%i', i))
## [1] "x1" "x2" "x3" "x4"

# Paste those variables together to make the argument of the pmax in the
# interpolated formula
dummy_vars_string = paste0(dummy_vars, collapse=',')
## [1] "x1,x2,x3,x4"

# Make a named list that maps the dummy variable names (e.g., x1) to the
# real variable names (e.g., Sepal.Length)
dummy_vars_list = lapply(target_columns, as.name) %>% setNames(dummy_vars)
## $x1
## Sepal.Length
##
## $x2
## Sepal.Width
##
## $x3
## Petal.Length
##
## $x4
## Petal.Width

# Make a pmax formula using the dummy variables
max_formula = as.formula(paste0(c('~pmax(', dummy_vars_string, ')'), collapse=''))
## ~pmax(x1, x2, x3, x4)

# Interpolate the formula using the named variables
library(lazyeval)
iris %>%
  mutate_(max_attribute=interp(max_formula, .values=dummy_vars_list)) %>%
  head(3)
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species max_attribute
## 1          5.1         3.5          1.4         0.2  setosa           5.1
## 2          4.9         3.0          1.4         0.2  setosa           4.9
## 3          4.7         3.2          1.3         0.2  setosa           4.7


问:
Optimizing PHP Code
Is there a way to optimize this?

```<code>// Zählt die Anzahl an KWs
$sum = 0;
for ($i = 1; $i < 105; $i++) {
    $count = db_query('SELECT cw' . $i . ' FROM `prefix_projekteStep` WHERE kategoryid = ' . $row->id . ' AND id = ' . $rowStep->id.' AND jahr = '.$currentYear.' OR jahr = '.$nextYear.'');
    while ($rowStepC = db_fetch_object($count)) {
        $var = "cw" . $i;
        if ($rowStepC->$var === 1) {
            $sum += 1;
        }
    }
}
echo $sum;
</code>```

At the moment the script runs about 104 times in a call and I call this about 40 times. It takes very long to finish.

答:
If I understand what you are trying to do, this might work. Run it and echo the SQL statement to see what it might look like:</p>

```<code>$qstr .= "SELECT \n";
$cols = array();
for($i=1;$i<105;$i++) {
    $cols[$i] .= "IF(NOT `cw".$i."` IS NULL,1,0)";
}
$qstr .= implode(' + ',$cols)." AS `totalscore`, \n";
$qstr .= "FROM `prefix_projekteStep` \n";
$qstr .= "WHERE kategoryid = " . $row->id . " AND id = " . $rowStep->id." AND jahr = ".$currentYear." OR jahr = ".$nextYear."\n";

ECHO "<p>Query:```".$qstr."```</p>\n";
</code>```

Title: Optimizing PHP Code

Body:
Is there a way to optimize this?

// Zählt die Anzahl an KWs
$sum = 0;
for ($i = 1; $i < 105; $i++) {
    $count = db_query('SELECT cw' . $i . ' FROM `prefix_projekteStep` WHERE kategoryid = ' . $row->id . ' AND id = ' . $rowStep->id.' AND jahr = '.$currentYear.' OR jahr = '.$nextYear.'');
    while ($rowStepC = db_fetch_object($count)) {
        $var = "cw" . $i;
        if ($rowStepC->$var === 1) {
            $sum += 1;
        }
    }
}
echo $sum;

At the moment the script runs about 104 times in a call and I call this about 40 times. It takes very long to finish.

Body:
If I understand what you are trying to do, this might work. Run it and echo the SQL statement to see what it might look like:

$qstr .= "SELECT \n";
$cols = array();
for($i=1;$i<105;$i++) {
    $cols[$i] .= "IF(NOT `cw".$i."` IS NULL,1,0)";
}
$qstr .= implode(' + ',$cols)." AS `totalscore`, \n";
$qstr .= "FROM `prefix_projekteStep` \n";
$qstr .= "WHERE kategoryid = " . $row->id . " AND id = " . $rowStep->id." AND jahr = ".$currentYear." OR jahr = ".$nextYear."\n";

ECHO "<p>Query:<pre>".$qstr."</pre></p>\n";


问:
http://sub.site.com is incorrectly redirecting to http://www.sub.site.com instead of https://sub.site.com
Using Apache 2.4.18 on Ubuntu 16.04.2

I have blog.ryangiglio.com set up as a virtualhost. I used the letsencrypt certbot to generate an SSL cert for the server, and set it to force redirects from http://blog.ryangiglio.com to https://blog.ryangiglio.com. When you go directly to https://blog.ryangiglio.com, everything works fine. But if you go to http://blog.ryangiglio.com instead, you get redirected to http://www.blog.ryangiglio.com which doesn't and shouldn't exist.

There is no .htaccess file in the webroot for this domain that could be causing a conflict.

Here is the blog.ryangiglio.com.conf config file

```<code><VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName blog.ryangiglio.com

    DocumentRoot /var/www/blog.ryangiglio.com/public_html
    ErrorLog /var/www/blog.ryangiglio.com/error.log
    # CustomLog /var/www/blog.ryangiglio.com/access.log combined

  <Directory /var/www/blog.ryangiglio.com/public_html/>
    Options FollowSymLinks
    AllowOverride All
    Order allow,deny
    allow from all
  </Directory>
RewriteEngine on
RewriteCond %{SERVER_NAME} =blog.ryangiglio.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,QSA,R=permanent]
</VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
</code>```

And the blog.ryangiglio.com-le-ssl.conf file generated by certbot

```<code><IfModule mod_ssl.c>
<VirtualHost *:443>
    ServerAdmin webmaster@localhost
    ServerName blog.ryangiglio.com

    DocumentRoot /var/www/blog.ryangiglio.com/public_html
    ErrorLog /var/www/blog.ryangiglio.com/error.log
    # CustomLog /var/www/blog.ryangiglio.com/access.log combined

  <Directory /var/www/blog.ryangiglio.com/public_html/>
    Options FollowSymLinks
    AllowOverride All
    Order allow,deny
    allow from all
  </Directory>
SSLCertificateFile /etc/letsencrypt/live/blog.ryangiglio.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/blog.ryangiglio.com/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
</IfModule>
</code>```

I don't see anything in either of these files that could be causing the error. Does anyone have any suggestions?

Thanks

答:
At least I can tell you that you get redirected with code 301 (=permanent). Normally that's only the case when you told your Apache to do so. I am not entirely sure what %{SERVER_NAME} got filled with, but your rewrite is 'permanent'. I'd try this:

```<code>RewriteCond %{HTTPS} !=on
RewriteRule .? https://blog.ryangiglio.com%{REQUEST_URI} [END,QSA,R=301]
</code>```

R=301 and R=permanent is the same, order of parameters doesn't matter.

Body:
Using Apache 2.4.18 on Ubuntu 16.04.2

I have blog.ryangiglio.com set up as a virtualhost. I used the letsencrypt certbot to generate an SSL cert for the server, and set it to force redirects from http://blog.ryangiglio.com to https://blog.ryangiglio.com. When you go directly to https://blog.ryangiglio.com, everything works fine. But if you go to http://blog.ryangiglio.com instead, you get redirected to http://www.blog.ryangiglio.com which doesn't and shouldn't exist.

There is no .htaccess file in the webroot for this domain that could be causing a conflict.

Here is the blog.ryangiglio.com.conf config file

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName blog.ryangiglio.com

    DocumentRoot /var/www/blog.ryangiglio.com/public_html
    ErrorLog /var/www/blog.ryangiglio.com/error.log
    # CustomLog /var/www/blog.ryangiglio.com/access.log combined

  <Directory /var/www/blog.ryangiglio.com/public_html/>
    Options FollowSymLinks
    AllowOverride All
    Order allow,deny
    allow from all
  </Directory>
RewriteEngine on
RewriteCond %{SERVER_NAME} =blog.ryangiglio.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,QSA,R=permanent]
</VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

And the blog.ryangiglio.com-le-ssl.conf file generated by certbot

<IfModule mod_ssl.c>
<VirtualHost *:443>
    ServerAdmin webmaster@localhost
    ServerName blog.ryangiglio.com

    DocumentRoot /var/www/blog.ryangiglio.com/public_html
    ErrorLog /var/www/blog.ryangiglio.com/error.log
    # CustomLog /var/www/blog.ryangiglio.com/access.log combined

  <Directory /var/www/blog.ryangiglio.com/public_html/>
    Options FollowSymLinks
    AllowOverride All
    Order allow,deny
    allow from all
  </Directory>
SSLCertificateFile /etc/letsencrypt/live/blog.ryangiglio.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/blog.ryangiglio.com/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
</IfModule>

I don't see anything in either of these files that could be causing the error. Does anyone have any suggestions?

Thanks

Body:
At least I can tell you that you get redirected with code 301 (=permanent). Normally that's only the case when you told your Apache to do so. I am not entirely sure what %{SERVER_NAME} got filled with, but your rewrite is 'permanent'. I'd try this:

RewriteCond %{HTTPS} !=on
RewriteRule .? https://blog.ryangiglio.com%{REQUEST_URI} [END,QSA,R=301]

R=301 and R=permanent is the same, order of parameters doesn't matter.


问:
Aliasing jar target of maven_jar rule
I have the following maven_jar in my workspace:

```<code>maven_jar(
    name = "com_google_code_findbugs_jsr305",
    artifact = "com.google.code.findbugs:jsr305:3.0.1",
    sha1 = "f7be08ec23c21485b9b5a1cf1654c2ec8c58168d",
)
</code>```

In my project I reference it through @com_google_code_findbugs_jsr305//jar. However, I now want to depend on a third party library that references @com_google_code_findbugs_jsr305 without the jar target.

I tried looking into both bind and alias, however alias cannot be applied inside the WORKSPACE and bind doesn't seem to allow you to define targets as external repositories.

I could rename the version I use so it doesn't conflict, but that feels like the wrong solution.

答:
IIUC, your code needs to depend on both @com_google_code_findbugs_jsr305//jar and @com_google_code_findbugs_jsr305//:com_google_code_findbugs_jsr305. Unfortunately, there isn't any pre-built rule that generates BUILD files for both of those targets, so you basically have to define the BUILD files yourself.  Fortunately, @jart has written most of it for you in the closure rule you linked to.  You just need to add //jar:jar by appending a couple of lines, after line 69 add something like:

```<code>repository_ctx.file(
    'jar/BUILD',
    "\n".join([
       "package(default_visibility = '//visibility:public')"] + _make_java_import('jar', '//:com_google_code_findbugs_jsr305.jar')
</code>```

This creates a //jar:jar (or equivalently, //jar) target in the repository.

Title: Aliasing jar target of maven_jar rule

Body:
I have the following maven_jar in my workspace:

maven_jar(
    name = "com_google_code_findbugs_jsr305",
    artifact = "com.google.code.findbugs:jsr305:3.0.1",
    sha1 = "f7be08ec23c21485b9b5a1cf1654c2ec8c58168d",
)

In my project I reference it through @com_google_code_findbugs_jsr305//jar. However, I now want to depend on a third party library that references @com_google_code_findbugs_jsr305 without the jar target.

I tried looking into both bind and alias, however alias cannot be applied inside the WORKSPACE and bind doesn't seem to allow you to define targets as external repositories.

I could rename the version I use so it doesn't conflict, but that feels like the wrong solution.

Body:
IIUC, your code needs to depend on both @com_google_code_findbugs_jsr305//jar and @com_google_code_findbugs_jsr305//:com_google_code_findbugs_jsr305. Unfortunately, there isn't any pre-built rule that generates BUILD files for both of those targets, so you basically have to define the BUILD files yourself.  Fortunately, @jart has written most of it for you in the closure rule you linked to.  You just need to add //jar:jar by appending a couple of lines, after line 69 add something like:

repository_ctx.file(
    'jar/BUILD',
    "\n".join([
       "package(default_visibility = '//visibility:public')"] + _make_java_import('jar', '//:com_google_code_findbugs_jsr305.jar')

This creates a //jar:jar (or equivalently, //jar) target in the repository.


问:
Minify PHP in Visual Studio 2015
Is there any way to minify (or remove comments) in PHP using Visual Studio 2015? I use PHP Tools and when i release php scripts to public server, i would like at least remove all comments from code. I know, is there way to remove comments with content menu, but i wish to have comments in my project and no comments (or minimal and unread code) in publish scripts (some like Bundler & Minifier tool, but for php). Thanks</p>

答:
There is basically no point in minifying Php since there is no performance gain in doing so. Although if you insist, there are a few ways to remove comments/whitespaces from source. (and these are not limited to just VisualStudio) -

Use Gulp.

Use Command line options: php -w file.php => generates file without comments & whitespaces. Equivalent to php_strip_whitespace()

Use Regular Expression in Find-Replace Function of your IDE. You can use the following inside Find FieldBox. (and keep Replace fieldbox empty)

//.* or /.

Use a Library/tool like Php-Minify

Hope that helps!

Title: Minify PHP in Visual Studio 2015


问:
Add checkbox button
I'm creating list view with checkboxes, and I need in this a button that adds next checkbox in my form app. I know how to add single box, but idk how to make a loop that will helps me to add next checkboxes. Here, I give u a piece of code. At the start I have 24 checkboxes, next must be on 612 px position. </p>

```<code>private void btnAdd_Click(object sender, EventArgs e)
    {
         CheckBox box;
         box = new CheckBox();
         box.AutoSize = true;
         box.Location = new Point(30, 612);
         this.Controls.Add(box);
    }
</code>```

答:
I've noticed that your checkbox exist within a button click event, is that what you truly want?

You can loop, in this manner:

```<code>var coordinates = new List<Coordinate>();
foreach(var coordinate in coordinates)
{
      Checkbox checkbox = CreachCheckbox(coordinate.X, coordinate.Y);
      this.Controls.Add(checkbox);
}

protected Checkbox CreateCheckbox(int x, int y)
{
     var checkbox = new Checkbox();
     checkbox.AutoSize = true;
     checkbox.Location = new Point(x, y);
     return checkbox;
}
</code>```

You simply need to build an object called Coordinates with your desired locations, then you would iterate through those objects for each of your Checkbox which will populate based on your desired positioning.

Title: Add checkbox button

Body:
I'm creating list view with checkboxes, and I need in this a button that adds next checkbox in my form app. I know how to add single box, but idk how to make a loop that will helps me to add next checkboxes. Here, I give u a piece of code. At the start I have 24 checkboxes, next must be on 612 px position.

private void btnAdd_Click(object sender, EventArgs e)
    {
         CheckBox box;
         box = new CheckBox();
         box.AutoSize = true;
         box.Location = new Point(30, 612);
         this.Controls.Add(box);
    }

Body:
I've noticed that your checkbox exist within a button click event, is that what you truly want?

You can loop, in this manner:

var coordinates = new List<Coordinate>();
foreach(var coordinate in coordinates)
{
      Checkbox checkbox = CreachCheckbox(coordinate.X, coordinate.Y);
      this.Controls.Add(checkbox);
}

protected Checkbox CreateCheckbox(int x, int y)
{
     var checkbox = new Checkbox();
     checkbox.AutoSize = true;
     checkbox.Location = new Point(x, y);
     return checkbox;
}

You simply need to build an object called Coordinates with your desired locations, then you would iterate through those objects for each of your Checkbox which will populate based on your desired positioning.


问:
Unable to use ng-if with ng-repeat $index
I'm trying to use ng-if to display a button based on filters being present on screen. I'm using md-chips to show filters in categories.

HTML:

```<code><div ng-repeat="filter in sc.filters track by $index">
  <md-chips ng-model="filter.value" ng-if="sc.isArray(filter.value)" md-on-remove="sc.filter()"></md-chips>
</div>
<button ng-if="$first" ng-click="sc.newSearch()">clear filters</button>
</code>```

I track the index and try to add the button if first item was present. It doesn't show the button at all. Any help appreciated.

答:
$first should be used within an ng-repeat statement. In this case you don't want to use $first though.

If you want to add the button if the first item is present, why not just do something like this:

```<code><button ng-if="sc.filters.length" ng-click="sc.newSearch()">clear filters</button>
</code>```

Body:
I'm trying to use ng-if to display a button based on filters being present on screen. I'm using md-chips to show filters in categories.

HTML:

  <md-chips ng-model="filter.value" ng-if="sc.isArray(filter.value)" md-on-remove="sc.filter()"></md-chips>

<button ng-if="$first" ng-click="sc.newSearch()">clear filters</button>

I track the index and try to add the button if first item was present. It doesn't show the button at all. Any help appreciated.

Body:
$first should be used within an ng-repeat statement. In this case you don't want to use $first though.

If you want to add the button if the first item is present, why not just do something like this:

<button ng-if="sc.filters.length" ng-click="sc.newSearch()">clear filters</button>


问:
Bootstrap navbar width issue
I have annoying problem in my bootstrap menu, when I added " navbar Form" in the menu the width of the menu become larger than the width of the screen in mobile mode (when I decrease browser width for example, or when I open the page on the mobile). Knowing that the issue disappear whenever I remove the form code.
See my code:

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

          <form class="navbar-form" role="search" action="ActionPages\index_Search_Action.php" method="post" accept-charset="utf-8">

                    <input type="text" name="txtSearch" class="form-control" placeholder="Search" aria-describedby="basic-addon1">

        </form>

```

What Should I do?

答:
Maybe try removing your
 tags. These tags are intended to be used inside some kind of list.

Title: Bootstrap navbar width issue

Body:
I have annoying problem in my bootstrap menu, when I added " navbar Form" in the menu the width of the menu become larger than the width of the screen in mobile mode (when I decrease browser width for example, or when I open the page on the mobile). Knowing that the issue disappear whenever I remove the form code.
See my code:

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

          <form class="navbar-form" role="search" action="ActionPages\index_Search_Action.php" method="post" accept-charset="utf-8">

                    <input type="text" name="txtSearch" class="form-control" placeholder="Search" aria-describedby="basic-addon1">

        </form>

What Should I do?

Body: Maybe try removing your <li> tags. These tags are intended to be used inside some kind of list.


问:
AWK - error in script with count variable OR error in AWK Implementation / version?

Awk version: GNU Awk 3.1.1

Platform: OpenVMS 8.4-L1

Awk knowledge: limited

Script (Awk one liner).
NOTE: OpenVMS parameter parsing requires quotes

```<code>gawk "-F" ";" "BEGIN {x = 0} ; x++ {print $0,$1"";""x}" in.file > out.file

**in.file**
file.log;2000
file.log;1999
file.log;1998
file.log;1997

**out.file**
file.log;1999 file.log;2
file.log;1998 file.log;3
file.log;1997 file.log;4
</code>```

I wanted the following instead

```<code>file.log;2000 file.log;1
file.log;1999 file.log;2
file.log;1998 file.log;3
file.log;1997 file.log;4
</code>```

If I change the awk command above to: ...{x = -1}... I get

```<code>**out.file**
file.log;2000 file.log;0
file.log;1998 file.log;2
file.log;1997 file.log;3
</code>```

What I am wondering is

Can someone else using a different platform test this to see if it produces the same output?

Could it be the awk version I am running that is at fault OR is there something wrong with my awk script that I am not understanding

It really seems to me that it should produce a file.log;1999 file.log;1 line but it doesn't. I'm at a loss and need some pointers / awk education

Thanks in advance :-)

答:
Since you don't know AWK too well, may I suggest to skip it altogether and switch to PERL?

But first things first. What problem are you really trying to solve?
Seems to me you obtained a list of file names (DIR/COL=2/OUT=x.x)
You want to use that list to generate a rename where the file with the highest version number becomes number 1, the next down 2 and so on.
Is that correct?

I hope there no need to worry about overlap perhaps thanks to a version limit in place.

DCL defaults can do that just fine.
 - Using PERL here just as a handy way to create a bunch of files
 - Using FILE_ID to show which file is which
Here it goes.

```<code>$perl -e "open X,qq(>file.log;$_) for 1997..2000"
$dir/file
FILE.LOG;2000        (59705,105,0)
FILE.LOG;1999        (46771,399,0)
FILE.LOG;1998        (42897,980,0)
FILE.LOG;1997        (24538,519,0)
$rena/log file.log.* tmp.log;
%RENAME-I-RENAMED, FILE.LOG;2000 renamed to TMP.LOG;1
%RENAME-I-RENAMED, FILE.LOG;1999 renamed to TMP.LOG;2
%RENAME-I-RENAMED, FILE.LOG;1998 renamed to TMP.LOG;3
%RENAME-I-RENAMED, FILE.LOG;1997 renamed to TMP.LOG;4
$rena tmp.log;* file.log/log
%RENAME-I-RENAMED, TMP.LOG;4 renamed to FILE.LOG;4
%RENAME-I-RENAMED, TMP.LOG;3 renamed to FILE.LOG;3
%RENAME-I-RENAMED, TMP.LOG;2 renamed to FILE.LOG;2
%RENAME-I-RENAMED, TMP.LOG;1 renamed to FILE.LOG;1
$dir/file file.log;*
FILE.LOG;4           (24538,519,0)
FILE.LOG;3           (42897,980,0)
FILE.LOG;2           (46771,399,0)
FILE.LOG;1           (59705,105,0)
</code>```

ok? No helpers needed. Just two commands relying on the ";" magic to stop inheritance.

Now let's see how to do this in Perl directly.

```<code>$ dir/file
FILE.LOG;2000        (59705,105,0)
FILE.LOG;1999        (46771,399,0)
FILE.LOG;1998        (42897,980,0)
FILE.LOG;1997        (24538,519,0)
$ perl -e "for (<file.log;*>) {$i++; $old = $_; s/;\d+/;$i/; rename $old, $_}"
$ dir/file
FILE.LOG;4           (24538,522,0)
FILE.LOG;3           (42897,983,0)
FILE.LOG;2           (46771,402,0)
FILE.LOG;1           (59705,108,0)
</code>```

Broken down in steps:

```<code><xxx> = glob("xxx") = glob(qq(xxx) = wildcard lookup with interpolated string.
for (<file.log;*>)        # Loop over all files matching pattern, output into $_
{                         # code block
$i++;                     # increment for each iteration. start at 1
$old = $_;                # save the fetched file name
s/;\d+/;$i/;              # substitute a semicolon followed by numbers
rename $old, $_           # Actual rename. Try with PRINT first.
}                         # end of code block
</code>```

ok?

Body:
Awk version: GNU Awk 3.1.1

Platform: OpenVMS 8.4-L1

Awk knowledge: limited

Script (Awk one liner).
NOTE: OpenVMS parameter parsing requires quotes

gawk "-F" ";" "BEGIN {x = 0} ; x++ {print $0,$1"";""x}" in.file > out.file

**in.file**
file.log;2000
file.log;1999
file.log;1998
file.log;1997

**out.file**
file.log;1999 file.log;2
file.log;1998 file.log;3
file.log;1997 file.log;4

I wanted the following instead

file.log;2000 file.log;1
file.log;1999 file.log;2
file.log;1998 file.log;3
file.log;1997 file.log;4

If I change the awk command above to: ...{x = -1}... I get

**out.file**
file.log;2000 file.log;0
file.log;1998 file.log;2
file.log;1997 file.log;3

What I am wondering is

Can someone else using a different platform test this to see if it produces the same output?

Could it be the awk version I am running that is at fault OR is there something wrong with my awk script that I am not understanding

It really seems to me that it should produce a file.log;1999 file.log;1 line but it doesn't. I'm at a loss and need some pointers / awk education

Thanks in advance :-)

Body:
Since you don't know AWK too well, may I suggest to skip it altogether and switch to PERL?

But first things first. What problem are you really trying to solve?
Seems to me you obtained a list of file names (DIR/COL=2/OUT=x.x)
You want to use that list to generate a rename where the file with the highest version number becomes number 1, the next down 2 and so on.
Is that correct?

I hope there no need to worry about overlap perhaps thanks to a version limit in place.

DCL defaults can do that just fine.
 - Using PERL here just as a handy way to create a bunch of files
 - Using FILE_ID to show which file is which
Here it goes.

$perl -e "open X,qq(>file.log;$_) for 1997..2000"
$dir/file
FILE.LOG;2000        (59705,105,0)
FILE.LOG;1999        (46771,399,0)
FILE.LOG;1998        (42897,980,0)
FILE.LOG;1997        (24538,519,0)
$rena/log file.log.* tmp.log;
%RENAME-I-RENAMED, FILE.LOG;2000 renamed to TMP.LOG;1
%RENAME-I-RENAMED, FILE.LOG;1999 renamed to TMP.LOG;2
%RENAME-I-RENAMED, FILE.LOG;1998 renamed to TMP.LOG;3
%RENAME-I-RENAMED, FILE.LOG;1997 renamed to TMP.LOG;4
$rena tmp.log;* file.log/log
%RENAME-I-RENAMED, TMP.LOG;4 renamed to FILE.LOG;4
%RENAME-I-RENAMED, TMP.LOG;3 renamed to FILE.LOG;3
%RENAME-I-RENAMED, TMP.LOG;2 renamed to FILE.LOG;2
%RENAME-I-RENAMED, TMP.LOG;1 renamed to FILE.LOG;1
$dir/file file.log;*
FILE.LOG;4           (24538,519,0)
FILE.LOG;3           (42897,980,0)
FILE.LOG;2           (46771,399,0)
FILE.LOG;1           (59705,105,0)

ok? No helpers needed. Just two commands relying on the ";" magic to stop inheritance.

Now let's see how to do this in Perl directly.

$ dir/file
FILE.LOG;2000        (59705,105,0)
FILE.LOG;1999        (46771,399,0)
FILE.LOG;1998        (42897,980,0)
FILE.LOG;1997        (24538,519,0)
$ perl -e "for (<file.log;*>) {$i++; $old = $_; s/;\d+/;$i/; rename $old, $_}"
$ dir/file
FILE.LOG;4           (24538,522,0)
FILE.LOG;3           (42897,983,0)
FILE.LOG;2           (46771,402,0)
FILE.LOG;1           (59705,108,0)

Broken down in steps:

<xxx> = glob("xxx") = glob(qq(xxx) = wildcard lookup with interpolated string.
for (<file.log;*>)        # Loop over all files matching pattern, output into $_
{                         # code block
$i++;                     # increment for each iteration. start at 1
$old = $_;                # save the fetched file name
s/;\d+/;$i/;              # substitute a semicolon followed by numbers
rename $old, $_           # Actual rename. Try with PRINT first.
}                         # end of code block

ok?


问:
How to make a masonry layout grid in bootstrap 3?
I am using boostrap to make a masonry layout. But I am having a problem. As you can see in my code, I have 5 divs. I want Div 4 and 5 to move up(check the attached image) but I have no idea how to do it. I can do it with margin-top but it will break the responsive layout. So, what's the possible solution for this? I am a newbie, it will be a great help. Thanks in advance.

```<code><html>
<head>

    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="css/font-awesome.min.css">
    <style>
        .div1{
            border: 2px solid;
        }
        .div2{
            border: 2px solid;
        }
        .div3{
            border: 2px solid;
            height: 100px;
        }
        .div4{
            border: 2px solid;
        }
        .div5{
            border: 2px solid;
            height: 40px;
        }
    </style>
</head>
<body>
    <div class="col-md-12">
        <div class="col-md-4 div1">Div1</div>
        <div class="col-md-4 div2">Div2</div>
        <div class="col-md-4 div3">Div3</div>
        <div class="col-md-8 div4">Div4</div>
        <div class="col-md-8 div5">Div5</div>
    </div>
<!-- Loading minified js. jQuery and Bootstrap -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</body>
</html>
</code>```

The current layout is:

But I want it like this:

答:
In this specific case you can use nesting..

```<code><div class="col-md-12">
    <div class="row">
        <div class="col-md-8">
            <div class="row">
                <div class="col-md-6 div1">Div1</div>
                <div class="col-md-6 div2">Div2</div>
                <div class="col-md-12 div4">Div4</div>
                <div class="col-md-12 div5">Div5</div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="row">
                <div class="col-md-12 div3">Div3</div>
            </div>
        </div>
    </div>
</div>
</code>```

Or, use pull-right on div3...

```<code><div class="col-md-12">
   <div class="row">
    <div class="col-md-4 div1">Div1</div>
    <div class="col-md-4 div2">Div2</div>
    <div class="col-md-4 div3 pull-right">Div3</div>
    <div class="col-md-8 div4">Div4</div>
    <div class="col-md-8 div5">Div5</div>
    </div>
</div>
</code>```

Demo of both solutions

If you want to use Masonry, see my answer for Bootstrap Masonry solutions.

Body:
I am using boostrap to make a masonry layout. But I am having a problem. As you can see in my code, I have 5 divs. I want Div 4 and 5 to move up(check the attached image) but I have no idea how to do it. I can do it with margin-top but it will break the responsive layout. So, what's the possible solution for this? I am a newbie, it will be a great help. Thanks in advance.

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="css/font-awesome.min.css">

Div1

Div2

Div3

Div4

Div5

The current layout is:

But I want it like this:

Body:
In this specific case you can use nesting..

<div class="col-md-12">
    <div class="row">
        <div class="col-md-8">
            <div class="row">
                <div class="col-md-6 div1">Div1</div>
                <div class="col-md-6 div2">Div2</div>
                <div class="col-md-12 div4">Div4</div>
                <div class="col-md-12 div5">Div5</div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="row">
                <div class="col-md-12 div3">Div3</div>
            </div>
        </div>
    </div>
</div>

Or, use pull-right on div3...

<div class="col-md-12">
   <div class="row">
    <div class="col-md-4 div1">Div1</div>
    <div class="col-md-4 div2">Div2</div>
    <div class="col-md-4 div3 pull-right">Div3</div>
    <div class="col-md-8 div4">Div4</div>
    <div class="col-md-8 div5">Div5</div>
    </div>
</div>

Demo of both solutions

If you want to use Masonry, see my answer for Bootstrap Masonry solutions.


问:
MySQL where subselect on multiple fields
I'm trying to do a single MySQL query to select data inside a third party function, the problem I have however they only pass me the ID.  I need to use that ID to select all the related records.

Currently the MySQL statement looks something like this:

```<code>SELECT h.id, h.notification_id, h.status, d.detail
FROM headers h, details d
WHERE h.host_id = (SELECT host_id FROM headers WHERE id = '{$rowid}')
AND h.service_id = (SELECT service_id FROM headers WHERE id = '{$rowid}')
AND h.instance = (SELECT instance from headers where id = '{$rowid}')
AND h.id = d.header_id;
</code>```

Now this works, but I'm thinking the poor MySQL engine is running 3 subqueries because I don't have 3 pieces of information available to me.

So I was wondering if there a way to run this with one query and one subquery to save the load on the database?

Thanks in advance.

答:
You can work with tuples (i.e. rather than looking up host_id and service_id and instance you'd look up the combination (host_id, service_id, instance)):

```<code>SELECT h.id, h.notification_id, h.status, d.detail
FROM headers h
JOIN details d ON d.header_id = h.id
WHERE (h.host_id, h.service_id, h.instance) =
  (SELECT host_id, service_id, instance FROM headers WHERE id = '{$rowid}')
;
</code>```

This puts criteria wehere it belongs: in the where clause (just as in your query). You select from headers and details where the combination (host_id, service_id, instance) matches the record with the given ID.

Body:
I'm trying to do a single MySQL query to select data inside a third party function, the problem I have however they only pass me the ID.  I need to use that ID to select all the related records.

Currently the MySQL statement looks something like this:

SELECT h.id, h.notification_id, h.status, d.detail
FROM headers h, details d
WHERE h.host_id = (SELECT host_id FROM headers WHERE id = '{$rowid}')
AND h.service_id = (SELECT service_id FROM headers WHERE id = '{$rowid}')
AND h.instance = (SELECT instance from headers where id = '{$rowid}')
AND h.id = d.header_id;

Now this works, but I'm thinking the poor MySQL engine is running 3 subqueries because I don't have 3 pieces of information available to me.

So I was wondering if there a way to run this with one query and one subquery to save the load on the database?

Thanks in advance.

Body:
You can work with tuples (i.e. rather than looking up host_id and service_id and instance you'd look up the combination (host_id, service_id, instance)):

SELECT h.id, h.notification_id, h.status, d.detail
FROM headers h
JOIN details d ON d.header_id = h.id
WHERE (h.host_id, h.service_id, h.instance) =
  (SELECT host_id, service_id, instance FROM headers WHERE id = '{$rowid}')
;

This puts criteria wehere it belongs: in the where clause (just as in your query). You select from headers and details where the combination (host_id, service_id, instance) matches the record with the given ID.


问:
How can I generate a cube using JavaScript and this coordinate format?
Given this code:

```<code>{
( 256 64 16 ) ( 256 64 0 ) ( 256 0 16 ) mmetal1_2 0 0 0 1 1
( 0 0 0 ) ( 0 64 0 ) ( 0 0 16 ) mmetal1_2 0 0 0 1 1
( 64 256 16 ) ( 0 256 16 ) ( 64 256 0 ) mmetal1_2 0 0 0 1 1
( 0 0 0 ) ( 0 0 16 ) ( 64 0 0 ) mmetal1_2 0 0 0 1 1
( 64 64 0 ) ( 64 0 0 ) ( 0 64 0 ) mmetal1_2 0 0 0 1 1
( 0 0 -64 ) ( 64 0 -64 ) ( 0 64 -64 ) mmetal1_2 0 0 0 1 1
}
</code>```

How can I generate a cube using JavaScript (or any additional library) and the coordinates above? The code above should be interpreted as follows:

In the example shown here, this brush is a 6 sided cuboid. The plane
  of its first face is defined by 3 points, ( 256 64 16 ) ( 256 64 0 ) (
  256 0 16 ). The other information supplied is the texture used by the
  face. "mmetal1_2" is the name of the texture, a single plane may only
  have a single texture. "0 0 0 1 1" are how the texture is display, and
  are respectively "X offset" "Y offset" "Rotation" "X scale" and "Y
  scale".

The plane points ( p1 ) ( p2 ) ( p3 ) are interpreted as follows. The
  plane points must be arranged such that the cross product of the
  vectors (p3 - p1) and (p2 - p1) is not null, that is, the three points
  must be linearly independent. Then, the normalized cross product
  represents the normal vector of the plane. Every point p for which (p
  - p1) * normal <= 0 (where * is the dot product) holds is considered to be in the half space defined by the plane. Every other point is
  considered not to be in the half space.

Note #1: CSS can be used, if necessary.

Note #2: What I actually need here is the concept and the mathematical functions. I can extract the coordinates using a JavaScript loop, but I don't know how to initially approach this. I just need a nudge in the right direction.

Note #3: I only need the first three sets of values, not the texture and the offset.

Here are the specifications for this coordinates system:
https://quakewiki.org/wiki/Quake_Map_Format

答:
The points (p1)(p2)(p3) define a plane in terms of a triangle that lies on the plane. The points are arranged so that the plane's normal (the normalized "cross product of the vectors (p3 - p1) and (p2 - p1)") points outward. We can define the plane in terms of the plane equation Ax+Bx+Cx+D=0 as follows:

```<code>   (A, B, C) = N = normalize(cross(p3-p1,p2-p1))
   D = -dot(p1,N)
</code>```

The intersection of these planes forms a convex polyhedron. Finding this polyhedron involves finding the vertices of the intersection of the planes as one of the steps. The wiki article you mention links to a journal article explaining one way to generate these vertices.

The format you mention describes a convex polyhedron (convex polytope) using its half-space representation (or h-representation or h-rep). Since a given set of planes can describe many convex polyhedra, it's more likely you want to convert the minimal half-space representation of the convex polyhedron to its minimal vertex representation (or v-representation or v-rep). Here, a minimal representation is one whose vertices intersect at least three planes but describe a solid that intersects all the half-spaces. Then, you need to generate the convex hull of the minimal vertex representation.

Since the question requests more detail, I will add it:

Generating a mesh of the polyhedron involves
the following steps.

For each set of plane points (p1)(p2)(p3), find the coefficients
of the plane equation, as defined above.

Find the set of points that intersect three or more planes. This
is done by checking whether each set of three planes intersects
in a point. The result will generally be many more points than there
are vertices in the final polyhedron, so now we need to cull them.

For each point, check whether that point is inside all of the
planes. More specifically, a point is inside a plane if D+dot(P,N) <= 0,
where D and N are the plane's parameters as given above, and P
is the point in question. Only points that are inside all the planes are kept.

Eliminate duplicate points. Duplicates usually indicate that more
than three planes intersect in the same point.

The final step is to generate the convex hull of the points. Algorithms
such as QuickHull can be useful here. The result will be a convex
polyhedron with each face a convex polygon. If necessary, each
face of the polyhedron can be triangulated using a relatively trivial
procedure.

I have written code that implements this method.

Body:
Given this code:

{
( 256 64 16 ) ( 256 64 0 ) ( 256 0 16 ) mmetal1_2 0 0 0 1 1
( 0 0 0 ) ( 0 64 0 ) ( 0 0 16 ) mmetal1_2 0 0 0 1 1
( 64 256 16 ) ( 0 256 16 ) ( 64 256 0 ) mmetal1_2 0 0 0 1 1
( 0 0 0 ) ( 0 0 16 ) ( 64 0 0 ) mmetal1_2 0 0 0 1 1
( 64 64 0 ) ( 64 0 0 ) ( 0 64 0 ) mmetal1_2 0 0 0 1 1
( 0 0 -64 ) ( 64 0 -64 ) ( 0 64 -64 ) mmetal1_2 0 0 0 1 1
}

How can I generate a cube using JavaScript (or any additional library) and the coordinates above? The code above should be interpreted as follows:

In the example shown here, this brush is a 6 sided cuboid. The plane
  of its first face is defined by 3 points, ( 256 64 16 ) ( 256 64 0 ) (
  256 0 16 ). The other information supplied is the texture used by the
  face. "mmetal1_2" is the name of the texture, a single plane may only
  have a single texture. "0 0 0 1 1" are how the texture is display, and
  are respectively "X offset" "Y offset" "Rotation" "X scale" and "Y
  scale".

The plane points ( p1 ) ( p2 ) ( p3 ) are interpreted as follows. The
  plane points must be arranged such that the cross product of the
  vectors (p3 - p1) and (p2 - p1) is not null, that is, the three points
  must be linearly independent. Then, the normalized cross product
  represents the normal vector of the plane. Every point p for which (p
  - p1) * normal <= 0 (where * is the dot product) holds is considered to be in the half space defined by the plane. Every other point is
  considered not to be in the half space.

Note #1: CSS can be used, if necessary.

Note #2: What I actually need here is the concept and the mathematical functions. I can extract the coordinates using a JavaScript loop, but I don't know how to initially approach this. I just need a nudge in the right direction.

Note #3: I only need the first three sets of values, not the texture and the offset.

Here are the specifications for this coordinates system:
https://quakewiki.org/wiki/Quake_Map_Format

Body:
The points (p1)(p2)(p3) define a plane in terms of a triangle that lies on the plane. The points are arranged so that the plane's normal (the normalized "cross product of the vectors (p3 - p1) and (p2 - p1)") points outward. We can define the plane in terms of the plane equation Ax+Bx+Cx+D=0 as follows:

   (A, B, C) = N = normalize(cross(p3-p1,p2-p1))
   D = -dot(p1,N)

The intersection of these planes forms a convex polyhedron. Finding this polyhedron involves finding the vertices of the intersection of the planes as one of the steps. The wiki article you mention links to a journal article explaining one way to generate these vertices.

The format you mention describes a convex polyhedron (convex polytope) using its half-space representation (or h-representation or h-rep). Since a given set of planes can describe many convex polyhedra, it's more likely you want to convert the minimal half-space representation of the convex polyhedron to its minimal vertex representation (or v-representation or v-rep). Here, a minimal representation is one whose vertices intersect at least three planes but describe a solid that intersects all the half-spaces. Then, you need to generate the convex hull of the minimal vertex representation.

Since the question requests more detail, I will add it:

Generating a mesh of the polyhedron involves
the following steps.

For each set of plane points (p1)(p2)(p3), find the coefficients
of the plane equation, as defined above.

Find the set of points that intersect three or more planes. This
is done by checking whether each set of three planes intersects
in a point. The result will generally be many more points than there
are vertices in the final polyhedron, so now we need to cull them.

For each point, check whether that point is inside all of the
planes. More specifically, a point is inside a plane if D+dot(P,N) <= 0,
where D and N are the plane's parameters as given above, and P
is the point in question. Only points that are inside all the planes are kept.

Eliminate duplicate points. Duplicates usually indicate that more
than three planes intersect in the same point.

The final step is to generate the convex hull of the points. Algorithms
such as QuickHull can be useful here. The result will be a convex
polyhedron with each face a convex polygon. If necessary, each
face of the polyhedron can be triangulated using a relatively trivial
procedure.

I have written code that implements this method.


答:
Certainly the database structure is a poor design, so fixing that should be a priority.

Also, without a higher level understanding of what you are trying to achieve its hard to give a comprehensive answer, however given the info that can be gleaned from the code in your question, you could certainly just switch the loops, selecting the entire row in your sql and calculate the sum in a nested php loop, reducing your queries to 1:

```<code>$count = db_query('SELECT * FROM `prefix_projekteStep` WHERE kategoryid = ' . $row->id . ' AND id = ' . $rowStep->id.' AND jahr = '.$currentYear.' OR jahr = '.$nextYear.'');

while ($rowStepC = db_fetch_object($count)) {
     for ($i = 1; $i < 105; $i++) {
         $var = "cw" . $i;
         if ($rowStepC->$var === 1) {
               $sum += 1;
         }
     }
}
</code>```

But refactoring the database should be considered a priority.

Title: Optimizing PHP Code

Body:
Is there a way to optimize this?

// Zählt die Anzahl an KWs
$sum = 0;
for ($i = 1; $i < 105; $i++) {
    $count = db_query('SELECT cw' . $i . ' FROM `prefix_projekteStep` WHERE kategoryid = ' . $row->id . ' AND id = ' . $rowStep->id.' AND jahr = '.$currentYear.' OR jahr = '.$nextYear.'');
    while ($rowStepC = db_fetch_object($count)) {
        $var = "cw" . $i;
        if ($rowStepC->$var === 1) {
            $sum += 1;
        }
    }
}
echo $sum;

At the moment the script runs about 104 times in a call and I call this about 40 times. It takes very long to finish.

Body:
Certainly the database structure is a poor design, so fixing that should be a priority.

Also, without a higher level understanding of what you are trying to achieve its hard to give a comprehensive answer, however given the info that can be gleaned from the code in your question, you could certainly just switch the loops, selecting the entire row in your sql and calculate the sum in a nested php loop, reducing your queries to 1:

$count = db_query('SELECT * FROM `prefix_projekteStep` WHERE kategoryid = ' . $row->id . ' AND id = ' . $rowStep->id.' AND jahr = '.$currentYear.' OR jahr = '.$nextYear.'');

while ($rowStepC = db_fetch_object($count)) {
     for ($i = 1; $i < 105; $i++) {
         $var = "cw" . $i;
         if ($rowStepC->$var === 1) {
               $sum += 1;
         }
     }
}

But refactoring the database should be considered a priority.


问:
How to send a clean GraphQL request
I'm new to GraphQL. I've created a working schema implementation but my problem is making my API developer friendly. If users want to send the query below it seems very kludgy to ask them to compress it to one line, remove spaces, then urlencode it to fit into a query parameter or even json encoding it as well. Overall, I know this is suppose to be easier than REST so I figure I must be doing something wrong.

Question

What are some efficient ways of transforming the following GrapqhQL query into a format that can be transmitted across the internet?

```<code> search(firstName:"bob",lastName:"Smith", num: 0, max: 10)
    {
        age,
        height,
        email,
        country,
        occupation
    }
</code>```

Problem

Documentation on the Graphql sites always reference the simplest use-case of a query like { age }. But when it comes to real queries so far this seems uglier than REST.

答:
Your GraphQL syntax is wrong. That is why its not being encoded. If your syntax was right all you need to do is push the whole String into a URL/URI encoder and thats it. Heres the corrected syntax, you're missing brackets.

```<code>{
 search(firstName:"bob",lastName:"Smith", num: 0, max: 10)
    {
        age,
        height,
        email,
        country,
        occupation
    }
}
</code>```

Here is some additional documentation with some examples at the bottom
http://dev.apollodata.com/tools/graphql-server/requests.html

Title: How to send a clean GraphQL request

Body:
I'm new to GraphQL. I've created a working schema implementation but my problem is making my API developer friendly. If users want to send the query below it seems very kludgy to ask them to compress it to one line, remove spaces, then urlencode it to fit into a query parameter or even json encoding it as well. Overall, I know this is suppose to be easier than REST so I figure I must be doing something wrong.

Question

What are some efficient ways of transforming the following GrapqhQL query into a format that can be transmitted across the internet?

 search(firstName:"bob",lastName:"Smith", num: 0, max: 10)
    {
        age,
        height,
        email,
        country,
        occupation
    }

Problem

Documentation on the Graphql sites always reference the simplest use-case of a query like { age }. But when it comes to real queries so far this seems uglier than REST.

Body:
Your GraphQL syntax is wrong. That is why its not being encoded. If your syntax was right all you need to do is push the whole String into a URL/URI encoder and thats it. Heres the corrected syntax, you're missing brackets.

{
 search(firstName:"bob",lastName:"Smith", num: 0, max: 10)
    {
        age,
        height,
        email,
        country,
        occupation
    }
}

Here is some additional documentation with some examples at the bottom
http://dev.apollodata.com/tools/graphql-server/requests.html


问:
cannot resolve method 'getFont(?)'
As the documentation states:

Android O lets you bundle fonts as resources by adding the font file
  in the res/font/ folder.

As a result:

You can retrieve fonts by using the getFont(int) method, where you
  need to pass the resource identifier of the font that you want to
  retrieve. This method returns a Typeface object. This encodes the
  first of the weight or style variants of your font, if it is a font
  family. You can then use the Typeface.create(typeface, style) method
  to retrieve specific styles.

Note: The TextView already does this for you.

Typeface typeface = getResources().getFont(R.font.myfont);
  textView.setTypeface(typeface);

Unfortunately when I am using the above code I get the following error:

```<code>cannot resolve method 'getFont(?)'
</code>```

Previously I used to do the following:

```<code>Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/myfont.ttf");
</code>```

But now when I try to create the fonts folder inside assets folder, it automatically jumps inside res folder.

I am using android studio 2.3. Thanks in advance for any help.

答:
Since I was not able to create fonts folder directly from Android Studio, I opened the project folder using windows explorer and created the fonts  inside app\src\main\assets\ folder and pasted my font file there.

As so many other guys suggested in the answers I had to use Android Studio 2.4 Canary to be able to use Android O new features. The documentation states:

Only Android Studio 2.4 includes support for all the new developer
  features available with Android O. So you need to get the canary
  version of Android Studio 2.4 to begin using the Android O SDK. But
  you can still keep your stable version of Android Studio installed.

Title: cannot resolve method 'getFont(?)'

Body:
As the documentation states:

Android O lets you bundle fonts as resources by adding the font file
  in the res/font/ folder.

As a result:

You can retrieve fonts by using the getFont(int) method, where you
  need to pass the resource identifier of the font that you want to
  retrieve. This method returns a Typeface object. This encodes the
  first of the weight or style variants of your font, if it is a font
  family. You can then use the Typeface.create(typeface, style) method
  to retrieve specific styles.

Note: The TextView already does this for you.

Typeface typeface = getResources().getFont(R.font.myfont);
  textView.setTypeface(typeface);

Unfortunately when I am using the above code I get the following error:

cannot resolve method 'getFont(?)'

Previously I used to do the following:

Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/myfont.ttf");

But now when I try to create the fonts folder inside assets folder, it automatically jumps inside res folder.

I am using android studio 2.3. Thanks in advance for any help.


问:
Reading uncommitted transactions in Android
I have database heavy operations happening, which adds around 10,000 records to my Database. Since this could take a very long time, it would be better to use transactions.

```<code>db.startTransaction();
....
do write operations.
....
db.setTransactionSuccessful();
db.endTransaction();
</code>```

Now, I have some read operations inside the transactions, and since the inserts are not committed until endTransaction, those records are not fetched. I have heard about something called Transaction Isolation Levels, which enables us to read dirty (uncommitted) records as well. Any idea how to do this?

答:
Have you tried this</p>

```<code>// outer transaction
db.startTransaction();
....

    //roll out a new transaction
    db.startTransaction();
    ....
    do write operations.
    ....
    db.setTransactionSuccessful();// <-- you do commint inside of this transaction

    // you can read data from here on from the previous committed transaction

....
db.setTransactionSuccessful();
db.endTransaction();
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have database heavy operations happening, which adds around 10,000 records to my Database. Since this could take a very long time, it would be better to use transactions.

db.startTransaction();
....
do write operations.
....
db.setTransactionSuccessful();
db.endTransaction();

Now, I have some read operations inside the transactions, and since the inserts are not committed until endTransaction, those records are not fetched. I have heard about something called Transaction Isolation Levels, which enables us to read dirty (uncommitted) records as well. Any idea how to do this?

Body:
Have you tried this

// outer transaction
db.startTransaction();
....

    //roll out a new transaction
    db.startTransaction();
    ....
    do write operations.
    ....
    db.setTransactionSuccessful();// <-- you do commint inside of this transaction

    // you can read data from here on from the previous committed transaction

....
db.setTransactionSuccessful();
db.endTransaction();


问:
How to reuse a result column in an expression for another result column
Example:

```<code>SELECT
   (SELECT SUM(...) FROM ...) as turnover,
   (SELECT SUM(...) FROM ...) as cost,
   turnover - cost as profit
</code>```

Sure this is invalid (at least in Postgres) but how to achieve the same in a query without rewriting the sub-query twice?

答:
this is pretty old but i ran into this problem and saw this post but didnt manage to solve my problem using the given answers so i eventually arrived at this solution :

if your query is :

```<code>SELECT
   (SELECT SUM(...) FROM ...) as turnover,
   (SELECT SUM(...) FROM ...) as cost,
   turnover - cost as profit
</code>```

you can turn it into a subquery and then use the fields such as :

```<code>SELECT *,(myFields.turnover-myFields.cost) as profit
FROM
(
SELECT
       (SELECT SUM(...) FROM ...) as turnover,
       (SELECT SUM(...) FROM ...) as cost

) as myFields
</code>```

i'm not entirely sure if this is a bad way of doing things but performance wise it seems okay for me querying over 224,000 records took 1.5 sec
not sure if its later on turned into 2x of the same sub query by DB.

Body:
Example:

SELECT
   (SELECT SUM(...) FROM ...) as turnover,
   (SELECT SUM(...) FROM ...) as cost,
   turnover - cost as profit

Sure this is invalid (at least in Postgres) but how to achieve the same in a query without rewriting the sub-query twice?

Body:
this is pretty old but i ran into this problem and saw this post but didnt manage to solve my problem using the given answers so i eventually arrived at this solution :

if your query is :

SELECT
   (SELECT SUM(...) FROM ...) as turnover,
   (SELECT SUM(...) FROM ...) as cost,
   turnover - cost as profit

you can turn it into a subquery and then use the fields such as :

SELECT *,(myFields.turnover-myFields.cost) as profit
FROM
(
SELECT
       (SELECT SUM(...) FROM ...) as turnover,
       (SELECT SUM(...) FROM ...) as cost

) as myFields

i'm not entirely sure if this is a bad way of doing things but performance wise it seems okay for me querying over 224,000 records took 1.5 sec
not sure if its later on turned into 2x of the same sub query by DB.


问:
Sending icmp packet with boost clears checksum bytes
When sending an ICMPv6 echo request with Boost Asio, some layer appears to be clearing out the checksum whenever I do a send_to or async_send_to call.  When using the command line ping utility, there is no issue.  With any call, all of the fields: type, code, identifier, sequence and the payload are represented when I look at the outgoing packet in Wireshark.  Plus the correct bytes are in the buffer before and after the call.  Take a look at the picture here:

Wireshark capture icmpv6

Here's code to reproduce. This is Boost 1.62, VS2015.

#include <boost\asio.hpp>
#include <boost\thread.hpp>

using boost::asio::ip::address_v6;
using boost::asio::ip::icmp;

const char* ICMPREQUESTBODY_ = "abcdefghijklmnopqrstuvwabcdefghi";
const unsigned short ICMPIDENTIFIER_ = 1;
unsigned short tempchecksum = 0x5d46;
unsigned int icmpsequence_ = 70;
unsigned char ICMPv6TYPEECHOREQUEST_ = 128;
unsigned char ICMPv6CODE_ = 0;

int main()
{
    boost::asio::io_service io;
    boost::asio::io_service::work iowrk(io);
    boost::thread iothread(boost::bind(&boost::asio::io_service::run, &io));

    auto source = address_v6::from_string("2601:XXX:XXX:XXX::106");
    auto destination = address_v6::from_string("2601:XXX:XXX:XXX::202");
    icmp::endpoint remote_endpoint = boost::asio::ip::icmp::endpoint(destination, 0);
    icmp::endpoint local_endpoint(icmp::v6(), 0);

    icmp::socket elsocko(io, local_endpoint);

    unsigned char icmppacket[40];
    icmppacket[0] = ICMPv6TYPEECHOREQUEST_;
    icmppacket[1] = ICMPv6CODE_;
    icmppacket[2] = (tempchecksum & 0xff00) >> 8;
    icmppacket[3] = (tempchecksum & 0x00ff);
    icmppacket[4] = (ICMPIDENTIFIER_ & 0xff00) >> 8;
    icmppacket[5] = (ICMPIDENTIFIER_ & 0x00ff);
    icmppacket[6] = (icmpsequence_ & 0xff00) >> 8;
    icmppacket[7] = (icmpsequence_ & 0x00ff);
    memcpy(&icmppacket[8], ICMPREQUESTBODY_, 32);

    elsocko.send_to(boost::asio::buffer(icmppacket), remote_endpoint);

    //boost::asio::streambuf reply_buffer_;
    //elsocko.receive_from(reply_buffer_.prepare(65535), remote_endpoint);
}
```

The destination does not respond because the checksum is invalid.  What can cause this / how can I fix it?

答: Disabling McAfee LiveSafe Firewall allowed the icmpv6 ping to work.  There doesn't appear to be a setting that addresses this directly.  </p>

Body:
When sending an ICMPv6 echo request with Boost Asio, some layer appears to be clearing out the checksum whenever I do a send_to or async_send_to call.  When using the command line ping utility, there is no issue.  With any call, all of the fields: type, code, identifier, sequence and the payload are represented when I look at the outgoing packet in Wireshark.  Plus the correct bytes are in the buffer before and after the call.  Take a look at the picture here:

Wireshark capture icmpv6

Here's code to reproduce. This is Boost 1.62, VS2015.

#include <boost\asio.hpp>
#include <boost\thread.hpp>

using boost::asio::ip::address_v6;
using boost::asio::ip::icmp;

const char* ICMPREQUESTBODY_ = "abcdefghijklmnopqrstuvwabcdefghi";
const unsigned short ICMPIDENTIFIER_ = 1;
unsigned short tempchecksum = 0x5d46;
unsigned int icmpsequence_ = 70;
unsigned char ICMPv6TYPEECHOREQUEST_ = 128;
unsigned char ICMPv6CODE_ = 0;

int main()
{
    boost::asio::io_service io;
    boost::asio::io_service::work iowrk(io);
    boost::thread iothread(boost::bind(&boost::asio::io_service::run, &io));

    auto source = address_v6::from_string("2601:XXX:XXX:XXX::106");
    auto destination = address_v6::from_string("2601:XXX:XXX:XXX::202");
    icmp::endpoint remote_endpoint = boost::asio::ip::icmp::endpoint(destination, 0);
    icmp::endpoint local_endpoint(icmp::v6(), 0);

    icmp::socket elsocko(io, local_endpoint);

    unsigned char icmppacket[40];
    icmppacket[0] = ICMPv6TYPEECHOREQUEST_;
    icmppacket[1] = ICMPv6CODE_;
    icmppacket[2] = (tempchecksum & 0xff00) >> 8;
    icmppacket[3] = (tempchecksum & 0x00ff);
    icmppacket[4] = (ICMPIDENTIFIER_ & 0xff00) >> 8;
    icmppacket[5] = (ICMPIDENTIFIER_ & 0x00ff);
    icmppacket[6] = (icmpsequence_ & 0xff00) >> 8;
    icmppacket[7] = (icmpsequence_ & 0x00ff);
    memcpy(&icmppacket[8], ICMPREQUESTBODY_, 32);

    elsocko.send_to(boost::asio::buffer(icmppacket), remote_endpoint);

    //boost::asio::streambuf reply_buffer_;
    //elsocko.receive_from(reply_buffer_.prepare(65535), remote_endpoint);
}

The destination does not respond because the checksum is invalid.  What can cause this / how can I fix it?


问:
Telling regex search to only start searching at a certain index
Normally, a regex search will start searching for matches from the beginning of the string I provide. In this particular case, I'm working with a very large string (up to several megabytes), and I'd like to run successive regex searches on that string, but beginning at specific indices.

Now, I'm aware that I could use the substr function to simply throw away the part at the beginning I want to exclude from the search, but I'm afraid this is not very efficient, since I'll be doing it several thousand times.

The specific purpose I want to use this for is to jump from word to word in a very large text, skipping whitespace (regardless of whether it's simple space, tabs, newlines, etc). I know that I could just use the split function to split the text into words by passing \s+ as the delimiter, but that would make things for more complicated for me later on, as there a various other possible word delimiters such as quotes (ok, I'm using the term 'word' a bit generously here), so it would be easier for me if I could just hop from word to word using successive regex searches on the same string, always specifying the next index at which to start looking as I go. Is this doable in Perl?

答:
So you want to match against the words of a body of text.

(The examples find words that contain i.)

You think having the starting positions of the words would help, but it isn't useful. The following illustrates what it might look like to obtain the positions and use them:

```<code>my @positions;
while ($text =~ /\w+/g) {
   push @positions, $-[0];
}

my @matches;
for my $pos (@positions) {
   pos($text) = $pos;
   push @matches $1 if $text =~ /\G(\w*i\w*)/g;
}
</code>```

If would far simpler not to use the starting positions at all. Aside from being far simpler, we also remove the need for two different regex patterns to agree as to what constitute a word. The result is the following:

```<code>my @matches;
while ($text =~ /\b(\w*i\w*)/g) {
   push @matches $1;
}
</code>```

or

```<code>my @matches = $text =~ /\b(\w*i\w*)/g;
</code>```

A far better idea, however, is to extra the words themselves in advance. This approach allows for simpler patterns and more advanced definitions of "word"[1].

```<code>my @matches;
while ($text =~ /(\w+)/g) {
   my $word = $1;
   push @matches, $word if $word =~ /i/;
}
</code>```

or

```<code>my @matches = grep { /i/ } $text =~ /\w+/g;
</code>```

For example, a proper tokenizer could be used.

Body:
So you want to match against the words of a body of text.

(The examples find words that contain i.)

You think having the starting positions of the words would help, but it isn't useful. The following illustrates what it might look like to obtain the positions and use them:

my @positions;
while ($text =~ /\w+/g) {
   push @positions, $-[0];
}

my @matches;
for my $pos (@positions) {
   pos($text) = $pos;
   push @matches $1 if $text =~ /\G(\w*i\w*)/g;
}

If would far simpler not to use the starting positions at all. Aside from being far simpler, we also remove the need for two different regex patterns to agree as to what constitute a word. The result is the following:

my @matches;
while ($text =~ /\b(\w*i\w*)/g) {
   push @matches $1;
}

or

my @matches = $text =~ /\b(\w*i\w*)/g;

A far better idea, however, is to extra the words themselves in advance. This approach allows for simpler patterns and more advanced definitions of "word"[1].

my @matches;
while ($text =~ /(\w+)/g) {
   my $word = $1;
   push @matches, $word if $word =~ /i/;
}

or

my @matches = grep { /i/ } $text =~ /\w+/g;

For example, a proper tokenizer could be used.


问:
How to remove combiner output and keep only reducer output in mapreduce final output
Hi i am running an application which reads records from HBase and writes into text files .

I have used combiner in my application and custom partitioner also. I have used 41 reducer in my application because i need to create 40 reducer output file that satisfies my condition in custom partitioner.

All working fine but when i use combiner in my application it creates map output file per regions or per mapper .

Foe example i have 40 regions in my application so 40 mapper getting initiated then it create 40 map-output files . But reducer is not able to combine all map-output and generate final reducer output file that will be 40 reducer output files.

Data in the files are correct but no of files has increased .

Any idea how can i get only reducer output files.

```<code>import java.io.IOException;
import org.apache.log4j.Logger;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs;

public class CommonCombiner extends Reducer<NullWritable, Text, NullWritable, Text> {

    private Logger logger = Logger.getLogger(CommonCombiner.class);
    private MultipleOutputs<NullWritable, Text> multipleOutputs;
    String strName = "";
    private static final String DATA_SEPERATOR = "\\|\\!\\|";

    public void setup(Context context) {
        logger.info("Inside Combiner.");
        multipleOutputs = new MultipleOutputs<NullWritable, Text>(context);
    }

    @Override
    public void reduce(NullWritable Key, Iterable<Text> values, Context context)
            throws IOException, InterruptedException {

        for (Text value : values) {
            final String valueStr = value.toString();
            StringBuilder sb = new StringBuilder();
            if ("".equals(strName) && strName.length() == 0) {
                String[] strArrFileName = valueStr.split(DATA_SEPERATOR);
                String strFullFileName[] = strArrFileName[1].split("\\|\\^\\|");

                strName = strFullFileName[strFullFileName.length - 1];

                String strArrvalueStr[] = valueStr.split(DATA_SEPERATOR);
                if (!strArrvalueStr[0].contains(HbaseBulkLoadMapperConstants.FF_ACTION)) {
                    sb.append(strArrvalueStr[0] + "|!|");
                }
                multipleOutputs.write(NullWritable.get(), new Text(sb.toString()), strName);
                context.getCounter(Counters.FILE_DATA_COUNTER).increment(1);

            }

        }
    }

    public void cleanup(Context context) throws IOException, InterruptedException {
        multipleOutputs.close();
    }
}
</code>```

答:
Lets get the basics clear

Combiner is a optimization and can run both at mapper as well as in reduce (merge phase of reduce) (fetch merge reduce phases ).

Find out distribution of keys in your data , does a given mapper access lot of same key if yes, then combiner is helping else it has no effect.

1 K regions no where gurantees that they are equally partitioned.  You are having some hot regions

Find the hot regions and split.

Please follow : http://bytepadding.com/big-data/map-reduce/understanding-map-reduce-the-missing-guide/

Body:
Hi i am running an application which reads records from HBase and writes into text files .

I have used combiner in my application and custom partitioner also. I have used 41 reducer in my application because i need to create 40 reducer output file that satisfies my condition in custom partitioner.

All working fine but when i use combiner in my application it creates map output file per regions or per mapper .

Foe example i have 40 regions in my application so 40 mapper getting initiated then it create 40 map-output files . But reducer is not able to combine all map-output and generate final reducer output file that will be 40 reducer output files.

Data in the files are correct but no of files has increased .

Any idea how can i get only reducer output files.

import java.io.IOException;
import org.apache.log4j.Logger;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs;

public class CommonCombiner extends Reducer<NullWritable, Text, NullWritable, Text> {

    private Logger logger = Logger.getLogger(CommonCombiner.class);
    private MultipleOutputs<NullWritable, Text> multipleOutputs;
    String strName = "";
    private static final String DATA_SEPERATOR = "\\|\\!\\|";

    public void setup(Context context) {
        logger.info("Inside Combiner.");
        multipleOutputs = new MultipleOutputs<NullWritable, Text>(context);
    }

    @Override
    public void reduce(NullWritable Key, Iterable<Text> values, Context context)
            throws IOException, InterruptedException {

        for (Text value : values) {
            final String valueStr = value.toString();
            StringBuilder sb = new StringBuilder();
            if ("".equals(strName) && strName.length() == 0) {
                String[] strArrFileName = valueStr.split(DATA_SEPERATOR);
                String strFullFileName[] = strArrFileName[1].split("\\|\\^\\|");

                strName = strFullFileName[strFullFileName.length - 1];

                String strArrvalueStr[] = valueStr.split(DATA_SEPERATOR);
                if (!strArrvalueStr[0].contains(HbaseBulkLoadMapperConstants.FF_ACTION)) {
                    sb.append(strArrvalueStr[0] + "|!|");
                }
                multipleOutputs.write(NullWritable.get(), new Text(sb.toString()), strName);
                context.getCounter(Counters.FILE_DATA_COUNTER).increment(1);

            }

        }
    }

    public void cleanup(Context context) throws IOException, InterruptedException {
        multipleOutputs.close();
    }
}


问:
VIM macro editing
Suppose that I have recorded a long macro with many commands and special characters. Odds are I have made an error somewhere :) How can I edit a macro, correct errors and save it again?

For example:

I wish to copy a line and then increase the digit in it by one.

Macro for this is

```<code>yyp/\d<C-A>
</code>```

but it is saved as

```<code>yyp/\d^M^A
</code>```

and I can't see this special characters when I paste the register. I also have to play with 'let' when I wish to copy a register, because standard paste to screen and copy to another register doesn't work. How can I efficiently edit register with special characters?

Thanks

答: Press <C-r><C-r>q (here q is the register name) in insert mode. Execute :h ctrl-r_ctrl-r to see the details.

Title: VIM macro editing

Body:
Suppose that I have recorded a long macro with many commands and special characters. Odds are I have made an error somewhere :) How can I edit a macro, correct errors and save it again?

For example:

I wish to copy a line and then increase the digit in it by one.

Macro for this is

yyp/\d<C-A>

but it is saved as

yyp/\d^M^A

and I can't see this special characters when I paste the register. I also have to play with 'let' when I wish to copy a register, because standard paste to screen and copy to another register doesn't work. How can I efficiently edit register with special characters?

Thanks


问:
Turbolinks 5 : Show progress Bar
There is a progress bar when Turbolinks.visit is called.

I want to show and hide it manually (because some of my xhr request are a bit long), is it possible?

(In Turbolinks 3, there was Turbolinks.ProgressBar.start(); but it was not a public api and not working anymore)

答:
In Rails 5 (Turbolinks 5), the progress bar is enabled by default. It appears automatically for any page that takes longer than 500ms to load.

To disable the progress bar entirely, set its visibility style to hidden:

```<code>.turbolinks-progress-bar {
  visibility: hidden;
}
</code>```

More info here.

Title: Turbolinks 5 : Show progress Bar

Body:
In Rails 5 (Turbolinks 5), the progress bar is enabled by default. It appears automatically for any page that takes longer than 500ms to load.

To disable the progress bar entirely, set its visibility style to hidden:

.turbolinks-progress-bar {
  visibility: hidden;
}

More info here.


问:
How do I add a gradient to the text of a UILabel, but not the background?
hey, I want to be able to have a gradient fill on the text in a UILabel I know about CGGradient but i dont know how i would use it on a UILabel's text

i found this on google but i cant manage to get it to work

http://silverity.livejournal.com/26436.html

答:
Simplest Swift 3 Solution

Add an image to your project assets or create one programmatically then do the following:

```<code>let image = UIImage(named: "myGradient.png")!
label.textColor = UIColor.init(patternImage: image)
</code>```

Body:
Simplest Swift 3 Solution

Add an image to your project assets or create one programmatically then do the following:

let image = UIImage(named: "myGradient.png")!
label.textColor = UIColor.init(patternImage: image)


问:
"WITH" clause optimization in oracle query
When I use many WITH clauses in query, it executes longer, rather than without it.
Query structure like this:

```<code>with t1 as (select some_fields from table1 inner join table2),
     t2 as (select some_fields from t1 inner join table3),
     t3 as (select some_fields from t2 inner join table4)
select * from t3
</code>```

What approach should be used for optimization of similar queries?
In my case each subquery returns about 10 million rows.

答:
I confirm that the WITH CLAUSE does not improve performance in Oracle databases.
It only allows to use query names instead of the repetition of the whole query texts.

In addition, it allows to define PL/SQL functions to be used subsequently in the query.

Body:
When I use many WITH clauses in query, it executes longer, rather than without it.
Query structure like this:

with t1 as (select some_fields from table1 inner join table2),
     t2 as (select some_fields from t1 inner join table3),
     t3 as (select some_fields from t2 inner join table4)
select * from t3

What approach should be used for optimization of similar queries?
In my case each subquery returns about 10 million rows.


问:
using html tag and elements in text box leads to error: A potentially dangerous Request.Form value was detected from the client
i want to convert my html file to pdf in that process i took all html tags and elements into an asp textfield on button click its giving the above error

code is

```<code>code.aspx

<asp:TextBox ID="TxtHtmlCode"  CausesValidation="false" runat="server" Width="90%" Text="" TextMode="MultiLine" Height="150px"></asp:TextBox>

 <asp:Button ID="BtnCreatePdf" runat="server" Text="Create PDF" OnClick="BtnCreatePdf_Click" CssClass="mybutton" />

code.aspx.cs

protected void BtnCreatePdf_Click(object sender, EventArgs e)
   {
    htmlString = TxtHtmlCode.Text;
    HtmlToPdf converter = new HtmlToPdf();
    PdfDocument doc = converter.ConvertHtmlString(htmlString);
    doc.Save(Response, false, "Sample.pdf");
    doc.Close();
}
</code>```

i check with breakpoints even its not going to button click function.

please help me..

答:
You want to use HTML editor like opensource ckeditor.

It'll basically encode and decode html elements when you post the page back to server.

```<code><%@ Register Assembly="CKEditor.NET" Namespace="CKEditor.NET" TagPrefix="CKEditor" %>
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <CKEditor:CKEditorControl ID="CKEditor1" BasePath="/ckeditor/" runat="server">
        </CKEditor:CKEditorControl>

        <asp:Button ID="BtnCreatePdf" runat="server" Text="Create PDF"
            OnClick="BtnCreatePdf_Click" CssClass="mybutton" />
    </form>
</body>
</html>
</code>```

FYI: I personally do not like to use validateRequest="false"; it'll end up creating security hole.

Body:
i want to convert my html file to pdf in that process i took all html tags and elements into an asp textfield on button click its giving the above error

code is

code.aspx

<asp:TextBox ID="TxtHtmlCode"  CausesValidation="false" runat="server" Width="90%" Text="" TextMode="MultiLine" Height="150px"></asp:TextBox>

 <asp:Button ID="BtnCreatePdf" runat="server" Text="Create PDF" OnClick="BtnCreatePdf_Click" CssClass="mybutton" />

code.aspx.cs

protected void BtnCreatePdf_Click(object sender, EventArgs e)
   {
    htmlString = TxtHtmlCode.Text;
    HtmlToPdf converter = new HtmlToPdf();
    PdfDocument doc = converter.ConvertHtmlString(htmlString);
    doc.Save(Response, false, "Sample.pdf");
    doc.Close();
}

i check with breakpoints even its not going to button click function.

please help me..

Body:
You want to use HTML editor like opensource ckeditor.

It'll basically encode and decode html elements when you post the page back to server.

<%@ Register Assembly="CKEditor.NET" Namespace="CKEditor.NET" TagPrefix="CKEditor" %>
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <CKEditor:CKEditorControl ID="CKEditor1" BasePath="/ckeditor/" runat="server">
        </CKEditor:CKEditorControl>

        <asp:Button ID="BtnCreatePdf" runat="server" Text="Create PDF"
            OnClick="BtnCreatePdf_Click" CssClass="mybutton" />
    </form>
</body>
</html>

FYI: I personally do not like to use validateRequest="false"; it'll end up creating security hole.


问:
How can I used Swagger to generate a mocked server?
I want to generate a mocked server using Swagger YML files, for other services to connect to (eg, the front-end app connecting to a mocked API).

Is there an easy way to achieve this? Ideally, I'd use NodeJS but open to using any language if something already exists.

I want this to be entirely using the Swagger YML and any example data inside the objects rather than having to write code for the API.

Thanks

答:
You can use swagger code-gen to generate server mocks and scafolding projects using a swagger file.

This project it is in git hub:
https://github.com/swagger-api/swagger-codegen