问:
Multiple htaccess rewrite rule
here is my code for .htaccess file

```<code>Options -Indexes
RewriteEngine On
RewriteCond %(REQUEST_FILENAME) !-f
RewriteCond %(REQUEST_FILENAME) !-d
RewriteRule ^([a-z0-9]+)$ /profile.php?username=$1 [L]
RewriteRule ^([a-z0-9]+)$ /display.php?page=$1 [L]
</code>```

For the first one it works correctly and is displaying like this:
www.site.com/user

The second one is not working, normally is displaying like this www.site.com/display.php?page=10. I want to display the page like this www.site.com/article
I tried different things and no result. Please tell me how to make to work with multiple rules. Also please give me an advice on how to use this functionalities in php because I think I done something not really good. My php code for using this rule is:

```<code><p><a class="button" href="/<?php echo $user_data['username']; ?>"> Profile</a></p>
</code>```

It works, but maybe is a better way to make a link to take advantage of htaccess.

答:
```<code>Options -Indexes
RewriteEngine On

RewriteCond %(REQUEST_FILENAME) !-f
RewriteCond %(REQUEST_FILENAME) !-d
RewriteRule ^user/([a-z0-9]+)$ /profile.php?username=$1 [N]
RewriteRule ^page/([a-z0-9]+)$ /display.php?page=$1 [L]
</code>```

use [N] (next) continue adding rules to the same condition
and [L] (last) to identify the last rule

Title: Multiple htaccess rewrite rule

Body:
here is my code for .htaccess file

Options -Indexes
RewriteEngine On
RewriteCond %(REQUEST_FILENAME) !-f
RewriteCond %(REQUEST_FILENAME) !-d
RewriteRule ^([a-z0-9]+)$ /profile.php?username=$1 [L]
RewriteRule ^([a-z0-9]+)$ /display.php?page=$1 [L]

For the first one it works correctly and is displaying like this:
www.site.com/user

The second one is not working, normally is displaying like this www.site.com/display.php?page=10. I want to display the page like this www.site.com/article
I tried different things and no result. Please tell me how to make to work with multiple rules. Also please give me an advice on how to use this functionalities in php because I think I done something not really good. My php code for using this rule is:

<a class="button" href="/<?php echo $user_data['username']; ?>"> Profile

It works, but maybe is a better way to make a link to take advantage of htaccess.

Body:
Options -Indexes
RewriteEngine On

RewriteCond %(REQUEST_FILENAME) !-f
RewriteCond %(REQUEST_FILENAME) !-d
RewriteRule ^user/([a-z0-9]+)$ /profile.php?username=$1 [N]
RewriteRule ^page/([a-z0-9]+)$ /display.php?page=$1 [L]

use [N] (next) continue adding rules to the same condition
and [L] (last) to identify the last rule


来源: stackexchange

问:
Is this a method or a function?
Am I correct in assuming that getDataPoint() is a method as opposed to a function when used in this context?

```<code>class Globals: NSObject{
   static let sharedInstance = Globals()

   func getDataPoint() -> Int {
      var theValue: Int
      //Some JSON code here
      return theValue
   }
}

class GameScene: SKScene{
   override func didMove(to: view: SKView){
      let globals = Globals.sharedInstance()

      var x = globals.getDataPoint() //Is a method?
   }
}
</code>```

But if I used within the Globals class, I would call it a function.

```<code> class Globals: NSObject{
   static let sharedInstance = Globals()

   func foo() {
      print(\(getDataPoint())) //Is a function?
   }

   func getDataPoint() -> Int {
      var theValue: Int
      //Some JSON code here
      return theValue
   }
}
</code>```

答:
It’s a method. This is just an artefact of Swift’s shorthand for referring to methods and properties without the self. qualifier.

```<code>func foo() {
   print(\(getDataPoint()))
}
</code>```

is exactly the same as writing

```<code>func foo() {
   print(\(self.getDataPoint()))
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Is this a method or a function?

Body:
Am I correct in assuming that getDataPoint() is a method as opposed to a function when used in this context?

class Globals: NSObject{
   static let sharedInstance = Globals()

   func getDataPoint() -> Int {
      var theValue: Int
      //Some JSON code here
      return theValue
   }
}

class GameScene: SKScene{
   override func didMove(to: view: SKView){
      let globals = Globals.sharedInstance()

      var x = globals.getDataPoint() //Is a method?
   }
}

But if I used within the Globals class, I would call it a function.

 class Globals: NSObject{
   static let sharedInstance = Globals()

   func foo() {
      print(\(getDataPoint())) //Is a function?
   }

   func getDataPoint() -> Int {
      var theValue: Int
      //Some JSON code here
      return theValue
   }
}

Body:
It’s a method. This is just an artefact of Swift’s shorthand for referring to methods and properties without the self. qualifier.

func foo() {
   print(\(getDataPoint()))
}

is exactly the same as writing

func foo() {
   print(\(self.getDataPoint()))
}


问:
Vagrant: How to set the default owner and group permissions
While creating a Ubuntu VM, I am providing a provisioning script to install some of the packages once the guest OS is installed.

```<code>config.vm.provision :shell, :path => "vm_provision/provision-node01.sh"
</code>```

The bash script contains:

```<code>#!/usr/bin/env bash

# Intended for Ubuntu 14.04 (Trusty)

# Update the Ubuntu
sudo apt-get -y update
sudo apt-get -y install build-essential

mkdir zookeeper
https://github.com/apache/zookeeper
</code>```

The VM gets created as well as above shell script commands are also executed fine. However, the default owner and the group permission to the folder 'zookeeper' is both set to the root.

```<code>vagrant@ubuntu-14:~$ ls -lrt
total 4
drwxr-xr-x 4 root root 4096 Mar 30 08:55 zookeeper
</code>```

I want it to be vagrant  vagrant so that  I do not have change to super user all the time.

There are steps provided for setting the owner/group permission for the shared folder, but that is set via Vagrantfile. Vagrant sync folder creation

In my provisioning shell script, I tried changing the user (like below) before creating the folder and cloning the github repo, but that did not help.

```<code>su - vagrant
</code>```

答:
by default vagrant runs the provisioner as root, you can change this behavior with following option

```<code>config.vm.provision :shell, :path => "vm_provision/provision-node01.sh", privileged: false
</code>```

when running with privileged: false (see https://www.vagrantup.com/docs/provisioning/shell.html#privileged) the provisioner will be run with vagrant user. In your case this is fine as your script as already sudo for running apt command

Body:
While creating a Ubuntu VM, I am providing a provisioning script to install some of the packages once the guest OS is installed.

config.vm.provision :shell, :path => "vm_provision/provision-node01.sh"

The bash script contains:

#!/usr/bin/env bash

# Intended for Ubuntu 14.04 (Trusty)

# Update the Ubuntu
sudo apt-get -y update
sudo apt-get -y install build-essential

mkdir zookeeper
https://github.com/apache/zookeeper

The VM gets created as well as above shell script commands are also executed fine. However, the default owner and the group permission to the folder 'zookeeper' is both set to the root.

vagrant@ubuntu-14:~$ ls -lrt
total 4
drwxr-xr-x 4 root root 4096 Mar 30 08:55 zookeeper

I want it to be vagrant  vagrant so that  I do not have change to super user all the time.

There are steps provided for setting the owner/group permission for the shared folder, but that is set via Vagrantfile. Vagrant sync folder creation

In my provisioning shell script, I tried changing the user (like below) before creating the folder and cloning the github repo, but that did not help.

su - vagrant

Body:
by default vagrant runs the provisioner as root, you can change this behavior with following option

config.vm.provision :shell, :path => "vm_provision/provision-node01.sh", privileged: false

when running with privileged: false (see https://www.vagrantup.com/docs/provisioning/shell.html#privileged) the provisioner will be run with vagrant user. In your case this is fine as your script as already sudo for running apt command


问:
Programmatically check state of do not disturb on OS X
Using Objective-C, how can I programmatically check the state of the system "Do Not Disturb" setting on OS X? I'm fine with using hacks or private APIs since I don't need to submit to the Mac App Store.</p>

答:
In Objective-C, you can access the value like this:</p>

```<code>NSUserDefaults* defaults = [[NSUserDefaults alloc]initWithSuiteName:@"com.apple.notificationcenterui"];
BOOL dnd = [defaults boolForKey:@"doNotDisturb"];
</code>```

Body:
In Objective-C, you can access the value like this:

NSUserDefaults* defaults = [[NSUserDefaults alloc]initWithSuiteName:@"com.apple.notificationcenterui"];
BOOL dnd = [defaults boolForKey:@"doNotDisturb"];


问:
Error "Asp.net 4.0 has not been registered on the webserver you need to manually configure your webserver" while adding new project in visual studio
I got error

Asp.net 4.0 has not been registered on the webserver you need to
  manually configure your webserver

while adding new project in visual studio 2012, I already have register asp.net 4.0.

答:
This should solved the problem

Run the command prompt "As Administrator". Copy following command to command prompt :

C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis -i

If this doesn't solve the problem then try following :

Manually configure your Web server for ASP.NET 4.0 :

Make sure the IIS feature is turned on with ASP.NET. Go to Control Panel > Programs and Features > then click 'Turn Windows Featrues on. Find Internet Information Service > WWW servers > App Dev Features, make sure that ASP.NET is checked.

Then try again : Run the command prompt "As Administrator". Copy following command to command prompt :

C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis -i

This solutions will work,.. good luck (y)


问:
How does password salt help against a rainbow table attack?
I'm having some trouble understanding the purpose of a salt to a password.  It's my understanding that the primary use is to hamper a rainbow table attack.  However, the methods I've seen to implement this don't seem to really make the problem harder.

I've seen many tutorials suggesting that the salt be used as the following:

```<code>$hash =  md5($salt.$password)
</code>```

The reasoning being that the hash now maps not to the original password, but a combination of the password and the salt.  But say $salt=foo and $password=bar and $hash=3858f62230ac3c915f300c664312c63f.  Now somebody with a rainbow table could reverse the hash and come up with the input "foobar".  They could then try all combinations of passwords (f, fo, foo, ... oobar, obar, bar, ar, ar).  It might take a few more milliseconds to get the password, but not much else.

The other use I've seen is on my linux system.  In the /etc/shadow the hashed passwords are actually stored with the salt.  For example, a salt of "foo" and password of "bar" would hash to this: $1$foo$te5SBM.7C25fFDu6bIRbX1.  If a hacker somehow were able to get his hands on this file, I don't see what purpose the salt serves, since the reverse hash of te5SBM.7C25fFDu6bIRbX is known to contain "foo".

Thanks for any light anybody can shed on this.

EDIT:  Thanks for the help.  To summarize what I understand, the salt makes the hashed password more complex, thus making it much less likely to exist in a precomputed rainbow table.  What I misunderstood before was that I was assuming a rainbow table existed for ALL hashes.

答:
Yet another great question, with many very thoughtful answers -- +1 to SO!

One small point that I haven't seen mentioned explicitly is that, by adding a random salt to each password, you're virtually guaranteeing that two users who happened to choose the same password will produce different hashes.

Why is this important?

Imagine the password database at a large software company in the northwest US.  Suppose it contains 30,000 entries, of which 500 have the password bluescreen.  Suppose further that a hacker manages to obtain this password, say by reading it in an email from the user to the IT department.  If the passwords are unsalted, the hacker can find the hashed value in the database, then simply pattern-match it to gain access to the other 499 accounts.

Salting the passwords ensures that each of the 500 accounts has a unique (salt+password), generating a different hash for each of them, and thereby reducing the breach to a single account.  And let's hope, against all probability, that any user naive enough to write a plaintext password in an email message doesn't have access to the undocumented API for the next OS.

OwnerDisplayName: Rich

Body:
I'm having some trouble understanding the purpose of a salt to a password.  It's my understanding that the primary use is to hamper a rainbow table attack.  However, the methods I've seen to implement this don't seem to really make the problem harder.

I've seen many tutorials suggesting that the salt be used as the following:

$hash =  md5($salt.$password)

The reasoning being that the hash now maps not to the original password, but a combination of the password and the salt.  But say $salt=foo and $password=bar and $hash=3858f62230ac3c915f300c664312c63f.  Now somebody with a rainbow table could reverse the hash and come up with the input "foobar".  They could then try all combinations of passwords (f, fo, foo, ... oobar, obar, bar, ar, ar).  It might take a few more milliseconds to get the password, but not much else.

The other use I've seen is on my linux system.  In the /etc/shadow the hashed passwords are actually stored with the salt.  For example, a salt of "foo" and password of "bar" would hash to this: $1$foo$te5SBM.7C25fFDu6bIRbX1.  If a hacker somehow were able to get his hands on this file, I don't see what purpose the salt serves, since the reverse hash of te5SBM.7C25fFDu6bIRbX is known to contain "foo".

Thanks for any light anybody can shed on this.

EDIT:  Thanks for the help.  To summarize what I understand, the salt makes the hashed password more complex, thus making it much less likely to exist in a precomputed rainbow table.  What I misunderstood before was that I was assuming a rainbow table existed for ALL hashes.

LastEditorDisplayName: Rich

OwnerDisplayName: Adam Liss

ContentLicense: CC BY-SA 2.5


问:
how to create a device specific app in objective c
I want to create an app which is specific to the device type.Say my app should work only on  iPhone but not on iPad or iPod even if it (the app) has common features.</p>

答:
[[UIDevice currentDevice] model]; would give you the current device model.

Now, compare strings with the isEqualToString: rather than using the comparison operator.

Once done, you should write the functionality that you want to run, after doing the comparison.


问:
How to get a posterior of a difference using MCMCpack?
I'm trying to get a posterior distribution using MCMCpack of a difference between two conversion rates, akin to the A and B Together section of this PyMC tutorial.

I can get the posteriors of the two sampled rates just fine, but I'm struggling how to implement the sampled delta.. Any ideas?

Edit The true delta (which would have been unknown if we hadn't fabricated the data and is what we want to estimate using MCMC) is the difference between the two rates true_p_a and true_p_b i.e. 0.01.

```<code># define true success rates
true_p_a = 0.05
true_p_b = 0.04

