问:
How do I write a batch file which opens the GitBash shell and runs a command in the shell?
I'm on Windows 7 trying to use a batch file to open the GitBash shell and make a git call.
This is the contents of my batch file:

```<code>REM Open GitBash
C:\Windows\SysWOW64\cmd.exe /c ""C:\Program Files (x86)\Git\bin\sh.exe" --login -i"
REM retrieve archive
git archive master | tar -x -C %~1
REM quit GitBash
exit
</code>```

I noticed that the GitBash is logging out before the next command "git archive...". Does anybody know if I can pass the command into GitBash and how?

Mike

答:
In my case, a certain HTTP Request would work in curl within Git Bash on Windows.  However, I would get a Connection Reset error when running on Java using HttpClient and HttpGet (org.apache.http.client.methods.HttpGet).

If I tried to use exec to directly run the command, for some reason it would not work.

As a workaround, this code will write the command in a batch file, then run the batch file and place the output in command.txt.

Here is the command which needs to be in the command.bat file (I have changed the endpoint and password):

```<code>"C:\Users\scottizu\AppData\Local\Programs\Git\bin\sh.exe" --login -i -c "curl 'https://my.server.com/validate/user/scottizu' -H 'Password: MY_PASSWORD' > command.txt"
</code>```

Here is the code (notice the command has special characters escaped):

```<code>import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

public class CURL_Runner {
    public static void main (String[] args) throws Exception {
        String command = "\"C:\\Users\\scottizu\\AppData\\Local\\Programs\\Git\\bin\\sh.exe\" --login -i -c \"curl 'https://my.server.com/validate/user/scottizu' -H 'Password: MY_PASSWORD' > command.txt\"";
        createAndExecuteBatchFile(command);
    }

    public static void createAndExecuteBatchFile(String command) throws Exception {

        // Step 1: Write command in command.bat
        File fileToUpload = new File("C:\\command.bat");
        try {
            if(fileToUpload.getParentFile() != null && !fileToUpload.exists()) {
                fileToUpload.getParentFile().mkdirs();
            }
            FileWriter fw = new FileWriter(fileToUpload);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(command);
            bw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Step 2: Execute command.bat
        String[] cmdArray = new String[1];
        cmdArray[0] = "C:\\command.bat";

        Process process = Runtime.getRuntime().exec(cmdArray, null, new File("C:\\"));
        int processComplete = process.waitFor();
    }
}
</code>```

Body:
I'm on Windows 7 trying to use a batch file to open the GitBash shell and make a git call.
This is the contents of my batch file:

REM Open GitBash
C:\Windows\SysWOW64\cmd.exe /c ""C:\Program Files (x86)\Git\bin\sh.exe" --login -i"
REM retrieve archive
git archive master | tar -x -C %~1
REM quit GitBash
exit

I noticed that the GitBash is logging out before the next command "git archive...". Does anybody know if I can pass the command into GitBash and how?

Mike

Body:
In my case, a certain HTTP Request would work in curl within Git Bash on Windows.  However, I would get a Connection Reset error when running on Java using HttpClient and HttpGet (org.apache.http.client.methods.HttpGet).

If I tried to use exec to directly run the command, for some reason it would not work.

As a workaround, this code will write the command in a batch file, then run the batch file and place the output in command.txt.

Here is the command which needs to be in the command.bat file (I have changed the endpoint and password):

"C:\Users\scottizu\AppData\Local\Programs\Git\bin\sh.exe" --login -i -c "curl 'https://my.server.com/validate/user/scottizu' -H 'Password: MY_PASSWORD' > command.txt"

Here is the code (notice the command has special characters escaped):

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

public class CURL_Runner {
    public static void main (String[] args) throws Exception {
        String command = "\"C:\\Users\\scottizu\\AppData\\Local\\Programs\\Git\\bin\\sh.exe\" --login -i -c \"curl 'https://my.server.com/validate/user/scottizu' -H 'Password: MY_PASSWORD' > command.txt\"";
        createAndExecuteBatchFile(command);
    }

    public static void createAndExecuteBatchFile(String command) throws Exception {

        // Step 1: Write command in command.bat
        File fileToUpload = new File("C:\\command.bat");
        try {
            if(fileToUpload.getParentFile() != null && !fileToUpload.exists()) {
                fileToUpload.getParentFile().mkdirs();
            }
            FileWriter fw = new FileWriter(fileToUpload);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(command);
            bw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Step 2: Execute command.bat
        String[] cmdArray = new String[1];
        cmdArray[0] = "C:\\command.bat";

        Process process = Runtime.getRuntime().exec(cmdArray, null, new File("C:\\"));
        int processComplete = process.waitFor();
    }
}


来源: stackexchange

问:
What the plus operator does with an array?
I found this code in one of Arduino libraries

```<code>u8 buf[6];
Host2SCS(buf+0, buf+1, Position);
Host2SCS(buf+2, buf+3, Time);
Host2SCS(buf+4, buf+5, Speed);
</code>```

What the plus operator does with the array?

答:
buf is a pointer (to an array), and the + operator, in this context, does pointer arithmetic. For example:

```<code>int A[] = {5, 1, 4, 8};
std::cout << A << std::endl;
std::cout << A+3 << std::endl;

output:
0x7d972ee131c0
0x7d972ee131cc
</code>```

so A+3 = address of A + 3 * sizeof (int)

Similarly, buf+3 = address of buf + 3 * sizeof (u8)

ContentLicense: CC BY-SA 3.0

Body:
I found this code in one of Arduino libraries

u8 buf[6];
Host2SCS(buf+0, buf+1, Position);
Host2SCS(buf+2, buf+3, Time);
Host2SCS(buf+4, buf+5, Speed);

What the plus operator does with the array?

Body:
buf is a pointer (to an array), and the + operator, in this context, does pointer arithmetic. For example:

int A[] = {5, 1, 4, 8};
std::cout << A << std::endl;
std::cout << A+3 << std::endl;

output:
0x7d972ee131c0
0x7d972ee131cc

so A+3 = address of A + 3 * sizeof (int)

Similarly, buf+3 = address of buf + 3 * sizeof (u8)


问:
Capistrano rbenv not configured to use the proper ruby: 1.9.1 system ruby instead of 2.2.3
I am trying to fix one production server's deploy process that is currently failing due to using the wrong ruby being executed. The target ruby with rbenv is 2.2.3. However, the Ubuntu 14 system on the server seems to be defaulting to ruby 1.9.1. I'm hoping someone on S.O. could perhaps pinpoint where the problem could possibly reside. Below is the full error:

```<code>Tasks: TOP => deploy:restart
(See full trace by running task with --trace)
The deploy has failed with an error: Exception while executing as serv-deployer@server: cd '/var/local/fisbot/releases/20170707184851'; RAILS_ENV=production ./slave restart exit status: 1
cd '/var/local/fisbot/releases/20170707184851'; RAILS_ENV=production ./slave restart stdout: Nothing written
cd '/var/local/fisbot/releases/20170707184851'; RAILS_ENV=production ./slave restart stderr: /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require': cannot load such file -- bundler/setup (LoadError)
    from /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from /var/local/fisbot/releases/20170707184851/config/boot.rb:3:in `<top (required)>'
    from /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from /var/local/fisbot/releases/20170707184851/config/application.rb:1:in `<top (required)>'
    from /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from /var/local/fisbot/releases/20170707184851/config/environment.rb:2:in `<top (required)>'
    from ./slave:4:in `require_relative'
    from ./slave:4:in `<main>'
</code>```

So from the documentation of rbenv rbenv.

Step 1: Checking to see if shims is in my path

```<code>printenv | grep PATH

PATH=/home/serv-deployer/.rbenv/shims:/home/serv-deployer/.rbenv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/opt/puppetlabs/bin
</code>```

As can be seen from the above PATH, shims is correctly placed in the front of the path.

Step 2: Checking for RBENV_VERSION

```<code>rbenv shell

rbenv: no shell-specific version configured
</code>```

So this is not applied here to my shell, but according to the documentation, if this fails, the next step will be executed so onwards.

Step 3: checking .ruby-version

When I execute both rbenv local and rbenv global, I can see that the output is ruby 2.2.3. Additionally, in my rails application on the target server, the .ruby-version's contents contains 2.2.3. So on those fronts I should be fine.

Step 4: Check ~/.rbenv/versions

Looking in this directory reveals that I have 2.2.3.

Step 5: I have executed echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc, Ran, ~/.rbenv/bin/rbenv init, and opened up a new window.

Finally for good measure, by executing gem env I can see that I am using 2.2.3

```<code>    RubyGems Environment:
  - RUBYGEMS VERSION: 2.4.5.1
  - RUBY VERSION: 2.2.3 (2015-08-18 patchlevel 173) [x86_64-linux]
  - INSTALLATION DIRECTORY: /home/serv-deployer/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0
  - RUBY EXECUTABLE: /home/serv-deployer/.rbenv/versions/2.2.3/bin/ruby
  - EXECUTABLE DIRECTORY: /home/serv-deployer/.rbenv/versions/2.2.3/bin
  - SPEC CACHE DIRECTORY: /home/serv-deployer/.gem/specs
  - SYSTEM CONFIGURATION DIRECTORY: /home/serv-deployer/.rbenv/versions/2.2.3/etc
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86_64-linux
  - GEM PATHS:
     - /home/serv-deployer/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0
     - /home/serv-deployer/.gem/ruby/2.2.0
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :backtrace => false
     - :bulk_threshold => 1000
  - REMOTE SOURCES:
     - https://rubygems.org/
  - SHELL PATH:
     - /home/serv-deployer/.rbenv/versions/2.2.3/bin
     - /home/serv-deployer/.rbenv/libexec
     - /home/serv-deployer/.rbenv/plugins/ruby-build/bin
     - /home/serv-deployer/.rbenv/shims
     - /home/serv-deployer/.rbenv/bin
     - /usr/local/sbin
     - /usr/local/bin
     - /usr/sbin
     - /usr/bin
     - /sbin
     - /bin
     - /usr/games
     - /usr/local/games
     - /opt/puppetlabs/bin
</code>```

Am I missing anything here? Everything indicates that I should be running the correct ruby so why is the command failing?

--------------EDIT------------

executing rbenv versions shows that I have two ruby versions

system
2.2.3 (set by /var/local/fisbot/current/.ruby-version)

As I should, is it recommended to purge the system ruby. If I can get rid of the system version then perhaps I can be set. I don't know if this is recommended though as this is a production system.

答: I'm not clear from the question which commands you are running on your local machine and which you are running on the server. But I think the most likely scenario is that 1) your local machine has rbenv but 2) your server does not. In this scenario, your server doesn't have any idea what a .ruby-version file is and will need its system Ruby updated to match the .ruby-version that you use for development.

Body:
I am trying to fix one production server's deploy process that is currently failing due to using the wrong ruby being executed. The target ruby with rbenv is 2.2.3. However, the Ubuntu 14 system on the server seems to be defaulting to ruby 1.9.1. I'm hoping someone on S.O. could perhaps pinpoint where the problem could possibly reside. Below is the full error:

Tasks: TOP => deploy:restart
(See full trace by running task with --trace)
The deploy has failed with an error: Exception while executing as serv-deployer@server: cd '/var/local/fisbot/releases/20170707184851'; RAILS_ENV=production ./slave restart exit status: 1
cd '/var/local/fisbot/releases/20170707184851'; RAILS_ENV=production ./slave restart stdout: Nothing written
cd '/var/local/fisbot/releases/20170707184851'; RAILS_ENV=production ./slave restart stderr: /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require': cannot load such file -- bundler/setup (LoadError)
    from /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from /var/local/fisbot/releases/20170707184851/config/boot.rb:3:in `<top (required)>'
    from /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from /var/local/fisbot/releases/20170707184851/config/application.rb:1:in `<top (required)>'
    from /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from /var/local/fisbot/releases/20170707184851/config/environment.rb:2:in `<top (required)>'
    from ./slave:4:in `require_relative'
    from ./slave:4:in `'

So from the documentation of rbenv rbenv.

Step 1: Checking to see if shims is in my path

printenv | grep PATH

PATH=/home/serv-deployer/.rbenv/shims:/home/serv-deployer/.rbenv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/opt/puppetlabs/bin

As can be seen from the above PATH, shims is correctly placed in the front of the path.

Step 2: Checking for RBENV_VERSION

rbenv shell

rbenv: no shell-specific version configured

So this is not applied here to my shell, but according to the documentation, if this fails, the next step will be executed so onwards.

Step 3: checking .ruby-version

When I execute both rbenv local and rbenv global, I can see that the output is ruby 2.2.3. Additionally, in my rails application on the target server, the .ruby-version's contents contains 2.2.3. So on those fronts I should be fine.

Step 4: Check ~/.rbenv/versions

Looking in this directory reveals that I have 2.2.3.

Step 5: I have executed echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc, Ran, ~/.rbenv/bin/rbenv init, and opened up a new window.

Finally for good measure, by executing gem env I can see that I am using 2.2.3

