问:
Tired of reinstalling Bitnami WAMP Stack 7.0 over and over again. Cannot install stack in a deeper directory
This is really REALLY damn frustrating. For some reason Bitnami WAMP Stack keeps on FAILING to install in a deeper directory D:\***\***\***\***\***\wampstack. It ONLY works when I'm installing in the root (one folder in D:\Bitnami\wampstack). My set up NEEDS to have the stack server installed deeper down for organization's sake, but it won't work. It keeps failing.
I then tried installing it in the root directory, then tried moving the whole folder (since IT IS supposed to be self-contained.) into the proper directory (deeper down), and then changing the ImagePath of the wampserverApache and wampserverMySQL to reflect that of the new location. IT STILL WON'T START.
I keep getting this error:

```<code>> Starting all servers... Starting MySQL Database... Exit code: 1
> Stdout:
>
> Stderr: Unknown error starting mysql Starting Apache Web Server...
> Exit code: 1 Stdout:
>
> Stderr: Unknown error starting apache
</code>```

Any idea on how to fix this? Or am I just doing something extremely wrong. Please help. My OCD is killing me spent a good 3 hours on this stupid issue. I just don't understand why the installer won't let me just install in a deeper directory. It lets me change the directory during installation but it doesn't ever work. Bitnami really should fix this if they're letting you change the directory in which to install, or at least limit the choices so that the user doesn't get stuck needlessly trying to figure out the problem with the installation.

答:
Bitnami developer here.

The problem you're facing must be related to the length of your path. This is a NTFS limitation, this is a related case:

Maximum filename length in NTFS (Windows XP and Windows Vista)?

Could you check if your path is longer than 255 characters?

Also spaces in directory names can be an issue, as all this software is ported from unix where spaces in directory names require the use of quotes around paths that contain spaces. So either check the config and put quotes around your paths that contain spaces like "folder 1/folder 2" or remove/replace the spaces in the paths.

Body:
This is really REALLY damn frustrating. For some reason Bitnami WAMP Stack keeps on FAILING to install in a deeper directory D:\***\***\***\***\***\wampstack. It ONLY works when I'm installing in the root (one folder in D:\Bitnami\wampstack). My set up NEEDS to have the stack server installed deeper down for organization's sake, but it won't work. It keeps failing.
I then tried installing it in the root directory, then tried moving the whole folder (since IT IS supposed to be self-contained.) into the proper directory (deeper down), and then changing the ImagePath of the wampserverApache and wampserverMySQL to reflect that of the new location. IT STILL WON'T START.
I keep getting this error:

> Starting all servers... Starting MySQL Database... Exit code: 1
> Stdout:
>
> Stderr: Unknown error starting mysql Starting Apache Web Server...
> Exit code: 1 Stdout:
>
> Stderr: Unknown error starting apache

Any idea on how to fix this? Or am I just doing something extremely wrong. Please help. My OCD is killing me spent a good 3 hours on this stupid issue. I just don't understand why the installer won't let me just install in a deeper directory. It lets me change the directory during installation but it doesn't ever work. Bitnami really should fix this if they're letting you change the directory in which to install, or at least limit the choices so that the user doesn't get stuck needlessly trying to figure out the problem with the installation.


来源: stackexchange

问:
Ionic don't compile last changes
I'm getting a problem compiling my App using Ionic 2 framework.

I just noticed there was a bug and trying to fix it, I just changed the app login url from the client's server to my test server, also added a few console.log. The problem is that after changing the code and compiling the code, the cordova still compiling the app without the console.log and to the client server.

I have tried

npm uninstall -g ionic

npm install -g ionic

cordova platform rm android --save

cordova platform add android --save

I also have cleaned my mobile cache and data and did a reset on it too.

Thank you in advance for the help.

EDIT: SOLVED

I was using PowerShell to launch the commands, changing it to the normal CMD running as administrator, it compiled the latest changes.