# set sample sizes
n_samples_a = 1000
n_samples_b = 1000

# fabricate some data
set.seed(10);
obs_a = rbinom(n=n_samples_a, size=1, prob=true_p_a)
set.seed(1);
obs_b = rbinom(n=n_samples_b, size=1, prob=true_p_b)

# what are the observed conversion rates?
mean(obs_a) #0.056
mean(obs_b) #0.042

# convert to number of successes
successes_a = sum(obs_a) #56
successes_b = sum(obs_b) #42

# calculate the posterior
require(MCMCpack)

simulations = 20000

posterior_a = MCbinomialbeta(successes_a ,n_samples_a, alpha=1, beta=1,mc=simulations)
posterior_b = MCbinomialbeta(successes_b ,n_samples_b, alpha=1, beta=1,mc=simulations)

posterior_delta = ????

posterior_density_a = density(posterior_a)
posterior_density_b = density(posterior_b)

# plot the posteriors
require(ggplot2)
ggplot() +
  geom_area(aes(posterior_density_a$x, posterior_density_a$y), fill="#7ad2f6", alpha=.5) +
  geom_vline(aes(xintercept=.05), color="#7ad2f6", linetype="dotted", size=2) +
  geom_area(aes(posterior_density_b$x, posterior_density_b$y), fill="#014d64", alpha=.5) +
  geom_vline(aes(xintercept=.04), color="#014d64", linetype="dotted", size=2) +
  scale_x_continuous(labels=percent_format(), breaks=seq(0,0.1, 0.01))
</code>```

答:
You are only struggling because you haven't fully adopted a Bayesian mindset. It's totally OK, I had a lot of the same conceptual issues when I started out. (This question is way old, so you've probably figured it out already).

A Bayesian posterior density incorporates all the available information about the distribution of the parameters of the model. Thus to calculate a function of any of the parameters of the model, you simply calculate that function for each draw from the posterior distribution. You don't need to worry about standard errors and asymptotic inference because you already have all the information you need.

In this case, because the difference between the parameters is a constant, and you have plenty of data, there is little uncertainty about delta. It is estimated at a mean of 0.014 with a SD (not SE) of .009.

Your code with finished analysis:

```<code>  # define true success rates
  true_p_a = 0.05
  true_p_b = 0.04

  # set sample sizes
  n_samples_a = 1000
  n_samples_b = 1000

  # fabricate some data
  set.seed(10);
  obs_a = rbinom(n=n_samples_a, size=1, prob=true_p_a)
  set.seed(1);
  obs_b = rbinom(n=n_samples_b, size=1, prob=true_p_b)

  # what are the observed conversion rates?
  mean(obs_a) #0.056
  mean(obs_b) #0.042

  # convert to number of successes
  successes_a = sum(obs_a) #56
  successes_b = sum(obs_b) #42

  # calculate the posterior
  require(MCMCpack)

  simulations = 20000

  posterior_a = MCbinomialbeta(successes_a ,n_samples_a, alpha=1, beta=1,mc=simulations)
  posterior_b = MCbinomialbeta(successes_b ,n_samples_b, alpha=1, beta=1,mc=simulations)

  # Subtract the posterior deltas, look at empirical summaries and plot the empirical density function

  posterior_delta = posterior_a - posterior_b

  summary(posterior_delta)

  require(ggplot2)

  ggplot(data.frame(delta=as.numeric(posterior_delta)),aes(x=delta)) + geom_density() + theme_minimal()
</code>```

Body:
I'm trying to get a posterior distribution using MCMCpack of a difference between two conversion rates, akin to the A and B Together section of this PyMC tutorial.

I can get the posteriors of the two sampled rates just fine, but I'm struggling how to implement the sampled delta.. Any ideas?

Edit The true delta (which would have been unknown if we hadn't fabricated the data and is what we want to estimate using MCMC) is the difference between the two rates true_p_a and true_p_b i.e. 0.01.

# define true success rates
true_p_a = 0.05
true_p_b = 0.04

# set sample sizes
n_samples_a = 1000
n_samples_b = 1000

# fabricate some data
set.seed(10);
obs_a = rbinom(n=n_samples_a, size=1, prob=true_p_a)
set.seed(1);
obs_b = rbinom(n=n_samples_b, size=1, prob=true_p_b)

# what are the observed conversion rates?
mean(obs_a) #0.056
mean(obs_b) #0.042

# convert to number of successes
successes_a = sum(obs_a) #56
successes_b = sum(obs_b) #42

# calculate the posterior
require(MCMCpack)

simulations = 20000

posterior_a = MCbinomialbeta(successes_a ,n_samples_a, alpha=1, beta=1,mc=simulations)
posterior_b = MCbinomialbeta(successes_b ,n_samples_b, alpha=1, beta=1,mc=simulations)

posterior_delta = ????

posterior_density_a = density(posterior_a)
posterior_density_b = density(posterior_b)

# plot the posteriors
require(ggplot2)
ggplot() +
  geom_area(aes(posterior_density_a$x, posterior_density_a$y), fill="#7ad2f6", alpha=.5) +
  geom_vline(aes(xintercept=.05), color="#7ad2f6", linetype="dotted", size=2) +
  geom_area(aes(posterior_density_b$x, posterior_density_b$y), fill="#014d64", alpha=.5) +
  geom_vline(aes(xintercept=.04), color="#014d64", linetype="dotted", size=2) +
  scale_x_continuous(labels=percent_format(), breaks=seq(0,0.1, 0.01))

Body:
You are only struggling because you haven't fully adopted a Bayesian mindset. It's totally OK, I had a lot of the same conceptual issues when I started out. (This question is way old, so you've probably figured it out already).

A Bayesian posterior density incorporates all the available information about the distribution of the parameters of the model. Thus to calculate a function of any of the parameters of the model, you simply calculate that function for each draw from the posterior distribution. You don't need to worry about standard errors and asymptotic inference because you already have all the information you need.

In this case, because the difference between the parameters is a constant, and you have plenty of data, there is little uncertainty about delta. It is estimated at a mean of 0.014 with a SD (not SE) of .009.

Your code with finished analysis:

  # define true success rates
  true_p_a = 0.05
  true_p_b = 0.04

  # set sample sizes
  n_samples_a = 1000
  n_samples_b = 1000

  # fabricate some data
  set.seed(10);
  obs_a = rbinom(n=n_samples_a, size=1, prob=true_p_a)
  set.seed(1);
  obs_b = rbinom(n=n_samples_b, size=1, prob=true_p_b)

  # what are the observed conversion rates?
  mean(obs_a) #0.056
  mean(obs_b) #0.042

  # convert to number of successes
  successes_a = sum(obs_a) #56
  successes_b = sum(obs_b) #42

  # calculate the posterior
  require(MCMCpack)

  simulations = 20000

  posterior_a = MCbinomialbeta(successes_a ,n_samples_a, alpha=1, beta=1,mc=simulations)
  posterior_b = MCbinomialbeta(successes_b ,n_samples_b, alpha=1, beta=1,mc=simulations)

  # Subtract the posterior deltas, look at empirical summaries and plot the empirical density function

  posterior_delta = posterior_a - posterior_b

  summary(posterior_delta)

  require(ggplot2)

  ggplot(data.frame(delta=as.numeric(posterior_delta)),aes(x=delta)) + geom_density() + theme_minimal()


问:
How can I merge two object arrays by index in JavaScript?
What would be the best way to combine the two arrays below to get the desired result. I would want them to be combined by index.

Input is:

```<code>var array1 = [[1,2,3,4],[4,5,6,7]]
var array2 = [[a,b,c,d],[e,f,g,h]]
</code>```

Desired output would be:

```<code>var array3 =[{
              array1:[1,2,3,4],
              array2:[a,b,c,d]
             },
             {
              array1:[4,5,6,7],
              array2:[a,b,c,d]
             }]