    RubyGems Environment:
  - RUBYGEMS VERSION: 2.4.5.1
  - RUBY VERSION: 2.2.3 (2015-08-18 patchlevel 173) [x86_64-linux]
  - INSTALLATION DIRECTORY: /home/serv-deployer/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0
  - RUBY EXECUTABLE: /home/serv-deployer/.rbenv/versions/2.2.3/bin/ruby
  - EXECUTABLE DIRECTORY: /home/serv-deployer/.rbenv/versions/2.2.3/bin
  - SPEC CACHE DIRECTORY: /home/serv-deployer/.gem/specs
  - SYSTEM CONFIGURATION DIRECTORY: /home/serv-deployer/.rbenv/versions/2.2.3/etc
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86_64-linux
  - GEM PATHS:
     - /home/serv-deployer/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0
     - /home/serv-deployer/.gem/ruby/2.2.0
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :backtrace => false
     - :bulk_threshold => 1000
  - REMOTE SOURCES:
     - https://rubygems.org/
  - SHELL PATH:
     - /home/serv-deployer/.rbenv/versions/2.2.3/bin
     - /home/serv-deployer/.rbenv/libexec
     - /home/serv-deployer/.rbenv/plugins/ruby-build/bin
     - /home/serv-deployer/.rbenv/shims
     - /home/serv-deployer/.rbenv/bin
     - /usr/local/sbin
     - /usr/local/bin
     - /usr/sbin
     - /usr/bin
     - /sbin
     - /bin
     - /usr/games
     - /usr/local/games
     - /opt/puppetlabs/bin

Am I missing anything here? Everything indicates that I should be running the correct ruby so why is the command failing?

--------------EDIT------------

executing rbenv versions shows that I have two ruby versions

system
2.2.3 (set by /var/local/fisbot/current/.ruby-version)

As I should, is it recommended to purge the system ruby. If I can get rid of the system version then perhaps I can be set. I don't know if this is recommended though as this is a production system.


问:
Shortcut key for commenting out lines of Python code in Spyder
I recently changed from the Enthought Canopy Python distribution to Anaconda, which includes the Spyder IDE.

In Canopy's code editor, it was possible to comment and uncomment lines of code by pressing the "Cntrl+/" shortcut key sequence. In Spyder I was unable to find an equivalent shortcut key in the introductory tutorial.

Is there a shortcut key for commenting and uncommenting code in Spyder?

答:
Unblock multi-line comment

Ctrl+5

Multi-line comment

Ctrl+4

NOTE: For my version of Spyder (3.1.4) if I highlighted the entire multi-line comment and used Ctrl+5 the block remained commented out. Only after highlighting a small portion of the multi-line comment did Ctrl+5 work.


问:
Change price of product in WooCommerce cart and checkout
I'm creating a WooCommerce add-on to customize the product, based on selected options by the visitor and custom price is calculated and stored into session table also.

I am able to get that value in cart page also.

My problem:
 I would like to change the default price of the product and  replace it with new calculated value in the WooCommerce process as cart, checkout, payment, mail notifications, order...

Any advice please?

Thanks

答:
Ce right hook to get it working is woocommerce_before_calculate_totals. But you will have to complete (replace) the code to get the new price in the hooked function below:

```<code>add_action( 'woocommerce_before_calculate_totals', 'custom_cart_items_prices', 10, 1 );
function custom_cart_items_prices( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Loop Through cart items
    foreach ( $cart->get_cart() as $cart_item ) {
        // Get the product id (or the variation id)
        $product_id = $cart_item['data']->get_id();

        // GET THE NEW PRICE (code to be replace by yours)
        $new_price = 500; // <== Add your code HERE

        // Updated cart item price
        $cart_item['data']->set_price( $new_price );
    }
}
</code>```

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works on WooCommerce versions 3+. But as you don't give any code I can't test it for real getting the new price from session…

Body:
Ce right hook to get it working is woocommerce_before_calculate_totals. But you will have to complete (replace) the code to get the new price in the hooked function below:

add_action( 'woocommerce_before_calculate_totals', 'custom_cart_items_prices', 10, 1 );
function custom_cart_items_prices( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Loop Through cart items
    foreach ( $cart->get_cart() as $cart_item ) {
        // Get the product id (or the variation id)
        $product_id = $cart_item['data']->get_id();

        // GET THE NEW PRICE (code to be replace by yours)
        $new_price = 500; // <== Add your code HERE

        // Updated cart item price
        $cart_item['data']->set_price( $new_price );
    }
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works on WooCommerce versions 3+. But as you don't give any code I can't test it for real getting the new price from session…

ContentLicense: CC BY-SA 4.0


问:
Cannot add foreign key restraint error in MySQL?
I keep getting the same error in MySQL and i'm not sure what I missing here.
I am very new to working with MySQL, so I am not sure if I need to add a constraint maybe? If I do not need a constraint, is there another way to go about defining the relationships? Below is my syntax:</p>

```<code>    DROP TABLE IF EXISTS `art`;
    CREATE TABLE `art` (

   `art_id` INT NOT NULL,
   `art_name` VARCHAR(45) NULL,
   `artist_id` INT(11) NULL,
   `location_id` INT(11) NULL,
   `employee_id` INT(11) NULL,
   `art_received` DATE NULL,

  primary key (`art_id`),
  FOREIGN KEY (`artist_id`) REFERENCES artist(`artist_id`),
  FOREIGN KEY (`location_id`) REFERENCES location(`location_id`),
  FOREIGN KEY (`employee_id`) REFERENCES employee(`employee_id`)

  );

  DROP TABLE IF EXISTS `employee`;
 CREATE TABLE `employee` (

`employee_id` int(11),
`employee_userid` varchar(45),
`employee_fname` varchar(45),
`employee_lname` varchar(45),
`employee_phone` varchar (10),

primary key (`employee_id`)

);

 DROP TABLE IF EXISTS `artist`;
 CREATE TABLE `artist` (
`artist_id` int(11),
`artist_first` varchar(45),
`artist_last` varchar(45),
`artwork_title` varchar(45),

primary key (`artist_id`)

 );

 DROP TABLE IF EXISTS `location`;
 CREATE TABLE `location` (
`location_id` int(11),
`location_name` varchar(45),
`start_date` date,
`end_date` date,

primary key (`location_id`)

);
</code>```

答:
simply switch the order of which table gets created first. when you created
 table art the other three table still have not be created so it doesn't know what artist(artist_id),location(location_id),employee(employee_id)
are.

```<code> DROP TABLE IF EXISTS `employee`;
 CREATE TABLE `employee` (

   `employee_id` int(11),
   `employee_userid` varchar(45),
   `employee_fname` varchar(45),
   `employee_lname` varchar(45),
   `employee_phone` varchar (10),

   primary key (`employee_id`)

);

 DROP TABLE IF EXISTS artist;
 CREATE TABLE `artist` (
   `artist_id` int(11),
   `artist_first` varchar(45),
   `artist_last` varchar(45),
   `artwork_title` varchar(45),

   primary key (`artist_id`)

 );

 DROP TABLE IF EXISTS `location`;
 CREATE TABLE `location` (
   `location_id` int(11),
   `location_name` varchar(45),
   `start_date` date,
   `end_date` date,

   primary key (`location_id`)

);

DROP TABLE IF EXISTS `art`;
CREATE TABLE `art` (

   `art_id` INT NOT NULL,
   `art_name` VARCHAR(45) NULL,
   `artist_id` int(11) NULL,
   `location_id` int(11) NULL,
   `employee_id` int(11) NULL,
   `art_received` DATE NULL,

    primary key (`art_id`),

    FOREIGN KEY (`artist_id`) REFERENCES artist(`artist_id`),
    FOREIGN KEY (`location_id`) REFERENCES location(`location_id`),
    FOREIGN KEY (`employee_id`) REFERENCES employee(`employee_id`)

);
</code>```

And welcome to StackOverflow. if you find this answer or any other answer helpful please mark it as the solution. That way would help the community and if fellow programmers run into the same problem as you did in the future they can find the solution easily.

Body:
I keep getting the same error in MySQL and i'm not sure what I missing here.
I am very new to working with MySQL, so I am not sure if I need to add a constraint maybe? If I do not need a constraint, is there another way to go about defining the relationships? Below is my syntax:

    DROP TABLE IF EXISTS `art`;
    CREATE TABLE `art` (

   `art_id` INT NOT NULL,
   `art_name` VARCHAR(45) NULL,
   `artist_id` INT(11) NULL,
   `location_id` INT(11) NULL,
   `employee_id` INT(11) NULL,
   `art_received` DATE NULL,

  primary key (`art_id`),
  FOREIGN KEY (`artist_id`) REFERENCES artist(`artist_id`),
  FOREIGN KEY (`location_id`) REFERENCES location(`location_id`),
  FOREIGN KEY (`employee_id`) REFERENCES employee(`employee_id`)

  );

  DROP TABLE IF EXISTS `employee`;
 CREATE TABLE `employee` (

`employee_id` int(11),
`employee_userid` varchar(45),
`employee_fname` varchar(45),
`employee_lname` varchar(45),
`employee_phone` varchar (10),

primary key (`employee_id`)

);

 DROP TABLE IF EXISTS `artist`;
 CREATE TABLE `artist` (
`artist_id` int(11),
`artist_first` varchar(45),
`artist_last` varchar(45),
`artwork_title` varchar(45),

primary key (`artist_id`)

 );

 DROP TABLE IF EXISTS `location`;
 CREATE TABLE `location` (
`location_id` int(11),
`location_name` varchar(45),
`start_date` date,
`end_date` date,

primary key (`location_id`)

);

Body:
simply switch the order of which table gets created first. when you created
 table art the other three table still have not be created so it doesn't know what artist(artist_id),location(location_id),employee(employee_id)
are.

 DROP TABLE IF EXISTS `employee`;
 CREATE TABLE `employee` (

   `employee_id` int(11),
   `employee_userid` varchar(45),
   `employee_fname` varchar(45),
   `employee_lname` varchar(45),
   `employee_phone` varchar (10),

   primary key (`employee_id`)

);

 DROP TABLE IF EXISTS artist;
 CREATE TABLE `artist` (
   `artist_id` int(11),
   `artist_first` varchar(45),
   `artist_last` varchar(45),
   `artwork_title` varchar(45),

   primary key (`artist_id`)

 );

 DROP TABLE IF EXISTS `location`;
 CREATE TABLE `location` (
   `location_id` int(11),
   `location_name` varchar(45),
   `start_date` date,
   `end_date` date,

   primary key (`location_id`)

);

DROP TABLE IF EXISTS `art`;
CREATE TABLE `art` (

   `art_id` INT NOT NULL,
   `art_name` VARCHAR(45) NULL,
   `artist_id` int(11) NULL,
   `location_id` int(11) NULL,
   `employee_id` int(11) NULL,
   `art_received` DATE NULL,

    primary key (`art_id`),

    FOREIGN KEY (`artist_id`) REFERENCES artist(`artist_id`),
    FOREIGN KEY (`location_id`) REFERENCES location(`location_id`),
    FOREIGN KEY (`employee_id`) REFERENCES employee(`employee_id`)

);

And welcome to StackOverflow. if you find this answer or any other answer helpful please mark it as the solution. That way would help the community and if fellow programmers run into the same problem as you did in the future they can find the solution easily.


问:
Instagram API custom image width
I am trying to set custom width for images in Instagram, using Instagram API. I am using hashtag to grab all images related. Can I ask Instagram to serve me custom image sizes? I know there are 3 sizes: thumbnail, low_resolution, standard_resolution. Is that all what I can get? Thanks! </p>

答:
As the previous posters described, there's no way of Instagram serving images in the exact size you need. They only have three or four default sizes available.

You'll need to implement some kind of middleware that resizes the images for you or use a service like https://tiny.pictures/ (disclaimer: which I am a developer at) to do it for you.

Title: Instagram API custom image width


问:
How do I use Java to read from a file that is actively being written to?
I have an application that writes information to file. This information is used post-execution to determine pass/failure/correctness of the application. I'd like to be able to read the file as it is being written so that I can do these pass/failure/correctness checks in real time.

I assume it is possible to do this, but what are the gotcha's involved when using Java? If the reading catches up to the writing, will it just wait for more writes up until the file is closed, or will the read throw an exception at this point? If the latter, what do I do then?

My intuition is currently pushing me towards BufferedStreams. Is this the way to go?

答:
The answer seems to be "no" ... and "yes". There seems to be no real way to know if a file is open for writing by another application. So, reading from such a file will just progress until content is exhausted. I took Mike's advice and wrote some test code:

Writer.java writes a string to file and then waits for the user to hit enter before writing another line to file. The idea being that it could be started up, then a reader can be started to see how it copes with the "partial" file. The reader I wrote is in Reader.java.

Writer.java

```<code>public class Writer extends Object
{
    Writer () {

    }

    public static String[] strings =
        {
            "Hello World",
            "Goodbye World"
        };

    public static void main(String[] args)
        throws java.io.IOException {

        java.io.PrintWriter pw =
            new java.io.PrintWriter(new java.io.FileOutputStream("out.txt"), true);

        for(String s : strings) {
            pw.println(s);
            System.in.read();
        }

        pw.close();
    }
}
</code>```

Reader.java

```<code>public class Reader extends Object
{
    Reader () {

    }

    public static void main(String[] args)
        throws Exception {

        java.io.FileInputStream in = new java.io.FileInputStream("out.txt");

        java.nio.channels.FileChannel fc = in.getChannel();
        java.nio.ByteBuffer bb = java.nio.ByteBuffer.allocate(10);

        while(fc.read(bb) >= 0) {
            bb.flip();
            while(bb.hasRemaining()) {
                System.out.println((char)bb.get());
            }
            bb.clear();
        }

        System.exit(0);
    }
}
</code>```

No guarantees that this code is best practice.

This leaves the option suggested by Mike of periodically checking if there is new data to be read from the file. This then requires user intervention to close the file reader when it is determined that the reading is completed. Or, the reader needs to be made aware the content of the file and be able to determine and end of write condition. If the content were XML, the end of document could be used to signal this.

Body:
The answer seems to be "no" ... and "yes". There seems to be no real way to know if a file is open for writing by another application. So, reading from such a file will just progress until content is exhausted. I took Mike's advice and wrote some test code:

Writer.java writes a string to file and then waits for the user to hit enter before writing another line to file. The idea being that it could be started up, then a reader can be started to see how it copes with the "partial" file. The reader I wrote is in Reader.java.

Writer.java

public class Writer extends Object
{
    Writer () {

    }

    public static String[] strings =
        {
            "Hello World",
            "Goodbye World"
        };

    public static void main(String[] args)
        throws java.io.IOException {

        java.io.PrintWriter pw =
            new java.io.PrintWriter(new java.io.FileOutputStream("out.txt"), true);

        for(String s : strings) {
            pw.println(s);
            System.in.read();
        }

        pw.close();
    }
}

Reader.java

public class Reader extends Object
{
    Reader () {

    }

    public static void main(String[] args)
        throws Exception {

        java.io.FileInputStream in = new java.io.FileInputStream("out.txt");

        java.nio.channels.FileChannel fc = in.getChannel();
        java.nio.ByteBuffer bb = java.nio.ByteBuffer.allocate(10);

        while(fc.read(bb) >= 0) {
            bb.flip();
            while(bb.hasRemaining()) {
                System.out.println((char)bb.get());
            }
            bb.clear();
        }

        System.exit(0);
    }
}

No guarantees that this code is best practice.

This leaves the option suggested by Mike of periodically checking if there is new data to be read from the file. This then requires user intervention to close the file reader when it is determined that the reading is completed. Or, the reader needs to be made aware the content of the file and be able to determine and end of write condition. If the content were XML, the end of document could be used to signal this.

ContentLicense: CC BY-SA 2.5


问:
How can I split a URL string up into separate parts in Python?
I decided that I'll learn Python tonight :)
I know C pretty well (wrote an OS in it), so I'm not a noob in programming, so everything in Python seems pretty easy, but I don't know how to solve this problem:
let's say I have this address:

http://example.com/random/folder/path.html

Now how can I create two strings from this, one containing the "base" name of the server, so in this example it would be

http://example.com/

and another containing the thing without the last filename, so in this example it would be

http://example.com/random/folder/

Also I of course know the possibility to just find the third and last slash respectively, but is there a better way?

Also it would be cool to have the trailing slash in both cases, but I don't care since it can be added easily.
So is there a good, fast, effective solution for this? Or is there only "my" solution, finding the slashes?

答:
In Python, a lot of operations are done using lists.  The urlparse module mentioned by Sebasian Dietz may well solve your specific problem, but if you're generally interested in Pythonic ways to find slashes in strings, for example, try something like this:

```<code>url = 'http://example.com/random/folder/path.html'

# Create a list of each bit between slashes
slashparts = url.split('/')

# Now join back the first three sections 'http:', '' and 'example.com'
basename = '/'.join(slashparts[:3]) + '/'

# All except the last one
dirname = '/'.join(slashparts[:-1]) + '/'

print 'slashparts = %s' % slashparts
print 'basename = %s' % basename
print 'dirname = %s' % dirname
</code>```

The output of this program is this:

```
slashparts = ['http:', '', 'example.com', 'random', 'folder', 'path.html']
basename = http://example.com/
dirname = http://example.com/random/folder/
```

The interesting bits are split, join, the slice notation array[A:B] (including negatives for offsets-from-the-end) and, as a bonus, the % operator on strings to give printf-style formatting.

OwnerDisplayName: Language

LastEditorDisplayName: Simucal

Body:
In Python, a lot of operations are done using lists.  The urlparse module mentioned by Sebasian Dietz may well solve your specific problem, but if you're generally interested in Pythonic ways to find slashes in strings, for example, try something like this:

url = 'http://example.com/random/folder/path.html'

# Create a list of each bit between slashes
slashparts = url.split('/')

# Now join back the first three sections 'http:', '' and 'example.com'
basename = '/'.join(slashparts[:3]) + '/'

# All except the last one
dirname = '/'.join(slashparts[:-1]) + '/'

print 'slashparts = %s' % slashparts
print 'basename = %s' % basename
print 'dirname = %s' % dirname

The output of this program is this:

slashparts = ['http:', '', 'example.com', 'random', 'folder', 'path.html']
basename = http://example.com/
dirname = http://example.com/random/folder/

The interesting bits are split, join, the slice notation array[A:B] (including negatives for offsets-from-the-end) and, as a bonus, the % operator on strings to give printf-style formatting.

OwnerDisplayName: Paul Stephenson


问:
WPF - Why doesn't Microsoft supply a decent set of most-used controls ?
I've been playing with WPF for some months now, and I quite like it.
But one of the things I don't get is why MS doesn't put a little more effort in helping developers by supplying basic controls, and I need to get this off my chest :)

For example, I figure most applications somewhere will need to let you edit some properties - for configuration or whatever.
What would be the most used types in a proprety-grid editor ?

text

numbers (byte, float/double, int, etc)

colors

....etc.

So why isn't there even something as simple as a control to edit numbers ? Like a generic NumericUpDown control that allows you to type in numbers (no text, no pasting invalid input) or spin them up/down according to some given rules (decimal, floating point, min/maxvalue) ?
Why isn't there a generic colorpicker, so people get the same user-experience in every application ?
Why isn't there a standard implementation of a SearchTextBox, a BreadCrumb-control, or all these other standard control types users have gotten accustomed to the last 10 years ?

(..but at least they DID have the time to implement a generic splashscreen - because everyone knows that greatly increases user-productivity....)

The well-known ideal is always to give people the same user-experience over different applications. So even if some of those controls would be easy to make - it would be preferred to have one version over different applications.

I see people all over the internet trying to do the same stuff over and over again.
Okay, so MS started a WPF Toolkit project on Codeplex that tries to implement some controls, but only did so half-heartedly and is completely dead by now (last update of the roadmap dates back to Mar 21 2009).

The result of this is that a lot of people starting a WPF-project end up spending a lot of time on trying to figure out how to create some generic controls and get really frustrated.

Wasn't the mantra "Developers, developers, developers!" ..?

/Rant

答: Because its ridiculously easy to make these in WPF. With WPF and silverlight microsoft's focus is on a core framework that makes many tasks (such as stylable controls) dead simple. Tools are more important than prebuilt controls. They are focusing on the NEXT thing rather than a better Winforms. </p>


问:
Particles.js creates unclickable screen in Angular 2
I am having an issue with Particles.js.

Whenever I load in particles, the search-box becomes un-clickable (I can still select it by tabbing to it).

Below is an example of the problem

The searchbox is un-selectable

Here is how I load in Particles in my:

index.html

```<code><!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>Title</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>

<body>
  <app-root></app-root>
  <div id="particles-js" style="position: absolute; display: block; top: 0; left: 0; width: 100%; height: 100%; z-index: 0;"> </div>
  <script src="https://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js"></script>
</body>
</html>
</code>```

And I load it in my page here, in my:

landingpage.component

```<code>  ngOnInit(): void {
    //particles
    particlesJS.load('particles-js', 'particles.json', null);
  }
</code>```

There are no errors when I run the page, so I'm not sure what's going wrong. I know it's possible to fix, because https://rocket.chat/ seems to do what I'm attempting, and it works fine.

How can I fix the particles so that I can select page elements?

答:
found the problem

I needed to set the z-index in my landingpage container to higher than that of the z-index in my index.html

```<code><body>
  <app-root></app-root>
  <div id="particles-js" style="position: absolute; display: block; top: 0; left: 0; width: 100%; height: 100%; z-index: 0;"> </div>
  <script src="https://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js"></script>
</body>
</code>```

And I set my contentContainer div to z-index: 5

```<code><div class="landingpageContainer">
  <div class="background" [ngStyle]="{'background-image':'url(' + backgroundPlaceholder.info.name + ')'}">
    <div class="contentContainer" style="z-index: 5;">
      <img width="300" src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxOS4xLjAsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4NCjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iTGF5ZXJfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiDQoJIHZpZXdCb3g9IjAgMCAyNTAgMjUwIiBzdHlsZT0iZW5hYmxlLWJhY2tncm91bmQ6bmV3IDAgMCAyNTAgMjUwOyIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+DQo8c3R5bGUgdHlwZT0idGV4dC9jc3MiPg0KCS5zdDB7ZmlsbDojREQwMDMxO30NCgkuc3Qxe2ZpbGw6I0MzMDAyRjt9DQoJLnN0MntmaWxsOiNGRkZGRkY7fQ0KPC9zdHlsZT4NCjxnPg0KCTxwb2x5Z29uIGNsYXNzPSJzdDAiIHBvaW50cz0iMTI1LDMwIDEyNSwzMCAxMjUsMzAgMzEuOSw2My4yIDQ2LjEsMTg2LjMgMTI1LDIzMCAxMjUsMjMwIDEyNSwyMzAgMjAzLjksMTg2LjMgMjE4LjEsNjMuMiAJIi8+DQoJPHBvbHlnb24gY2xhc3M9InN0MSIgcG9pbnRzPSIxMjUsMzAgMTI1LDUyLjIgMTI1LDUyLjEgMTI1LDE1My40IDEyNSwxNTMuNCAxMjUsMjMwIDEyNSwyMzAgMjAzLjksMTg2LjMgMjE4LjEsNjMuMiAxMjUsMzAgCSIvPg0KCTxwYXRoIGNsYXNzPSJzdDIiIGQ9Ik0xMjUsNTIuMUw2Ni44LDE4Mi42aDBoMjEuN2gwbDExLjctMjkuMmg0OS40bDExLjcsMjkuMmgwaDIxLjdoMEwxMjUsNTIuMUwxMjUsNTIuMUwxMjUsNTIuMUwxMjUsNTIuMQ0KCQlMMTI1LDUyLjF6IE0xNDIsMTM1LjRIMTA4bDE3LTQwLjlMMTQyLDEzNS40eiIvPg0KPC9nPg0KPC9zdmc+DQo="
      />
      <h1>Enter a show</h1>
      <div class="inputBoxArea">
        <input type="text" class="inputArea" placeholder={{backgroundPlaceholder.info.placeholderText}} [(ngModel)]="keystroke" (ngModelChange)="getKey($event)">
      </div>
      <div class="resultListArea">
        <ol>
          <li (click)="setTitle(list)" [routerLink]="['/details', list.id]" *ngFor="let list of shows"> <img class="liPosters" src="https://image.tmdb.org/t/p/w92/{{list.poster}}" />
            <div class="title">{{list.show}}</div> (
            <div class="year">{{list.year}}</div>)
          </li>
        </ol>
      </div>
    </div>
  </div>
</code>```

Body:
I am having an issue with Particles.js.

Whenever I load in particles, the search-box becomes un-clickable (I can still select it by tabbing to it).

Below is an example of the problem

The searchbox is un-selectable

Here is how I load in Particles in my:

index.html

<!doctype html>