答:
I found the solution, in case somebody else has same problem
in package.json I update "@ionic/app-scripts" from 0.0.43 to 0.0.44 and then npm install
"devDependencies": {
"@ionic/app-scripts": "0.0.44",

try this
https://github.com/ionic-team/ionic-app-scripts/issues/363

ContentLicense: CC BY-SA 3.0

Title: Ionic don't compile last changes


问:
Get headers from http response
I am new to elm,
I have a login api which returns a JWT token in its hedears

```<code>curl  http://localhost:4000/api/login?email=bob@example&password=1234
</code>```

response:

```<code>HTTP/1.1 200 OK
authorization: Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXyLp0aSI6ImefP2GOWEFYWM47ig2W6nrhw
x-expires: 1499255103
content-type: text/plain; charset=utf-8

success
</code>```

now Im trying to write a function that will send request and return the token from the headers in elm

```<code>authUser =
    Http.send "http://localhost:4000/api/login?email=bob@example&password=1234"
</code>```

how do I do this in a simple way?

答:
May I humbly suggest you look at my elm-jwt library, and the get function there?

```<code>Jwt.get token "/api/data" dataDecoder
    |> Jwt.send DataResult
</code>```

JWT tokens normally need to be sent as a Authorization header and this function helps you create a Request type that can be passed to Http.send or Jwt.send

Title: Get headers from http response

Body:
I am new to elm,
I have a login api which returns a JWT token in its hedears

curl  http://localhost:4000/api/login?email=bob@example&password=1234

response:

HTTP/1.1 200 OK
authorization: Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXyLp0aSI6ImefP2GOWEFYWM47ig2W6nrhw
x-expires: 1499255103
content-type: text/plain; charset=utf-8

success

now Im trying to write a function that will send request and return the token from the headers in elm

authUser =
    Http.send "http://localhost:4000/api/login?email=bob@example&password=1234"

how do I do this in a simple way?

Body:
May I humbly suggest you look at my elm-jwt library, and the get function there?

Jwt.get token "/api/data" dataDecoder
    |> Jwt.send DataResult

JWT tokens normally need to be sent as a Authorization header and this function helps you create a Request type that can be passed to Http.send or Jwt.send


问:
Pandas groupby with delimiter join
I tried to use groupby to group rows with multiple values.

```<code>col val
A  Cat
A  Tiger
B  Ball
B  Bat

import pandas as pd
df = pd.read_csv("Inputfile.txt", sep='\t')
group = df.groupby(['col'])['val'].sum()
</code>```

I got

```<code>A CatTiger
B BallBat
</code>```

I want to introduce a delimiter, so that my output looks like

```<code>A Cat-Tiger
B Ball-Bat
</code>```

I tried,

```<code>group = df.groupby(['col'])['val'].sum().apply(lambda x: '-'.join(x))
</code>```

this yielded,

```<code>A C-a-t-T-i-g-e-r
B B-a-l-l-B-a-t
</code>```

What is the issue here ?

Thanks,

AP

答:
just try</p>

```<code>group = df.groupby(['col'])['val'].apply(lambda x: '-'.join(x))
</code>```

Title: Pandas groupby with delimiter join

Body:
I tried to use groupby to group rows with multiple values.

col val
A  Cat
A  Tiger
B  Ball
B  Bat

import pandas as pd
df = pd.read_csv("Inputfile.txt", sep='\t')
group = df.groupby(['col'])['val'].sum()

I got

A CatTiger
B BallBat

I want to introduce a delimiter, so that my output looks like

A Cat-Tiger
B Ball-Bat

I tried,

group = df.groupby(['col'])['val'].sum().apply(lambda x: '-'.join(x))

this yielded,

A C-a-t-T-i-g-e-r
B B-a-l-l-B-a-t

What is the issue here ?

Thanks,

AP

Body:
just try

group = df.groupby(['col'])['val'].apply(lambda x: '-'.join(x))


问:
Breaking the Parent-Child Relationship between Rectangles in SSRS
I'm creating a report in SSRS and I am using rectangles as containers. I moved one of the rectangles a bit to close to another and now it has become the 'child' of the rectangle. This has been confirmed to me because in the properties dialogue box it indicates that this other rectangle is now the 'Parent'. However I can't seem to find any option to break this relationship as the box is greyed out in the properties section meaning I can't edit it. I thought there would be an option to ungroup the report items but I can't find anything, i'm hoping I am missing something rather simple.</p>

答:
In Visual Studio (I'm currently latest 2017 but 2015 was pretty much the same)

Open the Document Outliner from View->Other Windows or [Ctrl+Alt+T] for short. From there you can cut and paste objects between containers (e.g. rectangles).

Be warned

There is no reliable drag and drop unfortunately. You must cut and paste in the document outline.

It's a bit hit and miss. Sometimes you have to paste it onto a non-container object inside the container before it gets the hint, other times you just have to select the container you want when pasting.

When moving between containers the object will end up being repositioned on the report, most annoying. If you drag it to the correct position you can end up dropping it back into the container you have just moved it from, so dragging can change container but rarely the way you want. The best way to move the object without risking container change is to change the Position Location in the object properties.

If your really brave you can always View Source and hack the RDL file directly.


问:
Make a Toplevel window take up the entire monitor space?
I'm trying to make a tkinter Toplevel window to go full screen and take up the entire monitor space (going over the task bar as well). I am able to do this with the Tk() using the code: window.attributes("-fullscreen", True). But I know you can't have two instances of Tk() so I need to use a Toplevel and root.attributes("-fullscreen", True) does not work with Toplevel.

The code I have in place at the moment to make the Toplevel fullscreen is this:

```<code>window = Toplevel()
 w = window.winfo_screenwidth()
 h = window.winfo_screenheight()
 window.geometry("%dx%d+0+0" % (w,h))
</code>```

But this does not even go into a proper fullscreen mode as the left side of the interface does not reach the edge of the screen.

How can I get a Toplevel window to take up the entire space of the screen like a Tk() window can?

答: I found a work around to this issue. What I did was I set the Tk() interface to take up the entire screen, and I placed a frame on top of it and made it fit the Tk(). That way I could put the desired widgets on the frame and when I'm done, destroy the frame and reset the size of the Tk() frame.

Body:
I'm trying to make a tkinter Toplevel window to go full screen and take up the entire monitor space (going over the task bar as well). I am able to do this with the Tk() using the code: window.attributes("-fullscreen", True). But I know you can't have two instances of Tk() so I need to use a Toplevel and root.attributes("-fullscreen", True) does not work with Toplevel.

The code I have in place at the moment to make the Toplevel fullscreen is this:

window = Toplevel()
 w = window.winfo_screenwidth()
 h = window.winfo_screenheight()
 window.geometry("%dx%d+0+0" % (w,h))

But this does not even go into a proper fullscreen mode as the left side of the interface does not reach the edge of the screen.

How can I get a Toplevel window to take up the entire space of the screen like a Tk() window can?


问:
Score Function of Cox proportional hazard in JuMP
I am not very experienced in converting equations to code. I got stuck on converting the score function of the partial likelihood to code in julia to be evaluated in JuMP.

The score function which, when solved for beta at 0, is the max.

I made a small simple data set.

```<code>Using DataFrames, DataFramesMeta, JuMP, Ipopt
#build DataFrame
times = [6,7,10,15,19,25]
is_censored = [1,0,1,1,0,1]
x= is_control = [1,1,0,1,0,0]

m = Model(solver=IpoptSolver(print_level=0))
using DataFrames

df = DataFrame();
df[:times]=times;
df[:is_censored]= is_censored;
df[:x]=x;
df

#sort df
df_sorted = sort!(df, cols = [order(:times)])

#make df_risk and df_uncensored
df_uncensored = @where(df_sorted, :is_censored .== 0)
df_risk = df_sorted

#use JuMP

##convert df to array

uncensored = convert(Array,df_uncensored[:x])
risk_set = convert(Array,df_risk[:x])
risk_index = convert(Array,find(is_censored .== 0))
x = convert(Array, x)
@variable(m, β, start = 0.0)

# score
@NLobjective(m, Max, sum(uncensored[i] - (([sum(exp(risk_set[j]*β)*x[j]) for j = risk_index[i]:length(risk_set)]) / ([(sum(exp(risk_set[j]*β)*x[j])) for j=risk_index[i]:length(risk_set)])) for i = 1:length(uncensored)))
</code>```

The error I am getting is

```<code>ERROR: exp is not defined for type AffExpr. Are you trying to build a nonlinear problem? Make sure you use @NLconstraint/@NLobjective.
Stacktrace:
 [1] exp(::JuMP.GenericAffExpr{Float64,JuMP.Variable}) at /home/icarus/.julia/v0.6/JuMP/src/operators.jl:630
 [2] collect(::Base.Generator{UnitRange{Int64},##58#60}) at ./array.jl:418
 [3] macro expansion at /home/icarus/.julia/v0.6/JuMP/src/parseExpr_staged.jl:489 [inlined]
 [4] macro expansion at /home/icarus/.julia/v0.6/JuMP/src/parsenlp.jl:226 [inlined]
 [5] macro expansion at /home/icarus/.julia/v0.6/JuMP/src/macros.jl:1086 [inlined]
 [6] anonymous at ./<missing>:?
</code>```

The error says the the exponential is the problem, but I previously did the log likelihood which has an exponential in it and got no errors.

In R the beta = -1.3261

If the above code was working I would expect that same output after running

```<code>solve(m)

println("β = ", getvalue(β))
</code>```

答:
The code in the question is a bit convoluted, but the following is an attempt to extract the relevant parts for a working method:

```<code>using JuMP, Ipopt

times = [6,7,10,15,19,25];
is_censored = 1-[1,0,1,1,0,1];
is_control = 1-[1,1,0,1,0,0];

uncensored = find(is_censored .== 0)

println("times = $times")
println("is_censored = $is_censored")
println("is_control = $is_control")

m = Model(solver=IpoptSolver(print_level=0))
@variable(m, β, start = 0.0)
@NLobjective(m, Max, sum(log(1+(-1)^is_control[uncensored[i]]*
  sum((-1)^is_control[j]*exp(is_control[j]*β) for j=uncensored[i]:length(times))/
  sum( exp(is_control[j]*β) for j=uncensored[i]:length(times)))
     for i=1:length(uncensored)))

solve(m)
println("β = ", getvalue(β))
</code>```

This outputs:

```<code>times = [6,7,10,15,19,25]
is_censored = [0,1,0,0,1,0]
is_control = [0,0,1,0,1,1]

β = -1.3261290591982942
</code>```

The β is the same one from the question, so I guess the tweaks to the input are correct and the formula is the log-likelihood. The beginning of the expression inside the log uses a common trick of choosing a +1 or -1 sign according to a 0/1 value bool with (-1)^bool.

Body:
I am not very experienced in converting equations to code. I got stuck on converting the score function of the partial likelihood to code in julia to be evaluated in JuMP.

The score function which, when solved for beta at 0, is the max.

I made a small simple data set.

Using DataFrames, DataFramesMeta, JuMP, Ipopt
#build DataFrame
times = [6,7,10,15,19,25]
is_censored = [1,0,1,1,0,1]
x= is_control = [1,1,0,1,0,0]

m = Model(solver=IpoptSolver(print_level=0))
using DataFrames

df = DataFrame();
df[:times]=times;
df[:is_censored]= is_censored;
df[:x]=x;
df

#sort df
df_sorted = sort!(df, cols = [order(:times)])

#make df_risk and df_uncensored
df_uncensored = @where(df_sorted, :is_censored .== 0)
df_risk = df_sorted

#use JuMP

##convert df to array

uncensored = convert(Array,df_uncensored[:x])
risk_set = convert(Array,df_risk[:x])
risk_index = convert(Array,find(is_censored .== 0))
x = convert(Array, x)
@variable(m, β, start = 0.0)

# score
@NLobjective(m, Max, sum(uncensored[i] - (([sum(exp(risk_set[j]*β)*x[j]) for j = risk_index[i]:length(risk_set)]) / ([(sum(exp(risk_set[j]*β)*x[j])) for j=risk_index[i]:length(risk_set)])) for i = 1:length(uncensored)))

The error I am getting is

ERROR: exp is not defined for type AffExpr. Are you trying to build a nonlinear problem? Make sure you use @NLconstraint/@NLobjective.
Stacktrace:
 [1] exp(::JuMP.GenericAffExpr{Float64,JuMP.Variable}) at /home/icarus/.julia/v0.6/JuMP/src/operators.jl:630
 [2] collect(::Base.Generator{UnitRange{Int64},##58#60}) at ./array.jl:418
 [3] macro expansion at /home/icarus/.julia/v0.6/JuMP/src/parseExpr_staged.jl:489 [inlined]
 [4] macro expansion at /home/icarus/.julia/v0.6/JuMP/src/parsenlp.jl:226 [inlined]
 [5] macro expansion at /home/icarus/.julia/v0.6/JuMP/src/macros.jl:1086 [inlined]
 [6] anonymous at ./<missing>:?

The error says the the exponential is the problem, but I previously did the log likelihood which has an exponential in it and got no errors.

In R the beta = -1.3261

If the above code was working I would expect that same output after running

solve(m)

println("β = ", getvalue(β))

Body:
The code in the question is a bit convoluted, but the following is an attempt to extract the relevant parts for a working method:

using JuMP, Ipopt

times = [6,7,10,15,19,25];
is_censored = 1-[1,0,1,1,0,1];
is_control = 1-[1,1,0,1,0,0];

uncensored = find(is_censored .== 0)

println("times = $times")
println("is_censored = $is_censored")
println("is_control = $is_control")

m = Model(solver=IpoptSolver(print_level=0))
@variable(m, β, start = 0.0)
@NLobjective(m, Max, sum(log(1+(-1)^is_control[uncensored[i]]*
  sum((-1)^is_control[j]*exp(is_control[j]*β) for j=uncensored[i]:length(times))/
  sum( exp(is_control[j]*β) for j=uncensored[i]:length(times)))
     for i=1:length(uncensored)))

solve(m)
println("β = ", getvalue(β))

This outputs:

times = [6,7,10,15,19,25]
is_censored = [0,1,0,0,1,0]
is_control = [0,0,1,0,1,1]

β = -1.3261290591982942

The β is the same one from the question, so I guess the tweaks to the input are correct and the formula is the log-likelihood. The beginning of the expression inside the log uses a common trick of choosing a +1 or -1 sign according to a 0/1 value bool with (-1)^bool.


问:
how to implement elastic search using Java?
I want to implement elastic search using Java in windows environment.please provide me some implementation details.</p>

答:
To know more about the elastic search based on the Lucene
See the following link

Elastic Search Java API

ContentLicense: CC BY-SA 2.5


问:
Keyboard listener can't change this.state
I want an animation to be executed when i open my keyboard and revert back when I close it.

The problem is:

undefined is not an object (evaluating 'this.state.scaleValue')

I have Keyboard.listener which works good.

State:

```<code>this.state = {
      scaleValue: new Animated.Value(0),
    }
</code>```

Animated View

```<code><Animated.View style={styles.logoContainer,
  {
      transform: [
          {scale: logoScale}
      ]
  }
}>
  <Image source={require('./someimage.png')} style={{width: 64, height: 64}} />
</Animated.View>
</code>```

Interpolate

```<code>const logoScale = this.state.scaleValue.interpolate({
      inputRange: [0, 0.5, 1],
      outputRange: [1, 0.5, 0]
    });
</code>```

Trigger

```<code>  _keyboardDidShow () {
    this.state.scaleValue.setValue(0);
    Animated.timing(
        this.state.ScaleValue,
        {
          toValue: 1,
          duration: 300,
          easing: Easing.easeOutBack
        }
    ).start();
  }
</code>```

So, when I put the code from trigger into a function and call it onPress with Touchable, it works.

答:
this does not have the same context inside the function supplied to Animated.timing.

You need to bind the method:

this._keyboardDidShow = this._keyboardDidShow.bind(this)

If that doesn't work you could probably even set let me = this above the call to timing (and refer to it as me within the body of the timing method call).

Body:
I want an animation to be executed when i open my keyboard and revert back when I close it.

The problem is:

undefined is not an object (evaluating 'this.state.scaleValue')

I have Keyboard.listener which works good.

State:

this.state = {
      scaleValue: new Animated.Value(0),
    }

Animated View

<Animated.View style={styles.logoContainer,
  {
      transform: [
          {scale: logoScale}
      ]
  }
}>
  <Image source={require('./someimage.png')} style={{width: 64, height: 64}} />
</Animated.View>

Interpolate

const logoScale = this.state.scaleValue.interpolate({
      inputRange: [0, 0.5, 1],
      outputRange: [1, 0.5, 0]
    });

Trigger

  _keyboardDidShow () {
    this.state.scaleValue.setValue(0);
    Animated.timing(
        this.state.ScaleValue,
        {
          toValue: 1,
          duration: 300,
          easing: Easing.easeOutBack
        }
    ).start();
  }

So, when I put the code from trigger into a function and call it onPress with Touchable, it works.


问:
how to set path for File Input Stream
i was trying to use a txt file but i got this eror "FileNotFoundException"
but it was readable and it exist but on line FileInputStream i got that error
whats the matter?</p>

```<code>        System.out.println(Files.isReadable(Paths.get("I:/Code/Coding/src/Files/" + path + ".txt")));
        System.out.println(Files.exists(Paths.get("I:/Code/Coding/src/Files/" + path + ".txt")));
        FileInputStream f1=new FileInputStream("I:/Code/Coding/src/Files/" + path + ".txt");
        reader = new ObjectInputStream(f1);

java.io.FileNotFoundException: I:\Code\Coding\src\Files\Artists.txt (The system cannot find the path specified)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileInputStream.<init>(FileInputStream.java:93)
    at sample.Datebase.Server.readFiles(Server.java:70)
    at sample.Datebase.Server.run(Server.java:99)
    at sample.Datebase.Server.main(Server.java:54)
Exception in thread "main" java.lang.NullPointerException
    at sample.Datebase.Server.readFiles(Server.java:94)
    at sample.Datebase.Server.run(Server.java:99)
    at sample.Datebase.Server.main(Server.java:54)
</code>```

答:
The first 3 lines of this code snippet looks ok, ideally it should not throw a FileNotFoundException if the Files.exists, and Files.isReadable gives true.

But you can not use an ObjectInputStream to read a normal text file, as it will look for certain file headers to interpret the java object serialized.

Can you please copy paste the exception trace ?

Title: how to set path for File Input Stream

Body:
i was trying to use a txt file but i got this eror "FileNotFoundException"
but it was readable and it exist but on line FileInputStream i got that error
whats the matter?

        System.out.println(Files.isReadable(Paths.get("I:/Code/Coding/src/Files/" + path + ".txt")));
        System.out.println(Files.exists(Paths.get("I:/Code/Coding/src/Files/" + path + ".txt")));
        FileInputStream f1=new FileInputStream("I:/Code/Coding/src/Files/" + path + ".txt");
        reader = new ObjectInputStream(f1);

java.io.FileNotFoundException: I:\Code\Coding\src\Files\Artists.txt (The system cannot find the path specified)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileInputStream.<init>(FileInputStream.java:93)
    at sample.Datebase.Server.readFiles(Server.java:70)
    at sample.Datebase.Server.run(Server.java:99)
    at sample.Datebase.Server.main(Server.java:54)
Exception in thread "main" java.lang.NullPointerException
    at sample.Datebase.Server.readFiles(Server.java:94)
    at sample.Datebase.Server.run(Server.java:99)
    at sample.Datebase.Server.main(Server.java:54)


问:
Ruby on Rails: Are "form_for(:product, ...)" and "form_for(@product, ...)" equivalent?
Is

```<code><%= form_for(:product, :url => {:action => 'update', :id => @product.id})) do |f| %>
  ...
<% end %>
</code>```

and

```<code><%= form_for(@product, :url => {:action => 'update', :id => @product.id})) do |f| %>
  ...
<% end %>
</code>```

exactly the same ?

答:
Similar, but not the same. When you use @product you have the benefit of being able to automatically populate values to the form fields from the model instance.

For example, if you in the action :new in your Controller assign @product like this:

```<code>@product = Product.new
</code>```

Then there will probably not be any difference in the generated form. However, if you follow this up in you :create action like this:

```<code>@product = Product.new(params[:product])
if @product.save
  ...
else
  render :action => :new
end
</code>```

Then if it is unable to save the @product instance, then it will render the same form as in :new but this time have all the fields populated with the values posted. That would not have been possible if you used :product

Body:
Is

<%= form_for(:product, :url => {:action => 'update', :id => @product.id})) do |f| %>
  ...
<% end %>

and

<%= form_for(@product, :url => {:action => 'update', :id => @product.id})) do |f| %>
  ...
<% end %>

exactly the same ?

Body:
Similar, but not the same. When you use @product you have the benefit of being able to automatically populate values to the form fields from the model instance.

For example, if you in the action :new in your Controller assign @product like this:

@product = Product.new

Then there will probably not be any difference in the generated form. However, if you follow this up in you :create action like this:

@product = Product.new(params[:product])
if @product.save
  ...
else
  render :action => :new
end

Then if it is unable to save the @product instance, then it will render the same form as in :new but this time have all the fields populated with the values posted. That would not have been possible if you used :product


问:
How to implement a method with an unknown number of arguments?
I have 1 interface and 3 class. I would like the class to be able to both implement the interface which need a transform method. This method must exist but there can't be more than one per class. I don't know the number of parameters taken by this class.

Example :

```<code>public interface A{
    public void transform(Object ... args);
}

public class B implements A{
    public void transform(String a){
        System.out.println(a);
    }
}

public class C implements A{
    public void transform(Integer a, Character b){
        System.out.println(a+b);
    }
}

// super generic case if possible with Objects + primitive
public class D implements A{
    public void transform(int a, String b){
        System.out.println(a+b);
    }
}
</code>```

This doesn't work. But I hope you got the idea. Is something like this possible in java ? How should I call them in a generic way ? Let's say if I have an other method like :

```<code>void callTransf(A a, Object ... objs){
    Method m = a.getClass().getMethods()[0];
    m.invoke(a, objs)
}
</code>```

答:
As per your requirement  you want to override method from your interface in class B and C , but you cannot do the way you have done that.

One way to do is as :

```<code>public interface A<T> {

    public void transform(T ... args);
}

public class B implements A<String> {

    @Override
    public void transform(String... args) {

    }

}

public class C implements A<Integer> {

    @Override
    public void transform(Integer... args) {

    }

}
</code>```

Body:
I have 1 interface and 3 class. I would like the class to be able to both implement the interface which need a transform method. This method must exist but there can't be more than one per class. I don't know the number of parameters taken by this class.

Example :

public interface A{
    public void transform(Object ... args);
}

public class B implements A{
    public void transform(String a){
        System.out.println(a);
    }
}

public class C implements A{
    public void transform(Integer a, Character b){
        System.out.println(a+b);
    }
}

// super generic case if possible with Objects + primitive
public class D implements A{
    public void transform(int a, String b){
        System.out.println(a+b);
    }
}

This doesn't work. But I hope you got the idea. Is something like this possible in java ? How should I call them in a generic way ? Let's say if I have an other method like :

void callTransf(A a, Object ... objs){
    Method m = a.getClass().getMethods()[0];
    m.invoke(a, objs)
}

Body:
As per your requirement  you want to override method from your interface in class B and C , but you cannot do the way you have done that.

One way to do is as :

public interface A<T> {

    public void transform(T ... args);
}

public class B implements A<String> {

    @Override
    public void transform(String... args) {

    }

}

public class C implements A<Integer> {

    @Override
    public void transform(Integer... args) {

    }

}


问:
Intellij code style setting for wrapping on multi line function arguments
The Spark code style requires four character indentation for multi parameter methods.  So: the following code -as presently formatted by IJ - is incorrect:

```<code>def generateCirclesRdd(sc: SparkContext,
                       nCircles: Int = 3,
                       nTotalPoints: Int = 30,
                       outerRadius: Double): RDD[(Long, Long, Double)] = {
</code>```

It should apparently be:

```<code>def generateCirclesRdd(sc: SparkContext,
    nCircles: Int = 3,
    nTotalPoints: Int = 30,
    outerRadius: Double): RDD[(Long, Long, Double)] = {
</code>```

Where is this setting in the IJ code style?  Screenshot shows what I was able to find.

UPDATE There is a comment about "Tabs and Indents" here it is :

Another Update: @yole has provided a helpful answer. However, I am still left with 2 spaces instead of 4 on the continuation.

For reference, here is the correct/required indentation within Spark. Notice the continuation on method declarations is 4 spaces.

```<code>  def train(
      data: RDD[Vector],
      k: Int,
      maxIterations: Int,
      runs: Int,
      initializationMode: String,
      seed: Long): KMeansModel = {
</code>```

However the continuation on method invocations is only two:

```<code>    new KMeans().setK(k)
      .setMaxIterations(maxIterations)
      .setRuns(runs)
      .setInitializationMode(initializationMode)
      .setSeed(seed)
      .run(data)
</code>```

答: enable "other | Alternate indentation for constructor args and parameter declarations with 4 spaces" help me out finally</p>

Body:
The Spark code style requires four character indentation for multi parameter methods.  So: the following code -as presently formatted by IJ - is incorrect:

def generateCirclesRdd(sc: SparkContext,
                       nCircles: Int = 3,
                       nTotalPoints: Int = 30,
                       outerRadius: Double): RDD[(Long, Long, Double)] = {

It should apparently be:

def generateCirclesRdd(sc: SparkContext,
    nCircles: Int = 3,
    nTotalPoints: Int = 30,
    outerRadius: Double): RDD[(Long, Long, Double)] = {

Where is this setting in the IJ code style?  Screenshot shows what I was able to find.

UPDATE There is a comment about "Tabs and Indents" here it is :

Another Update: @yole has provided a helpful answer. However, I am still left with 2 spaces instead of 4 on the continuation.

For reference, here is the correct/required indentation within Spark. Notice the continuation on method declarations is 4 spaces.

  def train(
      data: RDD[Vector],
      k: Int,
      maxIterations: Int,
      runs: Int,
      initializationMode: String,
      seed: Long): KMeansModel = {

However the continuation on method invocations is only two:

    new KMeans().setK(k)
      .setMaxIterations(maxIterations)
      .setRuns(runs)
      .setInitializationMode(initializationMode)
      .setSeed(seed)
      .run(data)


问:
Python 3: search for a specific string in a file
I have a txt file with strings assigned to each other like "sun - moon" and I want to get the assigned value (no matter which one) of a particular string if it would come from user input, and if not then create a new pair for file and write it to it:</p>

```<code>user_input = input()

if user_input in open('base.txt').read():
    print(True) # it's just to be sure that everything really works
else:
    base_file = open('base.txt', 'a+')
    base_file.write(user_input)
    base_file.write('\n')
    base_file.close()
</code>```

答:
```<code>import pickle

myDictA = {'sun': 'moon'}

with open('myFile.pkl', 'w') as file:
    pickle.dump(myDict, file)

with open('myFile.pkl', 'r') as file:
    myDictB = pickle.load(file)

print("myDictA:", myDictA)
print("myDictB:", myDictB)
</code>```

you can also integrate gzip in the file save load process to save disk space if you want.  Another option is to use cPickle which should be written the same way and is said to be up to 1000x faster.

Body:
I have a txt file with strings assigned to each other like "sun - moon" and I want to get the assigned value (no matter which one) of a particular string if it would come from user input, and if not then create a new pair for file and write it to it:

user_input = input()

if user_input in open('base.txt').read():
    print(True) # it's just to be sure that everything really works
else:
    base_file = open('base.txt', 'a+')
    base_file.write(user_input)
    base_file.write('\n')
    base_file.close()

Body:
import pickle

myDictA = {'sun': 'moon'}

with open('myFile.pkl', 'w') as file:
    pickle.dump(myDict, file)

with open('myFile.pkl', 'r') as file:
    myDictB = pickle.load(file)

print("myDictA:", myDictA)
print("myDictB:", myDictB)

you can also integrate gzip in the file save load process to save disk space if you want.  Another option is to use cPickle which should be written the same way and is said to be up to 1000x faster.


问:
Nginx not matching server_name on https
my nginx configuration doesn´t match my https server and redirects to the server ip instead.

```<code>server {
    listen 80 default_server;
    listen [::]:80 default_server;

    server_name www.example.de example.de;

    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl default_server;
    listen [::]:443 ssl default_server;

    include snippets/example.conf;
    include snippets/ssl-params.conf;

    server_name www.example.de example.de;

    root /var/www/html;
    index index.php index.html;

    location / {
            try_files $uri $uri/ /index.php?q=$uri&$args;
    }

    location ~ /.well-known {
            allow all;
    }

    error_page 404 /404.html;

    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
            root /usr/share/nginx/html;
    }

    location ~ .php$ {
            try_files $uri =404;
            fastcgi_split_path_info ^(.+.php)(/.+)$;
            fastcgi_pass unix:/var/run/php/php7.0-fpm-butterbirne.sock;
            fastcgi_index index.php;
            include fastcgi.conf;
    }

    client_max_body_size 50m;
}
</code>```

I have added default_server to it because some answers suggested that a default_server is necessary for matching.
Http is somehow fine but then it redirects to the machines ip instead. I will write 127.0.0.1 instead of the real ip

```<code>root@v22017043237047379:/etc/nginx# curl -I -L http://example.de
HTTP/1.1 301 Moved Permanently
Server: nginx/1.10.3
Date: Mon, 05 Jun 2017 08:30:09 GMT
Content-Type: text/html
Content-Length: 185
Connection: keep-alive
Location: https://www.example.de/

HTTP/1.1 301 Moved Permanently
Server: nginx/1.10.3
Date: Mon, 05 Jun 2017 08:30:10 GMT
Content-Type: text/html; charset=UTF-8
Connection: keep-alive
X-Pingback: https://127.0.0.1/xmlrpc.php
Location: https://127.0.0.1/
Strict-Transport-Security: max-age=63072000; includeSubdomains
X-Frame-Options: DENY
X-Content-Type-Options: nosniff

curl: (51) SSL: certificate subject name 'example.de' does not match target host name '127.0.0.1'
</code>```

nginx is 1.10.3 and os Debian Jessi

答: The mistake was something different. The error came from wordpress. It was configured to listen to an ip instead of the domain causing the wrong redirect.</p>

Title: Nginx not matching server_name on https

Body:
my nginx configuration doesn´t match my https server and redirects to the server ip instead.

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    server_name www.example.de example.de;

    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl default_server;
    listen [::]:443 ssl default_server;

    include snippets/example.conf;
    include snippets/ssl-params.conf;

    server_name www.example.de example.de;

    root /var/www/html;
    index index.php index.html;

    location / {
            try_files $uri $uri/ /index.php?q=$uri&$args;
    }

    location ~ /.well-known {
            allow all;
    }

    error_page 404 /404.html;

    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
            root /usr/share/nginx/html;
    }

    location ~ .php$ {
            try_files $uri =404;
            fastcgi_split_path_info ^(.+.php)(/.+)$;
            fastcgi_pass unix:/var/run/php/php7.0-fpm-butterbirne.sock;
            fastcgi_index index.php;
            include fastcgi.conf;
    }

    client_max_body_size 50m;
}

I have added default_server to it because some answers suggested that a default_server is necessary for matching.
Http is somehow fine but then it redirects to the machines ip instead. I will write 127.0.0.1 instead of the real ip

root@v22017043237047379:/etc/nginx# curl -I -L http://example.de
HTTP/1.1 301 Moved Permanently
Server: nginx/1.10.3
Date: Mon, 05 Jun 2017 08:30:09 GMT
Content-Type: text/html
Content-Length: 185
Connection: keep-alive
Location: https://www.example.de/

HTTP/1.1 301 Moved Permanently
Server: nginx/1.10.3
Date: Mon, 05 Jun 2017 08:30:10 GMT
Content-Type: text/html; charset=UTF-8
Connection: keep-alive
X-Pingback: https://127.0.0.1/xmlrpc.php
Location: https://127.0.0.1/
Strict-Transport-Security: max-age=63072000; includeSubdomains
X-Frame-Options: DENY
X-Content-Type-Options: nosniff

curl: (51) SSL: certificate subject name 'example.de' does not match target host name '127.0.0.1'

nginx is 1.10.3 and os Debian Jessi


问:
Android architecture component room library - How to handle livedata from DAO
I am not clear how to set the live data that is returned from a dao in room. Lets look at a example DAO in room:

```<code>    @Dao
public interface EventDao {

   @Query("SELECT * FROM " + Event.TABLE_NAME + " WHERE " + Event.DATE_FIELD + " > :minDate limit 1")
   LiveData<List<Event>> getEvents(LocalDateTime minDate);

   @Insert(onConflict = REPLACE)
   void addEvent(Event event);

   @Delete
   void deleteEvent(Event event);

   @Update(onConflict = REPLACE)
   void updateEvent(Event event);

}
</code>```

In particular, i want to look at the getEvents Query call.  It will return a list of events in a liveData object. How is this called from the callers end ?  Anyone have an example with an observable/flowable as well as plain old java ?

答:
If you are calling from directly activity then your activity must extends LifecycleActivity .

and write below code.

```<code>db.getEventDao().getEventList().observe(this, new Observer<List<Event>>() {
    @Override
    public void onChanged(@Nullable List<Event> events) {
        // update your UI.
    }
</code>```

Live data are lifecycle aware. so live data need to know the lifecycle.
So here in observe method first argument need the parameter of LifecycleOwner which is comes from LifecycleActivity.

And if you don't want to use LifeCycleActivity then you must have to use ViewModel. Prefer this link for more detail https://developer.android.com/topic/libraries/architecture/viewmodel.html

Note: In current alpha version LifecycleActivity is not extending AppCompatActivity. In future release it will be part of support library.

Body:
I am not clear how to set the live data that is returned from a dao in room. Lets look at a example DAO in room:

    @Dao
public interface EventDao {

   @Query("SELECT * FROM " + Event.TABLE_NAME + " WHERE " + Event.DATE_FIELD + " > :minDate limit 1")
   LiveData<List<Event>> getEvents(LocalDateTime minDate);

   @Insert(onConflict = REPLACE)
   void addEvent(Event event);

   @Delete
   void deleteEvent(Event event);

   @Update(onConflict = REPLACE)
   void updateEvent(Event event);

}

In particular, i want to look at the getEvents Query call.  It will return a list of events in a liveData object. How is this called from the callers end ?  Anyone have an example with an observable/flowable as well as plain old java ?

Body:
If you are calling from directly activity then your activity must extends LifecycleActivity .

and write below code.

db.getEventDao().getEventList().observe(this, new Observer<List<Event>>() {
    @Override
    public void onChanged(@Nullable List<Event> events) {
        // update your UI.
    }

Live data are lifecycle aware. so live data need to know the lifecycle.
So here in observe method first argument need the parameter of LifecycleOwner which is comes from LifecycleActivity.

And if you don't want to use LifeCycleActivity then you must have to use ViewModel. Prefer this link for more detail https://developer.android.com/topic/libraries/architecture/viewmodel.html

Note: In current alpha version LifecycleActivity is not extending AppCompatActivity. In future release it will be part of support library.


问:
Can't find kubeadm token after initializing master
When i run kubeadm init it shows a token that I should use from the other hosts to connect to this host.  Where is that token stored?  I'm trying to figure out more ways to automate this by adding kubeadm inside of Terraform.

Thanks for any help!

答:
Run this command in the master node to get the token</p>

```<code>kubeadm token list
</code>```

Body:
Run this command in the master node to get the token

kubeadm token list


问:
ramda findIndex with gaps
I have the following code where I want to fill in the id, so I'm thinking to write something like this:

```<code>const data = [
 { id: 'some-id' },
 { id: 'some-other-id' },
 { id: 'third-id' },
];

const tabIndex = R.findIndex(R.propEq('id', R.__))(data);
</code>```

So I can use it like this tabIndex('third-id'), but this is not a function.
What do I miss or confuse with this?

The following works

```<code>const tabIndex = (id) => R.findIndex(R.propEq('id', id))(data);
</code>```

But I thought, that is the point of R.__ gaps function.

答:
I'm still trying to master this dark art myself but I think the issue is that R.findIndex expects a predicate (a function / assertion) as an argument and does not differentiate between predicates and regular curried functions as input.

To resolve this a new function can be composed (evaluated right to left):

const data = [
    { id: 'some-id' },
    { id: 'some-other-id' },
    { id: 'third-id' }
];

const tabIndex = R.compose(R.findIndex(R.__, data), R.propEq('id'));

console.log(tabIndex('third-id')); // 2```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.24.1/ramda.min.js"></script></code>```

Side Note: the R.__ placeholder is inferred automatically for missing right-most arguments - e.g. R.propEq('id') and R.propEq('id', R.__) are equivalent.

Title: ramda findIndex with gaps

Body:
I have the following code where I want to fill in the id, so I'm thinking to write something like this:

const data = [
 { id: 'some-id' },
 { id: 'some-other-id' },
 { id: 'third-id' },
];

const tabIndex = R.findIndex(R.propEq('id', R.__))(data);

So I can use it like this tabIndex('third-id'), but this is not a function.
What do I miss or confuse with this?

The following works

const tabIndex = (id) => R.findIndex(R.propEq('id', id))(data);

But I thought, that is the point of R.__ gaps function.

Body:
I'm still trying to master this dark art myself but I think the issue is that R.findIndex expects a predicate (a function / assertion) as an argument and does not differentiate between predicates and regular curried functions as input.

To resolve this a new function can be composed (evaluated right to left):

const data = [
    { id: 'some-id' },
    { id: 'some-other-id' },
    { id: 'third-id' }
];

const tabIndex = R.compose(R.findIndex(R.__, data), R.propEq('id'));

console.log(tabIndex('third-id')); // 2

<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.24.1/ramda.min.js"></script>

Side Note: the R.__ placeholder is inferred automatically for missing right-most arguments - e.g. R.propEq('id') and R.propEq('id', R.__) are equivalent.


问:
Merge 2 arrays of objects
Lets have a look at an example.

```<code>var arr1 = new Array({name: "lang", value: "English"},
                     {name: "age", value: "18"});

var arr2 = new Array({name : "childs", value: '5'},
                     {name: "lang", value: "German"});
</code>```

I need to merge those 2 arrays of objects and create the following array:

```<code>var arr3 = new Array({name: "lang", value: "German"},
                     {name: "age", value: "18"},
                     {name : "childs", value: '5'});
</code>```

Is there any JavaScript or jQuery function to do this?

$.extend doesn't suit me. It returns

```<code>var arr4 = new Array({name : "childs", value: '5'},
                     {name: "lang", value: "German"});
</code>```

答:
The easiest way is with some ES6 magic:

Merge two with duplicates:

```<code>const a = [{a: 1}, {b: 2}]
const b = [{a: 1}]

const result = a.concat(b) // [{a: 1}, {b: 2}, {a: 1}]
</code>```

Without duplicates it is same as the above plus:

const distinct = [...new Set(result.map(item => item.YOUR_PROP_HERE))]

ContentLicense: CC BY-SA 4.0

Title: Merge 2 arrays of objects

Body:
Lets have a look at an example.

var arr1 = new Array({name: "lang", value: "English"},
                     {name: "age", value: "18"});

var arr2 = new Array({name : "childs", value: '5'},
                     {name: "lang", value: "German"});

I need to merge those 2 arrays of objects and create the following array:

var arr3 = new Array({name: "lang", value: "German"},
                     {name: "age", value: "18"},
                     {name : "childs", value: '5'});

Is there any JavaScript or jQuery function to do this?

$.extend doesn't suit me. It returns

var arr4 = new Array({name : "childs", value: '5'},
                     {name: "lang", value: "German"});

Body:
The easiest way is with some ES6 magic:

Merge two with duplicates:

const a = [{a: 1}, {b: 2}]
const b = [{a: 1}]

const result = a.concat(b) // [{a: 1}, {b: 2}, {a: 1}]

Without duplicates it is same as the above plus:

const distinct = [...new Set(result.map(item => item.YOUR_PROP_HERE))]


问:
Error on Zookeeper cluster mode with Docker?
I am trying to deploy a zookeeper cluster using docker on differents hosts. I use the next docker-compose where I run zoo1 in host1 zoo2 in host2 and zoo3 in host3.

```<code>version: '2'
services:
    zoo1:
        image: 31z4/zookeeper
        restart: always
        ports:
            - 2181:2181
            - 2888:2888
            - 3888:3888
        environment:
            ZOO_MY_ID: 1
            ZOO_SERVERS: server.1=host1-IP:2888:3888 server.2=host2-IP:2888:3888 server.3=host3-IP:2888:3888

    zoo2:
        image: 31z4/zookeeper
        restart: always
        ports:
            - 2182:2181
            - 2888:2888
            - 3888:3888
        environment:
            ZOO_MY_ID: 2
            ZOO_SERVERS: server.1=host1-IP:2888:3888 server.2=host2-IP:2888:3888 server.3=host3-IP:2888:3888

    zoo3:
        image: 31z4/zookeeper
        restart: always
        ports:
            - 2183:2181
            - 2888:2888
            - 3888:3888
        environment:
            ZOO_MY_ID: 3
            ZOO_SERVERS: server.1=host1-IP:2888:3888 server.2=host2-IP:2888:3888 server.3=host3-IP:2888:3888
</code>```

The code is added from: https://github.com/31z4/zookeeper-docker

I just try with the next docker-compose too, and adding zoo1, zoo2 and zoo3 to the /etc/hosts file:

```<code>version: '2'
services:
    zoo1:
        image: 31z4/zookeeper
        restart: always
        ports:
            - 2181:2181
            - 2888:2888
            - 3888:3888
        environment:
            ZOO_MY_ID: 1
            ZOO_SERVERS: server.1=zoo1:2888:3888 server.2=zoo2:2888:3888 server.3=zoo3:2888:3888

    zoo2:
        image: 31z4/zookeeper
        restart: always
        ports:
            - 2182:2181
            - 2888:2888
            - 3888:3888
        environment:
            ZOO_MY_ID: 2
            ZOO_SERVERS: server.1=zooo1:2888:3888 server.2=zoo2:2888:3888 server.3=zoo3:2888:3888

    zoo3:
        image: 31z4/zookeeper
        restart: always
        ports:
            - 2183:2181
            - 2888:2888
            - 3888:3888
        environment:
            ZOO_MY_ID: 3
            ZOO_SERVERS: server.1=zoo1:2888:3888 server.2=zoo2:2888:3888 server.3=zoo3:2888:3888
</code>```

But it is not working, if I check the status:

```<code>./bin/zkServer.sh status
ZooKeeper JMX enabled by default
Using config: /conf/zoo.cfg
Error contacting service. It is probably not running.
</code>```

答:
The left part of an exposing port is the local port of the host, that can only be used once. Also, you don't need to expose ports for containers interconnection, as they are in the same network.

So remove the left part 2888:2888, leave it as this: 2888, then docker will find a free port in the host (use docker ps to find out it). Or directly remove the ports directive if you don't need exposing ports.

```<code>version: '2'
services:
    zoo1:
        image: 31z4/zookeeper
        restart: always
        ports:
            - 2181
            - 2888
            - 3888
        environment:
            ZOO_MY_ID: 1
            ZOO_SERVERS: server.1=zoo1:2888:3888 server.2=zoo2:2888:3888 server.3=zoo3:2888:3888

    zoo2:
        image: 31z4/zookeeper
        restart: always
        ports:
            - 2181
            - 2888
            - 3888
        environment:
            ZOO_MY_ID: 2
            ZOO_SERVERS: server.1=zoo1:2888:3888 server.2=zoo2:2888:3888 server.3=zoo3:2888:3888

    zoo3:
        image: 31z4/zookeeper
        restart: always
        ports:
            - 2181
            - 2888
            - 3888
        environment:
            ZOO_MY_ID: 3
            ZOO_SERVERS: server.1=zoo1:2888:3888 server.2=zoo2:2888:3888 server.3=zoo3:2888:3888
</code>```

Body:
I am trying to deploy a zookeeper cluster using docker on differents hosts. I use the next docker-compose where I run zoo1 in host1 zoo2 in host2 and zoo3 in host3.

version: '2'
services:
    zoo1:
        image: 31z4/zookeeper
        restart: always
        ports:
            - 2181:2181
            - 2888:2888
            - 3888:3888
        environment:
            ZOO_MY_ID: 1
            ZOO_SERVERS: server.1=host1-IP:2888:3888 server.2=host2-IP:2888:3888 server.3=host3-IP:2888:3888

    zoo2:
        image: 31z4/zookeeper
        restart: always
        ports:
            - 2182:2181
            - 2888:2888
            - 3888:3888
        environment:
            ZOO_MY_ID: 2
            ZOO_SERVERS: server.1=host1-IP:2888:3888 server.2=host2-IP:2888:3888 server.3=host3-IP:2888:3888

    zoo3:
        image: 31z4/zookeeper
        restart: always
        ports:
            - 2183:2181
            - 2888:2888
            - 3888:3888
        environment:
            ZOO_MY_ID: 3
            ZOO_SERVERS: server.1=host1-IP:2888:3888 server.2=host2-IP:2888:3888 server.3=host3-IP:2888:3888

The code is added from: https://github.com/31z4/zookeeper-docker

I just try with the next docker-compose too, and adding zoo1, zoo2 and zoo3 to the /etc/hosts file:

version: '2'
services:
    zoo1:
        image: 31z4/zookeeper
        restart: always
        ports:
            - 2181:2181
            - 2888:2888
            - 3888:3888
        environment:
            ZOO_MY_ID: 1
            ZOO_SERVERS: server.1=zoo1:2888:3888 server.2=zoo2:2888:3888 server.3=zoo3:2888:3888

    zoo2:
        image: 31z4/zookeeper
        restart: always
        ports:
            - 2182:2181
            - 2888:2888
            - 3888:3888
        environment:
            ZOO_MY_ID: 2
            ZOO_SERVERS: server.1=zooo1:2888:3888 server.2=zoo2:2888:3888 server.3=zoo3:2888:3888

    zoo3:
        image: 31z4/zookeeper
        restart: always
        ports:
            - 2183:2181
            - 2888:2888
            - 3888:3888
        environment:
            ZOO_MY_ID: 3
            ZOO_SERVERS: server.1=zoo1:2888:3888 server.2=zoo2:2888:3888 server.3=zoo3:2888:3888

But it is not working, if I check the status:

./bin/zkServer.sh status
ZooKeeper JMX enabled by default
Using config: /conf/zoo.cfg
Error contacting service. It is probably not running.

Body:
The left part of an exposing port is the local port of the host, that can only be used once. Also, you don't need to expose ports for containers interconnection, as they are in the same network.

So remove the left part 2888:2888, leave it as this: 2888, then docker will find a free port in the host (use docker ps to find out it). Or directly remove the ports directive if you don't need exposing ports.

version: '2'
services:
    zoo1:
        image: 31z4/zookeeper
        restart: always
        ports:
            - 2181
            - 2888
            - 3888
        environment:
            ZOO_MY_ID: 1
            ZOO_SERVERS: server.1=zoo1:2888:3888 server.2=zoo2:2888:3888 server.3=zoo3:2888:3888

    zoo2:
        image: 31z4/zookeeper
        restart: always
        ports:
            - 2181
            - 2888
            - 3888
        environment:
            ZOO_MY_ID: 2
            ZOO_SERVERS: server.1=zoo1:2888:3888 server.2=zoo2:2888:3888 server.3=zoo3:2888:3888

    zoo3:
        image: 31z4/zookeeper
        restart: always
        ports:
            - 2181
            - 2888
            - 3888
        environment:
            ZOO_MY_ID: 3
            ZOO_SERVERS: server.1=zoo1:2888:3888 server.2=zoo2:2888:3888 server.3=zoo3:2888:3888


问:
Can't remove LFCR from text with the usual methods, Excel bug?
I have a list of strings littered with carriage return and line feed which I am trying to clean. I have tried the following methods:

find and replace of CTRL+J in excel

find and replace of ALT+0010/ALT+0013 in excel

find and replace of ALT+010/ALT+013 in excel

CLEAN in excel

copy list in excel, paste into notepad++, save as txt, reimport into excel ("Â" character was added on import) and finally replace "Â"

I've also tried the Text to Columns option with CTRL+J, absolutely no result whatsoever

EDIT: SUBSTITUTE CHAR(10) and CHAR(13) in excel didn't work either

None of the above worked, my list still contains line feeds and carriage returns. Is this a bug in excel?

Manually deleting these is out of the question due to the size of the list. I tried replacing these characters in notepad++ with pipe, and importing back into excel (choose delimited by pipe upon import and then copy/paste transpose), but again, the list is too long.

Anyone ideas?
Many thankZ

答:
If you wish to remove these items and manual methods ae too burdensome, then consider the following macro:

```<code>Sub KleanUp()
    Dim s1 As String, s2 As String
    s1 = Chr(10)
    s2 = Chr(13)
    Cells.Replace what:=s1, replacement:=""
    Cells.Replace what:=s2, replacement:=""
End Sub
</code>```

It will remove CR and LF in data in the active worksheet, but not change formulas like:

```<code>=A1 & CHAR(10) & A2
</code>```

or:

```<code>="alpha" & CHAR(4+6) & "beta"
</code>```

Body:
If you wish to remove these items and manual methods ae too burdensome, then consider the following macro:

Sub KleanUp()
    Dim s1 As String, s2 As String
    s1 = Chr(10)
    s2 = Chr(13)
    Cells.Replace what:=s1, replacement:=""
    Cells.Replace what:=s2, replacement:=""
End Sub

It will remove CR and LF in data in the active worksheet, but not change formulas like:

=A1 & CHAR(10) & A2

or:

="alpha" & CHAR(4+6) & "beta"


问:
React Router v4 not rendering anything when files separated
I have been able to get this to work with a single file, but moving routes to a route.js results in the component not being rendered. Clearly I am missing something. I have looked at a lot of tutorials but they seems to all be for React Router < v4.0

index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import {
  BrowserRouter as Router,
  Link,
  Route
} from 'react-router-dom';

import { AppContainer } from 'react-hot-loader';

import routes from './routes.js';

ReactDOM.render(
  <Router>
    <div>
      <Link to="/">/</Link><br />
      <Link to="/login">Login</Link><br />
    </div>
  </Router>,
  document.getElementById('root'),
);

// Hot Module Replacement API
if (module.hot) {
  module.hot.accept('./Home/Home', () => {
    render(Home);
  });
}
</code>```

routes.js

```<code>import React from 'react';
import {
  BrowserRouter as Router,
  Route
} from 'react-router-dom';
import ReactDOM from 'react-dom';

import Home from './Home/Home';
import Login from './Login/Login';

export default (
  <Route path="/" component={Home}>
    <Route path="/login" component={Login} />
  </Route>
)
</code>```

I have tried to actually have the bottom of route.js structured as below but i get an error

Adjacent JSX elements must be wrapped in an enclosing tag

Desired route.js

```<code>export default (
  <Route exact path="/" component={Home} />
  <Route path="/login" component={Login} />
)
</code>```

If I change this so that I have it all in index.js as below, everything works as expected.

Working index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import {
  BrowserRouter as Router,
  Link,
  Route
} from 'react-router-dom';

import { AppContainer } from 'react-hot-loader';

import Home from './Home/Home';
import Login from './Login/Login';

ReactDOM.render(
  <Router>
    <div>
      <Link to="/">/</Link><br />
      <Link to="/login">Login</Link><br />

      <Route exact path="/" component={Home} />
      <Route path="/login" component={Login} />
    </div>
  </Router>,
  document.getElementById('root'),
);

// Hot Module Replacement API
if (module.hot) {
  module.hot.accept('./Home/Home', () => {
    render(Home);
  });
}
</code>```

To save the question from getting too long I have not initially pasted my component code. If this is helpful let me know in the comments.

If it also makes a difference I am using ExpressJS, Webpack and React Hot Loader.

答:
Although you have imported routes you have not used them in your component

Use

```<code>ReactDOM.render(
  <Router>
    <div>
      <Link to="/">/</Link><br />
      <Link to="/login">Login</Link><br />
    </div>
    {routes}
  </Router>,
  document.getElementById('root'),
);
</code>```

and your routes.js file will be

```<code>import React from 'react';
import {
  BrowserRouter as Router,
  Switch
  Route
} from 'react-router-dom';
import ReactDOM from 'react-dom';

import Home from './Home/Home';
import Login from './Login/Login';

export default (
  <Switch>
  <Route exact path="/" component={Home} />
  <Route path="/login" component={Login} />
  </Switch>
)
</code>```

Body:
I have been able to get this to work with a single file, but moving routes to a route.js results in the component not being rendered. Clearly I am missing something. I have looked at a lot of tutorials but they seems to all be for React Router < v4.0

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import {
  BrowserRouter as Router,
  Link,
  Route
} from 'react-router-dom';

import { AppContainer } from 'react-hot-loader';

import routes from './routes.js';

ReactDOM.render(
  <Router>

      <Link to="/">/</Link>

      <Link to="/login">Login</Link>

  </Router>,
  document.getElementById('root'),
);

// Hot Module Replacement API
if (module.hot) {
  module.hot.accept('./Home/Home', () => {
    render(Home);
  });
}

routes.js

import React from 'react';
import {
  BrowserRouter as Router,
  Route
} from 'react-router-dom';
import ReactDOM from 'react-dom';

import Home from './Home/Home';
import Login from './Login/Login';

export default (
  <Route path="/" component={Home}>
    <Route path="/login" component={Login} />
  </Route>
)

I have tried to actually have the bottom of route.js structured as below but i get an error

Adjacent JSX elements must be wrapped in an enclosing tag

Desired route.js

export default (
  <Route exact path="/" component={Home} />
  <Route path="/login" component={Login} />
)

If I change this so that I have it all in index.js as below, everything works as expected.

Working index.js

import React from 'react';
import ReactDOM from 'react-dom';
import {
  BrowserRouter as Router,
  Link,
  Route
} from 'react-router-dom';

import { AppContainer } from 'react-hot-loader';

import Home from './Home/Home';
import Login from './Login/Login';

ReactDOM.render(
  <Router>

      <Link to="/">/</Link>

      <Link to="/login">Login</Link>

      <Route exact path="/" component={Home} />
      <Route path="/login" component={Login} />

  </Router>,
  document.getElementById('root'),
);

// Hot Module Replacement API
if (module.hot) {
  module.hot.accept('./Home/Home', () => {
    render(Home);
  });
}

To save the question from getting too long I have not initially pasted my component code. If this is helpful let me know in the comments.

If it also makes a difference I am using ExpressJS, Webpack and React Hot Loader.

Body:
Although you have imported routes you have not used them in your component

Use

ReactDOM.render(
  <Router>
    <div>
      <Link to="/">/</Link><br />
      <Link to="/login">Login</Link><br />
    </div>
    {routes}
  </Router>,
  document.getElementById('root'),
);

and your routes.js file will be

import React from 'react';
import {
  BrowserRouter as Router,
  Switch
  Route
} from 'react-router-dom';
import ReactDOM from 'react-dom';

import Home from './Home/Home';
import Login from './Login/Login';

export default (
  <Switch>
  <Route exact path="/" component={Home} />
  <Route path="/login" component={Login} />
  </Switch>
)


问:
Raw socket seems to get all packets in some cases, but not others
I have a little program where I'm sniffing the raw packets coming in over my ethernet interface. My code looks like:

```<code>        Socket ReceiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
        EndPoint DefaultIPEndpoint = new IPEndPoint(IPAddress.Parse("10.0.2.0"), 0); // 10.0.2.0 is static ip on ethernet interface

        ReceiveSocket.ReceiveTimeout = 5000;
        ReceiveSocket.Bind(DefaultIPEndpoint);
        ReceiveSocket.IOControl(IOControlCode.ReceiveAll, new byte[4] { 1, 0, 0, 0 }, null);

        while (true)
        {
            byte[] ReceiveBuffer = new byte[512];
            int ByteCount = 0;

            ByteCount = ReceiveSocket.ReceiveFrom(ReceiveBuffer, ref DefaultIPEndpoint);
            // Handle Packets...
        }
</code>```

What I'm finding is that this works only in certain implementations. By work, I mean that it actually receives all the packets on the interface. I can use wireshark to see whats coming, so I know about how much traffic I should receive, and when it "isnt working" it only receives a handful of packets, and they are only broadcasts (10.0.255.255) and what look like http notify's like this.

Now, it "works" when I build in debug, but not when I build in release. Additionally, I have this in its own standalone console app, and in another app where it works in a background thread. In the console app it works, but in the threaded app it does not work.

Any thoughts? Reasons why I might not be getting the rest of my packets?

EDIT: Looked at it again, and over wireshark, plus some breakpoints after receiving, and it looks like I can change my definition of "not working" to: I'm only getting the packets being sent. I'm not getting any of the packets received.

答: Going to answer my own question on this one. Turns out, it worked fine no matter the implementation once I tried it on a different computer with a different NIC. Leads me to believe that its a bug in my laptop's ethernet interface driver or something like that.</p>

Body:
I have a little program where I'm sniffing the raw packets coming in over my ethernet interface. My code looks like:

        Socket ReceiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
        EndPoint DefaultIPEndpoint = new IPEndPoint(IPAddress.Parse("10.0.2.0"), 0); // 10.0.2.0 is static ip on ethernet interface

        ReceiveSocket.ReceiveTimeout = 5000;
        ReceiveSocket.Bind(DefaultIPEndpoint);
        ReceiveSocket.IOControl(IOControlCode.ReceiveAll, new byte[4] { 1, 0, 0, 0 }, null);

        while (true)
        {
            byte[] ReceiveBuffer = new byte[512];
            int ByteCount = 0;

            ByteCount = ReceiveSocket.ReceiveFrom(ReceiveBuffer, ref DefaultIPEndpoint);
            // Handle Packets...
        }

What I'm finding is that this works only in certain implementations. By work, I mean that it actually receives all the packets on the interface. I can use wireshark to see whats coming, so I know about how much traffic I should receive, and when it "isnt working" it only receives a handful of packets, and they are only broadcasts (10.0.255.255) and what look like http notify's like this.

Now, it "works" when I build in debug, but not when I build in release. Additionally, I have this in its own standalone console app, and in another app where it works in a background thread. In the console app it works, but in the threaded app it does not work.

Any thoughts? Reasons why I might not be getting the rest of my packets?

EDIT: Looked at it again, and over wireshark, plus some breakpoints after receiving, and it looks like I can change my definition of "not working" to: I'm only getting the packets being sent. I'm not getting any of the packets received.


答:
You can use switch in route.js to export single element. Switch ensures only one Route component is being rendered.

```<code>import { Switch } from 'react-router-dom'

export default (
   <Switch>
      <Route exact path="/" component={Home} />
      <Route path="/login" component={Login} />
   </Switch>
)
</code>```

Title: React Router v4 not rendering anything when files separated

Body:
You can use switch in route.js to export single element. Switch ensures only one Route component is being rendered.

import { Switch } from 'react-router-dom'

export default (
   <Switch>
      <Route exact path="/" component={Home} />
      <Route path="/login" component={Login} />
   </Switch>
)


问:
Leave out parentheses in method call
I am writing a DSL in Scala where I'd like to achieve a chain of method calls as follows:

```<code>def x(i:Int) = i
x 1 equals 1 //doesn't compile
</code>```

I am not sure why the compiler is happy if I leave out the second parentheses but not the first one:

```<code>x(1) equals 1 //works fine
</code>```

Is there a way to achieve the first version?

答:
You can invoke methods without parenthesis, but not functions.

So the following works:

```<code>scala> object Foo {
     |   def x(i:Int) = i
     | }
defined object Foo

scala> Foo x 1
res9: Int = 1

scala> Foo x 1 equals 1
res10: Boolean = true
</code>```

Title: Leave out parentheses in method call

Body:
I am writing a DSL in Scala where I'd like to achieve a chain of method calls as follows:

def x(i:Int) = i
x 1 equals 1 //doesn't compile

I am not sure why the compiler is happy if I leave out the second parentheses but not the first one:

x(1) equals 1 //works fine

Is there a way to achieve the first version?

Body:
You can invoke methods without parenthesis, but not functions.

So the following works:

scala> object Foo {
     |   def x(i:Int) = i
     | }
defined object Foo

scala> Foo x 1
res9: Int = 1

scala> Foo x 1 equals 1
res10: Boolean = true


问:
Are default mysql parameters in RDS sane?
RDS uses the same set of parameters for all instance sizes and they don't seem to be that far from defaults (max_packet_size being too small etc.)

Has anyone looked at them and reviewed them for how sensible they are, especially on relatively bigger instances?

答: you can always change the parameter set to fit your application.</p>


问:
incorrect strcpy in buffer from python input
I'm trying to fill a simple buffer in C with an input generated with Python.  This is practice for a ROP project.  Here's the simple C-code:

```<code>#include <string.h>
int main(int argc, char **argv)
{
  char buf[128];
  strcpy(buf, argv[1]);
}
</code>```

compiled as: gcc -m32 -ggdb -fno-stack-protector -mpreferred-stack-boundary=2 test.c -o test

my hardware: x86-64, Linux Mint.

Here's part of the python input:

```<code>from struct import pack
p = '//bin/sh'  #address 0xffffd15c
p += 'A'*28

#null terminate our string
p += pack("<I", 0x0806e67a) # pop edx ; ret
p += pack("<I", 0xffffd163) # @ "/bin/sh" + 7
p += pack("<I", 0x080bac56) # pop eax ; ret
p += pack("<I", 0xffffffff) # 0xffffffff, or could xor the instruction
p += pack("<I", 0x0807b0cf) # inc eax ; ret
p += pack("<I", 0x08099fad) # mov dword ptr [edx], eax ; ret
</code>```

For some reason when I input this as argv[1] the buffer fills correctly up until the last line.  Instead of filling the buffer with 0x08099fad, it says 0x00009fad.  There's more input to follow this line, but this is where is screws up, causing the rest of the input to be junk (not what I inputed).

For some reason it seems like a null byte was put into strcpy, possibly terminating it prematurely.  But I don't know where the null byte is.  The same happens when I try to input this address, as well later on: 0x080acedc.

Any thoughts?

Thanks!

答:
Just so someone who searches this for an answer gets actual help.

I encountered the same problem today.
What I found out is, that python itself escapes these characters.
If you write the same program in C it will work.
If you print a var like this:

```<code>jmpto = "\xbf\x84\x04\x08"
print(jmpto)
</code>```

save the output to a file and use a hex editor to view it you will see it actually printed:

```<code>"C3 BB C2 84 04 08"
</code>```

When I instead tried the same with:

```<code>jmpto = "\x41\x42\x43\x44"
print(jmpto)
</code>```

looking at it in a hex editor it printed:

```<code>"41 42 43 44"
</code>```

I sadly don't know a solution as to how to print those characters correctly using python.
Simplest solution seems to be writing it in C.

P.S: @weather-vane, what is the point in shaming someone for being interested to learn how it works underneath the hood?
Security by obscurity (aka not telling so noone finds out) doesn't work.
Someone is gonna break it.
Better show interested white hats how to do it, they might try to fix those problems.

EDIT:
I found the solution to it thanks to someone at Frauenhofer FKIE.
Using sys.stdout.buffer.write(ex_str)
Where ex_str needs to be of type bytes.
First create your string as a bytearray, than cast it to bytes type:

```<code>import sys
#convert this Hex Address or Hex ASM Code to int: fb 84 04 08
jmpto = [251, 132, 4, 8]
ex_str = bytes(bytearray(b"A"*(132 + 4)) + bytearray(jmpto))
sys.stdout.buffer.write(ex_str)
</code>```

You can also use subprocess.call() or subprocess.run() to start the executable and pass it the bytes Object.

Hope someone found this helpful.

Body:
I'm trying to fill a simple buffer in C with an input generated with Python.  This is practice for a ROP project.  Here's the simple C-code:

#include <string.h>
int main(int argc, char **argv)
{
  char buf[128];
  strcpy(buf, argv[1]);
}

compiled as: gcc -m32 -ggdb -fno-stack-protector -mpreferred-stack-boundary=2 test.c -o test

my hardware: x86-64, Linux Mint.

Here's part of the python input:

from struct import pack
p = '//bin/sh'  #address 0xffffd15c
p += 'A'*28

#null terminate our string
p += pack("<I", 0x0806e67a) # pop edx ; ret
p += pack("<I", 0xffffd163) # @ "/bin/sh" + 7
p += pack("<I", 0x080bac56) # pop eax ; ret
p += pack("<I", 0xffffffff) # 0xffffffff, or could xor the instruction
p += pack("<I", 0x0807b0cf) # inc eax ; ret
p += pack("<I", 0x08099fad) # mov dword ptr [edx], eax ; ret

For some reason when I input this as argv[1] the buffer fills correctly up until the last line.  Instead of filling the buffer with 0x08099fad, it says 0x00009fad.  There's more input to follow this line, but this is where is screws up, causing the rest of the input to be junk (not what I inputed).

For some reason it seems like a null byte was put into strcpy, possibly terminating it prematurely.  But I don't know where the null byte is.  The same happens when I try to input this address, as well later on: 0x080acedc.

Any thoughts?

Thanks!

Body:
Just so someone who searches this for an answer gets actual help.

I encountered the same problem today.
What I found out is, that python itself escapes these characters.
If you write the same program in C it will work.
If you print a var like this:

jmpto = "\xbf\x84\x04\x08"
print(jmpto)

save the output to a file and use a hex editor to view it you will see it actually printed:

"C3 BB C2 84 04 08"

When I instead tried the same with:

jmpto = "\x41\x42\x43\x44"
print(jmpto)

looking at it in a hex editor it printed:

"41 42 43 44"

I sadly don't know a solution as to how to print those characters correctly using python.
Simplest solution seems to be writing it in C.

P.S: @weather-vane, what is the point in shaming someone for being interested to learn how it works underneath the hood?
Security by obscurity (aka not telling so noone finds out) doesn't work.
Someone is gonna break it.
Better show interested white hats how to do it, they might try to fix those problems.

EDIT:
I found the solution to it thanks to someone at Frauenhofer FKIE.
Using sys.stdout.buffer.write(ex_str)
Where ex_str needs to be of type bytes.
First create your string as a bytearray, than cast it to bytes type:

import sys
#convert this Hex Address or Hex ASM Code to int: fb 84 04 08
jmpto = [251, 132, 4, 8]
ex_str = bytes(bytearray(b"A"*(132 + 4)) + bytearray(jmpto))
sys.stdout.buffer.write(ex_str)

You can also use subprocess.call() or subprocess.run() to start the executable and pass it the bytes Object.

Hope someone found this helpful.


问:
How to check exact values in linq
i have list like this

```<code>Porfolio Value  CumulativeWeights
1246.540179      0.30873%
1254.380054      0.33031%
1258.260394      0.57136%
1262.300797      4.98794%
1262.710843      5.07213%
</code>```

First:  if that list contains first value is greater than 5% select That value and
Second: i have to check list contains exact 5% select That value.

if not satisfy above two condition we do some calculations. so how to select.

ConfidenceValue  is 5%

```<code>private static double CaluculateInterpolation(List<AgeWeightedHistorical> Weights, Double ConfidenceValue, CalaculationSettings oCalcSettings)
{
    double interpolation=0;

    var CumulativeVal = Weights.Find(n => n.CumulativeWeights > ConfidenceValue);
    if (CumulativeVal.CumulativeWeights >= ConfidenceValue)
    {
        interpolation = CumulativeVal.ProfolioPrices;
    }
    else
    {
        var LowestValues = Weights.Last(n => n.CumulativeWeights <= ConfidenceValue);
        if (LowestValues.CumulativeWeights == ConfidenceValue)
        {
            interpolation = CumulativeVal.ProfolioPrices;
        }
        else
        {
            var HightValues = Weights.FirstOrDefault(n => n.CumulativeWeights >= ConfidenceValue);
            double avgPrices = (LowestValues.ProfolioPrices + HightValues.ProfolioPrices) / 2;
            double avgWeights = (LowestValues.CumulativeWeights + HightValues.CumulativeWeights) / 2;
            if (avgWeights == ConfidenceValue)
            {
                interpolation = LowestValues.ProfolioPrices;
            }
            else
            {
                double Lowest_val = Math.Abs(LowestValues.CumulativeWeights - ConfidenceValue);
                double Higest_val = Math.Abs(HightValues.CumulativeWeights - ConfidenceValue);
                var FinalWeight = (Lowest_val < Higest_val) ? LowestValues : HightValues;
                double minWeight = Math.Min(avgWeights, FinalWeight.CumulativeWeights) / 100;
                double maxWeight = Math.Max(avgWeights, FinalWeight.CumulativeWeights) / 100;
                interpolation = avgPrices - ((avgPrices - FinalWeight.ProfolioPrices) * (((1 - (oCalcSettings.PercentageLevelOfConfidence / 100)) - minWeight) / (maxWeight - minWeight)));
            }
        }
    }
    return interpolation;

}
</code>```

im geting error please help me

答:
I suggest in C#, for precision calculation you should be using

```<code>decimal
</code>```

This will avoid many rounding problems..

Replace all your double with decimal, check your algorithm and it should work.

Title: How to check exact values in linq

Body:
i have list like this

Porfolio Value  CumulativeWeights
1246.540179      0.30873%
1254.380054      0.33031%
1258.260394      0.57136%
1262.300797      4.98794%
1262.710843      5.07213%

First:  if that list contains first value is greater than 5% select That value and
Second: i have to check list contains exact 5% select That value.

if not satisfy above two condition we do some calculations. so how to select.

ConfidenceValue  is 5%

private static double CaluculateInterpolation(List<AgeWeightedHistorical> Weights, Double ConfidenceValue, CalaculationSettings oCalcSettings)
{
    double interpolation=0;

    var CumulativeVal = Weights.Find(n => n.CumulativeWeights > ConfidenceValue);
    if (CumulativeVal.CumulativeWeights >= ConfidenceValue)
    {
        interpolation = CumulativeVal.ProfolioPrices;
    }
    else
    {
        var LowestValues = Weights.Last(n => n.CumulativeWeights <= ConfidenceValue);
        if (LowestValues.CumulativeWeights == ConfidenceValue)
        {
            interpolation = CumulativeVal.ProfolioPrices;
        }
        else
        {
            var HightValues = Weights.FirstOrDefault(n => n.CumulativeWeights >= ConfidenceValue);
            double avgPrices = (LowestValues.ProfolioPrices + HightValues.ProfolioPrices) / 2;
            double avgWeights = (LowestValues.CumulativeWeights + HightValues.CumulativeWeights) / 2;
            if (avgWeights == ConfidenceValue)
            {
                interpolation = LowestValues.ProfolioPrices;
            }
            else
            {
                double Lowest_val = Math.Abs(LowestValues.CumulativeWeights - ConfidenceValue);
                double Higest_val = Math.Abs(HightValues.CumulativeWeights - ConfidenceValue);
                var FinalWeight = (Lowest_val < Higest_val) ? LowestValues : HightValues;
                double minWeight = Math.Min(avgWeights, FinalWeight.CumulativeWeights) / 100;
                double maxWeight = Math.Max(avgWeights, FinalWeight.CumulativeWeights) / 100;
                interpolation = avgPrices - ((avgPrices - FinalWeight.ProfolioPrices) * (((1 - (oCalcSettings.PercentageLevelOfConfidence / 100)) - minWeight) / (maxWeight - minWeight)));
            }
        }
    }
    return interpolation;

}

im geting error please help me

Body:
I suggest in C#, for precision calculation you should be using

decimal

This will avoid many rounding problems..

Replace all your double with decimal, check your algorithm and it should work.


问:
How to make an element move up with the keyboard on android (HTML 5 app)
I want to make my text field that I've fixed to the bottom of the screen move up with the keyboard, basically making it stick to the keyboard.
This is how it looks without the keyboard, the element I want to move up with the keyboard is the footer.
When the keyboard pops-up it now goes over the input field, so you can't see what your typing. How could I fix this? Thanks in advace!

The html for this part:

```<code>    <footer class="mdl-shadow--8dp">
        <div class="mdl-textfield mdl-js-textfield">
            <input class="mdl-textfield__input" type="text" id="addItemDescription">
            <label class="mdl-textfield__label" for="addItemDescription">What do I need to do?</label>
        </div>
        <button id="addItemButton" class="mdl-button mdl-js-button mdl-button--fab mdl-js-ripple-effect mdl-button--colored mdl-shadow--2dp">
        <img class="material-icons" src="./res/material_icons/ic_add_white_24px.svg"></img>
        </button>
    </footer>
</code>```

And the CSS:

```<code>    footer{
    position: fixed;
    z-index: 700;
    text-align: center;
    right: 0;
    bottom: 0;
    left: 0;
    padding: 1rem;
    background-color: #bdbdbd;
}

.mdl-textfield__label{
    color: #4c4c4c;
    font-size: 30px;
}

.mdl-textfield__label:after{
    background: #f2f2f2;
}

.mdl-button--fab.mdl-button--colored {
    background:  #778f9b;
}

.mdl-button--fab.mdl-button--colored:hover {
    background:  #8d8d8d ;
}

#addItemButton{
    position: absolute;
    margin-left: 50px;
    margin-top: -45px;
}
</code>```

答:
If found a method that works, it's not really perfect, but it works pretty good. It works like this: run a function when the input is clicked that checks if the device is a phone and than add 50vh to the padding-bottom of the footer. There's also an function  that gets run when the input is getting blurred, this function resets the padding.

The css looks like this:

```<code>footer{
    position: fixed;
    z-index: 700;
    text-align: center;
    right: 0;
    bottom: 0;
    left: 0;
    padding: 1rem;
    background-color: #bdbdbd;
}
</code>```

The JS (with a bit of jquery) looks like this:

```<code>document.querySelector(DOM.description).addEventListener('click', input);
document.querySelector(DOM.description).addEventListener('blur', uniput);

var input = function(){
        if(document.querySelector(DOM.description) === document.activeElement){
            console.log('focused');

            if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i.test(navigator.userAgent)) {
                $('footer').css({'padding-bottom': '50vh'})
            }
    }
};

var uniput = function(){
    $('footer').css({'padding-bottom': '1rem'})
    }
</code>```

It's not to difficult, but it took some time to find out if there was a better way to it, but this actually works really nicely.

Body:
I want to make my text field that I've fixed to the bottom of the screen move up with the keyboard, basically making it stick to the keyboard.
This is how it looks without the keyboard, the element I want to move up with the keyboard is the footer.
When the keyboard pops-up it now goes over the input field, so you can't see what your typing. How could I fix this? Thanks in advace!

The html for this part:

            <input class="mdl-textfield__input" type="text" id="addItemDescription">
            What do I need to do?

        <button id="addItemButton" class="mdl-button mdl-js-button mdl-button--fab mdl-js-ripple-effect mdl-button--colored mdl-shadow--2dp">

        </button>

And the CSS:

    footer{
    position: fixed;
    z-index: 700;
    text-align: center;
    right: 0;
    bottom: 0;
    left: 0;
    padding: 1rem;
    background-color: #bdbdbd;
}

.mdl-textfield__label{
    color: #4c4c4c;
    font-size: 30px;
}

.mdl-textfield__label:after{
    background: #f2f2f2;
}

.mdl-button--fab.mdl-button--colored {
    background:  #778f9b;
}

.mdl-button--fab.mdl-button--colored:hover {
    background:  #8d8d8d ;
}

#addItemButton{
    position: absolute;
    margin-left: 50px;
    margin-top: -45px;
}

Body:
If found a method that works, it's not really perfect, but it works pretty good. It works like this: run a function when the input is clicked that checks if the device is a phone and than add 50vh to the padding-bottom of the footer. There's also an function  that gets run when the input is getting blurred, this function resets the padding.

The css looks like this:

footer{
    position: fixed;
    z-index: 700;
    text-align: center;
    right: 0;
    bottom: 0;
    left: 0;
    padding: 1rem;
    background-color: #bdbdbd;
}

The JS (with a bit of jquery) looks like this:

document.querySelector(DOM.description).addEventListener('click', input);
document.querySelector(DOM.description).addEventListener('blur', uniput);

var input = function(){
        if(document.querySelector(DOM.description) === document.activeElement){
            console.log('focused');

            if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i.test(navigator.userAgent)) {
                $('footer').css({'padding-bottom': '50vh'})
            }
    }
};

var uniput = function(){
    $('footer').css({'padding-bottom': '1rem'})
    }

It's not to difficult, but it took some time to find out if there was a better way to it, but this actually works really nicely.


问:
C# How to convert irregular date and time String into DateTime?
I have a program which converts a irregular date and time string into a system DateTime.

However as the system does not recognize irregular strings, the method .ParseExact, toDateTime and TryParse has not worked.

There are only 2 types of date time strings that the program needs to convert:

```<code> Thu Dec  9 05:12:42 2010
 Mon Dec 13 06:45:58 2010
</code>```

Please note that the single date has a double spacing which I have used the .replace method to convert the single date to Thu Dec 09 05:12:42 2010.

May someone please advise on the codes? Thanks!

The codes:

```<code>        String rb = re.Replace("  ", " 0");

        DateTime time = DateTime.ParseExact(rb, "ddd MMM dd hh:mm:ss yyyy", CultureInfo.CurrentCulture);

        Console.WriteLine(time.ToString("dddd, dd MMMM yyyy HH:mm:ss"));
</code>```

答:
You should capture the parts of your datetime into capture groups in the Match Object, then reconstitute them any way you want.

You can use this Regex statement with named groups to make it easier

```<code>((?<day>)\w{3})\s+((?<month>)\w{3})\s+((?<date>)\d)\s((?<time>)[0-9:]+)\s+((?<year>)\d{4})
</code>```

Body:
I have a program which converts a irregular date and time string into a system DateTime.

However as the system does not recognize irregular strings, the method .ParseExact, toDateTime and TryParse has not worked.

There are only 2 types of date time strings that the program needs to convert:

 Thu Dec  9 05:12:42 2010
 Mon Dec 13 06:45:58 2010

Please note that the single date has a double spacing which I have used the .replace method to convert the single date to Thu Dec 09 05:12:42 2010.

May someone please advise on the codes? Thanks!

The codes:

        String rb = re.Replace("  ", " 0");

        DateTime time = DateTime.ParseExact(rb, "ddd MMM dd hh:mm:ss yyyy", CultureInfo.CurrentCulture);

        Console.WriteLine(time.ToString("dddd, dd MMMM yyyy HH:mm:ss"));

Body:
You should capture the parts of your datetime into capture groups in the Match Object, then reconstitute them any way you want.

You can use this Regex statement with named groups to make it easier

((?<day>)\w{3})\s+((?<month>)\w{3})\s+((?<date>)\d)\s((?<time>)[0-9:]+)\s+((?<year>)\d{4})


问:
Downsizing header, removing footer entirely
I am working/designing the front-end (working on the layout html+css, later will use php, mvc pattern) of a website. The website has a header, body, side menu and a footer The layout is ready.

There are a few forms which are unusually long/huge since all fields are necessary and I could not make them any shorter. The form opens in a new page.

Not to scare the user away I am planning to downsize the header on the form template (the design change will only apply to the form templates) and get rid of the footer completely.

I tried looking a few places but did not find how to go it done. In short, I want the site to have all block i.e. header, body, footer but when it comes to the form I would want to downsize the header and remove the footer to make the form look sleeker.

Is there a way to do this?

Note: I post no code because I have no problem with the code but the concept.

答:
You can use display: none for the footerelement in CSS rules that only apply to this page (for example in a style tag in the head of that page).

Concerning the header, it depends how it is built, if it has a logo, background image, text, menu, whatever. In general you could reduce the height, make the logo smaller, hide parts of the text in there etc.


问:
Only allow EC2 instance to access static website on S3
I have a static website hosted on S3, I have set all files to be public.
Also, I have an EC2 instance with nginx that acts as a reverse proxy and can access the static website, so S3 plays the role of the origin.

What I would like to do now is set all files on S3 to be private, so that the website can only be accessed by traffic coming from the nginx (EC2).

So far I have tried the following. I have created and attached a new policy role to the EC2 instance with

Policies Granting Permission: AmazonS3ReadOnlyAccess

And have rebooted the EC2 instance.

I then created a policy in my S3 bucket console > Permissions > Bucket Policy

```<code>{
    "Version": "xxxxx",
    "Id": "xxxxxxx",
    "Statement": [
        {
            "Sid": "xxxxxxx",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::XXXXXXXXXX:role/MyROLE"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::XXX-bucket/*"
        }
    ]
}
</code>```

As principal I have set the ARN I got when I created the role for the EC2 instance.

```<code>"Principal": {
                "AWS": "arn:aws:iam::XXXXXXXXXX:role/MyROLE"
            },
</code>```

However, this does not work, any help is appreciated.

答:
Permissions in Amazon S3 can be granted in several ways:

Directly on an object (known as an Access Control List or ACL)

Via a Bucket Policy (which applies to the whole bucket, or a directory)

To an IAM User/Group/Role

If any of the above grant access, then the object can be accessed publicly.

Your scenario requires the following configuration:

The ACL on each object should not permit public access

There should be no Bucket Policy

You should assign permissions in the Policy attached to the IAM Role

Whenever you have permissions relating to a User/Group/Role, it is better to assign the permission in IAM rather than on the Bucket. Use Bucket Policies for general access to all users.

The policy on the Role would be:

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AllowBucketAccess",
            "Effect": "Allow",
            "Action": [
                "s3:GetObject"
            ],
            "Resource": [
                "arn:aws:s3:::my-bucket/*"
            ]
        }
    ]
}
</code>```

This policy is directly applied to the IAM Role, so there is no need for a principal field.

Please note that this policy only allows GetObject -- it does not permit listing of buckets, uploading objects, etc.

You also mention that "I have set all files to be public". If you did this by making each individual object publicly readable, then anyone will still be able to access the objects. There are two ways to prevent this -- either remove the permissions from each object, or create a Bucket Policy with a Deny statement that stops access, but still permits the Role to get access.

That's starting to get a bit tricky and hard to maintain, so I'd recommend removing the permissions from each object. This can be done via the management console by editing the permissions on each object, or by using the AWS Command-Line Interface (CLI) with a command like:

```<code>aws s3 cp s3://my-bucket s3://my-bucket --recursive --acl private
</code>```

This copies the files in-place but changes the access settings.

(I'm not 100% sure whether to use --acl private or --acl bucket-owner-full-control, so play around a bit.)

Body:
I have a static website hosted on S3, I have set all files to be public.
Also, I have an EC2 instance with nginx that acts as a reverse proxy and can access the static website, so S3 plays the role of the origin.

What I would like to do now is set all files on S3 to be private, so that the website can only be accessed by traffic coming from the nginx (EC2).

So far I have tried the following. I have created and attached a new policy role to the EC2 instance with

Policies Granting Permission: AmazonS3ReadOnlyAccess

And have rebooted the EC2 instance.

I then created a policy in my S3 bucket console > Permissions > Bucket Policy

{
    "Version": "xxxxx",
    "Id": "xxxxxxx",
    "Statement": [
        {
            "Sid": "xxxxxxx",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::XXXXXXXXXX:role/MyROLE"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::XXX-bucket/*"
        }
    ]
}

As principal I have set the ARN I got when I created the role for the EC2 instance.

"Principal": {
                "AWS": "arn:aws:iam::XXXXXXXXXX:role/MyROLE"
            },

However, this does not work, any help is appreciated.

Body:
Permissions in Amazon S3 can be granted in several ways:

Directly on an object (known as an Access Control List or ACL)

Via a Bucket Policy (which applies to the whole bucket, or a directory)

To an IAM User/Group/Role

If any of the above grant access, then the object can be accessed publicly.

Your scenario requires the following configuration:

The ACL on each object should not permit public access

There should be no Bucket Policy

You should assign permissions in the Policy attached to the IAM Role

Whenever you have permissions relating to a User/Group/Role, it is better to assign the permission in IAM rather than on the Bucket. Use Bucket Policies for general access to all users.

The policy on the Role would be:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AllowBucketAccess",
            "Effect": "Allow",
            "Action": [
                "s3:GetObject"
            ],
            "Resource": [
                "arn:aws:s3:::my-bucket/*"
            ]
        }
    ]
}

This policy is directly applied to the IAM Role, so there is no need for a principal field.

Please note that this policy only allows GetObject -- it does not permit listing of buckets, uploading objects, etc.

You also mention that "I have set all files to be public". If you did this by making each individual object publicly readable, then anyone will still be able to access the objects. There are two ways to prevent this -- either remove the permissions from each object, or create a Bucket Policy with a Deny statement that stops access, but still permits the Role to get access.

That's starting to get a bit tricky and hard to maintain, so I'd recommend removing the permissions from each object. This can be done via the management console by editing the permissions on each object, or by using the AWS Command-Line Interface (CLI) with a command like:

aws s3 cp s3://my-bucket s3://my-bucket --recursive --acl private

This copies the files in-place but changes the access settings.

(I'm not 100% sure whether to use --acl private or --acl bucket-owner-full-control, so play around a bit.)