</code>```

Any variation of the output would work as long as they are grouped by indexes. Thanks in advance.

EDIT: not a duplicate of what was suggestion. Suggestion out [a,1,b,2] and does not group the way the desired output shows.

答:
This is very similar to How do I zip two arrays in JavaScript?, except you just change the output format from an array to an object:

var array1 = [[1,2,3,4],[4,5,6,7]];
var array2 = [['a','b','c','d'],['e','f','g','h']];

var array3 = array1.map(function(_, i) {
  return {
    array1: array1[i],
    array2: array2[i]
  };
});

console.log(array3);```

Body:
What would be the best way to combine the two arrays below to get the desired result. I would want them to be combined by index.

Input is:

var array1 = [[1,2,3,4],[4,5,6,7]]
var array2 = [[a,b,c,d],[e,f,g,h]]

Desired output would be:

var array3 =[{
              array1:[1,2,3,4],
              array2:[a,b,c,d]
             },
             {
              array1:[4,5,6,7],
              array2:[a,b,c,d]
             }]

Any variation of the output would work as long as they are grouped by indexes. Thanks in advance.

EDIT: not a duplicate of what was suggestion. Suggestion out [a,1,b,2] and does not group the way the desired output shows.


问:
Postgres building an index concurrently
I'm reading this from the Postgres docs:

Building Indexes Concurrently

...
PostgreSQL supports building indexes without locking out writes. This
method is invoked by specifying the CONCURRENTLY option of CREATE
INDEX. When this option is used, PostgreSQL must perform two scans of
the table, and in addition it must wait for all existing transactions
that could potentially modify or use the index to terminate. Thus this
method requires more total work than a standard index build and takes
significantly longer to complete. However, since it allows normal
operations to continue while the index is built, this method is useful
for adding new indexes in a production environment....

In a concurrent index build, the index is actually entered into the
system catalogs in one transaction, then two table scans occur in two
more transactions. Before each table scan, the index build must wait
for existing transactions that have modified the table to terminate.
After the second scan, the index build must wait for any transactions
that have a snapshot (see Chapter 13) predating the second scan to
terminate. Then finally the index can be marked ready for use, and the
CREATE INDEX command terminates. Even then, however, the index may not
be immediately usable for queries: in the worst case, it cannot be
used as long as transactions exist that predate the start of the index
build.

What is a system catalog? What is a table scan? So it sounds like the index is build first, then it must wait for existing transactions (ones that occurred during the index build?) to terminate, and then wait for any transactions that have a snapshot predating the second scan to terminate (what does this mean? How does it differ from the first statement). What are these scans?

答:
What is a system catalog? - https://www.postgresql.org/docs/current/static/catalogs.html

What is a table scan? - It reads table to get values of a column you build index on.

ones that occurred during the index build? - no, ones that could change data after first table scan

what does this mean? It means it waits transactions to end.

What are these scans? First scan reads table before starting to build index concurrently. Allowing changes to table to avoid lock. When build is done it scans roughly saying a difference, apply a short lock and mark index as usable. It is different from create index in a way the last locks table, not permitting any changes to data, while concurrently scans twice, but alows changing data while building index

Title: Postgres building an index concurrently


问:
How to ensure that keys in object are strings with jsonschema
I need a jsonschema to validate JSON where all keys are required to be strings. All keys are arbitrary.

For example this should be valid

```<code>{

    "123": "GET",
    "key2": "/mellons/and/strawberries",
    "arbitrary_key": {
        "SomeKey": "some data",
    },
}
</code>```

while this should not

```<code>{

    123: "GET",
    "key2": "/mellons/and/strawberries",
    "arbitrary_key": {
        "SomeKey": "some data",
    },
}
</code>```

Validating with patternProperties does not work, as this regex "^.*$" seems to match numbers as well as strings.

答:
According to JSON the object keys are always strings (just take a look at the first graph). Some parsers may allow the use of numbers too as a string though.

Since json schema is supposed to validate the structure of valid json documents, it won't recognize lexically malformed json strings. This is out of scope for json schema. You also shouldn't mix up JSON and javascript objects.

So if you are really sure about that you want to catch such non-well-formed JSONs then probably the best you can do is picking a parser that has a strict mode.

Body:
I need a jsonschema to validate JSON where all keys are required to be strings. All keys are arbitrary.

For example this should be valid

{

    "123": "GET",
    "key2": "/mellons/and/strawberries",
    "arbitrary_key": {
        "SomeKey": "some data",
    },
}

while this should not

{

    123: "GET",
    "key2": "/mellons/and/strawberries",
    "arbitrary_key": {
        "SomeKey": "some data",
    },
}

Validating with patternProperties does not work, as this regex "^.*$" seems to match numbers as well as strings.


问:
Static variable accessed from null variable
Why is a null reference exception not thrown when I try to print the value of a static field value from an uninitialized instance of a class.

I expected a Null reference exception in the following code:

```<code>public class Check {

  static int i=1;

  public static void main(String []args)
  {
     Check ch = null;
     System.out.print(ch.i);
  }

}
</code>```

Produces output as: 1.

答:
Because i is a static variable, it does not matter whether its value is obtained from an object or from the class.

See the note here:

https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

Body:
Why is a null reference exception not thrown when I try to print the value of a static field value from an uninitialized instance of a class.

I expected a Null reference exception in the following code:

public class Check {

  static int i=1;

  public static void main(String []args)
  {
     Check ch = null;
     System.out.print(ch.i);
  }

}

Produces output as: 1.


问:
How i can put radio button on image?
I want to code something like this:

I used CSS on my radio buttons but they are not positioning with my image as I want. Any ideas?

答:
I think I understand what you want.  If not, please post some code to help us help you...

This may be what you are looking for though:

#myDiv {
  width: 200px;
  height: 200px;
  background-image: url("http://www.25score.com/attachments/article/691/small/Taco%20Bell%20200x200%20(small).jpg")
}