  <meta charset="utf-8">
  <title>Title</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <app-root></app-root>

And I load it in my page here, in my:

landingpage.component

  ngOnInit(): void {
    //particles
    particlesJS.load('particles-js', 'particles.json', null);
  }

There are no errors when I run the page, so I'm not sure what's going wrong. I know it's possible to fix, because https://rocket.chat/ seems to do what I'm attempting, and it works fine.

How can I fix the particles so that I can select page elements?

Body:
found the problem

I needed to set the z-index in my landingpage container to higher than that of the z-index in my index.html

<body>
  <app-root></app-root>
  <div id="particles-js" style="position: absolute; display: block; top: 0; left: 0; width: 100%; height: 100%; z-index: 0;"> </div>
  <script src="https://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js"></script>
</body>

And I set my contentContainer div to z-index: 5

<div class="landingpageContainer">
  <div class="background" [ngStyle]="{'background-image':'url(' + backgroundPlaceholder.info.name + ')'}">
    <div class="contentContainer" style="z-index: 5;">
      <img width="300" src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxOS4xLjAsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4NCjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iTGF5ZXJfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiDQoJIHZpZXdCb3g9IjAgMCAyNTAgMjUwIiBzdHlsZT0iZW5hYmxlLWJhY2tncm91bmQ6bmV3IDAgMCAyNTAgMjUwOyIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+DQo8c3R5bGUgdHlwZT0idGV4dC9jc3MiPg0KCS5zdDB7ZmlsbDojREQwMDMxO30NCgkuc3Qxe2ZpbGw6I0MzMDAyRjt9DQoJLnN0MntmaWxsOiNGRkZGRkY7fQ0KPC9zdHlsZT4NCjxnPg0KCTxwb2x5Z29uIGNsYXNzPSJzdDAiIHBvaW50cz0iMTI1LDMwIDEyNSwzMCAxMjUsMzAgMzEuOSw2My4yIDQ2LjEsMTg2LjMgMTI1LDIzMCAxMjUsMjMwIDEyNSwyMzAgMjAzLjksMTg2LjMgMjE4LjEsNjMuMiAJIi8+DQoJPHBvbHlnb24gY2xhc3M9InN0MSIgcG9pbnRzPSIxMjUsMzAgMTI1LDUyLjIgMTI1LDUyLjEgMTI1LDE1My40IDEyNSwxNTMuNCAxMjUsMjMwIDEyNSwyMzAgMjAzLjksMTg2LjMgMjE4LjEsNjMuMiAxMjUsMzAgCSIvPg0KCTxwYXRoIGNsYXNzPSJzdDIiIGQ9Ik0xMjUsNTIuMUw2Ni44LDE4Mi42aDBoMjEuN2gwbDExLjctMjkuMmg0OS40bDExLjcsMjkuMmgwaDIxLjdoMEwxMjUsNTIuMUwxMjUsNTIuMUwxMjUsNTIuMUwxMjUsNTIuMQ0KCQlMMTI1LDUyLjF6IE0xNDIsMTM1LjRIMTA4bDE3LTQwLjlMMTQyLDEzNS40eiIvPg0KPC9nPg0KPC9zdmc+DQo="
      />
      <h1>Enter a show</h1>
      <div class="inputBoxArea">
        <input type="text" class="inputArea" placeholder={{backgroundPlaceholder.info.placeholderText}} [(ngModel)]="keystroke" (ngModelChange)="getKey($event)">
      </div>
      <div class="resultListArea">
        <ol>
          <li (click)="setTitle(list)" [routerLink]="['/details', list.id]" *ngFor="let list of shows"> <img class="liPosters" src="https://image.tmdb.org/t/p/w92/{{list.poster}}" />
            <div class="title">{{list.show}}</div> (
            <div class="year">{{list.year}}</div>)
          </li>
        </ol>
      </div>
    </div>
  </div>


问:
Elasticsearch post_filter on nested types not filtering on aggregations
Hello Elasticsearch gurus, I need your help!
We're using Elasticsearch v5.4 and
I have multiple nested types in elasticsearch in the form of:

```<code>"testLookup" : [
  {
    "id": 1001,
    "name": "test1"
  },
  {
    "id": 1002,
    "name": "test2"
  }
]
</code>```

which I'm trying to display the names as checkbox options in a filter.

I was trying to use the post_filter top level element to basically filter the aggregations so I can update and display ONLY the affected filter options, kinda like how it is being used on this demo site: http://demo.searchkit.co

```<code>  "post_filter": {
    "bool":{
      "must": [
     {
      "nested" : {
        "path" : "testLookup",
        "query": {
          "bool": {
            "filter":{
              "bool":{
                "should":[
                        { "term":  { "perTestLookup.name.keyword": "Adele"}}
         ]
            }
        }
      }
    }
    }
     },
              {
    "nested" : {
      "path" : "testLookup2",
      "query": {
        "bool": {
          "filter":{
            "bool":{
              "should":[
                { "term":  { "perTestLookup2.name.keyword": "Gene" }}
         ]
            }
        }
      }
    }
    }
    }
  ]
 }
}
</code>```

If i'm not mistaken I think what the post_filter does is apply the filter for each of the aggregations before the search request is sent, which you can observe that by looking into the request payload of the search filter after you click one of the filter checkboxes.

However, I can not get the post_filter to apply the filters to the aggregations, the filters are just not being applied. Why is this the case? is post_filter for nested types not supported?

Any tips or guidance will be greatly appreciated. Thank you!

答:
Note: I do not have any searchkit experience.

The post_filter in an Elasticsearch request is executed after the aggregations are calculated to reduce the hits result further. See the docs about post_filter.

The idea behind this is the fact that in a faceted search (i.e. imagine filtering by category), you still want to retrieve that category counts for all categories in your aggregations, but you want to filter for that clicked category in your the documents you are searching.

So this is expected behaviour from the Elasticsearch perspective.

Body:
Hello Elasticsearch gurus, I need your help!
We're using Elasticsearch v5.4 and
I have multiple nested types in elasticsearch in the form of:

"testLookup" : [
  {
    "id": 1001,
    "name": "test1"
  },
  {
    "id": 1002,
    "name": "test2"
  }
]

which I'm trying to display the names as checkbox options in a filter.

I was trying to use the post_filter top level element to basically filter the aggregations so I can update and display ONLY the affected filter options, kinda like how it is being used on this demo site: http://demo.searchkit.co