input[type="radio"] {
  position: absolute;
  top: 100px;
  left: 120px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="myDiv">
  <input type="radio">
</div></code>```

Title: How i can put radio button on image?

Body:
I think I understand what you want.  If not, please post some code to help us help you...

This may be what you are looking for though:

#myDiv {
  width: 200px;
  height: 200px;
  background-image: url("http://www.25score.com/attachments/article/691/small/Taco%20Bell%20200x200%20(small).jpg")
}

input[type="radio"] {
  position: absolute;
  top: 100px;
  left: 120px;
}

<div id="myDiv">
  <input type="radio">
</div>


问:
Retrieve sub-document in array as DBObject(s)
I'm very new to MongoDB, and I'm using it along with the Java driver.  I have this document structure:

```<code>{ "_id" : ObjectId("4f7d2ba6fd5a306d82687d48"), "room" : "Den" }
{ "_id" : ObjectId("4f7d2baafd5a306d82687d49"), "room" : "Foyer" }
{ "_id" : ObjectId("4f7d2fdcfd5a306d82687d4a"), "room" : "Master Bedroom" }
{ "_id" : ObjectId("4f7d301afd5a306d82687d4b"), "room" : "Guest Bedroom" }
{ "_id" : ObjectId("4f7d2b98fd5a306d82687d47"), "code" : "A", "lights" : [ { "name" : "Overhead", "code" : "1" } ], "room" : "Kitchen" }
</code>```

Where the last line is of particular interest in illustrating what I want to do.  Each document is a room and may have a "lights" key corresponding to a value that is an array of sub-documents.  From a modeling perspective, I have a house, which has 0-n rooms, each of which has 0-n lights in it.  What I want to do in Java is take the name of the room as a parameter, and return a collection of DBObject corresponding to the sub-documents in the lights array -- "get me all lights for room 'kitchen'", for example.

So far, proceeding incrementally in TDD style, I've constructed this query:

```<code>public static final String ROOM_KEY = "room";

public static final String EQUALS_KEY = "$eq";

private BasicDBObject buildRoomNameQuery(String roomName) {

    BasicDBObject myQuery = new BasicDBObject();
    myQuery.put(ROOM_KEY, new BasicDBObject(EQUALS_KEY, roomName));

    return myQuery;
}
</code>```

I realize that this is going to get me the entire room document for the room name I pass in.  I'm a bit stuck on what the best way to proceed from here is to get what I want.  Is what I'm doing even possible with a simple query, or will I have to retrieve the array and iterate through it in code, casting the elements as DBObject?  I'm also open to suggestions for a better document structure for my purpose -- I'm not married to this structure by any means.

For a bit of perspective, I'm quite well versed in SQL and traditional relational databases, if that helps in terms of explanatory analogies.  Also, if I'm butchering the MongoDB terminology, please correct me.  Thanks in advance.

答:
For newer versions, consider the use of the Document. To avoid unchecked casts and linter warnings, along with writing your own loop, use the libary's get(final Object key, final Class<T> clazz) method:

```<code>List<Document> comments = posts.get("comments", docClazz)
</code>```

where docClazz is something that you create once:

```<code>final static Class<? extends List> docClazz = new ArrayList<Document().getClass();
</code>```

Body:
I'm very new to MongoDB, and I'm using it along with the Java driver.  I have this document structure:

{ "_id" : ObjectId("4f7d2ba6fd5a306d82687d48"), "room" : "Den" }
{ "_id" : ObjectId("4f7d2baafd5a306d82687d49"), "room" : "Foyer" }
{ "_id" : ObjectId("4f7d2fdcfd5a306d82687d4a"), "room" : "Master Bedroom" }
{ "_id" : ObjectId("4f7d301afd5a306d82687d4b"), "room" : "Guest Bedroom" }
{ "_id" : ObjectId("4f7d2b98fd5a306d82687d47"), "code" : "A", "lights" : [ { "name" : "Overhead", "code" : "1" } ], "room" : "Kitchen" }

Where the last line is of particular interest in illustrating what I want to do.  Each document is a room and may have a "lights" key corresponding to a value that is an array of sub-documents.  From a modeling perspective, I have a house, which has 0-n rooms, each of which has 0-n lights in it.  What I want to do in Java is take the name of the room as a parameter, and return a collection of DBObject corresponding to the sub-documents in the lights array -- "get me all lights for room 'kitchen'", for example.

So far, proceeding incrementally in TDD style, I've constructed this query:

public static final String ROOM_KEY = "room";

public static final String EQUALS_KEY = "$eq";

private BasicDBObject buildRoomNameQuery(String roomName) {

    BasicDBObject myQuery = new BasicDBObject();
    myQuery.put(ROOM_KEY, new BasicDBObject(EQUALS_KEY, roomName));

    return myQuery;
}

I realize that this is going to get me the entire room document for the room name I pass in.  I'm a bit stuck on what the best way to proceed from here is to get what I want.  Is what I'm doing even possible with a simple query, or will I have to retrieve the array and iterate through it in code, casting the elements as DBObject?  I'm also open to suggestions for a better document structure for my purpose -- I'm not married to this structure by any means.

For a bit of perspective, I'm quite well versed in SQL and traditional relational databases, if that helps in terms of explanatory analogies.  Also, if I'm butchering the MongoDB terminology, please correct me.  Thanks in advance.

Body:
For newer versions, consider the use of the Document. To avoid unchecked casts and linter warnings, along with writing your own loop, use the libary's get(final Object key, final Class<T> clazz) method:

List<Document> comments = posts.get("comments", docClazz)

where docClazz is something that you create once:

final static Class<? extends List> docClazz = new ArrayList<Document().getClass();


问:
How to get only the text of a json object when saved into a variable?
I am using the following to retrieve results form google which works fine:

```<code>function myGoogle() {
  var termS;
  termS = $("#usp-title").val();
  var myKey = 'MY_KE';
  $.getJSON("https://www.googleapis.com/customsearch/v1", {
    q: termS,
    alt: "json",
    cx: "MY_CX",
    key: myKey,
    num: 10,
    hl: "it",
    siteSearch: "https://it.wikipedia.org/",
    language: "it",
    filter: "1",
    safe: "high"
  },
  function (data) {
    $.each(data.items, function(i, item) {
      var uniq = uniqueId('thing_');
      var $items = $($('<h3>"' + item.title + '"</h3>'));
      console.log($items);
    });
  });
}
</code>```

The console outputs all the objects while instead i would like to only see the actual title text

答:
How about?

```<code>$items.forEach(function(item) {
  console.log(item.title);
});
</code>```

* I am assuming that you are getting data similar to this

https://developers.google.com/custom-search/json-api/v1/reference/cse/list#response

"items" is an array, thus you can iterate through the array via array.forEach

Body:
I am using the following to retrieve results form google which works fine:

function myGoogle() {
  var termS;
  termS = $("#usp-title").val();
  var myKey = 'MY_KE';
  $.getJSON("https://www.googleapis.com/customsearch/v1", {
    q: termS,
    alt: "json",
    cx: "MY_CX",
    key: myKey,
    num: 10,
    hl: "it",
    siteSearch: "https://it.wikipedia.org/",
    language: "it",
    filter: "1",
    safe: "high"
  },
  function (data) {
    $.each(data.items, function(i, item) {
      var uniq = uniqueId('thing_');
      var $items = $($('
"' + item.title + '"
'));
      console.log($items);
    });
  });
}

The console outputs all the objects while instead i would like to only see the actual title text

Body:
How about?

$items.forEach(function(item) {
  console.log(item.title);
});

* I am assuming that you are getting data similar to this

https://developers.google.com/custom-search/json-api/v1/reference/cse/list#response

"items" is an array, thus you can iterate through the array via array.forEach


问:
Displaying raw JSON in a user friendly way
I am trying to create a raw JSON viewer for JSON strings. I understand there are apps that already do this but I am looking to load JSON from my server and display it for an internal tool for my company.

I am able to pretty print the JSON values, but this can still be difficult to read. Are there any Android libraries available for displaying color-coded JSON or JSON that can have its items expanded? If not can anyone suggest a way to do so? I've looked into ExpandableListView but this only goes up to two levels deep

答: Recommend you to see GSON, it simplify JSON. </p>


问:
How to get the values from a $.ajax using php
I'm trying to use $.ajax to send some values to a php page which then sends an email,
I can't figure out how to get the values from $.ajax in my php file,

any help would be appreciated,

```<code>$(function() {

$('form#email input[type=image]').click(function() {

    var name = $('form#email #name').val();
    var enq = $('form#email #enq').val();
    var dataString = 'name=' + name + '&enq=' + enq;

    $.ajax({
        type:'POST',
        url:'email.php',
        data:dataString,
        success:function() {
            $('form#email').fadeOut();
        }

    });
    $('form#email')[0].reset();
    return false;
 });
});
</code>```

php file

```<code>if (isset($_POST['submit_x'])) {

$name = $_POST['name'];
$enq = $_POST['enq'];
$name = htmlentities($name);
$enq = htmlentities($enq);

//echo $name,$enq;

$to = 'amirkarimian@hotmail.co.uk';
//$to = 'tutor@inspiretuition.co.uk'
$subject = 'Enquiry';
$message = $enq;

mail($to,$subject,$message);

if(!mail) {
    echo 'failed to send mail';
}
}
</code>```

the email doesn't get sent.
if I dont use $.ajax and submit the form normally the email get sent.

thanks

答:
You can use a data map to define your data:</p>

```<code>var name = $('form#email #name').val();
   var enq = $('form#email #enq').val();

   $.ajax({
    type: 'POST',
    url: 'email.php',
    dataType: 'html',
    data: {
     submit_x   : 1,
     name     : name,
     enq     : enq
   },
   success: function(html){
    $('form#email').fadeOut();
   },
   error:  function(e, xhr)  { alert('__a Error: e: ' + e + ', xhr:' + xhr); }
  });
</code>```

Body:
I'm trying to use $.ajax to send some values to a php page which then sends an email,
I can't figure out how to get the values from $.ajax in my php file,

any help would be appreciated,

$(function() {

$('form#email input[type=image]').click(function() {

    var name = $('form#email #name').val();
    var enq = $('form#email #enq').val();
    var dataString = 'name=' + name + '&enq=' + enq;

    $.ajax({
        type:'POST',
        url:'email.php',
        data:dataString,
        success:function() {
            $('form#email').fadeOut();
        }

    });
    $('form#email')[0].reset();
    return false;
 });
});

php file

if (isset($_POST['submit_x'])) {

$name = $_POST['name'];
$enq = $_POST['enq'];
$name = htmlentities($name);
$enq = htmlentities($enq);

//echo $name,$enq;

$to = 'amirkarimian@hotmail.co.uk';
//$to = 'tutor@inspiretuition.co.uk'
$subject = 'Enquiry';
$message = $enq;

mail($to,$subject,$message);

if(!mail) {
    echo 'failed to send mail';
}
}

the email doesn't get sent.
if I dont use $.ajax and submit the form normally the email get sent.

thanks

Body:
You can use a data map to define your data:

var name = $('form#email #name').val();
   var enq = $('form#email #enq').val();

   $.ajax({
    type: 'POST',
    url: 'email.php',
    dataType: 'html',
    data: {
     submit_x   : 1,
     name     : name,
     enq     : enq
   },
   success: function(html){
    $('form#email').fadeOut();
   },
   error:  function(e, xhr)  { alert('__a Error: e: ' + e + ', xhr:' + xhr); }
  });


问:
Why does the array still have a non-zero length after deletion?
I have the following code that outputs the length of an array, deletes it, and then outputs the new length:

```<code>console.log($scope.adviceList.activeAdvices.length); // *1*
$scope.adviceList.activeAdvices.splice(id,1); // *id is a parameter*
console.log($scope.adviceList.activeAdvices.length); // *0*

console.log($scope.adviceList.activeAdvices.length); // *1*
delete $scope.adviceList.activeAdvices[id];
console.log($scope.adviceList.activeAdvices.length); // *0*
console.log($scope.adviceList.activeAdvices); // *[]*
</code>```

After the deletion, the array is correctly displayed as empty. Its length, however, is still 1.

答:
I created a new array and pushed elements on it to get the right length.  For example, I had this for table headers:

```<code> var finalTableHeaderArray = [];

 tableHeaderArray.forEach(function (element, index, array) {
    if (removeDisplayItems.indexOf(index) === -1)
        finalTableHeaderArray.push(element);
 }, self);
</code>```

Not exactly your question, but it could help others.

Body:
I have the following code that outputs the length of an array, deletes it, and then outputs the new length:

console.log($scope.adviceList.activeAdvices.length); // *1*
$scope.adviceList.activeAdvices.splice(id,1); // *id is a parameter*
console.log($scope.adviceList.activeAdvices.length); // *0*

console.log($scope.adviceList.activeAdvices.length); // *1*
delete $scope.adviceList.activeAdvices[id];
console.log($scope.adviceList.activeAdvices.length); // *0*
console.log($scope.adviceList.activeAdvices); // *[]*

After the deletion, the array is correctly displayed as empty. Its length, however, is still 1.

Body:
I created a new array and pushed elements on it to get the right length.  For example, I had this for table headers:

 var finalTableHeaderArray = [];

 tableHeaderArray.forEach(function (element, index, array) {
    if (removeDisplayItems.indexOf(index) === -1)
        finalTableHeaderArray.push(element);
 }, self);

Not exactly your question, but it could help others.


问:
NumberFormatException For Input String in JAVA
I've written some code which calculate employee's Total overtime,Rate per hour,Total amount based on their overtime,medical,bonus,others etc etc.Here is the code,

```<code>    int salary = Integer.parseInt(txt_salary.getText().trim());
    int overtime = Integer.parseInt(txt_overtime.getText().trim());

    double eight = 8;
    double days = 25;
    double dbop = 0;
    double overtimeRate = 1.5;

    //calculate the total hours of overtime
    double Total_Overtime = overtime * overtimeRate;
    String x = (String.valueOf(Total_Overtime)).trim();
    txt_hw.setText(x);

    //calculate overall overtime
    dbop = salary /days/eight;
    String s = (String.valueOf(dbop)).trim();
    txt_rate.setText(s);

    int med = Integer.parseInt(txt_med.getText().trim());
    int bonus = Integer.parseInt(txt_bonus.getText().trim());
    int other = Integer.parseInt(txt_other.getText().trim());
    int f = med+bonus+other;
    double calc = Total_Overtime * dbop+f;
    String c = (String.valueOf(calc)).trim();
    lbl_total.setText(c);
</code>```

Why this is giving me the following error when I try to calculate,

```<code>Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "20000.0"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at Allowance.btn_calcAllwActionPerformed(Allowance.java:764)
at Allowance.access$500(Allowance.java:18)
at Allowance$5.actionPerformed(Allowance.java:248)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6535)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6300)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4891)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4713)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
at java.awt.Container.dispatchEventImpl(Container.java:2280)
at java.awt.Window.dispatchEventImpl(Window.java:2750)
at java.awt.Component.dispatchEvent(Component.java:4713)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
</code>```

Someone please help me. Can't figure out what I did wrong.

答:
You are trying to convert a String "20000.0" to an Integer. 20000.0 is NOT a valid integer value, so the conversion fails. You could e.g. try to parse the input as double.</p>

```<code>final String text = "20000.0";
try {
  final double value = Double.parseDouble(s);
  final int iValue = (int) value; // Be aware you are loosing precision here
  [...]
} catch (NumberFormatException exception){
  // Proper error handling
}
</code>```

Body:
I've written some code which calculate employee's Total overtime,Rate per hour,Total amount based on their overtime,medical,bonus,others etc etc.Here is the code,

    int salary = Integer.parseInt(txt_salary.getText().trim());
    int overtime = Integer.parseInt(txt_overtime.getText().trim());

    double eight = 8;
    double days = 25;
    double dbop = 0;
    double overtimeRate = 1.5;

    //calculate the total hours of overtime
    double Total_Overtime = overtime * overtimeRate;
    String x = (String.valueOf(Total_Overtime)).trim();
    txt_hw.setText(x);

    //calculate overall overtime
    dbop = salary /days/eight;
    String s = (String.valueOf(dbop)).trim();
    txt_rate.setText(s);

    int med = Integer.parseInt(txt_med.getText().trim());
    int bonus = Integer.parseInt(txt_bonus.getText().trim());
    int other = Integer.parseInt(txt_other.getText().trim());
    int f = med+bonus+other;
    double calc = Total_Overtime * dbop+f;
    String c = (String.valueOf(calc)).trim();
    lbl_total.setText(c);

Why this is giving me the following error when I try to calculate,

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "20000.0"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at Allowance.btn_calcAllwActionPerformed(Allowance.java:764)
at Allowance.access$500(Allowance.java:18)
at Allowance$5.actionPerformed(Allowance.java:248)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6535)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6300)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4891)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4713)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
at java.awt.Container.dispatchEventImpl(Container.java:2280)
at java.awt.Window.dispatchEventImpl(Window.java:2750)
at java.awt.Component.dispatchEvent(Component.java:4713)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

Someone please help me. Can't figure out what I did wrong.

Body:
You are trying to convert a String "20000.0" to an Integer. 20000.0 is NOT a valid integer value, so the conversion fails. You could e.g. try to parse the input as double.

final String text = "20000.0";
try {
  final double value = Double.parseDouble(s);
  final int iValue = (int) value; // Be aware you are loosing precision here
  [...]
} catch (NumberFormatException exception){
  // Proper error handling
}


问:
Installing Scrapy throws exceptions again and again
I've tried to install  Scrapy the usual way:
Python 2, pip, pip install Scrapy

I read that Python3, Windows10 and 64bit are not so good for Scrapy so I've installed 32bit Ubuntu to Oracle Virtualbox. I've also followed the advice of codereviewvideos and applied:

```<code>sudo apt-get install build-essential autoconf libtool pkg-config python-opengl python-imaging python-pyrex python-pyside.qtopengl idle-python2.7 qt4-dev-tools qt4-designer libqtgui4 libqtcore4 libqt4-xml libqt4-test libqt4-script libqt4-network libqt4-dbus python-qt4 python-qt4-gl libgle3 python-dev libxml2-dev libxslt1-dev python-dev libxml2-dev libxslt1-dev python-dev libxml2-dev libxslt-dev python-dev lib32z1-dev build-essential libssl-dev libffi-dev python-dev
</code>```

https://codereviewvideos.com/blog/scrapy-1-1-ubuntu-15-10/

...but still throws error code 1 about lxml and the installation apt-gethas thrown: unable to locate package lib32z1-dev

答:
The command you used won't work on windows....
have you try to follow indication to install scrapy on windows :

https://doc.scrapy.org/en/0.10.3/intro/install.html#intro-install-step3

And also you should install lxml :
pip install lxml

Scrapy need other packages, you will find the list here :

https://doc.scrapy.org/en/latest/intro/install.html

on windows it's recommended to use conda  (https://docs.continuum.io/anaconda/install)

"Though it’s possible to install Scrapy on Windows using pip, we recommend you to install Anaconda or Miniconda and use the package from the conda-forge channel, which will avoid most installation issues."

Body:
I've tried to install  Scrapy the usual way:
Python 2, pip, pip install Scrapy

I read that Python3, Windows10 and 64bit are not so good for Scrapy so I've installed 32bit Ubuntu to Oracle Virtualbox. I've also followed the advice of codereviewvideos and applied:

sudo apt-get install build-essential autoconf libtool pkg-config python-opengl python-imaging python-pyrex python-pyside.qtopengl idle-python2.7 qt4-dev-tools qt4-designer libqtgui4 libqtcore4 libqt4-xml libqt4-test libqt4-script libqt4-network libqt4-dbus python-qt4 python-qt4-gl libgle3 python-dev libxml2-dev libxslt1-dev python-dev libxml2-dev libxslt1-dev python-dev libxml2-dev libxslt-dev python-dev lib32z1-dev build-essential libssl-dev libffi-dev python-dev

https://codereviewvideos.com/blog/scrapy-1-1-ubuntu-15-10/

...but still throws error code 1 about lxml and the installation apt-gethas thrown: unable to locate package lib32z1-dev


问:
How to use template variable in a template tag in Django?
I have a custom template tag called cg

```<code>{% cg %}
</code>```

and I hava a varialbe {{ status }}

I need to wrap the result of {{ status }} inside a <special></special> HTML tag, and then pass into {%cg  %}, how to write this code in django template?

答:
You can write your own filter like this:

```<code>from django import template
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe

register = template.Library()

@register.filter
@stringfilter
def wrap(value, tag):
    return mark_safe("<%(tag)s>%(value)s</%(tag)s>" % {'value': value, 'tag': tag})
</code>```

and use it in template:
{% cg status|wrap:"special" %}

Edit-fixed.

Body:
I have a custom template tag called cg

{% cg %}

and I hava a varialbe {{ status }}

I need to wrap the result of {{ status }} inside a <special></special> HTML tag, and then pass into {%cg  %}, how to write this code in django template?

Body:
You can write your own filter like this:

from django import template
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe

register = template.Library()

@register.filter
@stringfilter
def wrap(value, tag):
    return mark_safe("<%(tag)s>%(value)s</%(tag)s>" % {'value': value, 'tag': tag})

and use it in template:
{% cg status|wrap:"special" %}

Edit-fixed.


问:
I found two identical entities in the database with the same Primary Key
I'm using Entity Framework 6 with Code First on an SQL server.  Today, with my greatest surprise, I received an exception Sequence contains more than one element on a a simple query by ID (in my domain, the primary Key of each object). After debugging, I found that in my database 2 identical entities with the same Primary Key exist.

Now, I have no idea how that could happen, but my biggest problem right now is how to solve the issue: I cannot just delete them both, since they are 2 users with important data associated to them. So I tried to remove just one, but I receive an exception due to the fact that some other object references this user (and again, I cannot delete those objects because they contain important data).

```<code>var users = _userService.GetAllBy().ToList();
var duplicatedUsers = users.Where(x => users.Count(y => y.Id == x.Id) > 1);

foreach (var user in duplicatedUsers)
{
    try
    {
        dbContext.Users.Remove(user);
        dbContext.SaveChanges();
    }
    catch (Exception e)
    {
        // it always enters here because of the foreign keys
    }
 }
</code>```

Basically, since the 2 identical objects have the same foreign key, they also share the same relationships with the other related entities. Therefore, I cannot just simply delete one of them because that causes an exception. But I don't want to delete them both either, because that would cause data loss. Any suggestion?

答:
If sql server you can use a window function to identify a row and delete it that way -- see How do I delete duplicate rows in SQL Server using the OVER clause? as an example. Alternatively, if the table has more columns that what is defined in the key, you can hopefully use the other columns to more uniquely identify the "duplicate" row.

If it is, say, Oracle, you can get the ROWID of the row (just do a select rowid, t.* from table_name_here t WHERE conditions_here) and then when you find the right rowid, just do a straight DELETE FROM table_name WHERE rowid = XYZ123

Body:
I'm using Entity Framework 6 with Code First on an SQL server.  Today, with my greatest surprise, I received an exception Sequence contains more than one element on a a simple query by ID (in my domain, the primary Key of each object). After debugging, I found that in my database 2 identical entities with the same Primary Key exist.

Now, I have no idea how that could happen, but my biggest problem right now is how to solve the issue: I cannot just delete them both, since they are 2 users with important data associated to them. So I tried to remove just one, but I receive an exception due to the fact that some other object references this user (and again, I cannot delete those objects because they contain important data).

var users = _userService.GetAllBy().ToList();
var duplicatedUsers = users.Where(x => users.Count(y => y.Id == x.Id) > 1);

foreach (var user in duplicatedUsers)
{
    try
    {
        dbContext.Users.Remove(user);
        dbContext.SaveChanges();
    }
    catch (Exception e)
    {
        // it always enters here because of the foreign keys
    }
 }

Basically, since the 2 identical objects have the same foreign key, they also share the same relationships with the other related entities. Therefore, I cannot just simply delete one of them because that causes an exception. But I don't want to delete them both either, because that would cause data loss. Any suggestion?


问:
Sort numbers based on divisors
I want to create a function that will print values of a given vector in a specific order: zeros, ones, numbers divisible by 2, numbers divisible by 3 (not by 2,excl.0), numbers divisible by 5 (not by 2 and 3, excl. 0), etc.

Would it be a good idea to use some vartiation of "bubble sort"? I think that a basic idea is to have if condition based on

```<code>if (x[i] %% divisor == 0 && x[i+1] %% divisor != 0)
</code>```

I also know that I should have a loop that will increase "divisor" values every turn, but besides I don't really know how to start. I was able to comprehend basic "bubble sort" algorithm, but it seems that I have too many gaps to work this out comfortably.

答:
```<code># generate a vector