  "post_filter": {
    "bool":{
      "must": [
     {
      "nested" : {
        "path" : "testLookup",
        "query": {
          "bool": {
            "filter":{
              "bool":{
                "should":[
                        { "term":  { "perTestLookup.name.keyword": "Adele"}}
         ]
            }
        }
      }
    }
    }
     },
              {
    "nested" : {
      "path" : "testLookup2",
      "query": {
        "bool": {
          "filter":{
            "bool":{
              "should":[
                { "term":  { "perTestLookup2.name.keyword": "Gene" }}
         ]
            }
        }
      }
    }
    }
    }
  ]
 }
}

If i'm not mistaken I think what the post_filter does is apply the filter for each of the aggregations before the search request is sent, which you can observe that by looking into the request payload of the search filter after you click one of the filter checkboxes.

However, I can not get the post_filter to apply the filters to the aggregations, the filters are just not being applied. Why is this the case? is post_filter for nested types not supported?

Any tips or guidance will be greatly appreciated. Thank you!


问:
How to test faster GUI applications?
I'd like to know to test faster my GUI applications.

For the backend I got a good set of unit-tests, so I think that's quite ok and I can iterate quite fast.

But to test the frontend logic I find myself running over and over repeating the same sequence of events to test certain part of the logic... and that feels like I'm doing something clearly wrong here because my iteration cycle is not as faster as I'd like it to.

So, could you suggest me a good way to test GUI applications? in particular I'm pretty much interested to know how to speed-up my PyQt apps testing cycle.

答: Looks like pywinauto should be good for PyQt5 now (using backend="uia" released in November, 2016).

Title: How to test faster GUI applications?


问:
How to find URLs in a string with PHP?
I know there is filter_var() but I don't want to validate a URL, I want to spot them in a whole text (e.g. a tweet). So you got any idea?

答:
The regular expression solutions are fine, but here's another simple way: use strpos.

```
if(strpos($text, "http://") !== false) {
   print "url found";
}

```

use stripos for case-insensitive.

Also, be aware that the other regular expression examples don't check for 'https' or just urls starting with 'www' only!

http://php.net/manual/en/function.strpos.php

Title: How to find URLs in a string with PHP?

Body:
The regular expression solutions are fine, but here's another simple way: use strpos.

if(strpos($text, "http://") !== false) {
   print "url found";
}

use stripos for case-insensitive.

Also, be aware that the other regular expression examples don't check for 'https' or just urls starting with 'www' only!

http://php.net/manual/en/function.strpos.php


问:
reactjs npm start ELIFECYCLE error
This is my first attempt at learning react, and it's started terribly. I've gone through the instructions directed here: https://facebook.github.io/react/docs/installation.html on the "Create a New App" tab exactly. Haven't done anything differently.

I'm using node 8.1.3, and npm 5.0.4

(I've also tried downgrading node to 6.11 without success).

I don't get any errors at all during installation.

When I run npm start, I get this super unhelpful error:

```<code>Starting the development server...

events.js:182
  throw er; // Unhandled 'error' event
  ^

Error: watch /var/phil-machine/Code/react/test1/public ENOSPC
at exports._errnoException (util.js:1022:11)
at FSWatcher.start (fs.js:1384:19)
at Object.fs.watch (fs.js:1410:11)
at createFsWatchInstance (/var/phil-machine/Code/react/test1/node_modules/chokidar/lib/nodefs-handler.js:37:15)
at setFsWatchListener (/var/phil-machine/Code/react/test1/node_modules/chokidar/lib/nodefs-handler.js:80:15)
at FSWatcher.NodeFsHandler._watchWithNodeFs (/var/phil-machine/Code/react/test1/node_modules/chokidar/lib/nodefs-handler.js:228:14)
at FSWatcher.NodeFsHandler._handleDir (/var/phil-machine/Code/react/test1/node_modules/chokidar/lib/nodefs-handler.js:407:19)
at FSWatcher.<anonymous> (/var/phil-machine/Code/react/test1/node_modules/chokidar/lib/nodefs-handler.js:455:19)
at FSWatcher.<anonymous> (/var/phil-machine/Code/react/test1/node_modules/chokidar/lib/nodefs-handler.js:460:16)
at FSReqWrap.oncomplete (fs.js:153:5)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! test1@0.1.0 start: `react-scripts start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the test1@0.1.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/phil/.npm/_logs/2017-07-05T23_52_25_652Z-debug.log
</code>```

I'm at a loss. I've googled it (as best as I can - I'm not even sure what to google apart from the generic "react start error"), and got this answer https://stackoverflow.com/a/39960890/1569591 but that didn't help either.

When I run npm start it brings up the above error, and opens the bowser with a "Site cant be reached" error.

Can anyone help point me in the direction of how to fix this?

I've also tried changing the start command to use a different port:

```<code>PORT=3001 react-scripts start
</code>```

Didn't work either.

答:
I'm not entirely sure if this was the issue, but I've got it working.

It turns out another service, Grafana was using localhost port 3000. I removed Grafana and it still failed. After rebooting it appeared to work.

Again, I'm not sure if this will solve it 100% if others have the same problem, but this is what solved it for me.

Title: reactjs npm start ELIFECYCLE error

Body:
This is my first attempt at learning react, and it's started terribly. I've gone through the instructions directed here: https://facebook.github.io/react/docs/installation.html on the "Create a New App" tab exactly. Haven't done anything differently.

I'm using node 8.1.3, and npm 5.0.4

(I've also tried downgrading node to 6.11 without success).

I don't get any errors at all during installation.

When I run npm start, I get this super unhelpful error:

Starting the development server...

events.js:182
  throw er; // Unhandled 'error' event
  ^

Error: watch /var/phil-machine/Code/react/test1/public ENOSPC
at exports._errnoException (util.js:1022:11)
at FSWatcher.start (fs.js:1384:19)
at Object.fs.watch (fs.js:1410:11)
at createFsWatchInstance (/var/phil-machine/Code/react/test1/node_modules/chokidar/lib/nodefs-handler.js:37:15)
at setFsWatchListener (/var/phil-machine/Code/react/test1/node_modules/chokidar/lib/nodefs-handler.js:80:15)
at FSWatcher.NodeFsHandler._watchWithNodeFs (/var/phil-machine/Code/react/test1/node_modules/chokidar/lib/nodefs-handler.js:228:14)
at FSWatcher.NodeFsHandler._handleDir (/var/phil-machine/Code/react/test1/node_modules/chokidar/lib/nodefs-handler.js:407:19)
at FSWatcher.<anonymous> (/var/phil-machine/Code/react/test1/node_modules/chokidar/lib/nodefs-handler.js:455:19)
at FSWatcher.<anonymous> (/var/phil-machine/Code/react/test1/node_modules/chokidar/lib/nodefs-handler.js:460:16)
at FSReqWrap.oncomplete (fs.js:153:5)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! test1@0.1.0 start: `react-scripts start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the test1@0.1.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/phil/.npm/_logs/2017-07-05T23_52_25_652Z-debug.log

I'm at a loss. I've googled it (as best as I can - I'm not even sure what to google apart from the generic "react start error"), and got this answer https://stackoverflow.com/a/39960890/1569591 but that didn't help either.

When I run npm start it brings up the above error, and opens the bowser with a "Site cant be reached" error.

Can anyone help point me in the direction of how to fix this?

I've also tried changing the start command to use a different port:

PORT=3001 react-scripts start

Didn't work either.


问:
vue-stripe-elements - Configuration of one file
I'm tyrnig to use vue-stripe-elements https://github.com/fromatob/vue-stripe-elements.

It is mentionned import { stripeKey, stripeOptions } from './stripeConfig.json'

But I don't know what the file stripeConfig.json should look like. I'm sure it should contains my stripe keys but I don't know which format it should be.

答:
Per this this Github issue, I originally addressed this by renaming ./stripeConfig.json to ./stripeConfig.js and entering the following:

```<code>export const stripeKey = 'pk_test_XXXXXXXXXXXXXXXXXXXXXXXX'
export const stripeOptions = {}
</code>```

Just fill in the X part with your public key from Stripe.

Regarding stripeOptions being empty, this worked as a basic config for me, but I think you can fill in other options by referring to Stripe Elements Documentation.

Later, I decided to skip loading the .js file altogether and simply return those variables from my data function.

Hope that helps!

Body:
Per this this Github issue, I originally addressed this by renaming ./stripeConfig.json to ./stripeConfig.js and entering the following:

export const stripeKey = 'pk_test_XXXXXXXXXXXXXXXXXXXXXXXX'
export const stripeOptions = {}

Just fill in the X part with your public key from Stripe.

Regarding stripeOptions being empty, this worked as a basic config for me, but I think you can fill in other options by referring to Stripe Elements Documentation.

Later, I decided to skip loading the .js file altogether and simply return those variables from my data function.

Hope that helps!


问:
Error getting response from QnA maker API with body parameters
I wrote the below code for calling microsoft QnA maker generate answer API.

var http=require('https');

var demo=[];
console.log("Doing the Post Operations...");
// Define an demo object with properties and values. This object will be used for POST request.

var demo=JSON.stringify({"question":"hi"});

var extServerOptionsPost={
  host:'westus.api.cognitive.microsoft.com',
  path:'/qnamaker/v2.0/knowledgebases/<my kb id>/generateAnswer',
  port:443,
  method:'POST',
  headers:{
    'Ocp-Apim-Subscription-Key':'my key',
    'Content-Type':'application/json'
  }
};

var reqPost=http.request(extServerOptionsPost,function(res){
console.log("response statusCode: ",res.statusCode);
res.on('data',function(data){
console.log('Posting Result:\n');
process.stdout.write(data);
console.log('\n\n POST Operation Completed');
});
});

reqPost.write(demo);

reqPost.end();
reqPost.on('error',function(e){
 console.error(e);
});```

However, the process.stdout.write(data);part is printing error code :Unspecified , along with a message "please try after some time".
What I think is happening here that it is returning the response before the body parameter is being written.So my question is, how do I get the response of the API printed in my console. Any help will be appreciated.

答:
The https package is flexible, but not particularly user-friendly.  Might you try request instead?

Anyway, to get your POST to work, you need to add the Content-Length header.  See this for a similar question.

```<code>headers:{
    'Ocp-Apim-Subscription-Key':'my key',
    'Content-Type':'application/json',
    'Content-Length':Buffer.byteLength(demo)
}
</code>```

Body:
I wrote the below code for calling microsoft QnA maker generate answer API.

var http=require('https');

var demo=[];
console.log("Doing the Post Operations...");
// Define an demo object with properties and values. This object will be used for POST request.

var demo=JSON.stringify({"question":"hi"});

var extServerOptionsPost={
  host:'westus.api.cognitive.microsoft.com',
  path:'/qnamaker/v2.0/knowledgebases/<my kb id>/generateAnswer',
  port:443,
  method:'POST',
  headers:{
    'Ocp-Apim-Subscription-Key':'my key',
    'Content-Type':'application/json'
  }
};

var reqPost=http.request(extServerOptionsPost,function(res){
console.log("response statusCode: ",res.statusCode);
res.on('data',function(data){
console.log('Posting Result:\n');
process.stdout.write(data);
console.log('\n\n POST Operation Completed');
});
});

reqPost.write(demo);

reqPost.end();
reqPost.on('error',function(e){
 console.error(e);
});

However, the process.stdout.write(data);part is printing error code :Unspecified , along with a message "please try after some time".
What I think is happening here that it is returning the response before the body parameter is being written.So my question is, how do I get the response of the API printed in my console. Any help will be appreciated.

Body:
The https package is flexible, but not particularly user-friendly.  Might you try request instead?

Anyway, to get your POST to work, you need to add the Content-Length header.  See this for a similar question.

headers:{
    'Ocp-Apim-Subscription-Key':'my key',
    'Content-Type':'application/json',
    'Content-Length':Buffer.byteLength(demo)
}


问:
HSM AES Key Extraction
I have a Thales nShield HSM in which I have created a (CKA_SENSATIVE, false) AES key that I want to extract but, I can not figure out how to do it in java at all. My Key creation looks just like this:</p>

```<code>CK_ATTRIBUTE[] aesKeyObject = new CK_ATTRIBUTE[14];

    try
    {
        aesKeyObject[0] = new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY);
        aesKeyObject[1] = new CK_ATTRIBUTE(CKA_KEY_TYPE, CKK_AES);
        aesKeyObject[2] = new CK_ATTRIBUTE(CKA_VALUE_LEN, 32);
        aesKeyObject[3] = new CK_ATTRIBUTE(CKA_TOKEN, true);
        aesKeyObject[4] = new CK_ATTRIBUTE(CKA_LABEL, "TestAES".getBytes());
        aesKeyObject[5] = new CK_ATTRIBUTE(CKA_PRIVATE, true);
        aesKeyObject[6] = new CK_ATTRIBUTE(CKA_EXTRACTABLE, true);
        aesKeyObject[7] = new CK_ATTRIBUTE(CKA_WRAP, true);
        aesKeyObject[8] = new CK_ATTRIBUTE(CKA_UNWRAP, true);
        aesKeyObject[9] = new CK_ATTRIBUTE(CKA_ENCRYPT, true);
        aesKeyObject[10] = new CK_ATTRIBUTE(CKA_DECRYPT, true);
        aesKeyObject[11] = new CK_ATTRIBUTE(CKA_TRUSTED, true);
        aesKeyObject[12] = new CK_ATTRIBUTE(CKA_ID, 1550);
        aesKeyObject[13] = new CK_ATTRIBUTE(CKA_SENSITIVE, false);

        CK_MECHANISM mech = new CK_MECHANISM(CKM_AES_KEY_GEN);

        long newAESKeyHandle = p11.C_GenerateKey(hSession, mech, aesKeyObject);
    }catch(Exception e)
    {
    }
</code>```

答: You need to read CKA_VALUE attribute of generated key object with C_GetAttributeValue function.

Title: HSM AES Key Extraction

Body:
I have a Thales nShield HSM in which I have created a (CKA_SENSATIVE, false) AES key that I want to extract but, I can not figure out how to do it in java at all. My Key creation looks just like this:

CK_ATTRIBUTE[] aesKeyObject = new CK_ATTRIBUTE[14];

    try
    {
        aesKeyObject[0] = new CK_ATTRIBUTE(CKA_CLASS, CKO_SECRET_KEY);
        aesKeyObject[1] = new CK_ATTRIBUTE(CKA_KEY_TYPE, CKK_AES);
        aesKeyObject[2] = new CK_ATTRIBUTE(CKA_VALUE_LEN, 32);
        aesKeyObject[3] = new CK_ATTRIBUTE(CKA_TOKEN, true);
        aesKeyObject[4] = new CK_ATTRIBUTE(CKA_LABEL, "TestAES".getBytes());
        aesKeyObject[5] = new CK_ATTRIBUTE(CKA_PRIVATE, true);
        aesKeyObject[6] = new CK_ATTRIBUTE(CKA_EXTRACTABLE, true);
        aesKeyObject[7] = new CK_ATTRIBUTE(CKA_WRAP, true);
        aesKeyObject[8] = new CK_ATTRIBUTE(CKA_UNWRAP, true);
        aesKeyObject[9] = new CK_ATTRIBUTE(CKA_ENCRYPT, true);
        aesKeyObject[10] = new CK_ATTRIBUTE(CKA_DECRYPT, true);
        aesKeyObject[11] = new CK_ATTRIBUTE(CKA_TRUSTED, true);
        aesKeyObject[12] = new CK_ATTRIBUTE(CKA_ID, 1550);
        aesKeyObject[13] = new CK_ATTRIBUTE(CKA_SENSITIVE, false);

        CK_MECHANISM mech = new CK_MECHANISM(CKM_AES_KEY_GEN);

        long newAESKeyHandle = p11.C_GenerateKey(hSession, mech, aesKeyObject);
    }catch(Exception e)
    {
    }


问:
Convert cell array of numbers to matrix (cell2mat) while converting empties to zeros
I have a function that uses strfind in a cellfun call to find which string items in a cell array match a specified string. For example:

```<code>cellfun( @(x) strfind( x , 'openmask'), fileNames, 'uniformoutput', false)
</code>```

The original cell matrix is like this:

```<code>fileNames = {'sub11att-openmask.txt', 'sub13det-masking', ...};
</code>```

The result for this looks like this:

```<code>[10]    []    [10]    []    [9]    []
</code>```

I am trying to find a function that will convert this to:

```<code>10  0  10  0  9  0
</code>```

Using cell2mat I get:

```<code>10  10  9
</code>```

So I have to use this currently:

```<code>x(cellfun('isempty', x))={0};
cell2mat(x);
</code>```

Is there a function that is cleaner than this (i.e. a one-liner solution)?

Thanks.

答:
For a new variable y:

```<code>y(~cellfun('isempty', x)) = cell2mat(x);
</code>```

It will break if a cell has more than one element tough.

Body:
I have a function that uses strfind in a cellfun call to find which string items in a cell array match a specified string. For example:

cellfun( @(x) strfind( x , 'openmask'), fileNames, 'uniformoutput', false)

The original cell matrix is like this:

fileNames = {'sub11att-openmask.txt', 'sub13det-masking', ...};

The result for this looks like this:

[10]    []    [10]    []    [9]    []

I am trying to find a function that will convert this to:

10  0  10  0  9  0

Using cell2mat I get:

10  10  9

So I have to use this currently:

x(cellfun('isempty', x))={0};
cell2mat(x);

Is there a function that is cleaner than this (i.e. a one-liner solution)?

Thanks.

Body:
For a new variable y:

y(~cellfun('isempty', x)) = cell2mat(x);

It will break if a cell has more than one element tough.


问:
Should you correct compiler warnings about type conversions using explicit typecasts?
In my current project, the compiler shows hundreds of warnings about type conversions.

There is a lot of code like this

```<code>iVar = fVar1*fVar2/fVar3;
// or even
iVar = fVar1*fVar2/fVar3+.5f;
</code>```

which intentionally assign float values to int.

Of course, I could fix these warnings using

```<code>iVar = (int)(...);
</code>```

but that looks kind of ugly.

Would you rather live with the ugliness or live with the warnings?

Or is there even a clean solution?

答:
In my view, sometimes compilers spew out warnings for issues that I regard as not problematic.  In that case the solution may be to switch off those particular warnings.  But you must exercise caution and be sure that you aren't also hiding significant warnings.

For implicit type conversion warnings you want them some of the time, but not all the time.  Typically you want to ignore int to float conversions, but hear about others.  Ideally the compiler would allow you to configure warning reporting at that level of granularity.

Body:
In my current project, the compiler shows hundreds of warnings about type conversions.

There is a lot of code like this

iVar = fVar1*fVar2/fVar3;
// or even
iVar = fVar1*fVar2/fVar3+.5f;

which intentionally assign float values to int.

Of course, I could fix these warnings using

iVar = (int)(...);

but that looks kind of ugly.

Would you rather live with the ugliness or live with the warnings?

Or is there even a clean solution?


问:
r - Populate matrix with count data
Assume I have the following data:

```<code>df <- data.frame(teams=c("A", "B", "C", "D"),
            players=c(5,2,1,2),
            stringsAsFactors = FALSE)

> df
  teams players
1     A       5
2     B       2
3     C       1
4     D       2
</code>```

I want to fill a weighted 4x4 matrix that resembles the pairwise combinations of one player on a team to all other players on all other teams.

With this example, the output should look like this:

```<code>m <- matrix(c(4,2,1,2,5,1,1,2,5,2,0,2,5,2,1,1), nrow=4, ncol=4)
colnames(m) <- df$teams
rownames(m) <- df$teams

> m
  A B C D
A 4 5 5 5
B 2 1 2 2
C 1 1 0 1
D 2 2 2 1
</code>```

Note that a player from team A can play with:

4 other players from team A

2 players from team B

1 player from team C

2 players from team D

Does anyone know how to do this?

The real data holds thousands of teams and millions of players.

答:
You can try this:

```<code>size <- nrow(df)
diag(-1, size, size) + df$players

#     [,1] [,2] [,3] [,4]
#[1,]    4    5    5    5
#[2,]    2    1    2    2
#[3,]    1    1    0    1
#[4,]    2    2    2    1
</code>```

To set up the dimension names:

```<code>with(df, {
    size <- length(teams)
    m <- diag(-1, size, size) + players
    dimnames(m) <- list(teams, teams)
    m
})

#  A B C D
#A 4 5 5 5
#B 2 1 2 2
#C 1 1 0 1
#D 2 2 2 1
</code>```

Title: r - Populate matrix with count data

Body:
Assume I have the following data:

df <- data.frame(teams=c("A", "B", "C", "D"),
            players=c(5,2,1,2),
            stringsAsFactors = FALSE)

> df
  teams players
1     A       5
2     B       2
3     C       1
4     D       2

I want to fill a weighted 4x4 matrix that resembles the pairwise combinations of one player on a team to all other players on all other teams.

With this example, the output should look like this:

m <- matrix(c(4,2,1,2,5,1,1,2,5,2,0,2,5,2,1,1), nrow=4, ncol=4)
colnames(m) <- df$teams
rownames(m) <- df$teams

> m
  A B C D
A 4 5 5 5
B 2 1 2 2
C 1 1 0 1
D 2 2 2 1

Note that a player from team A can play with:

4 other players from team A

2 players from team B

1 player from team C

2 players from team D

Does anyone know how to do this?

The real data holds thousands of teams and millions of players.

Body:
You can try this:

size <- nrow(df)
diag(-1, size, size) + df$players

#     [,1] [,2] [,3] [,4]
#[1,]    4    5    5    5
#[2,]    2    1    2    2
#[3,]    1    1    0    1
#[4,]    2    2    2    1

To set up the dimension names:

with(df, {
    size <- length(teams)
    m <- diag(-1, size, size) + players
    dimnames(m) <- list(teams, teams)
    m
})

#  A B C D
#A 4 5 5 5
#B 2 1 2 2
#C 1 1 0 1
#D 2 2 2 1


问:
Is it possible to run batch files in Android?
Is it possible to run batch/bat file in Android?
Or is there any app to run it?

I hope there is some app what can run it.

答:
Is it possible to run batch/bat file in Android? Or is there any app to run it?

No, in Linux(Android) it's called a script file, the one with the .sh extension (optional) ... Dig in this direction.

Reference: SO Android shell script questions.


问:
Huge amounts of lag when using kafka mirrormaker
I have set up a MirrorMaker cluster that consumes topics from clusters around the world.

The issue is the latency between the mirror cluster (located in the EU) and a source cluster (located in the US) creates a massive spike in offset lag.

The mirrors are consuming 9 topics, each one consisting of 24 partitions.

Mirror Settings

```<code>/opt/kafka/bin/kafka-run-class.sh kafka.tools.MirrorMaker --consumer.config /opt/kafka/config/us1.consumer.properties --num.streams 48 --producer.config /opt/kafka/config/glb.producer.properties --whitelist="a,b,c,d,e,f,g,h,i"
</code>```

The producer.properties Settings

```<code>bootstrap.servers=localhost:9092
acks=-1
retries=2147483647
client.id=us.mm.producer
batch.size=200
linger.ms=10
</code>```

I am playing around with increasing the batch size and introducing linger to try and increase throughput, but so far my efforts have failed.

What is the best way to work the ideal batch size, and is introducing a linger.ms going to be useful with such high latency rates?

Apologies if this seems vague, but I am new to Kafka, and tuning a server is proving difficult.

答:
For tuning producer settings I recommend starting by following the methodology described in this slide deck:
https://www.slideshare.net/JiangjieQin/producer-performance-tuning-for-apache-kafka-63147600

However, since mirror maker is running in the target cluster, I suspect that the bottleneck might be consumption from the source cluster (US->EU), not producing the target cluster, which is co-located with mirror maker, if I understood correctly.

Body:
I have set up a MirrorMaker cluster that consumes topics from clusters around the world.

The issue is the latency between the mirror cluster (located in the EU) and a source cluster (located in the US) creates a massive spike in offset lag.

The mirrors are consuming 9 topics, each one consisting of 24 partitions.

Mirror Settings

/opt/kafka/bin/kafka-run-class.sh kafka.tools.MirrorMaker --consumer.config /opt/kafka/config/us1.consumer.properties --num.streams 48 --producer.config /opt/kafka/config/glb.producer.properties --whitelist="a,b,c,d,e,f,g,h,i"

The producer.properties Settings

bootstrap.servers=localhost:9092
acks=-1
retries=2147483647
client.id=us.mm.producer
batch.size=200
linger.ms=10

I am playing around with increasing the batch size and introducing linger to try and increase throughput, but so far my efforts have failed.

What is the best way to work the ideal batch size, and is introducing a linger.ms going to be useful with such high latency rates?

Apologies if this seems vague, but I am new to Kafka, and tuning a server is proving difficult.


问:
How to create/make rounded corner buttons in WPF?
I need to create a rounded corner glossy button in WPF. Can anyone please explain me what steps are needed?

答:
As alternative, you can code something like this:

```<code>    <Border
            x:Name="borderBtnAdd"
            BorderThickness="1"
            BorderBrush="DarkGray"
            CornerRadius="360"
            Height="30"
            Margin="0,10,10,0"
            VerticalAlignment="Top" HorizontalAlignment="Right" Width="30">
        <Image x:Name="btnAdd"
               Source="Recursos/Images/ic_add_circle_outline_black_24dp_2x.png"
               Width="{Binding borderBtnAdd.Width}" Height="{Binding borderBtnAdd.Height}"/>
    </Border>
</code>```

The "Button" will look something like this:

You could set any other content instead of the image.

Body:
As alternative, you can code something like this:

    <Border
            x:Name="borderBtnAdd"
            BorderThickness="1"
            BorderBrush="DarkGray"
            CornerRadius="360"
            Height="30"
            Margin="0,10,10,0"
            VerticalAlignment="Top" HorizontalAlignment="Right" Width="30">
        <Image x:Name="btnAdd"
               Source="Recursos/Images/ic_add_circle_outline_black_24dp_2x.png"
               Width="{Binding borderBtnAdd.Width}" Height="{Binding borderBtnAdd.Height}"/>
    </Border>

The "Button" will look something like this:

You could set any other content instead of the image.


问:
elasticsearch 5.x truncating keyword value
I have a very lengthy string to be indexed in elasticsearch. I am using field type "keyword" (as I need to do aggregate on it) for indexing this field. The underlying lucene engine has a byte limit of 32766. Is there any option,plugin etc in elasticsearch to truncate the characters after this length automatically.

I don't want to do truncation programmatically, I want elasticsearch to handle this truncation.

答: I dont think you should never aggregate on such long fields. You could use an ingest processor (i.e. the script processor to reduce the field length before indexing).</p>


问:
Disable Body Parameters in Query for Struts 1
Regular use of the login page in the application uses a DynaValidatorForm that upon clicking 'submit' makes a POST request containing the username and password for the user. It is then validated and dealt with in the associated action class.

Server code:

```<code>protected ActionForward performAction(ActionMapping mapping,
        ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    DynaValidatorForm dynaForm = (DynaValidatorForm) form;
    //validation here
    //...
    //
    Login login = new Login();
    PropertyUtils.copyProperties(login, dynaForm);
    //login object is used from here on out
</code>```

However, it is possible to log in by making a GET request with parameters in the URL i.e. www.my-site.com/LoginPage.do?loginName=username&password=password

Is there some way to disable Struts from using URL parameters in the form?

My current workaround is to use a filter that checks the query string and redirects if it contains a parameter that should be in the POST body, but I am looking for a more elegant solution. I cannot just disable GET as some other pages that need a similar solution need to be accessible by GET.

Any help is greatly appreciated!

答:
You can check the requests' method and return from the action if it's GET</p>

```<code>if(request.getMethod().equalsIgnoreCase("GET")
    return mapping.findForward("error");
</code>```

Body:
Regular use of the login page in the application uses a DynaValidatorForm that upon clicking 'submit' makes a POST request containing the username and password for the user. It is then validated and dealt with in the associated action class.

Server code:

protected ActionForward performAction(ActionMapping mapping,
        ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    DynaValidatorForm dynaForm = (DynaValidatorForm) form;
    //validation here
    //...
    //
    Login login = new Login();
    PropertyUtils.copyProperties(login, dynaForm);
    //login object is used from here on out

However, it is possible to log in by making a GET request with parameters in the URL i.e. www.my-site.com/LoginPage.do?loginName=username&password=password

Is there some way to disable Struts from using URL parameters in the form?

My current workaround is to use a filter that checks the query string and redirects if it contains a parameter that should be in the POST body, but I am looking for a more elegant solution. I cannot just disable GET as some other pages that need a similar solution need to be accessible by GET.

Any help is greatly appreciated!

Body:
You can check the requests' method and return from the action if it's GET

if(request.getMethod().equalsIgnoreCase("GET")
    return mapping.findForward("error");


问:
emulator is out of date error in android studio
I tried to start AVD from terminal in Android studio and I am getting following error, Please help

```<code> C:\Users\rudraneel-admin\AppData\Local\Android\sdk1\tools>emulator -avd API_25 -gpu off
    init: Could not find wglGetExtensionsStringARB!
    emulator: ERROR: GPU emulation is disabled.
    Only screen size of 800 X 1280 or smaller is supported when GPU emulation is disabled.
    emulator: ERROR: GPU emulation is disabled: software gpu and screen too large
    Hax is enabled
    Hax ram_size 0x60000000
    HAX is working and emulator runs in fast virt mode.
    audio: Failed to create voice `goldfish_audio_in'
    qemu-system-i386.exe: warning: opening audio input failed
    audio: Failed to create voice `adc'
    emulator: emulator window was out of view and was recentered

    Your emulator is out of date, please update by launching Android Studio:
     - Start Android Studio
     - Select menu "Tools > Android > SDK Manager"
     - Click "SDK Tools" tab
     - Check "Android SDK Tools" checkbox
     - Click "OK"
</code>```

答:
Only screen size of 800 X 1280 or smaller is supported when GPU emulation is disabled.
    emulator: ERROR: GPU emulation is disabled: software gpu and screen too large

Just create a new emulator. Previous one was created with configuration which not supported with such conditions.

Body:
I tried to start AVD from terminal in Android studio and I am getting following error, Please help

 C:\Users\rudraneel-admin\AppData\Local\Android\sdk1\tools>emulator -avd API_25 -gpu off
    init: Could not find wglGetExtensionsStringARB!
    emulator: ERROR: GPU emulation is disabled.
    Only screen size of 800 X 1280 or smaller is supported when GPU emulation is disabled.
    emulator: ERROR: GPU emulation is disabled: software gpu and screen too large
    Hax is enabled
    Hax ram_size 0x60000000
    HAX is working and emulator runs in fast virt mode.
    audio: Failed to create voice `goldfish_audio_in'
    qemu-system-i386.exe: warning: opening audio input failed
    audio: Failed to create voice `adc'
    emulator: emulator window was out of view and was recentered

    Your emulator is out of date, please update by launching Android Studio:
     - Start Android Studio
     - Select menu "Tools > Android > SDK Manager"
     - Click "SDK Tools" tab
     - Check "Android SDK Tools" checkbox
     - Click "OK"


问:
Defining two objects of differeent classes inside each class
I created two classes.

One class is called Frames, and inside it I defined a Jframe and an Image.

In another class which is called Panels, I defined a Jpanel.

I want to pass the panel to Frames class  using getPanel method and pass the image to the Panels class using getImage methods.

So I created a Frames object inside Panels class to call getImage
and created a Panels object inside Frames class to call getPanel.
But when I run the code, this message appears:

Exception in thread "main" java.lang.StackOverflowError.

```<code>public class panels{

    frames framesObject = new frames();
    JPanel panel = new JPanel(){
        public void painComponent(Graphics g){
            super.paintComponent(g);
            g.drawImage(frames.getImage(),0,0,null);
        }
    };

    public Jpanel getPanel(){
        return panel;
    }

}

public class frames{

    JFrame frame= new JFrame();
    Toolkit toolkit= Toolkit.getDefaultToolkit();
    Image image = toolkit.getImage("..source file..");
    panels panelsObject= new panels();
    frame.add(panelsObject.getPanel());

    public Image getImage(){
        return image;
}
</code>```

答:
In your case you're building an endless recursion, which leads to a stackoverflow...

I think the simplest way to get this to work would be to instantiate class 2 in class 1 and then pass the object of class 1 to class 2. Doing so, you have a reference to each other in both of them.

```<code>public class panels{

    public JPanel panel;

    public panels(frames framesObject){
        panel = new JPanel(){
            public void painComponent(Graphics g){
                super.paintComponent(g);
                g.drawImage(framesObject.getImage(),0,0,null);
            }
        };
    }

    public Jpanel getPanel(){
        return panel;
    }

}

public class frames{

    public Image image;

    public static void main(String[] args){
        new frames();
    }

    public frames(){
        JFrame frame= new JFrame();
        Toolkit toolkit= Toolkit.getDefaultToolkit();
        image = toolkit.getImage("..source file..");
        panels panelsObject= new panels(this);
        frame.add(panelsObject.getPanel());
    }

    public Image getImage(){
        return image;
    }
}
</code>```

Body:
I created two classes.

One class is called Frames, and inside it I defined a Jframe and an Image.

In another class which is called Panels, I defined a Jpanel.

I want to pass the panel to Frames class  using getPanel method and pass the image to the Panels class using getImage methods.

So I created a Frames object inside Panels class to call getImage
and created a Panels object inside Frames class to call getPanel.
But when I run the code, this message appears:

Exception in thread "main" java.lang.StackOverflowError.

public class panels{

    frames framesObject = new frames();
    JPanel panel = new JPanel(){
        public void painComponent(Graphics g){
            super.paintComponent(g);
            g.drawImage(frames.getImage(),0,0,null);
        }
    };

    public Jpanel getPanel(){
        return panel;
    }

}

public class frames{

    JFrame frame= new JFrame();
    Toolkit toolkit= Toolkit.getDefaultToolkit();
    Image image = toolkit.getImage("..source file..");
    panels panelsObject= new panels();
    frame.add(panelsObject.getPanel());

    public Image getImage(){
        return image;
}

Body:
In your case you're building an endless recursion, which leads to a stackoverflow...

I think the simplest way to get this to work would be to instantiate class 2 in class 1 and then pass the object of class 1 to class 2. Doing so, you have a reference to each other in both of them.

public class panels{

    public JPanel panel;

    public panels(frames framesObject){
        panel = new JPanel(){
            public void painComponent(Graphics g){
                super.paintComponent(g);
                g.drawImage(framesObject.getImage(),0,0,null);
            }
        };
    }

    public Jpanel getPanel(){
        return panel;
    }

}

public class frames{

    public Image image;

    public static void main(String[] args){
        new frames();
    }

    public frames(){
        JFrame frame= new JFrame();
        Toolkit toolkit= Toolkit.getDefaultToolkit();
        image = toolkit.getImage("..source file..");
        panels panelsObject= new panels(this);
        frame.add(panelsObject.getPanel());
    }

    public Image getImage(){
        return image;
    }
}


问:
Set HttpContext.Current.User from Thread.CurrentPrincipal
I have a security manager in my application that works for both windows and web, the process is simple, just takes the user and pwd and authenticates them against a database then sets the  Thread.CurrentPrincipal with a custom principal. For windows applications this works fine, but I have problems with web applications.

After the process of authentication, when I'm trying to set the Current.User to the custom principal from Thread.CurrentPrincipal this last one contains a GenericPrincipal. Am I doing something wrong? This is my code:

Login.aspx

```<code>protected void btnAuthenticate_Click(object sender, EventArgs e)
{
    SecurityManager.Authenticate("user","pwd"); // This is where I set the custom principal in Thread.CurrentPrincipal
    FormsAuthenticationTicket authenticationTicket = new FormsAuthenticationTicket(1,
                        "user",
                        DateTime.Now,
                        DateTime.Now.AddMinutes(30),
                        false,
                        "");

    string ticket = FormsAuthentication.Encrypt(authenticationTicket);
    HttpCookie authenticationCookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticket);
    Response.Cookies.Add(authenticationCookie);
    Response.Redirect(FormsAuthentication.GetRedirectUrl("user", false));
}
</code>```

Global.asax (This is where the problem appears)

```<code>protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
    HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
    if (authCookie == null)
        return;

    if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated && HttpContext.Current.User.Identity is FormsIdentity)
    {
        HttpContext.Current.User = System.Threading.Thread.CurrentPrincipal; //Here the value is GenericPrincipal
    }
</code>```

Thanks in advance for any help.

答:
JFYI, you can replace

```<code>if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated && HttpContext.Current.User.Identity is FormsIdentity) { }
</code>```

with

```<code>FormsIdentity formsIdentity = HttpContext.Current.User as FormsIdentity;
if (formsIdentity != null & formsIdentity.IsAuthenticated) { }
</code>```

to reduce the length of if-clause

Body:
I have a security manager in my application that works for both windows and web, the process is simple, just takes the user and pwd and authenticates them against a database then sets the  Thread.CurrentPrincipal with a custom principal. For windows applications this works fine, but I have problems with web applications.

After the process of authentication, when I'm trying to set the Current.User to the custom principal from Thread.CurrentPrincipal this last one contains a GenericPrincipal. Am I doing something wrong? This is my code:

Login.aspx

protected void btnAuthenticate_Click(object sender, EventArgs e)
{
    SecurityManager.Authenticate("user","pwd"); // This is where I set the custom principal in Thread.CurrentPrincipal
    FormsAuthenticationTicket authenticationTicket = new FormsAuthenticationTicket(1,
                        "user",
                        DateTime.Now,
                        DateTime.Now.AddMinutes(30),
                        false,
                        "");

    string ticket = FormsAuthentication.Encrypt(authenticationTicket);
    HttpCookie authenticationCookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticket);
    Response.Cookies.Add(authenticationCookie);
    Response.Redirect(FormsAuthentication.GetRedirectUrl("user", false));
}

Global.asax (This is where the problem appears)

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
    HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
    if (authCookie == null)
        return;

    if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated && HttpContext.Current.User.Identity is FormsIdentity)
    {
        HttpContext.Current.User = System.Threading.Thread.CurrentPrincipal; //Here the value is GenericPrincipal
    }

Thanks in advance for any help.

Body:
JFYI, you can replace

if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated && HttpContext.Current.User.Identity is FormsIdentity) { }

with

FormsIdentity formsIdentity = HttpContext.Current.User as FormsIdentity;
if (formsIdentity != null & formsIdentity.IsAuthenticated) { }

to reduce the length of if-clause


问:
Service layer in Java or Only Repository
If i have Spring data repository which includes save, delete and modify operations. Should I create the following methods operations in service layer? And adding annotation @Transactional?
Or leave them as is? Or should I have them in repository layer?

Example service

```<code>@Service
public class RepositoryOperations{

@Autowired
ProductRepository productRepository;

@Transactional
public void saveProduct(){
    productRepository.save();
    }

...

}
</code>```

答:
I think that you are using a good approach for your code. You can create a service layer that will invoke the product repository methods in order to separate responsibilities (business from data logic).

A 3-layered architecture describes your approach as follows:

Controllers: Handle all the input values that enter to the system (from endpoins, for example) and passes them to the service. In Spring you can use the @Controller class annotation in order to differentiate them from other components.

Services: Components that handle all the business logic related to your application. You can use the @Service annotation.

DAO (Data Access Objects): Classes that contains the data logic (in your case, the repositories). You can use the @Repository annotation.

In order to prevent any inconsistent in your saveProduct() service method when a problem occurs, you can use the @Transactional annotation in order to rollback all the changes made by your method in the database, so i consider it's a good practice use that annotation when you are working with writing operations in database.

Body:
If i have Spring data repository which includes save, delete and modify operations. Should I create the following methods operations in service layer? And adding annotation @Transactional?
Or leave them as is? Or should I have them in repository layer?

Example service

@Service
public class RepositoryOperations{

@Autowired
ProductRepository productRepository;

@Transactional
public void saveProduct(){
    productRepository.save();
    }

...

}


问:
Dimensions must be equal, but are 1 and 128 for 'SparseSoftmaxCrossEntropyWithLogits
I tried to read an images as png format using conventional neural network in tensorflow. I faced a problem that I cannot deal with label in read data step, so, it gives me an error.

First thing I thought the problem is happened when I create batch queue and shuffle.
which was the problem in tf.train.shuffle_batch expected 1-D but actually it got shape as 3-D.

I fixed that. and then it gives me another error in loss function

The subcode is here

the problem is::

Traceback (most recent call last):   File "SVHN.py", line 280, in
        tf.app.run()   File "/home/ashwaq/anaconda3/lib/python3.6/site-packages/tensorflow/python/platform/app.py",
    line 48, in run
        _sys.exit(main(_sys.argv[:1] + flags_passthrough))   File "SVHN.py", line 269, in main
        train_op = SVHN_architecture_AND_optimize()   File "SVHN.py", line 203, in SVHN_architecture_AND_optimize
        cross_entropy =  tf.nn.sparse_softmax_cross_entropy_with_logits(logits = logits, labels
    = labels)   File "/home/ashwaq/anaconda3/lib/python3.6/site-packages/tensorflow/python/ops/nn_ops.py",
    line 1742, in sparse_softmax_cross_entropy_with_logits
        precise_logits, labels, name=name)   File "/home/ashwaq/anaconda3/lib/python3.6/site-packages/tensorflow/python/ops/gen_nn_ops.py",
    line 2418, in _sparse_softmax_cross_entropy_with_logits
        features=features, labels=labels, name=name)   File "/home/ashwaq/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py",
    line 768, in apply_op
        op_def=op_def)   File "/home/ashwaq/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/ops.py",
    line 2338, in create_op
        set_shapes_for_outputs(ret)   File "/home/ashwaq/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/ops.py",
    line 1719, in set_shapes_for_outputs
        shapes = shape_func(op)   File "/home/ashwaq/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/ops.py",
    line 1669, in call_with_requiring
        return call_cpp_shape_fn(op, require_shape_fn=True)   File "/home/ashwaq/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/common_shapes.py",
    line 610, in call_cpp_shape_fn
        debug_python_shape_fn, require_shape_fn)   File "/home/ashwaq/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/common_shapes.py",
    line 676, in _call_cpp_shape_fn_impl
        raise ValueError(err.message) ValueError: Dimensions must be equal, but are 1 and 128 for
    'SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits'
    (op: 'SparseSoftmaxCrossEntropyWithLogits') with input shapes: [1,10],
    [128].

答: I can't view your code (link doesn't work or the dropbox file isn't public) but based on the error, your labels are the wrong shape. For SparseSoftmaxCrossEntropyWithLogits the labels should be shaped [None,], where None is the batch dimension - i.e. your labels should be integers, not one-hot encoded vectors. </p>


问:
undefined local variable or method `on' for #<ActionDispatch::Routing::Mapper:0x007fd3b4516a00>
I am trying to replace the edit action of a controller with one having an extra parameter, but am getting:

```<code>undefined local variable or method `on' for #<ActionDispatch::Routing::Mapper:0x007fd3b4516a00>
</code>```

Here is the routes.rb section:

```<code>resources :structures, except: :edit do
  get '/:doctype' => :edit, on: :edit
end
</code>```

The issue is :edit. Using another action like :new works perfectly.

答:
You can try this instead:

```<code>resources :structures, except: :edit do
  get '/edit/:doctype' => :edit
end
</code>```

The syntax you've tried to use is intended to be used with on: (new|member|collection). edit is not a valid option here.

Body:
I am trying to replace the edit action of a controller with one having an extra parameter, but am getting:

undefined local variable or method `on' for #<ActionDispatch::Routing::Mapper:0x007fd3b4516a00>

Here is the routes.rb section:

resources :structures, except: :edit do
  get '/:doctype' => :edit, on: :edit
end

The issue is :edit. Using another action like :new works perfectly.

Body:
You can try this instead:

resources :structures, except: :edit do
  get '/edit/:doctype' => :edit
end

The syntax you've tried to use is intended to be used with on: (new|member|collection). edit is not a valid option here.


问:
Redirecting URLs that have 2nd url appended
According to our SEO person, we are getting traffic at URLs like so:

```<code>http://www.oursite.com/articles/article1/www.someothersite.com/page.aspx/sectionID%20=113/
</code>```

I would like to 301 redirect to http://www.oursite.com/articles/article1 (remove the extra URL). Tried this in .htaccess:

```<code>RedirectMatch 301 ^http://www.oursite.com/articles/article1/www.someothersite.com/page.aspx/sectionID%20=113/$ /articles/article1
</code>```

Which is not working...

答:
You can use this redirect rule in your site root .htaccess:</p>

```<code>RedirectMatch 301 /(.+)/www\.someothersite\.com/.*$ /$1
</code>```

Body:
According to our SEO person, we are getting traffic at URLs like so:

http://www.oursite.com/articles/article1/www.someothersite.com/page.aspx/sectionID%20=113/

I would like to 301 redirect to http://www.oursite.com/articles/article1 (remove the extra URL). Tried this in .htaccess:

RedirectMatch 301 ^http://www.oursite.com/articles/article1/www.someothersite.com/page.aspx/sectionID%20=113/$ /articles/article1

Which is not working...

Body:
You can use this redirect rule in your site root .htaccess:

RedirectMatch 301 /(.+)/www\.someothersite\.com/.*$ /$1