x <- 1:1000

# the function

order_n <- function(v)
  {

y <- 1:floor(v/2);

z <- y[v%%y == 0];

z <- z[z!=1];

return(ifelse(is.infinite(min(z)), 0, min(z))) }

# the ordering vector

xx <- rep(0, length(x))
for (i in 1:length(x)) {xx[i] <- order_n(x[i])}

head(xx,50)

[1] NA  0  0  2  0  2  0  2  3  2  0  2  0  2  3  2  0  2  0  2  3  2  0  2
[25]  5  2  3  2  0  2  0  2  3  2  5  2  0  2  3  2  0  2  0  2  3  2  0  2
[49]  7  2
</code>```

I should mention that the 0 value in xx means that the number is prime, therefore it should be assigned the highest possible order

Title: Sort numbers based on divisors

Body:
I want to create a function that will print values of a given vector in a specific order: zeros, ones, numbers divisible by 2, numbers divisible by 3 (not by 2,excl.0), numbers divisible by 5 (not by 2 and 3, excl. 0), etc.

Would it be a good idea to use some vartiation of "bubble sort"? I think that a basic idea is to have if condition based on

if (x[i] %% divisor == 0 && x[i+1] %% divisor != 0)

I also know that I should have a loop that will increase "divisor" values every turn, but besides I don't really know how to start. I was able to comprehend basic "bubble sort" algorithm, but it seems that I have too many gaps to work this out comfortably.

Body:
# generate a vector

x <- 1:1000

# the function

order_n <- function(v)
  {

y <- 1:floor(v/2);

z <- y[v%%y == 0];

z <- z[z!=1];

return(ifelse(is.infinite(min(z)), 0, min(z))) }

# the ordering vector

xx <- rep(0, length(x))
for (i in 1:length(x)) {xx[i] <- order_n(x[i])}

head(xx,50)

[1] NA  0  0  2  0  2  0  2  3  2  0  2  0  2  3  2  0  2  0  2  3  2  0  2
[25]  5  2  3  2  0  2  0  2  3  2  5  2  0  2  3  2  0  2  0  2  3  2  0  2
[49]  7  2

I should mention that the 0 value in xx means that the number is prime, therefore it should be assigned the highest possible order


问:
Powershell: Event in Foreach loop
I'm having problems with a foreach loop and setting a Add_MouseClick event.

Each loop the function generates a new clickable label. While the .Text variable setting works as intended, when setting the event listener, it will write out the last generated $labelName, regardless of which is clicked.

```<code>foreach($account in $resUserNameSearchArray){
    #Set form object variables
    $script:labelName = "res" + $i

    #Form Variable
    Set-Variable -Name $labelName -Value (New-Object System.Windows.Forms.Label)
    (Get-Variable $labelName -ValueOnly).Text = "$account"
    (Get-Variable $labelName -ValueOnly).Add_MouseClick{
        Write-Host "$labelName"
    }...
</code>```

There's a few non-relevant lines removed (location, font,etc)

答: I needed to use Write-Host $this.text within the Add_Click event to pull in the .text of the foreach variable.

Title: Powershell: Event in Foreach loop

Body:
I'm having problems with a foreach loop and setting a Add_MouseClick event.

Each loop the function generates a new clickable label. While the .Text variable setting works as intended, when setting the event listener, it will write out the last generated $labelName, regardless of which is clicked.

foreach($account in $resUserNameSearchArray){
    #Set form object variables
    $script:labelName = "res" + $i

    #Form Variable
    Set-Variable -Name $labelName -Value (New-Object System.Windows.Forms.Label)
    (Get-Variable $labelName -ValueOnly).Text = "$account"
    (Get-Variable $labelName -ValueOnly).Add_MouseClick{
        Write-Host "$labelName"
    }...

There's a few non-relevant lines removed (location, font,etc)


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

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

答:
Java array is an object the contains elements of similar data type. It is a data structure where we store similar elements. We can store only fixed set of elements in a java array.

Advantage of Java Array

Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
Random access: We can get any data located at any index position.

Disadvantage of Java Array

Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in java.

Title: Random Access in Array


问:
API not in Json?
I'm using this API: https://decapi.me/youtube/latest_video?id=UCFaV5im11vfhDs1BaaF9a0A which gets the latest youtube video of a user, but it's not in JSON so I'm not sure how I would retrieve the data. I'm using node-fetch by the way.

答:
node-fetch documentation :

Decode content encoding (gzip/deflate) properly, and convert string output (such as res.text() and res.json()) to UTF-8 automatically.

Try res.text() ?

Title: API not in Json?


答:
Add the following command to the end of your pipe in your script, after uniq:

```<code>... | awk '{print "ip: " $2 " attempts: " $1}'
</code>```

The output will be

```<code>ip: 108.166.98.9 attempts: 5
ip: 108.53.208.61 attempts: 1426
...
</code>```

Title: Formatting grep output. Bash

Body:
trying to format output from grep to make it look better, code is

grep "$1" "$2" | grep -E -o "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)" | sort | uniq -c

$ bash myScript.sh "Failed password for root" /home/user/auth.log
      5 108.166.98.9
   1426 108.53.208.61
      1 113.108.211.131
      1 117.79.91.195
    370 122.224.49.124
   3480 144.0.0.32
     11 162.144.94.250
      6 162.253.66.74
      3 186.67.83.58
      1 222.190.114.98
    205 59.90.242.69
    705 60.172.228.226
      3 64.251.21.104

and want it to look more like

ip: xxx.xxx.xxx.xxx attempts: X

Body:
Add the following command to the end of your pipe in your script, after uniq:

... | awk '{print "ip: " $2 " attempts: " $1}'

The output will be

ip: 108.166.98.9 attempts: 5
ip: 108.53.208.61 attempts: 1426
...


问:
spring, get json keys in the controller function
i am sending a JSON object to my controller using POST method inside the request body (using post man).

i want to receive the JSON parameters as variables of my controller function

for ample when i send this

```<code>{"A":"some a value", "B":"Some b value"}
</code>```

i want to get them like this in my controller

```<code>@RestController
public class UserController {
    @RequestMapping(value="/api/some-update-url"    , method=RequestMethod.POST)
    Boolean updateSomeData(@RequestParam String A, @RequestParam String B) {
        .....
    }
}
</code>```

but this is the result of my postman

```<code>{
    "timestamp": 1490896822946,
    "status": 400,
    "error": "Bad Request",
    "exception": "org.springframework.web.bind.MissingServletRequestParameterException",
    "message": "Required Gender parameter 'gender' is not present",
    "path": "/api/some-update-url"
}
</code>```

can you help me please

thank you !!

答:
@RequestParam annotated parameters get linked to specific Servlet request parameters. Parameter values are converted to the declared method argument type. This annotation indicates that a method parameter should be bound to a web request parameter.

If I were to pass email in as a request parameter, for example, I would annotate the method in my controller as such:

```<code>@RequestParam(value = "email", required = true) String email
</code>```

Calling such method would be done like:

```<code>http://some.service.url/verification?email=someone@somewhere.com
</code>```

Body:
i am sending a JSON object to my controller using POST method inside the request body (using post man).

i want to receive the JSON parameters as variables of my controller function

for ample when i send this

{"A":"some a value", "B":"Some b value"}

i want to get them like this in my controller

@RestController
public class UserController {
    @RequestMapping(value="/api/some-update-url"    , method=RequestMethod.POST)
    Boolean updateSomeData(@RequestParam String A, @RequestParam String B) {
        .....
    }
}

but this is the result of my postman

{
    "timestamp": 1490896822946,
    "status": 400,
    "error": "Bad Request",
    "exception": "org.springframework.web.bind.MissingServletRequestParameterException",
    "message": "Required Gender parameter 'gender' is not present",
    "path": "/api/some-update-url"
}

can you help me please

thank you !!

Body:
@RequestParam annotated parameters get linked to specific Servlet request parameters. Parameter values are converted to the declared method argument type. This annotation indicates that a method parameter should be bound to a web request parameter.

If I were to pass email in as a request parameter, for example, I would annotate the method in my controller as such:

@RequestParam(value = "email", required = true) String email

Calling such method would be done like:

http://some.service.url/verification?email=someone@somewhere.com


问:
Maven assembly : add different version of the same artifact
I create my application archive with the maven assembly plugin.
All the dependency present in my pom are included without any problem.

Now I need to include two or more version of the same artifact.

If in my pom I put

```<code><dependencies>
        [...]
        <dependency>
            <groupId>db.test</groupId>
            <artifactId>my-model</artifactId>
            <version>1.0.3</version>
        </dependency>
        <dependency>
            <groupId>db.test</groupId>
            <artifactId>my-model</artifactId>
            <version>1.1.0</version>
        </dependency>
</dependencies>
</code>```

Of source the dependenvcy resolver remove the old version and only the 1.1.0 is packaged in the archive

I try to include the jar by using assembly xml descriptor file. And I didn't find any solution.

A possible solution will be to manually put all the needed model.jar inside a folder and tell the assembly to copy it in the archive. But I'm looking for a more configurable solution.

Any idea ?

答:
Maven assumes it doesn't make any sense to have more than one version of a module at once.  It assumes that a newer version replaces the older version.  If it doesn't it is not the same module.  I suggest you give the newer module a different name and make sure it has different packages to avoid choising a random module.

In general Maven tried to encourage good application design and deliberately makes it difficult to do things it has determined to be a bad idea.

Body:
I create my application archive with the maven assembly plugin.
All the dependency present in my pom are included without any problem.

Now I need to include two or more version of the same artifact.

If in my pom I put

<dependencies>
        [...]
        <dependency>
            <groupId>db.test</groupId>
            <artifactId>my-model</artifactId>
            <version>1.0.3</version>
        </dependency>
        <dependency>
            <groupId>db.test</groupId>
            <artifactId>my-model</artifactId>
            <version>1.1.0</version>
        </dependency>
</dependencies>

Of source the dependenvcy resolver remove the old version and only the 1.1.0 is packaged in the archive

I try to include the jar by using assembly xml descriptor file. And I didn't find any solution.

A possible solution will be to manually put all the needed model.jar inside a folder and tell the assembly to copy it in the archive. But I'm looking for a more configurable solution.

Any idea ?


问:
Protractor: stop do while loop once element is found
In non-Angular page using Protractor I have a situation where I have to loop trough some list of elements on the page and once I find the element I'm looking for, I have to stop the loop and click on that element.

Page object file:

```<code>var homePage = function() {
    this.elementLists = browser.element(by.id('list')).all(by.css('div.list'));
    this.elementLink = browser.element(by.id('list')).element(by.css('div[data-code="GAA"]'));
    this.paginationRight = browser.element(by.css('.navi-right'));
    ...
}
module.exports = homePage;
</code>```

Spec file:

```<code>// page objects
var homePage = require('../home_page/home_page.js');

// variables
var maxLoopCount = '';
var i = 0;

describe(...
    it(...
        // initialize page object
        var home = new homePage();

        // store number of listsinto a variable
        home.elementLists.count().then(function(num) {
            maxLoopCount = num;

            // click on right paginator arrow until element is displayed in the list
            while (i < maxLoopCount) {
                home.paginationRight.click();
                browser.sleep(1500);
                if (expect(home.elementLink.isPresent()).toBeTruthy()) {
                    break;
                }
                i++;
            };
    });
});
</code>```

I know I should use if (elementFound === true), but how can I do that?

答:
you can use 'isDisplayed() or isPresent()' according to your need,  something like this:   </p>

```<code>home.elementLists.each(function(elem){
 home.paginationRight.click();
 home.elementLink.isDisplayed().then(function(value){
  if(value === true){
     break;
   }else {
     console.log("element not visible");
    }
 });
});
</code>```

Body:
In non-Angular page using Protractor I have a situation where I have to loop trough some list of elements on the page and once I find the element I'm looking for, I have to stop the loop and click on that element.

Page object file:

var homePage = function() {
    this.elementLists = browser.element(by.id('list')).all(by.css('div.list'));
    this.elementLink = browser.element(by.id('list')).element(by.css('div[data-code="GAA"]'));
    this.paginationRight = browser.element(by.css('.navi-right'));
    ...
}
module.exports = homePage;

Spec file:

// page objects
var homePage = require('../home_page/home_page.js');

// variables
var maxLoopCount = '';
var i = 0;

describe(...
    it(...
        // initialize page object
        var home = new homePage();

        // store number of listsinto a variable
        home.elementLists.count().then(function(num) {
            maxLoopCount = num;

            // click on right paginator arrow until element is displayed in the list
            while (i < maxLoopCount) {
                home.paginationRight.click();
                browser.sleep(1500);
                if (expect(home.elementLink.isPresent()).toBeTruthy()) {
                    break;
                }
                i++;
            };
    });
});

I know I should use if (elementFound === true), but how can I do that?

Body:
you can use 'isDisplayed() or isPresent()' according to your need,  something like this:

home.elementLists.each(function(elem){
 home.paginationRight.click();
 home.elementLink.isDisplayed().then(function(value){
  if(value === true){
     break;
   }else {
     console.log("element not visible");
    }
 });
});


问:
Get the right color in iOS7 translucent navigation bar
How can I get the right coloring for my translucent navigation bars in iOS 7? The navigation bar just adjusts the given color to a much brighter one. Changing brightness or saturation of the color also doesn´t deliver the right result.

Anyone having the same trouble? It seems to work somehow, looking at Facebook: they´re having their colors and translucent navigation bars.

Edit: Just to make it clear: I need the Bar to be translucent, not transparent (with some alpha), not solid! http://en.wikipedia.org/wiki/Transparency_and_translucency

Edit: Now posted to Apple BugReporter

答:
From comparing my before an after colors I found there was a drop of 21% in saturation while Hue and Brightness remained the same.

By adding the 21% back on I was able to improve the color matching significantly. Unfortunately our color had a saturation above 80 to start with so pushing it above 100% had diminishing returns and didn't match perfectly but it got much closer.

For colors with saturation below 80 it should do even better.

For info on how to adjust saturation of your color How can I modify a UIColor's hue, brightness and saturation?


问:
What's the best solution for Hive proxy user in HDFS?
I'm very confusing by the proxyuser setting in HDFS and Hive. I have the doAs option enabled in hive-site.xml

```<code><property>
    <name>hive.server2.enable.doAs</name>
    <value>true</value>
</property>
</code>```

And proxyuser in core-site.xml

```<code><property>
    <name>hadoop.proxyuser.hdfs.hosts</name>
    <value>*</value>
</property>

<property>
    <name>hadoop.proxyuser.hdfs.groups</name>
    <value>*</value>
</property>
</code>```

But this will cause:

```<code>2017-03-29 16:24:59,022 INFO org.apache.hadoop.ipc.Server: Connection from 172.16.0.239:60920 for protocol org.apache.hadoop.hdfs.protocol.ClientProtocol is unauthorized for user hive (auth:PROXY) via hive (auth:SIMPLE)
2017-03-29 16:24:59,023 INFO org.apache.hadoop.ipc.Server: Socket Reader #1 for port 9000: readAndProcess from client 172.16.0.239 threw exception [org.apache.hadoop.security.authorize.AuthorizationException: User: hive is not allowed to impersonate hive]
</code>```

I didn't set proxyuser to "hive" like most example saying is because core-site.xml is shared by other services, I don't like every service access HDFS as hive, but I still gave it a try so that now the core-site.xml looks as:

```<code><property>
    <name>hadoop.proxyuser.hive.hosts</name>
    <value>*</value>
</property>

<property>
    <name>hadoop.proxyuser.hive.groups</name>
    <value>*</value>
</property>
</code>```

I lunched beeline again, however, the login is fine this time, but when a command was running, yarn thrown exception:

```<code>Error: Error while processing statement: FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.mr.MapRedTask. Permission denied: user=hive, access=WRITE, inode="/user/yarn/hive/.staging":hdfs:supergroup:drwxr-xr-x
</code>```

proxyuser "hive" has been denied from the staging folder which is owned by "hdfs". I don't think give 777 to the staging folder is a good idea as it makes no sense to give HDFS protection but open the folder to everyone. So my question is what's the best solution to setup the permission between Hive, Hdfs and Yarn?

Hadoop permission is just a nightmare to me, please help.

答:
Adding proxyuser entries in core-site.xml would allow the superuser named hive to connect from any host (as value is *) to impersonate a user belonging to any group (as value is *).

```<code><property>
    <name>hadoop.proxyuser.hive.hosts</name>
    <value>*</value>
</property>

<property>
    <name>hadoop.proxyuser.hive.groups</name>
    <value>*</value>
</property>
</code>```

This can be made more restrictive by passing actual hostnames and group names (Refer Superusers). The access privileges the superuser hive has on the FS will be applicable for the impersonating users.

For a multi-user Hadoop environment, the best practice would be to create dedicated directories for every superuser and configure the associated service to store files in it. And create a group supergroup for all these superusers so that group level access privileges can be given for the files, if required.

Add this property in hdfs-site.xml to configure the supergroup

```<code><property>
   <name>dfs.permissions.superusergroup</name>
   <value>supergroup</value>
   <description>The name of the group of super-users.</description>
</property>
</code>```

Body:
I'm very confusing by the proxyuser setting in HDFS and Hive. I have the doAs option enabled in hive-site.xml

<property>
    <name>hive.server2.enable.doAs</name>
    <value>true</value>
</property>

And proxyuser in core-site.xml

<property>
    <name>hadoop.proxyuser.hdfs.hosts</name>
    <value>*</value>
</property>

<property>
    <name>hadoop.proxyuser.hdfs.groups</name>
    <value>*</value>
</property>

But this will cause:

2017-03-29 16:24:59,022 INFO org.apache.hadoop.ipc.Server: Connection from 172.16.0.239:60920 for protocol org.apache.hadoop.hdfs.protocol.ClientProtocol is unauthorized for user hive (auth:PROXY) via hive (auth:SIMPLE)
2017-03-29 16:24:59,023 INFO org.apache.hadoop.ipc.Server: Socket Reader #1 for port 9000: readAndProcess from client 172.16.0.239 threw exception [org.apache.hadoop.security.authorize.AuthorizationException: User: hive is not allowed to impersonate hive]

I didn't set proxyuser to "hive" like most example saying is because core-site.xml is shared by other services, I don't like every service access HDFS as hive, but I still gave it a try so that now the core-site.xml looks as:

<property>
    <name>hadoop.proxyuser.hive.hosts</name>
    <value>*</value>
</property>

<property>
    <name>hadoop.proxyuser.hive.groups</name>
    <value>*</value>
</property>

I lunched beeline again, however, the login is fine this time, but when a command was running, yarn thrown exception:

Error: Error while processing statement: FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.mr.MapRedTask. Permission denied: user=hive, access=WRITE, inode="/user/yarn/hive/.staging":hdfs:supergroup:drwxr-xr-x

proxyuser "hive" has been denied from the staging folder which is owned by "hdfs". I don't think give 777 to the staging folder is a good idea as it makes no sense to give HDFS protection but open the folder to everyone. So my question is what's the best solution to setup the permission between Hive, Hdfs and Yarn?

Hadoop permission is just a nightmare to me, please help.

Body:
Adding proxyuser entries in core-site.xml would allow the superuser named hive to connect from any host (as value is *) to impersonate a user belonging to any group (as value is *).

<property>
    <name>hadoop.proxyuser.hive.hosts</name>
    <value>*</value>
</property>

<property>
    <name>hadoop.proxyuser.hive.groups</name>
    <value>*</value>
</property>

This can be made more restrictive by passing actual hostnames and group names (Refer Superusers). The access privileges the superuser hive has on the FS will be applicable for the impersonating users.

For a multi-user Hadoop environment, the best practice would be to create dedicated directories for every superuser and configure the associated service to store files in it. And create a group supergroup for all these superusers so that group level access privileges can be given for the files, if required.

Add this property in hdfs-site.xml to configure the supergroup

<property>
   <name>dfs.permissions.superusergroup</name>
   <value>supergroup</value>
   <description>The name of the group of super-users.</description>
</property>


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

floated div

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

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

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>      <div style="float: left; width: 50%; background: orange">floated div</div>
      <div style="width: 30%; background: red">second div</div> </code>```

答:
In your first example, the first div is floated and therefore removed from the flow of the document. The second div then occupies the space behind the first div and since there just happens to be enough room for the text you've given in the second div, it all stays neatly on the same line. If you add a lot of text to your second div, you'll see that it will overflow and begin to wrap under the first div.

In your second example, again the first div is floated and removed from the flow of the document. Now however, since you only have the second div a width of 30%, there's not enough room for the text that it contains to exist on the same line since it's very narrow, so the text is forced below the text of the first div. If you remove the text from the second div, it will essentially disappear beneath the floated first div.

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

floated div

second div

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

floated div

second div


问:
Suppress scientific notation in Haxe across targets
Is there a way to suppress scientific notation in Haxe?

For example, if I have:

```<code>var f:Float = 0.00007075;
var s:String = Std.string(f);
</code>```

In targets such as html5, this outputs: 0.00007075

However, c++ targets output: 7.075e-05

Is there a way to control whether scientific notation is used for string format?

答:
Credits to Hugh Sanderson of GameHaxe who answered this at a forum.

Global output mode for floats can be changed using an extern:

```<code>class Test
{
  @:native("__hxcpp_set_float_format") @:extern
  static function setFloatFormat(format:String):Void { }

  public static function main()
  {
    trace(0.00005);
    trace(5e20);
    setFloatFormat("%.12f");
    trace(0.00005);
    trace(5e20);
  }
}
</code>```

Body:
Is there a way to suppress scientific notation in Haxe?

For example, if I have:

var f:Float = 0.00007075;
var s:String = Std.string(f);

In targets such as html5, this outputs: 0.00007075

However, c++ targets output: 7.075e-05

Is there a way to control whether scientific notation is used for string format?

Body:
Credits to Hugh Sanderson of GameHaxe who answered this at a forum.

Global output mode for floats can be changed using an extern:

class Test
{
  @:native("__hxcpp_set_float_format") @:extern
  static function setFloatFormat(format:String):Void { }

  public static function main()
  {
    trace(0.00005);
    trace(5e20);
    setFloatFormat("%.12f");
    trace(0.00005);
    trace(5e20);
  }
}


问:
Running vi in adb under Windows
Very occasionally, I will want to edit a file, say /system/build.prop or /etc/hosts on my Android device. I find that the easiest way to do it is:

```<code>c:\> adb shell
$ su
# vi /etc/hosts
</code>```

This works fine if I'm using Linux. However, attempting to run vi on my phone when using Windows results in a borked vi screen with strange characters. I'm assuming this is because cmd doesn't support ANSI control characters.

Is there any way to fix this (e.g., a cmd alternative that does the job)?

答:
This is a late answer to your question in 2012.  I found that if I run Windows PowerShell, I can do "vi" under the adb shell.

Launch PowerShell (use your Android SDK location, not mine)

```<code>PS C:\Users\Me> cd Downloads\Android\Sdk\Platform-Tools
PS C:\Users\Me\Downloads\Android\Sdk\Platform-Tools> .\adb shell
root@vbox86p:/ # cd data/data/com.mycorporation.myproj/shared_prefs
root@vbox86p:/data/data/com.mycorporation.myproj/shared_prefs # vi log_prefs
</code>```

I only used simple vi commands like 'o', 'esc', and ':wq', but it worked well using the full screen (none of the garbage you would see in the Windows Command Prompt).

Title: Running vi in adb under Windows

Body:
Very occasionally, I will want to edit a file, say /system/build.prop or /etc/hosts on my Android device. I find that the easiest way to do it is:

c:\> adb shell
$ su
# vi /etc/hosts

This works fine if I'm using Linux. However, attempting to run vi on my phone when using Windows results in a borked vi screen with strange characters. I'm assuming this is because cmd doesn't support ANSI control characters.

Is there any way to fix this (e.g., a cmd alternative that does the job)?

Body:
This is a late answer to your question in 2012.  I found that if I run Windows PowerShell, I can do "vi" under the adb shell.

Launch PowerShell (use your Android SDK location, not mine)

PS C:\Users\Me> cd Downloads\Android\Sdk\Platform-Tools
PS C:\Users\Me\Downloads\Android\Sdk\Platform-Tools> .\adb shell
root@vbox86p:/ # cd data/data/com.mycorporation.myproj/shared_prefs
root@vbox86p:/data/data/com.mycorporation.myproj/shared_prefs # vi log_prefs

I only used simple vi commands like 'o', 'esc', and ':wq', but it worked well using the full screen (none of the garbage you would see in the Windows Command Prompt).


问:
js-hotkeys, function raised twice when combination is more than 1 key
I am using js-hotkeys. I have a problem where when my key combination is more than 1 key, eg. "Shift+Tab", my function is raised twice. </p>

```<code>$("textarea").bind("keydown", "shift+tab", function() { ... });
</code>```

<p>See what happens here -> http://jsbin.com/osuza5/2/edit. seems like with 1 key it also triggers twice there. </p>

答:
Try Code:

$("textarea").bind("keydown", "shift+tab", function(e)
{ e.preventDefault;  bla..bla... });

Link: http://jsbin.com/osuza5/4/edit

Body:
I am using js-hotkeys. I have a problem where when my key combination is more than 1 key, eg. "Shift+Tab", my function is raised twice.

$("textarea").bind("keydown", "shift+tab", function() { ... });

See what happens here -> http://jsbin.com/osuza5/2/edit. seems like with 1 key it also triggers twice there.


问:
Using the ... operator on objects
I can't figure out how to go one level deeper with the spread operator. I'm using Redux and I have this user state:

```<code>const INITIAL_STATE = {
    token: null,
    progress: {
        hasSeenTutorial: false,
        hasSignedUp: false
    },
    information: {
        fullname: null,
        username: null,
        phone: null,
        verificationCode: null
    }
}
</code>```

And I'm trying to change hasSeenTutorial to true using the spread operator in my action:

```<code>case 'UPDATE_TUTORIAL_SEEN':
            return {...state, hasSeenTutorial: action.payload}
</code>```

But this adds a new hasSeenTutorial onto the end of my object, so obviously I want to use something like this:

```<code>case 'UPDATE_TUTORIAL_SEEN':
            return {...state, progress.hasSeenTutorial: action.payload}
</code>```

Note the added progress.

But this is not how you access it properly - it throws an error, what is the correct way?

NOTE: The key is to also not modify hasSignedUp - I want to only access and modify hasSeenTutorial using the spread operator.

EDIT: This question is unique - I'd like to know how to do it using only the spread syntax ... and not using Object.create or Object.assign - if I used those I probably would not be mixing in ... at the same time.

答:
```<code>case 'UPDATE_TUTORIAL_SEEN':
  return {
    ...state,
    progress: {
      ...state.progress,
      hasSeenTutorial: action.payload
    }
  };
</code>```

Title: Using the ... operator on objects

Body:
I can't figure out how to go one level deeper with the spread operator. I'm using Redux and I have this user state:

const INITIAL_STATE = {
    token: null,
    progress: {
        hasSeenTutorial: false,
        hasSignedUp: false
    },
    information: {
        fullname: null,
        username: null,
        phone: null,
        verificationCode: null
    }
}

And I'm trying to change hasSeenTutorial to true using the spread operator in my action:

case 'UPDATE_TUTORIAL_SEEN':
            return {...state, hasSeenTutorial: action.payload}

But this adds a new hasSeenTutorial onto the end of my object, so obviously I want to use something like this:

case 'UPDATE_TUTORIAL_SEEN':
            return {...state, progress.hasSeenTutorial: action.payload}

Note the added progress.

But this is not how you access it properly - it throws an error, what is the correct way?

NOTE: The key is to also not modify hasSignedUp - I want to only access and modify hasSeenTutorial using the spread operator.

EDIT: This question is unique - I'd like to know how to do it using only the spread syntax ... and not using Object.create or Object.assign - if I used those I probably would not be mixing in ... at the same time.


问:
change cron job for outside cron job service
is there a way to put those cron jobs in a php file

```<code>* * * * cd /var/www/vhosts/xxxxx.com/xxxx.com; /opt/plesk/php/7.0/bin/php-cgi artisan fc:livecron
* * * * cd /var/www/vhosts/xxxxx.com/xxxx.com; /opt/plesk/php/7.0/bin/php-cgi artisan fc:taskrunner
* * * * cd /var/www/vhosts/xxxxx.com/xxxx.com; /opt/plesk/php/7.0/bin/php-cgi artisan fc:ticketcron
</code>```

so that I can use a outside cron job service which calls the php file?

答:
You should consider to provide informations about your current Plesk version in use, because then we could guide you to the domain - specific scheduled tasks more easily.

The "normal" way with Plesk Onyx for example, is to go to your domain - specific subscription and just click on the "Scheduled Tasks" management option on the right side. You are able to "run a command", "Fetch an URL" and "Run a PHP script".

Consider to visit

https://docs.plesk.com/en-US/onyx/customer-guide/scheduling-tasks.65207/

... for more usefull Plesk informations/documentations.

ContentLicense: CC BY-SA 4.0

Body:
is there a way to put those cron jobs in a php file

* * * * cd /var/www/vhosts/xxxxx.com/xxxx.com; /opt/plesk/php/7.0/bin/php-cgi artisan fc:livecron
* * * * cd /var/www/vhosts/xxxxx.com/xxxx.com; /opt/plesk/php/7.0/bin/php-cgi artisan fc:taskrunner
* * * * cd /var/www/vhosts/xxxxx.com/xxxx.com; /opt/plesk/php/7.0/bin/php-cgi artisan fc:ticketcron

so that I can use a outside cron job service which calls the php file?