问:
Delegate method not called from TableViewCell
This is the first time I'm working with delegate in swift. I've a table view with fixed three number of rows and every row has a seprate .xib for cell.

I'm adjusting the height of each cell based on the data I am getting in the cell. So as the tableView is loaded before and the cells are loaded after so I've defined a protocol in UITableViewCell class.

Above CalenderTimeTableViewCell class I've:

```<code>protocol ReloadingTable {
    func updateTableView()
}
</code>```

Inside this class above awakeFromNib() I've: var myDelegate: ReloadingTable? and in the method I'm getting data (using Alamofire) I'm calling self.myDelegate?.updateTableView().

In the viewController in which I've the tableView first of all I extended the class ReloadingTable and in this class I've:

```<code>func updateTableView() {
        tableView.reloadData()
    }
</code>```

By applying break points the code did get to the self.myDelegate?.updateTableView() but in viewController updateTableView method is not being called.

答:
As @vadian has commented you should assign target class to myDelegate

in cellForRowAt function assign target class to my delegate

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! CalenderTimeTableViewCell
    cell.myDelegate = self
    //Other
  }
</code>```

Body:
This is the first time I'm working with delegate in swift. I've a table view with fixed three number of rows and every row has a seprate .xib for cell.

I'm adjusting the height of each cell based on the data I am getting in the cell. So as the tableView is loaded before and the cells are loaded after so I've defined a protocol in UITableViewCell class.

Above CalenderTimeTableViewCell class I've:

protocol ReloadingTable {
    func updateTableView()
}

Inside this class above awakeFromNib() I've: var myDelegate: ReloadingTable? and in the method I'm getting data (using Alamofire) I'm calling self.myDelegate?.updateTableView().

In the viewController in which I've the tableView first of all I extended the class ReloadingTable and in this class I've:

func updateTableView() {
        tableView.reloadData()
    }

By applying break points the code did get to the self.myDelegate?.updateTableView() but in viewController updateTableView method is not being called.

Body:
As @vadian has commented you should assign target class to myDelegate

in cellForRowAt function assign target class to my delegate

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! CalenderTimeTableViewCell
    cell.myDelegate = self
    //Other
  }


来源: stackexchange

问:
Select rows having equal values in one column but not those are alone
This is my SQLfiddle : http://sqlfiddle.com/#!9/6a335/1/0

The result I want is the same like picture but without the 2 red rows, because for id_association_mots_idM 476 and 478, there is no traduction in english in the table.

I tried many requests and many ways.
Is it possible and if yes, how ?

Thanks for your help.

答:
Is this what you want?</p>

```<code>select t.*
from t
where exists (select 1
              from t t2
              where t2.id_association_mots_idm = t.id_association_mots_idm and
                    t2.category_v = 'langue_anglais'
             );
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is this what you want?

select t.*
from t
where exists (select 1
              from t t2
              where t2.id_association_mots_idm = t.id_association_mots_idm and
                    t2.category_v = 'langue_anglais'
             );


问:
How to set a colormap in interactive plot animations in python
The code below creates an animation of 600k points by scatter plotting 30k of them per frame. The animation works flawlessly, except for the fact that I don't know how to include my colormap (Heatintensity) in the animation. The Xs and Ys are changing but the color of the points is just blue. </p>

```<code>import numpy as np
import matplotlib.pyplot as plt

Heatintensity=workdata[0:600000] #Values controlling scatter colormap
Xs=xCoord[0:600000]
Ys=yCoord[0:600000]

plt.ion()
fig, ax = plt.subplots()
sc = ax.scatter(Xs, Ys, c=Heatintensity, cmap=cm.jet, s=5)

plt.draw()
for i in range(20):
    sc.set_offsets(np.c_[Xs[(i*30000):(i*30000)+30000],\
                        Ys[(i*30000):(i*30000)+30000]])
    fig.canvas.draw_idle()
    plt.pause(0.1)
</code>```

答:
In order to change the colors, you need to use

```<code>sc.set_array(Heatintensity[(i*30000):(i*30000)+30000])
</code>```

in addition to changing the offsets.

In order for the colors to represent the same numerical values for each animation step, the scatter must be normalized to all data,

```<code>norm = plt.Normalize(Heatintensity.min(), Heatintensity.max())
</code>```

Complete example:

```<code>import numpy as np
import matplotlib.pyplot as plt

Heatintensity=np.random.rand(600000) #Values controlling scatter colormap
Xs=np.random.rand(600000)
Ys=np.random.rand(600000)

plt.ion()
fig, ax = plt.subplots()

norm = plt.Normalize(Heatintensity.min(), Heatintensity.max())
sc = ax.scatter(Xs, Ys, c=Heatintensity, s=5, cmap=plt.cm.jet, norm=norm)

plt.draw()
for i in range(20):
    # set coordinates
    sc.set_offsets(np.c_[Xs[(i*30000):(i*30000)+30000],\
                        Ys[(i*30000):(i*30000)+30000]])
    # set colors
    sc.set_array(Heatintensity[(i*30000):(i*30000)+30000])
    # draw and make pause
    plt.pause(0.1)

plt.ioff()
plt.show()
</code>```

The same can be achieved using a FuncAnimation:

```<code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

Heatintensity=np.random.rand(600000) #Values controlling scatter colormap
Xs=np.random.rand(600000)
Ys=np.random.rand(600000)

fig, ax = plt.subplots()

norm = plt.Normalize(Heatintensity.min(), Heatintensity.max())
sc = ax.scatter(Xs, Ys, c=Heatintensity, s=5, cmap=plt.cm.jet, norm=norm)

def update(i):
    # set coordinates
    sc.set_offsets(np.c_[Xs[(i*30000):(i*30000)+30000],\
                        Ys[(i*30000):(i*30000)+30000]])
    # set colors
    sc.set_array(Heatintensity[(i*30000):(i*30000)+30000])

ani = animation.FuncAnimation(fig, update, frames=range(20), interval=100)

plt.show()
</code>```

Body:
The code below creates an animation of 600k points by scatter plotting 30k of them per frame. The animation works flawlessly, except for the fact that I don't know how to include my colormap (Heatintensity) in the animation. The Xs and Ys are changing but the color of the points is just blue.

import numpy as np
import matplotlib.pyplot as plt

Heatintensity=workdata[0:600000] #Values controlling scatter colormap
Xs=xCoord[0:600000]
Ys=yCoord[0:600000]

plt.ion()
fig, ax = plt.subplots()
sc = ax.scatter(Xs, Ys, c=Heatintensity, cmap=cm.jet, s=5)

plt.draw()
for i in range(20):
    sc.set_offsets(np.c_[Xs[(i*30000):(i*30000)+30000],\
                        Ys[(i*30000):(i*30000)+30000]])
    fig.canvas.draw_idle()
    plt.pause(0.1)

Body:
In order to change the colors, you need to use

sc.set_array(Heatintensity[(i*30000):(i*30000)+30000])

in addition to changing the offsets.

In order for the colors to represent the same numerical values for each animation step, the scatter must be normalized to all data,

norm = plt.Normalize(Heatintensity.min(), Heatintensity.max())

Complete example:

import numpy as np
import matplotlib.pyplot as plt

Heatintensity=np.random.rand(600000) #Values controlling scatter colormap
Xs=np.random.rand(600000)
Ys=np.random.rand(600000)

plt.ion()
fig, ax = plt.subplots()

norm = plt.Normalize(Heatintensity.min(), Heatintensity.max())
sc = ax.scatter(Xs, Ys, c=Heatintensity, s=5, cmap=plt.cm.jet, norm=norm)

plt.draw()
for i in range(20):
    # set coordinates
    sc.set_offsets(np.c_[Xs[(i*30000):(i*30000)+30000],\
                        Ys[(i*30000):(i*30000)+30000]])
    # set colors
    sc.set_array(Heatintensity[(i*30000):(i*30000)+30000])
    # draw and make pause
    plt.pause(0.1)

plt.ioff()
plt.show()

The same can be achieved using a FuncAnimation:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

Heatintensity=np.random.rand(600000) #Values controlling scatter colormap
Xs=np.random.rand(600000)
Ys=np.random.rand(600000)

fig, ax = plt.subplots()

norm = plt.Normalize(Heatintensity.min(), Heatintensity.max())
sc = ax.scatter(Xs, Ys, c=Heatintensity, s=5, cmap=plt.cm.jet, norm=norm)

def update(i):
    # set coordinates
    sc.set_offsets(np.c_[Xs[(i*30000):(i*30000)+30000],\
                        Ys[(i*30000):(i*30000)+30000]])
    # set colors
    sc.set_array(Heatintensity[(i*30000):(i*30000)+30000])

ani = animation.FuncAnimation(fig, update, frames=range(20), interval=100)

plt.show()


问:
sass-brunch omits modified SCSS on live-reload
On my Phoenix project, I found a peculiar behavior of sass-brunch.

Here are the short descriptions of my problem:

It generates a correct app.css on the priv/static/css directory when the Phoenix server started in dev envrionment.

When I modify one of SCSS files, the app.css gets generated but lacks only the lines from the modified SCSS file. It keeps the lines from the unmodified files.

This problem occurs on Ubuntu 16.04, but not on macOS.

On the log file, I noticed an entry that may be related to this issue:

[debug] Duplicate channel join for topic "phoenix:live_reload" in Phoenix.LiveReloader.Socket. Closing existing channel for new join.

I don't see such a line on my Mac.

My environment:

Ubuntu 16.04 Desktop

Phoenix 1.2.5

Node.js 8.9.1

npm 5.5.1

Brunch 2.10.7

sass-brunch 2.10.4

My package.json:

{
  "repository": {},
  "license": "MIT",
  "scripts": {
    "deploy": "brunch build --production",
    "watch": "brunch watch --stdin"
  },
  "dependencies": {
    "phoenix": "file:deps/phoenix",
    "phoenix_html": "file:deps/phoenix_html"
  },
  "devDependencies": {
    "babel-brunch": "6.0.6",
    "brunch": "2.10.7",
    "clean-css-brunch": "2.10.0",
    "sass-brunch": "^2.10.4",
    "uglify-js-brunch": "2.1.1"
  }
}

[UPDATE]

I found an interesting fact.

When I edit SCSS files using vim, the app.css gets generated normally.

When I edit them using atom, things do not go well.

答:
I found a workaround to my problem.

Put these lines to the brunch-config.js:

  watcher: {
    usePolling: true
  }

As the documentation of Brunch says, watcher gets slower but can be more reliable by setting true to this option.

The usePolling option is passed to chokidar, whose document says:

usePolling (default: false). Whether to use fs.watchFile (backed by polling), or fs.watch. If polling leads to high CPU utilization, consider setting this to false. It is typically necessary to set this to true to successfully watch files over a network, and it may be necessary to successfully watch files in other non-standard situations.


问:
Red has no open function like Rebol?
I want to read 10 lines from the end of a big text file without loading the whole file in memory.

I wanted to try to use Open as explained here for Rebol In Rebol, what is the idiomatic way to read a text file line by line?

But Red doesn't have open function ?

答:
You can try a read/lines/seek/part %yourfile  offset blocksize

But I have no clue. You have to test and adapt your offset and blocksize.

Title: Red has no open function like Rebol?


问:
SQL Server was not found or was not accessible
What is the problem below?

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

How can this be solved?

答:
You need to restart the MS SQL service. Please follow these steps:

1- Press window sign + R to open Run Window.

2- Type services.msc and press Enter.

3- Look for SQLSERVER(MSSQLSERVER) in the services list.

4- Right click on that service and choose REFRESH or START.

Hopefully it works.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 4.0


问:
from Flask import Flask ImportError: No module named Flask
I am following the tutorial here.

My file looks like this:

```<code>from flask import Flask
app = Flask(__name__)

@app.route("/")
def main():
    return "Welcome!"

if __name__ == "__main__":
    app.run()
</code>```

I run python app.py and get the following:

```<code>Traceback (most recent call last):
File "app.py", line 1, in <module>
from flask import Flask
ImportError: No module named Flask
</code>```

I do have flask installed. I was thinking it's a $PATH issue. I don't really know where to begin as far as troubleshooting goes.

which flask gives me:
/usr/local/bin/flask

which python gives me:
/usr/bin/python

Any help is much appreciated, there are other similar issues out there but those solutions have not helped. Happy to answer any questions. Thank you.

Answers to questions:

Q. Which Python version? A. Python 2.7.10

Q. How did you install Flask? A. pip install flask

答:
before run your app.py you need to activate your server by this command </p>

```<code>. venv/bin/activate
</code>```

Body:
I am following the tutorial here.

My file looks like this:

from flask import Flask
app = Flask(__name__)

@app.route("/")
def main():
    return "Welcome!"

if __name__ == "__main__":
    app.run()

I run python app.py and get the following:

Traceback (most recent call last):
File "app.py", line 1, in <module>
from flask import Flask
ImportError: No module named Flask

I do have flask installed. I was thinking it's a $PATH issue. I don't really know where to begin as far as troubleshooting goes.

which flask gives me:
/usr/local/bin/flask

which python gives me:
/usr/bin/python

Any help is much appreciated, there are other similar issues out there but those solutions have not helped. Happy to answer any questions. Thank you.

Answers to questions:

Q. Which Python version? A. Python 2.7.10

Q. How did you install Flask? A. pip install flask

Body:
before run your app.py you need to activate your server by this command

. venv/bin/activate


问:
SpringBootServletInitializer for multiple services in war for Tomcat
Spec : SpringBoot 4.x,Tomcat 7.x,JDK1.7

Process : Have 2 Rest Services as in separate package

with unique @RequestMapping and deployed as war to tomcat7.x

```<code>package com.servives.webservice  ~ Service A
package com.servives.dbservive   ~ Service B
package com.initilizer          ~  Service C
</code>```

Problem  :

Service A works if the "SpringBootServletInitializer" is present in
same package , while Service B does not work.

Service B works if the "SpringBootServletInitializer" is present in
same package , while Service A does not work.

Service A & B does not work if "SpringBootServletInitializer" is present in
separate package 'C'

Question : Is this a Bug or Am i doing some mistake ?

Note: Code sample not sharable for huge dependency.

答:
You are missing the @ComponentScan annotation. You need to add the following to your Application.java

```<code>@ComponentScan({"package.A", "package.B",...})
</code>```

OR
just add the base package as follows.
 @ComponentScan("base.package")

Body:
Spec : SpringBoot 4.x,Tomcat 7.x,JDK1.7

Process : Have 2 Rest Services as in separate package

with unique @RequestMapping and deployed as war to tomcat7.x

package com.servives.webservice  ~ Service A
package com.servives.dbservive   ~ Service B
package com.initilizer          ~  Service C

Problem  :

Service A works if the "SpringBootServletInitializer" is present in
same package , while Service B does not work.

Service B works if the "SpringBootServletInitializer" is present in
same package , while Service A does not work.

Service A & B does not work if "SpringBootServletInitializer" is present in
separate package 'C'

Question : Is this a Bug or Am i doing some mistake ?

Note: Code sample not sharable for huge dependency.

Body:
You are missing the @ComponentScan annotation. You need to add the following to your Application.java

@ComponentScan({"package.A", "package.B",...})

OR
just add the base package as follows.
 @ComponentScan("base.package")


问:
ocaml in function type how to use match with?
I need to solve this. Write a function (type 'a listl = Empty | Cons of 'a listl * 'a) list.
I have never used match with without list.
It is very confusing to use match with as an integer.

```<code>type 'a listl = Empty | Cons of 'a listl * 'a

var: int -> (int -> 'a) ->'a listl

tabu 5 (fun x -> x^x) => [0;1;9;16;25]
</code>```

Such results must come out.

```<code>type 'a listl = Empty | Cons of 'a listl * 'a

let rec tabu n f =
match n with
| 0 ->
| n -> if n > 0 then f n :: (tabu (n-1) f) else Empty
;;
</code>```

In match with, how to use "0,n" instead of "Empty,Cons"?
Is there any good idea?

答:
If I understand correctly, you are asking how to match values of type int. If you want to distinguish whether your parameter n has the value 0 or some other value, you can do it like so:

```<code>match n with
| 0 -> ...
| _ -> ...
</code>```

where the underscore is an anonymous wildcard pattern that matches any value. (But in this match it will not match 0 because the first pattern takes precedence.) In this case you could achieve the same thing with an if like so:

```<code>if n=0
then ...
else ...
</code>```

If you want to compare n with something that is not a constant, say m, then you cannot do just

```<code>match n with
| m -> ...
</code>```

because that does not use m as its original binding. Instead it treats m as a non-anonymous wildcard pattern and introduces a new binding for m with the value of n in the expression following the pattern. So you have to do

```<code>if n=m
then ...
else ...
</code>```

or use a when clause like so:

```<code>match n with
| _ when n=m ->
</code>```

Body:
I need to solve this. Write a function (type 'a listl = Empty | Cons of 'a listl * 'a) list.
I have never used match with without list.
It is very confusing to use match with as an integer.

type 'a listl = Empty | Cons of 'a listl * 'a

var: int -> (int -> 'a) ->'a listl

tabu 5 (fun x -> x^x) => [0;1;9;16;25]

Such results must come out.

type 'a listl = Empty | Cons of 'a listl * 'a

let rec tabu n f =
match n with
| 0 ->
| n -> if n > 0 then f n :: (tabu (n-1) f) else Empty
;;

In match with, how to use "0,n" instead of "Empty,Cons"?
Is there any good idea?

Body:
If I understand correctly, you are asking how to match values of type int. If you want to distinguish whether your parameter n has the value 0 or some other value, you can do it like so:

match n with
| 0 -> ...
| _ -> ...

where the underscore is an anonymous wildcard pattern that matches any value. (But in this match it will not match 0 because the first pattern takes precedence.) In this case you could achieve the same thing with an if like so:

if n=0
then ...
else ...

If you want to compare n with something that is not a constant, say m, then you cannot do just

match n with
| m -> ...

because that does not use m as its original binding. Instead it treats m as a non-anonymous wildcard pattern and introduces a new binding for m with the value of n in the expression following the pattern. So you have to do

if n=m
then ...
else ...

or use a when clause like so:

match n with
| _ when n=m ->


问:
Why does adding an array to number return a string?
```<code>var array = [1,2,4];

array+1  //gives '1,2,41'.
</code>```

<p>Can anyone explain this behaviour? </p>

答: Array is casted to string - then concatenated with integer value which is also casted to string.</p>

Body:
var array = [1,2,4];

array+1  //gives '1,2,41'.

Can anyone explain this behaviour?


问:
Making Stretch Animation in Android
I need to Animate Splash Screen in Android and I'm having a circle in the center of the Screen and I want that to Stretch to fill the entire Screen in an Animated way.How do I make it?</p>

答:
Its call Scale Animation you can do it like that

```<code>    ScaleAnimation scal=new ScaleAnimation(0, 1f, 0, 1f, Animation.RELATIVE_TO_SELF, (float)0.5, Animation.RELATIVE_TO_SELF, (float)0.5);
    scal.setDuration(1000);
    scal.setFillAfter(true);
    YOUR_VIEW.setAnimation(scal);
</code>```

YOUR_VIEW is the view of your xml(like ImageView) which you want to perform animation.

Title: Making Stretch Animation in Android

Body:
Its call Scale Animation you can do it like that

    ScaleAnimation scal=new ScaleAnimation(0, 1f, 0, 1f, Animation.RELATIVE_TO_SELF, (float)0.5, Animation.RELATIVE_TO_SELF, (float)0.5);
    scal.setDuration(1000);
    scal.setFillAfter(true);
    YOUR_VIEW.setAnimation(scal);

YOUR_VIEW is the view of your xml(like ImageView) which you want to perform animation.


问:
IdentityServer4 Client Scopes and User Claims based authorization
I have an IdentityServer4 that I use for authentication/authorization and I am a little confused on how to achieve the following:

if I have let us say 2 clients, and they are trying to access 2 APIs (each client can access one of them), however I have users with different permissions (user1 can access first API, user2 can access second API, user3 can access both)

When user3 which should have access to both APIs login using first client (only api1 scope is requested by client), how will I provide him a token that grants him access to both APIs (scopes), so he should not login again when using the second client?

I have read a lot of discussions about user claims and client scopes, but still I do not have clear answer on how to use them in authenticating the above case.

答:
The client needs to request both scopes, or you need a scope that gives access to both apis.

Scopes are granted to the clients there is no way for your Ids to know that user3 should have access to both unless the client requests both scopes.


问:
How to unit test a Node.js module that requires other modules and how to mock the global require function?
This is a trivial example that illustrates the crux of my problem:

```<code>var innerLib = require('./path/to/innerLib');

function underTest() {
    return innerLib.doComplexStuff();
}

module.exports = underTest;
</code>```

I am trying to write a unit test for this code. How can I mock out the requirement for the innerLib without mocking out the require function entirely?

So this is me trying to mock out the global require and finding out that it won’t work even to do that:

```<code>var path = require('path'),
    vm = require('vm'),
    fs = require('fs'),
    indexPath = path.join(__dirname, './underTest');

var globalRequire = require;

require = function(name) {
    console.log('require: ' + name);
    switch(name) {
        case 'connect':
        case indexPath:
            return globalRequire(name);
            break;
    }
};
</code>```

The problem is that the require function inside the underTest.js file has actually not been mocked out. It still points to the global require function. So it seems that I can only mock out the require function within the same file I’m doing the mocking in. If I use the global require to include anything, even after I’ve overridden the local copy, the files being required will still have the global require reference.

答:
You can use mockery library:</p>

```<code>describe 'UnderTest', ->
  before ->
    mockery.enable( warnOnUnregistered: false )
    mockery.registerMock('./path/to/innerLib', { doComplexStuff: -> 'Complex result' })
    @underTest = require('./path/to/underTest')

  it 'should compute complex value', ->
    expect(@underTest()).to.eq 'Complex result'
</code>```

Body:
This is a trivial example that illustrates the crux of my problem:

var innerLib = require('./path/to/innerLib');

function underTest() {
    return innerLib.doComplexStuff();
}

module.exports = underTest;

I am trying to write a unit test for this code. How can I mock out the requirement for the innerLib without mocking out the require function entirely?

So this is me trying to mock out the global require and finding out that it won’t work even to do that:

var path = require('path'),
    vm = require('vm'),
    fs = require('fs'),
    indexPath = path.join(__dirname, './underTest');

var globalRequire = require;

require = function(name) {
    console.log('require: ' + name);
    switch(name) {
        case 'connect':
        case indexPath:
            return globalRequire(name);
            break;
    }
};

The problem is that the require function inside the underTest.js file has actually not been mocked out. It still points to the global require function. So it seems that I can only mock out the require function within the same file I’m doing the mocking in. If I use the global require to include anything, even after I’ve overridden the local copy, the files being required will still have the global require reference.

Body:
You can use mockery library:

describe 'UnderTest', ->
  before ->
    mockery.enable( warnOnUnregistered: false )
    mockery.registerMock('./path/to/innerLib', { doComplexStuff: -> 'Complex result' })
    @underTest = require('./path/to/underTest')

  it 'should compute complex value', ->
    expect(@underTest()).to.eq 'Complex result'


问:
Eclipse save automatically
I would like Eclipse to automatically save every time I edit a file, in much the same way that it builds automatically. Because I've been using IntelliJ for the last year (which saves automatically by default), I keep having the following problem:

Make some changes in Eclipse

Forget to press save

Run the build, unit tests, and notice some strange behaviour

(Some time later....) realize that the unexpected behaviour occurred because I forgot to save the changes

Is there any way I can make Eclipse save automatically?

答: For Eclipse Mars 2, the settings are below Window > Preferences > General > Workspace. These settings are in minutes and not in seconds.

Title: Eclipse save automatically


问:
How to return error messages on custom content-types in Spring?
I have some @RestController with Spring. I use the query parameter ?format= to control the returned content type (this is a spring build-in feature).

Problem: if content-type is not json/xml, but eg text or csv, spring will try to convert the error response returned into csv. Which of course fails and therefore I'm not returning eg an AuthenticationException, but a HttpMediaTypeNotAcceptableException.

?format=json:

```<code>{
    "timestamp": "2017-11-15T11:00:07.079+0000",
    "status": 401,
    "error": "Unauthorized",
    "message": "Bad credentials",
    "path": "..."
}
</code>```

?format=xml:

```<code><Map>
    <timestamp>2017-11-15T11:00:21.590+0000</timestamp>
    <status>401</status>
    <error>Unauthorized</error>
    <message>Bad credentials</message>
    <path>...</path>
</Map>
</code>```

?format=csv: (I offer some endpoints that directly create text csv files):

```<code>Response could not be created: org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
</code>```

Question: how can I tell spring to format any error responses as eg plain text, incase the format parameter is not json/xml?

答:
You can make use of the spring controller advice annotation and exception handlers. Thus catching all manner of error and responding in a general way.

```<code>@ControllerAdvice
class YourControllerAdviceClass {
    @ResponseStatus(value= HttpStatus.NOT_FOUND, reason="Exception occured")
    @ExceptionHandler({ Exception.class })
    public YourReturnType handleAllException() {
        return YourReturnType;
    }
}
</code>```

for more info you could read this article to give you more options with regards to your error handling and response possibilities.

http://www.baeldung.com/exception-handling-for-rest-with-spring

Body:
I have some @RestController with Spring. I use the query parameter ?format= to control the returned content type (this is a spring build-in feature).

Problem: if content-type is not json/xml, but eg text or csv, spring will try to convert the error response returned into csv. Which of course fails and therefore I'm not returning eg an AuthenticationException, but a HttpMediaTypeNotAcceptableException.

?format=json:

{
    "timestamp": "2017-11-15T11:00:07.079+0000",
    "status": 401,
    "error": "Unauthorized",
    "message": "Bad credentials",
    "path": "..."
}

?format=xml:

<Map>
    <timestamp>2017-11-15T11:00:21.590+0000</timestamp>
    <status>401</status>
    <error>Unauthorized</error>
    <message>Bad credentials</message>
    <path>...</path>
</Map>

?format=csv: (I offer some endpoints that directly create text csv files):

Response could not be created: org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation

Question: how can I tell spring to format any error responses as eg plain text, incase the format parameter is not json/xml?

Body:
You can make use of the spring controller advice annotation and exception handlers. Thus catching all manner of error and responding in a general way.

@ControllerAdvice
class YourControllerAdviceClass {
    @ResponseStatus(value= HttpStatus.NOT_FOUND, reason="Exception occured")
    @ExceptionHandler({ Exception.class })
    public YourReturnType handleAllException() {
        return YourReturnType;
    }
}

for more info you could read this article to give you more options with regards to your error handling and response possibilities.

http://www.baeldung.com/exception-handling-for-rest-with-spring


问:
java web application classpath
I am writing web app using spring. Which is created using standard web application.
I need ApplicationContext to be initialized using ClassPathXmlApplicationContext so i placed context.xml file in WEB-INF folder and created ApplicationContextusing following code.

ApplicationContext context = new ClassPathXmlApplicationContext("context.xml");

But I get FileNotFoundException saying  context.xml is not found.
When i tried to initilize application using FileSystemXmlApplicationContext it works.

But i want ClassPathXmlApplicationContext
what can i do so that context.xml is located in classpath.

答:
You need to place your context.xml inside classes folder or you can use

```<code>new ClassPathXmlApplicationContext("classpath:context.xml")
</code>```

Read the below definition
ClassPathXmlApplicationContext will read files from your classpath. They must be in classes folder of your web application or in a jar in your libfolder.
FileSystemXmlApplicationContext can access all your file system, for example c:/config/applicationContext.xml.
XmlWebApplicationContext certainly can access to files contained in your web application.

Title: java web application classpath

Body:
You need to place your context.xml inside classes folder or you can use

new ClassPathXmlApplicationContext("classpath:context.xml")

Read the below definition
ClassPathXmlApplicationContext will read files from your classpath. They must be in classes folder of your web application or in a jar in your libfolder.
FileSystemXmlApplicationContext can access all your file system, for example c:/config/applicationContext.xml.
XmlWebApplicationContext certainly can access to files contained in your web application.


问:
sql server openrowset to read huge xml files in one step
It's my first post ever... and I really need help on this one so any one who has some knowlege on the subject - please help!

What I need to do is to read an xml file into sql server data tables. I was looking over and over for solutions to this one and have found a few actualy. The problem is the size of the xml which is being loaded. It weights 2GB (and there will 10GB ones). I have managed to do this but I saw one particular solution which seems to me to be a great one but I cannot figure it out.

Ok lets get to the point. Currently I do it this way:

I read an entire XML using the openrowset into a variable. (this takes the whole ram memory...)

next I use the .node() thing to pull out the data and fill the tables with them.

Thats a two-step process. I was wondering if I could do it in only one step. I saw that there are things like format files and there are numerus examples on how to use that to pull out data from flat files or even excel documents in a record-based maner (in stead of sucking the whole thing into a variable) but I CANNOT find any example which would show how to read that huge XML into a table parsing the data on the fly (based on the format file). Is it even possible? I would really appreciate some help, or guidence on where to find a good example.

Pardon my English - it's been a while since I had to write so much in that language :-)
Thanks in advance!

答:
For very large files, you could use SSIS: Loading XML data into SQL Server 2008

It gives you the flexibility of transforming the XML data, as well as reducing your memory footprint for very large files. Of course, it might be slower compared to using OPENROWSET in BULK mode.


问:
One-liner version of this function? (Ruby 1.8.6)
In the version of Ruby i'm using, (1.8.6 - don't ask), the Hash class doesn't define the Hash#hash method, which means that calling uniq on an array of hashes doesn't test whether the content is the same - it tests whether the objects are the same (using the default base Object#hash method).

To get around this, I can use include?, like so:

```<code>hashes = <a big list of hashes>
uniq_hashes = []
hashes.each do |hash|
  unless uniq_hashes.include?(hash)
    uniq_hashes << hash
  end
end;uniq_hashes.size
</code>```

Can anyone think of a way to condense this into a one-line method?

答:
Can you use each_with_object?</p>

```<code>hashes = [{title: 'a'}, {title: 'b'}, {title: 'c'}, {title: 'a'}]
p hashes.each_with_object([]) { |el, array| array << el unless array.include? el }.size
# 3
</code>```

Body:
In the version of Ruby i'm using, (1.8.6 - don't ask), the Hash class doesn't define the Hash#hash method, which means that calling uniq on an array of hashes doesn't test whether the content is the same - it tests whether the objects are the same (using the default base Object#hash method).

To get around this, I can use include?, like so:

hashes =
uniq_hashes = []
hashes.each do |hash|
  unless uniq_hashes.include?(hash)
    uniq_hashes << hash
  end
end;uniq_hashes.size

Can anyone think of a way to condense this into a one-line method?

Body:
Can you use each_with_object?

hashes = [{title: 'a'}, {title: 'b'}, {title: 'c'}, {title: 'a'}]
p hashes.each_with_object([]) { |el, array| array << el unless array.include? el }.size
# 3


问:
Select rows having equal values in one column but not those are alone
This is my SQLfiddle : http://sqlfiddle.com/#!9/6a335/1/0

The result I want is the same like picture but without the 2 red rows, because for id_association_mots_idM 476 and 478, there is no traduction in english in the table.

I tried many requests and many ways.
Is it possible and if yes, how ?

Thanks for your help.

答:
You're really going to have to start formatting and indenting your SQLs nicely if you want them to be maintainable in future

The following query excludes the red rows:

```<code>SELECT
  ass_m_m.id_association_mots_idM,
  ass_m_m.id_vocab_idM,
  v_a_m.categorie_v ,
  v_a_m.mot_v

FROM
`association_mots_id_mot` AS ass_m_m
INNER JOIN
`association_mots_login` AS ass_m_l
ON
  ass_m_m.id_association_mots_idM = ass_m_l.id_association_mots AND
  ass_m_l.id_login_mL = '1'

INNER JOIN
`vocabulaire_a_memoriser` AS v_a_m
ON
  ass_m_m.id_vocab_idM = v_a_m.id_vocab AND
  (v_a_m.categorie_v = 'langue_francais' OR v_a_m.categorie_v = 'langue_anglais')

INNER JOIN
(
  SELECT
    ass_m_m.id_association_mots_idM
  FROM
    `association_mots_id_mot` AS ass_m_m
    INNER JOIN
    `vocabulaire_a_memoriser` AS v_a_m
    ON
      ass_m_m.id_vocab_idM = v_a_m.id_vocab AND
      (v_a_m.categorie_v = 'langue_francais' OR v_a_m.categorie_v = 'langue_anglais')
   GROUP BY
     ass_m_m.id_association_mots_idM
   HAVING COUNT(distinct categorie_v) = 2
) wanted
ON
  ass_m_m.id_association_mots_idM = wanted.id_association_mots_idM
</code>```

I've converted the query to ANSI join syntax - please avoid using the old SELECT * FROM a,b,c,d WHERE a.id=b.id ... syntax

The top part of your query is your query (converted join syntax, and laid out indented so we have a chance of seeing what's going on) unchanged

The bit that does the work is this subquery:

```<code>(
  SELECT
    ass_m_m.id_association_mots_idM
  FROM
    `association_mots_id_mot` AS ass_m_m
    INNER JOIN
    `vocabulaire_a_memoriser` AS v_a_m
    ON
      ass_m_m.id_vocab_idM = v_a_m.id_vocab AND
      (v_a_m.categorie_v = 'langue_francais' OR v_a_m.categorie_v = 'langue_anglais')
   GROUP BY
     ass_m_m.id_association_mots_idM
   HAVING COUNT(distinct categorie_v) = 2
) wanted
</code>```

It reduces the ass_m_m.id_association_mots_idM list of 2,2,5,5,5,476,478 to just 2,5 because they are the only ass_m_m.id_association_mots_idM that have a COUNT(DISTINCT language) of 2 - i.e. they're the only rows where 2 distinct language values appear

Then, because the output of this query is just 2,5 when it's joined into the main, it restricts the main query to just rows where the iass_m_m.id_association_mots_idM is 2 or 5

Body:
You're really going to have to start formatting and indenting your SQLs nicely if you want them to be maintainable in future

The following query excludes the red rows:

SELECT
  ass_m_m.id_association_mots_idM,
  ass_m_m.id_vocab_idM,
  v_a_m.categorie_v ,
  v_a_m.mot_v

FROM
`association_mots_id_mot` AS ass_m_m
INNER JOIN
`association_mots_login` AS ass_m_l
ON
  ass_m_m.id_association_mots_idM = ass_m_l.id_association_mots AND
  ass_m_l.id_login_mL = '1'

INNER JOIN
`vocabulaire_a_memoriser` AS v_a_m
ON
  ass_m_m.id_vocab_idM = v_a_m.id_vocab AND
  (v_a_m.categorie_v = 'langue_francais' OR v_a_m.categorie_v = 'langue_anglais')

INNER JOIN
(
  SELECT
    ass_m_m.id_association_mots_idM
  FROM
    `association_mots_id_mot` AS ass_m_m
    INNER JOIN
    `vocabulaire_a_memoriser` AS v_a_m
    ON
      ass_m_m.id_vocab_idM = v_a_m.id_vocab AND
      (v_a_m.categorie_v = 'langue_francais' OR v_a_m.categorie_v = 'langue_anglais')
   GROUP BY
     ass_m_m.id_association_mots_idM
   HAVING COUNT(distinct categorie_v) = 2
) wanted
ON
  ass_m_m.id_association_mots_idM = wanted.id_association_mots_idM

I've converted the query to ANSI join syntax - please avoid using the old SELECT * FROM a,b,c,d WHERE a.id=b.id ... syntax

The top part of your query is your query (converted join syntax, and laid out indented so we have a chance of seeing what's going on) unchanged

The bit that does the work is this subquery:

(
  SELECT
    ass_m_m.id_association_mots_idM
  FROM
    `association_mots_id_mot` AS ass_m_m
    INNER JOIN
    `vocabulaire_a_memoriser` AS v_a_m
    ON
      ass_m_m.id_vocab_idM = v_a_m.id_vocab AND
      (v_a_m.categorie_v = 'langue_francais' OR v_a_m.categorie_v = 'langue_anglais')
   GROUP BY
     ass_m_m.id_association_mots_idM
   HAVING COUNT(distinct categorie_v) = 2
) wanted

It reduces the ass_m_m.id_association_mots_idM list of 2,2,5,5,5,476,478 to just 2,5 because they are the only ass_m_m.id_association_mots_idM that have a COUNT(DISTINCT language) of 2 - i.e. they're the only rows where 2 distinct language values appear

Then, because the output of this query is just 2,5 when it's joined into the main, it restricts the main query to just rows where the iass_m_m.id_association_mots_idM is 2 or 5


问:
Web scraping and python data types
Web Scraping script using BeautifulSoup4 and Python 3.0
I want to remove the $ sign (in result) from price value, make it of type float and perform some numeric operation on it. But it is in text. </p>

```<code>import requests
from bs4 import BeautifulSoup

def bitcoin_scheduler():
    url = "https://coinmarketcap.com/currencies/bitcoin/"
    r = requests.get(url)
    offline_data = r.content
    soup = BeautifulSoup(offline_data, 'html.parser')

    name_box = soup.find('small', attrs={'class': 'bold hidden-xs'})
    name = name_box.text.strip()

    price_box = soup.find('span', attrs={'class': 'text-large'})
    price = price_box.text.strip()

    print(time.ctime(), name, price)
    threading.Timer(5.0, bitcoin_scheduler).start()

bitcoin_scheduler()
</code>```

<p>Result: </p>

```<code>Wed Nov 15 16:37:20 2017 (BTC) $6962.29
Wed Nov 15 16:37:25 2017 (BTC) $6962.29
Wed Nov 15 16:37:31 2017 (BTC) $6962.29
Wed Nov 15 16:37:36 2017 (BTC) $6962.29
</code>```

答:
You can check with isdigit() but default isdigit() method only
  works for int not for float so you can define your own isdigit()
  which will work for both:

```<code>import requests
from bs4 import BeautifulSoup
import time
import threading

new=[]

def isdigit(d):
    try:
        float(d)
        return True
    except ValueError:
        return False

def bitcoin_scheduler():
    url = "https://coinmarketcap.com/currencies/bitcoin/"
    r = requests.get(url)
    offline_data = r.content
    soup = BeautifulSoup(offline_data, 'html.parser')

    name_box = soup.find('small', attrs={'class': 'bold hidden-xs'})
    name = name_box.text.strip()

    price_box = soup.find('span', attrs={'class': 'text-large'})
    price = price_box.text.strip('$')
    if isdigit(price)==True:
        price=float(price)
        #do your stuff with price
        print(time.ctime(), name,price)
        print(type(price))

    threading.Timer(5.0, bitcoin_scheduler).start()

bitcoin_scheduler()
</code>```

output:

```<code>Wed Nov 15 17:07:22 2017 (BTC) 7003.54
<class 'float'>
Wed Nov 15 17:07:54 2017 (BTC) 7003.54
<class 'float'>
</code>```

Title: Web scraping and python data types

Body:
Web Scraping script using BeautifulSoup4 and Python 3.0
I want to remove the $ sign (in result) from price value, make it of type float and perform some numeric operation on it. But it is in text.

import requests
from bs4 import BeautifulSoup

def bitcoin_scheduler():
    url = "https://coinmarketcap.com/currencies/bitcoin/"
    r = requests.get(url)
    offline_data = r.content
    soup = BeautifulSoup(offline_data, 'html.parser')

    name_box = soup.find('small', attrs={'class': 'bold hidden-xs'})
    name = name_box.text.strip()

    price_box = soup.find('span', attrs={'class': 'text-large'})
    price = price_box.text.strip()

    print(time.ctime(), name, price)
    threading.Timer(5.0, bitcoin_scheduler).start()

bitcoin_scheduler()

Result:

Wed Nov 15 16:37:20 2017 (BTC) $6962.29
Wed Nov 15 16:37:25 2017 (BTC) $6962.29
Wed Nov 15 16:37:31 2017 (BTC) $6962.29
Wed Nov 15 16:37:36 2017 (BTC) $6962.29

Body:
You can check with isdigit() but default isdigit() method only
  works for int not for float so you can define your own isdigit()
  which will work for both:

import requests
from bs4 import BeautifulSoup
import time
import threading

new=[]

def isdigit(d):
    try:
        float(d)
        return True
    except ValueError:
        return False

def bitcoin_scheduler():
    url = "https://coinmarketcap.com/currencies/bitcoin/"
    r = requests.get(url)
    offline_data = r.content
    soup = BeautifulSoup(offline_data, 'html.parser')

    name_box = soup.find('small', attrs={'class': 'bold hidden-xs'})
    name = name_box.text.strip()

    price_box = soup.find('span', attrs={'class': 'text-large'})
    price = price_box.text.strip('$')
    if isdigit(price)==True:
        price=float(price)
        #do your stuff with price
        print(time.ctime(), name,price)
        print(type(price))

    threading.Timer(5.0, bitcoin_scheduler).start()

bitcoin_scheduler()

output:

Wed Nov 15 17:07:22 2017 (BTC) 7003.54
<class 'float'>
Wed Nov 15 17:07:54 2017 (BTC) 7003.54
<class 'float'>


问:
How to enable InstallShield Limited Edition 2015
I want to deploy my project, to do so I went to the file --> new project --> other project types --> setup and deployment
but there I couldn't find any option like
"setup project" I have downloaded InstallShield Limited Edition. But still same webpage is coming which is asking me to download InstallShield Limited Edition

and these are the options which I am getting when I click "other project types"

Any help?

答:
It happened to me. I had installed both VS2013 and VS2015. Initially enabled it for 2013 and worked. After that I installed VS 2015. Tried to enable InstallShield LE but nothing worked.

It finally worked after simply uninstalling the InstallShieldLE , restaring the PC and Installing it again. For both of my VS2013 and VS2015 installations.


问:
Evaluating predicted probabilities with histogram in R
I have a dataframe containing european football matches, their full time result and implied probability for home win result (using bookies odds).
looks as follow:

```<code>Div     Date HomeTeam       AwayTeam FTR  PSH  PSD  PSA PSCH PSCD PSCA homeprob
F2 28/07/17    Brest    Chateauroux   A 2.01 3.07 4.92 1.91 3.27 5.13     0.50
F2 28/07/17    Nimes          Reims   A 2.33 3.05 3.73 2.34 3.12 3.62     0.43
...
</code>```

So I created a histogram with the implied probability on the x axis and frequency on the y axis. And now I want to plot on the same graph the number of actual wins for each homeprob value (so I can compare observed vs expected)
this is the graph I have so far

I'm just not sure how to. Was thinking of running a loop through every possible value of homeprob and to add count if FTR == "H" ?

btw - please let me know if you think there is better way to compare observed and expected.

Thanks!

答:
I think you have a few different options for how to compare home win probability and "H" (which I'm guessing is actual or predicted win).  As suggested in the comment, you could cut homeprob into buckets and use dplyr for aggregate statistics.  Then use color for wins or simply plot homeprob vs wins.

Since there are a few ways to do it, I'll give some options and a reproducible example.

Here is some made up data that is similar to yours:

```<code># random normal data
randn_data <- rnorm(15000, 0.5, .05)
df <- data.frame(homeprob = randn_data)
# random uniform from 0 to 1
df$randunif <- runif(nrow(df))
# new feature is "H" if random uniform is less than homeprob
df$ftr <- ifelse(df$randunif < df$homeprob, "H", "A")
df$probcut <- cut(df$homeprob, seq(0.2, 0.8, 0.05))
</code>```

Now you could use color for total wins, although I don't think that would be the best option because your data is normal and the frequency will be higher towards the mean:

```<code>library(dplyr)
df_plot1 <- df %>%
  group_by(probcut) %>%
  summarise(hprob_counts = n(), wins = sum(ftr == "H"))
# wins as color
library(ggplot2)
ggplot(df_plot1, aes(x = probcut, y = hprob_counts, fill = wins)) +
  geom_col() +
  scale_y_sqrt()
</code>```

I think it would be better to use win rate to compare the expected and observed:

```<code>df_plot2 <- df %>%
  group_by(probcut) %>%
  summarise(hprob_counts = n(), wins = sum(ftr == "H")) %>%
  mutate(win_rate = wins / hprob_counts)

ggplot(df_plot2, aes(x = probcut, y = hprob_counts, fill = win_rate)) +
  geom_col() +
  scale_y_sqrt()
</code>```

You could also just plot homeprob and win_rate without the distribution:

```<code>ggplot(df_plot2, aes(x = probcut, y = win_rate)) +
  geom_col()
</code>```

Hopefully this is more or less what you were looking for.

Body:
I have a dataframe containing european football matches, their full time result and implied probability for home win result (using bookies odds).
looks as follow:

Div     Date HomeTeam       AwayTeam FTR  PSH  PSD  PSA PSCH PSCD PSCA homeprob
F2 28/07/17    Brest    Chateauroux   A 2.01 3.07 4.92 1.91 3.27 5.13     0.50
F2 28/07/17    Nimes          Reims   A 2.33 3.05 3.73 2.34 3.12 3.62     0.43
...

So I created a histogram with the implied probability on the x axis and frequency on the y axis. And now I want to plot on the same graph the number of actual wins for each homeprob value (so I can compare observed vs expected)
this is the graph I have so far

I'm just not sure how to. Was thinking of running a loop through every possible value of homeprob and to add count if FTR == "H" ?

btw - please let me know if you think there is better way to compare observed and expected.

Thanks!

Body:
I think you have a few different options for how to compare home win probability and "H" (which I'm guessing is actual or predicted win).  As suggested in the comment, you could cut homeprob into buckets and use dplyr for aggregate statistics.  Then use color for wins or simply plot homeprob vs wins.

Since there are a few ways to do it, I'll give some options and a reproducible example.

Here is some made up data that is similar to yours:

# random normal data
randn_data <- rnorm(15000, 0.5, .05)
df <- data.frame(homeprob = randn_data)
# random uniform from 0 to 1
df$randunif <- runif(nrow(df))
# new feature is "H" if random uniform is less than homeprob
df$ftr <- ifelse(df$randunif < df$homeprob, "H", "A")
df$probcut <- cut(df$homeprob, seq(0.2, 0.8, 0.05))

Now you could use color for total wins, although I don't think that would be the best option because your data is normal and the frequency will be higher towards the mean:

library(dplyr)
df_plot1 <- df %>%
  group_by(probcut) %>%
  summarise(hprob_counts = n(), wins = sum(ftr == "H"))
# wins as color
library(ggplot2)
ggplot(df_plot1, aes(x = probcut, y = hprob_counts, fill = wins)) +
  geom_col() +
  scale_y_sqrt()

I think it would be better to use win rate to compare the expected and observed:

df_plot2 <- df %>%
  group_by(probcut) %>%
  summarise(hprob_counts = n(), wins = sum(ftr == "H")) %>%
  mutate(win_rate = wins / hprob_counts)

ggplot(df_plot2, aes(x = probcut, y = hprob_counts, fill = win_rate)) +
  geom_col() +
  scale_y_sqrt()

You could also just plot homeprob and win_rate without the distribution:

ggplot(df_plot2, aes(x = probcut, y = win_rate)) +
  geom_col()

Hopefully this is more or less what you were looking for.


问:
GWT Overlay deep copy
What is the best way to make a deep copy of a gwt overlay type?

I'm looking for a function or library that inspects a GWT overlay and clones it. It must be able to clone contained arrays or objects.

Thanks

答:
There are 2 ways that I would consider.  Most of the time overlay objects are used in conjunction with JSON, so you could just stringify the object and parse the results:

```<code>public native MyOverlayType deepCopy()/*-{
  return JSON.parse(JSON.stringify(this));
}-*/;
</code>```

OR

```<code>public static native MyOverlayType fromJson(String json)/*-{
      return JSON.parse(json);
}-*/;
public native String getJson()/*-{
      return JSON.stringify(this);
}-*/;
public MyOverlayType deepCopy(){
      return fromJson(getJson());
}
</code>```

The other option is a pure javascript approach which will maintain other stuff such as function pointers and probably be more efficient.

```<code>public class JsoUtils
{
    @SuppressWarnings("unchecked")
    public static <T extends JavaScriptObject> T deepCopy(T obj)
    {
        return (T) deepCopyImpl(obj);
    }

    private static native JavaScriptObject deepCopyImpl(JavaScriptObject obj)/*-{
        if (typeof obj !== 'object' || obj === null) {
            return obj;
        }

        var c = obj instanceof Array ? [] : {};

        for (var i in obj) {
            if (obj.hasOwnProperty(i)) {
                if (typeof obj[i] !== 'object' || obj[i] === null)
                    c[i] = obj[i];
                else
                    c[i] = @com.example.gwt.client.JsoUtils::deepCopyImpl(Lcom/google/gwt/core/client/JavaScriptObject;)(obj[i]);
            }
        }

        return c;
    }-*/;
}
</code>```

Title: GWT Overlay deep copy

Body:
There are 2 ways that I would consider.  Most of the time overlay objects are used in conjunction with JSON, so you could just stringify the object and parse the results:

public native MyOverlayType deepCopy()/*-{
  return JSON.parse(JSON.stringify(this));
}-*/;

OR

public static native MyOverlayType fromJson(String json)/*-{
      return JSON.parse(json);
}-*/;
public native String getJson()/*-{
      return JSON.stringify(this);
}-*/;
public MyOverlayType deepCopy(){
      return fromJson(getJson());
}

The other option is a pure javascript approach which will maintain other stuff such as function pointers and probably be more efficient.

public class JsoUtils
{
    @SuppressWarnings("unchecked")
    public static <T extends JavaScriptObject> T deepCopy(T obj)
    {
        return (T) deepCopyImpl(obj);
    }

    private static native JavaScriptObject deepCopyImpl(JavaScriptObject obj)/*-{
        if (typeof obj !== 'object' || obj === null) {
            return obj;
        }

        var c = obj instanceof Array ? [] : {};

        for (var i in obj) {
            if (obj.hasOwnProperty(i)) {
                if (typeof obj[i] !== 'object' || obj[i] === null)
                    c[i] = obj[i];
                else
                    c[i] = @com.example.gwt.client.JsoUtils::deepCopyImpl(Lcom/google/gwt/core/client/JavaScriptObject;)(obj[i]);
            }
        }

        return c;
    }-*/;
}


问:
Dynamically add targets to a Prometheus configuration
For a particular job in Prometheus, it seems like the typical config is something like this:

```<code>static_configs:
- targets: ['localhost:9090']
</code>```

But in the case where I want a dynamic list of hosts, what would be the approach there? I was looking at scrape_config but that doesn't seem to accomplish what I'm after (unless I'm misreading?).

Thank you in advance!

答:
There are several ways of providing dynamic targets to your Prometheus. Please refer the link here

Some of them are:

azure_sd_config (for AzureVM metrics)

consul_sd_config (for Consul's Catalog API)

dns_sd_config (DNS-based service discovery)

ec2_sd_config (for AWS EC2 instances)

openstack_sd_config (for Openstack Nova instances)

file_sd_config (file-based service discovery)

I think what you require is file_sd_config. file_sd_config is a more generic way to configure static targets. You may provide the targets in a yaml or json format. Please follow the link for detailed information.

Body:
For a particular job in Prometheus, it seems like the typical config is something like this:

static_configs:
- targets: ['localhost:9090']

But in the case where I want a dynamic list of hosts, what would be the approach there? I was looking at scrape_config but that doesn't seem to accomplish what I'm after (unless I'm misreading?).

Thank you in advance!


问:
how get sql insert/update query before or after doing a flush() in symfony
I want to do this:

```<code>//insert
$entity = new House();
$entity->setName('5 Stars');
$entity->setAddress('Something');
$em->persist($entity);
//or a update
$entity->setName('New Name');
$em->persist($entity);
</code>```

now the function would come

```<code>$em->flush();
</code>```

I do not know if it would be before or after the flush() and how, but I would like to obtain what would be the query that would be executed to save the data in the database

答:
It is very simple, you need to use Doctrine Lifecycle Events, in your case it is - 'preFlush', 'onFlush', 'postFlush'.

see Doctrine's Lifecycle Events documentation.

Body:
I want to do this:

//insert
$entity = new House();
$entity->setName('5 Stars');
$entity->setAddress('Something');
$em->persist($entity);
//or a update
$entity->setName('New Name');
$em->persist($entity);

now the function would come

$em->flush();

I do not know if it would be before or after the flush() and how, but I would like to obtain what would be the query that would be executed to save the data in the database


问:
can not bind data in dynamically appends elements jquery
I have a row where i have a dropdownlist i can add row dynamically on page and binding an event to the selectbox.

The problem I have is that  select boxes I add via Ajax or DOM after the initial loop won't have the event bound.

here is my view part.

```<code><div class="row" id="dsp">
    <div class="col-md-2">
        <select name="p_name[]" class="form-control p_name">
            <option value="">-Select Product-</option>
            @foreach($products as $product)
            <option value="{{$product->product_id}}">{{$product->name}}</option>
            @endforeach
        </select>
    </div>
    <div class="col-md-2">
        <input type="text" name="p_code[]" id="p_code" class="form-control p_code" >
    </div>
</code>```

here is my jquery part.

```<code>$(document).ready(function(){
  $('#dsp').on('change','.p_name',function(){
    var pid=$(this).val();
    //alert(pid);
    $.ajax({
      url:"{{route('getinfo')}}",
      method:'post',
      data:{id:pid,'_token':"{{csrf_token()}}"},
      success:function(response) {

        //alert(response.code);
        $('.p_code').val(response.code);

      }
    });

  });
});
</code>```

here is image.

答:
You should use DOM relationship to target the desired element the set its value. Here .closest() can be used to target common ancestor element then use .find() to target the desired .p_code and unit_pctn elemen

```<code>$('#dsp').on('change', '.p_name', function () {

    var pid = $(this).val();

    //Target common parent
    var parent = $(this).closest('.row');

    //alert(pid);
    $.ajax({
        url: "{{route('getinfo')}}",
        success: function (response) {
            parent.find('.p_code').val(response.code);
            parent.find('.unit_pctn').val(response.pcs_per_ctn);
        }
    });

    $.ajax({
        url: "{{route('getprice')}}",
        success: function (response) {
            parent.find('.u_price').val(response.client_price);
        }
    });

});
</code>```

Note:  I think you should select the selector to bind event handler wisely. It seems you are using duplicate identifiers which will render your HTML invalid.

Body:
I have a row where i have a dropdownlist i can add row dynamically on page and binding an event to the selectbox.

The problem I have is that  select boxes I add via Ajax or DOM after the initial loop won't have the event bound.

here is my view part.

        <select name="p_name[]" class="form-control p_name">
            <option value="">-Select Product-</option>
            @foreach($products as $product)
            <option value="{{$product->product_id}}">{{$product->name}}</option>
            @endforeach
        </select>

        <input type="text" name="p_code[]" id="p_code" class="form-control p_code" >

here is my jquery part.

$(document).ready(function(){
  $('#dsp').on('change','.p_name',function(){
    var pid=$(this).val();
    //alert(pid);
    $.ajax({
      url:"{{route('getinfo')}}",
      method:'post',
      data:{id:pid,'_token':"{{csrf_token()}}"},
      success:function(response) {

        //alert(response.code);
        $('.p_code').val(response.code);

      }
    });

  });
});

here is image.

Body:
You should use DOM relationship to target the desired element the set its value. Here .closest() can be used to target common ancestor element then use .find() to target the desired .p_code and unit_pctn elemen

$('#dsp').on('change', '.p_name', function () {

    var pid = $(this).val();

    //Target common parent
    var parent = $(this).closest('.row');

    //alert(pid);
    $.ajax({
        url: "{{route('getinfo')}}",
        success: function (response) {
            parent.find('.p_code').val(response.code);
            parent.find('.unit_pctn').val(response.pcs_per_ctn);
        }
    });

    $.ajax({
        url: "{{route('getprice')}}",
        success: function (response) {
            parent.find('.u_price').val(response.client_price);
        }
    });

});

Note:  I think you should select the selector to bind event handler wisely. It seems you are using duplicate identifiers which will render your HTML invalid.


问:
Dynamically remove an item from a ViewPager with FragmentStatePagerAdapter
There are quite a few discussions around this topic

ViewPager PagerAdapter not updating the View

Update ViewPager dynamically?

Removing fragments from FragmentStatePagerAdapter

I have tried various solutions (including the invalidation with POSITION_NONE)
. But I still donT know how to remove an item properly.

What happens is

either I get a blank page (meaning the fragment is destroyed, but the
instantiateItem was not called for a replacement)

or the whole thing crashes probably because the way the Android manages the
fragment instances do not match how I keep them in my
arraylist/sparsearray

Here s my adapter

```<code>private class DatePickerPagerAdapter extends FragmentStatePagerAdapter {

    ArrayList<Fragment> registeredFragments = new ArrayList<Fragment>();

    public DatePickerPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return CreateWishFormDatePaginationFragment.newInstance(position);
    }

    @Override
    public int getItemPosition(Object object){ //doesnt change much..
        return PagerAdapter.POSITION_NONE;
    }

    @Override
    public int getCount() {
        return iPageCount;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Fragment fragment = (Fragment) super.instantiateItem(container, position);
        registeredFragments.add(position, fragment);
        return fragment;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        super.destroyItem(container, position, registeredFragments.get(position));
    }

    public void removePage(ViewGroup pager, int position) {
        destroyItem(pager, position, null);
        registeredFragments.remove(position);
        iPageCount--;
        pagerIndicator.notifyDataSetChanged();
        pagerAdapter.notifyDataSetChanged();
    }

    public void addPage() {

        iPageCount++;
        pagerIndicator.notifyDataSetChanged();
        pagerAdapter.notifyDataSetChanged();
    }
}
</code>```

I am using a view pager with ViewPagerIndicator and I want to be able to remove a page in between, for example.

Hence remains the question, what is the proper way handling addition and removal of fragments in a ViewPager?

Thanks!

答:
The ViewPager doesn't remove your fragments with the code above because it loads several views (or fragments in your case) into memory. In addition to the visible view, it also loads the view to either side of the visible one. This provides the smooth scrolling from view to view that makes the ViewPager so cool.

To achieve the effect you want, you need to do a couple of things.

Change the FragmentPagerAdapter to a FragmentStatePagerAdapter. The reason for this is that the FragmentPagerAdapter will keep all the views that it loads into memory forever. Where the FragmentStatePagerAdapter disposes of views that fall outside the current and traversable views.

Override the adapter method getItemPosition (shown below). When we call mAdapter.notifyDataSetChanged(); the ViewPager interrogates the adapter to determine what has changed in terms of positioning. We use this method to say that everything has changed so reprocess all your view positioning.
And here's the code...

```<code>private class MyPagerAdapter extends FragmentStatePagerAdapter {
    //... your existing code
    @Override
    public int getItemPosition(Object object){
        return PagerAdapter.POSITION_NONE;
    }
}
</code>```

Body:
There are quite a few discussions around this topic

ViewPager PagerAdapter not updating the View

Update ViewPager dynamically?

Removing fragments from FragmentStatePagerAdapter

I have tried various solutions (including the invalidation with POSITION_NONE)
. But I still donT know how to remove an item properly.

What happens is

either I get a blank page (meaning the fragment is destroyed, but the
instantiateItem was not called for a replacement)

or the whole thing crashes probably because the way the Android manages the
fragment instances do not match how I keep them in my
arraylist/sparsearray

Here s my adapter

private class DatePickerPagerAdapter extends FragmentStatePagerAdapter {

    ArrayList<Fragment> registeredFragments = new ArrayList<Fragment>();

    public DatePickerPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return CreateWishFormDatePaginationFragment.newInstance(position);
    }

    @Override
    public int getItemPosition(Object object){ //doesnt change much..
        return PagerAdapter.POSITION_NONE;
    }

    @Override
    public int getCount() {
        return iPageCount;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Fragment fragment = (Fragment) super.instantiateItem(container, position);
        registeredFragments.add(position, fragment);
        return fragment;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        super.destroyItem(container, position, registeredFragments.get(position));
    }

    public void removePage(ViewGroup pager, int position) {
        destroyItem(pager, position, null);
        registeredFragments.remove(position);
        iPageCount--;
        pagerIndicator.notifyDataSetChanged();
        pagerAdapter.notifyDataSetChanged();
    }

    public void addPage() {

        iPageCount++;
        pagerIndicator.notifyDataSetChanged();
        pagerAdapter.notifyDataSetChanged();
    }
}

I am using a view pager with ViewPagerIndicator and I want to be able to remove a page in between, for example.

Hence remains the question, what is the proper way handling addition and removal of fragments in a ViewPager?

Thanks!

Body:
The ViewPager doesn't remove your fragments with the code above because it loads several views (or fragments in your case) into memory. In addition to the visible view, it also loads the view to either side of the visible one. This provides the smooth scrolling from view to view that makes the ViewPager so cool.

To achieve the effect you want, you need to do a couple of things.

Change the FragmentPagerAdapter to a FragmentStatePagerAdapter. The reason for this is that the FragmentPagerAdapter will keep all the views that it loads into memory forever. Where the FragmentStatePagerAdapter disposes of views that fall outside the current and traversable views.

Override the adapter method getItemPosition (shown below). When we call mAdapter.notifyDataSetChanged(); the ViewPager interrogates the adapter to determine what has changed in terms of positioning. We use this method to say that everything has changed so reprocess all your view positioning.
And here's the code...

private class MyPagerAdapter extends FragmentStatePagerAdapter {
    //... your existing code
    @Override
    public int getItemPosition(Object object){
        return PagerAdapter.POSITION_NONE;
    }
}


问:
C# - Factorial and power in one function
I have this simple code that based on a dropdown list. If Factorial is selected then type a number and submit and for power it is the same.

I have:

```<code>    double x;
    double y;
    double result;
    double m;
    int answer = 1;

    private void factorial(int num)
    {
        for(int x = 1; x <= num; x++)
        {
            answer = answer * x;
        }
    }

    private void pow(double x, double y)
    {
        m = Math.Pow(x, y);
        result = m;
    }
</code>```

And the design:

```<code>        if(comboBox1.SelectedIndex == 0)
        {
            int fact;
            fact = int.Parse(textBox1.Text);
            factorial(fact);
            textBox2.Text = answer.ToString();
        }

        if(comboBox1.SelectedIndex == 1)
        {
            x = double.Parse(textBox1.Text);
            y = double.Parse(textBox3.Text);
            pow(x, y);
            textBox2.Text = Convert.ToString(result);
        }
</code>```

So, how can I make pow() and factorial() into one function and do the same thing?

答:
A bit messy, but it should do the job:

```<code>if(comboBox1.SelectedIndex == 0)
    {
        int fact;
        fact = int.Parse(textBox1.Text);
        factorialPow(fact, 0, 0, 0);
        textBox2.Text = answer.ToString();
    }

    if(comboBox1.SelectedIndex == 1)
    {
        x = double.Parse(textBox1.Text);
        y = double.Parse(textBox3.Text);
        factorialPow(0, x, y, 1);
        textBox2.Text = Convert.ToString(result);
    }
</code>```

And:

```<code>private void factorialPow(int num, double x, double y, int selectedIndex)
        {
            switch (selectedIndex)
            {
                case 0:
                    for (int i = 1; i <= num; i++)
                    {
                        answer = answer * i;
                    }
                    break;

                case 1:
                    m = Math.Pow(x, y);
                    result = m;
                    break;
            }
        }
</code>```

Disclaimer: I in no way condone this kind of coding, there are many, many ways to do this in a much cleaner, more efficient approach, but like I said it'll do the job.

Edit:

I also believe that what you posted was absolutely fine, you could add this extra method as a step between your functions, as so:

```<code>private void factorialOrPow(int num, double x, double y, int selectedIndex)
        {
            switch (selectedIndex)
            {
                case 0:
                    factorial(num);
                    break;

                case 1:
                    pow(x, y);
                    break;
            }
        }
</code>```

Body:
I have this simple code that based on a dropdown list. If Factorial is selected then type a number and submit and for power it is the same.

I have:

    double x;
    double y;
    double result;
    double m;
    int answer = 1;

    private void factorial(int num)
    {
        for(int x = 1; x <= num; x++)
        {
            answer = answer * x;
        }
    }

    private void pow(double x, double y)
    {
        m = Math.Pow(x, y);
        result = m;
    }

And the design:

        if(comboBox1.SelectedIndex == 0)
        {
            int fact;
            fact = int.Parse(textBox1.Text);
            factorial(fact);
            textBox2.Text = answer.ToString();
        }

        if(comboBox1.SelectedIndex == 1)
        {
            x = double.Parse(textBox1.Text);
            y = double.Parse(textBox3.Text);
            pow(x, y);
            textBox2.Text = Convert.ToString(result);
        }

So, how can I make pow() and factorial() into one function and do the same thing?

Body:
A bit messy, but it should do the job:

if(comboBox1.SelectedIndex == 0)
    {
        int fact;
        fact = int.Parse(textBox1.Text);
        factorialPow(fact, 0, 0, 0);
        textBox2.Text = answer.ToString();
    }

    if(comboBox1.SelectedIndex == 1)
    {
        x = double.Parse(textBox1.Text);
        y = double.Parse(textBox3.Text);
        factorialPow(0, x, y, 1);
        textBox2.Text = Convert.ToString(result);
    }

And:

private void factorialPow(int num, double x, double y, int selectedIndex)
        {
            switch (selectedIndex)
            {
                case 0:
                    for (int i = 1; i <= num; i++)
                    {
                        answer = answer * i;
                    }
                    break;

                case 1:
                    m = Math.Pow(x, y);
                    result = m;
                    break;
            }
        }

Disclaimer: I in no way condone this kind of coding, there are many, many ways to do this in a much cleaner, more efficient approach, but like I said it'll do the job.

Edit:

I also believe that what you posted was absolutely fine, you could add this extra method as a step between your functions, as so:

private void factorialOrPow(int num, double x, double y, int selectedIndex)
        {
            switch (selectedIndex)
            {
                case 0:
                    factorial(num);
                    break;

                case 1:
                    pow(x, y);
                    break;
            }
        }


问:
Why does adding an array to number return a string?
```<code>var array = [1,2,4];

array+1  //gives '1,2,41'.
</code>```

<p>Can anyone explain this behaviour? </p>

答:
When you use the + sign with a declared javascipt object (var array), even if one of the elements is a number, it doesn't perform an arithmetic addition operation - it concatenates the values as two strings.

In your example, your array [1,2,4] is being casted into a string with a value of 1,2,4. So 1,2,4 concatenated with 1 is 1,2,41

Body:
var array = [1,2,4];

array+1  //gives '1,2,41'.

Can anyone explain this behaviour?


问:
json in flashvars
I want to use josn in my flashvars and I'm having trouble

here is my json

```<code>var flashvars = {
                xmlFile: '<?php echo $preface.$xmlpath; ?>',
                preface: '<?php echo $preface; ?>',
                "preload": {
                    "url": "flash/someflash.swf",
                    "x": "375",
                    "y": "237"
                }
                };
</code>```

here is what I have been trying

```<code>    var jsondata:String  = this.loaderInfo.parameters.preload;
    if(jsondata){
        //var jsonData:Object = JSON.decode(jsondata.toString()) ;

     error_txt.text = jsondata.toString();
    }
</code>```

error_txt returns "object Object" but I can't access any part of the json object

答:
Flashvars are passed as a collection of name/value pairs, with the same format as GET or POST (url-encoded) parameters. So for both the name and the value you need the content to be a string, properly escaped. Other than hardcoding the JSON string, which is a bit error prone, you could write your data in a php assoc array, then encode it to JSON and then url encode it. The resulting string is what you will pass as the value.

Something like this (I haven't actually tested this snippet!)

```<code><?php
$preload_data = array(
     "url"      => "flash/someflash.swf",
        "x"     => "375",
        "y"     => "237"
);
$preload_flashvar = rawurlencode(json_encode($preload_data));
?>

var flashvars = {
                xmlFile: '<?php echo $preface.$xmlpath; ?>',
                preface: '<?php echo $preface; ?>',
                preload: '<?php echo $preload_flashvar; ?>'
                };
</code>```

PS

On second thoughts, it's quite likely that the SWFObject (which you seem to be using to embed the swf) does the url escaping for you (via encodeURIComponent or some home made function); I don't remember if that's the case, but if it is, you don't have to call rawurlencode in your php code, as your data will get urlencoded twice. I can't test this right now, but give it a try with and without url-encoding in php; one of the two should work fine.

Title: json in flashvars

Body:
I want to use josn in my flashvars and I'm having trouble

here is my json

var flashvars = {
                xmlFile: '<?php echo $preface.$xmlpath; ?>',
                preface: '<?php echo $preface; ?>',
                "preload": {
                    "url": "flash/someflash.swf",
                    "x": "375",
                    "y": "237"
                }
                };

here is what I have been trying

    var jsondata:String  = this.loaderInfo.parameters.preload;
    if(jsondata){
        //var jsonData:Object = JSON.decode(jsondata.toString()) ;

     error_txt.text = jsondata.toString();
    }

error_txt returns "object Object" but I can't access any part of the json object

Body:
Flashvars are passed as a collection of name/value pairs, with the same format as GET or POST (url-encoded) parameters. So for both the name and the value you need the content to be a string, properly escaped. Other than hardcoding the JSON string, which is a bit error prone, you could write your data in a php assoc array, then encode it to JSON and then url encode it. The resulting string is what you will pass as the value.

Something like this (I haven't actually tested this snippet!)

<?php
$preload_data = array(
     "url"      => "flash/someflash.swf",
        "x"     => "375",
        "y"     => "237"
);
$preload_flashvar = rawurlencode(json_encode($preload_data));
?>

var flashvars = {
                xmlFile: '<?php echo $preface.$xmlpath; ?>',
                preface: '<?php echo $preface; ?>',
                preload: '<?php echo $preload_flashvar; ?>'
                };

PS

On second thoughts, it's quite likely that the SWFObject (which you seem to be using to embed the swf) does the url escaping for you (via encodeURIComponent or some home made function); I don't remember if that's the case, but if it is, you don't have to call rawurlencode in your php code, as your data will get urlencoded twice. I can't test this right now, but give it a try with and without url-encoding in php; one of the two should work fine.


问:
uncaught type error cannot set property 'innerHTML' of null
I'm about to get final exam, this is the practice thing.

Please help me get throug it, i have got stuck here for a long time.

This is the question.

Look at the JavaScript program for this problem. It already contains a function called rollDie which returns a number between 1 and 6.

There are two buttons on the html document for player 1 and player 2 to click to roll a die.

When player one clicks the ‘Player 1 Roll’ button the onclick attribute should call the function playerOne which calls the rollDie function and stores the returned result in a variable.

When player two clicks the ‘Player 2 Roll’ button the onclick attribute should call the function playerTwo which calls the rollDie function and stores the returned result in a variable.

The two results should be displayed in the corresponding divs with id ‘playerOneResult’ and id ‘playerTwoResult’. Once both players have had a turn, the program should compare their results and display a message in another div with id ‘message’.

For example:
If Player 1’s roll is a 3 and Player 2’s roll is a 4, the message displayed should be “Player Two wins”.

This is JS code

```<code>    //Declare the variables
    var playerOneNumber = 0;
    var playerTwoNumber = 0;

    //Functions
    function rollDie()
    {
        //create a random integer between 1 and 6
        var randomSide = Math.floor( Math.random() * 6 ) + 1;
        return randomSide
    }

    function PlayerOne()
    {
        var playerOneNumber = rollDie();
        return playerOneNumber;
    }
        var playerOneNumber = PlayerOne();
        var playerOneR = document.getElementById("playerOneResult").innerHTML = playerOneNumber;

    function PlayerTwo()
    {
        var playerTwoNumber = rollDie();
        return playerTwoNumber;
    }
        var playerTwoNumber = PlayerTwo();
        var playerTwoR = document.getElementById("playerTwoResult").innerHTML = playerTwoNumber;

    if(playerOneNumber > playerTwoNumber)
    {
        document.getElementById("message").innerHTML = "Player One wins";
    }
    else if(playerOneNumber < playerTwoNumber)
    {
        document.getElementById("message").innerHTML = "Player Two wins";
    }
</code>```

This is HTML

```<code>    <body>
    <h2>Programming Project - Problem P</h2>
    <input type="button" id="player1" onclick="PlayerOne();" value="Player 1 Roll">
    <input type="button" id="player2" onclick="PlayerTwo();" value="Player 2 Roll">
    <p>Player One rolled a <span id="playerOneResult">***</span></p>
    <p>Player Two rolled a <span id="playerTwoResult">***</span></p>
    <p>Result: <span id="message">***</span></p>
    </body>
</code>```

答:
What happens is that your script runs before the HTML has completely loaded. So the elements you want the innerHTML of arent yet created. Try the following this prevents this from happening.

    var playerOnetrew = false;
    var playerTwotrew = false;

    //Functions
    function rollDie(){
        //create a random integer between 1 and 6
        var randomSide = Math.floor( Math.random() * 6 ) + 1;
        return randomSide
    }

    function PlayerOne(){
        document.getElementById("playerOneResult").innerHTML = rollDie();
        playerOnetrew = true;
        playerplayed();
    }

    function PlayerTwo(){
        document.getElementById("playerTwoResult").innerHTML = rollDie();
        playerTwotrew = true;
        playerplayed();
    }

    function playerplayed(){
        if(playerOnetrew && playerTwotrew){
            if(document.getElementById("playerOneResult").innerHTML > document.getElementById("playerTwoResult").innerHTML){
                document.getElementById("message").innerHTML = "Player One wins";
            }
            else if(document.getElementById("playerOneResult").innerHTML < document.getElementById("playerTwoResult").innerHTML){
                document.getElementById("message").innerHTML = "Player Two wins";
            }
        }
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
    <h2>Programming Project - Problem P</h2>
    <input type="button" id="player1" onclick="PlayerOne();" value="Player 1 Roll">
    <input type="button" id="player2" onclick="PlayerTwo();" value="Player 2 Roll">
    <p>Player One rolled a <span id="playerOneResult">***</span></p>
    <p>Player Two rolled a <span id="playerTwoResult">***</span></p>
    <p>Result: <span id="message">***</span></p>
    </body></code>```

let me know if you have any questions i tried to keep it as simple as possible. :)

Body:
I'm about to get final exam, this is the practice thing.

Please help me get throug it, i have got stuck here for a long time.

This is the question.

Look at the JavaScript program for this problem. It already contains a function called rollDie which returns a number between 1 and 6.

There are two buttons on the html document for player 1 and player 2 to click to roll a die.

When player one clicks the ‘Player 1 Roll’ button the onclick attribute should call the function playerOne which calls the rollDie function and stores the returned result in a variable.

When player two clicks the ‘Player 2 Roll’ button the onclick attribute should call the function playerTwo which calls the rollDie function and stores the returned result in a variable.

The two results should be displayed in the corresponding divs with id ‘playerOneResult’ and id ‘playerTwoResult’. Once both players have had a turn, the program should compare their results and display a message in another div with id ‘message’.

For example:
If Player 1’s roll is a 3 and Player 2’s roll is a 4, the message displayed should be “Player Two wins”.

This is JS code

    //Declare the variables
    var playerOneNumber = 0;
    var playerTwoNumber = 0;

    //Functions
    function rollDie()
    {
        //create a random integer between 1 and 6
        var randomSide = Math.floor( Math.random() * 6 ) + 1;
        return randomSide
    }

    function PlayerOne()
    {
        var playerOneNumber = rollDie();
        return playerOneNumber;
    }
        var playerOneNumber = PlayerOne();
        var playerOneR = document.getElementById("playerOneResult").innerHTML = playerOneNumber;

    function PlayerTwo()
    {
        var playerTwoNumber = rollDie();
        return playerTwoNumber;
    }
        var playerTwoNumber = PlayerTwo();
        var playerTwoR = document.getElementById("playerTwoResult").innerHTML = playerTwoNumber;

    if(playerOneNumber > playerTwoNumber)
    {
        document.getElementById("message").innerHTML = "Player One wins";
    }
    else if(playerOneNumber < playerTwoNumber)
    {
        document.getElementById("message").innerHTML = "Player Two wins";
    }

This is HTML

Programming Project - Problem P

    <input type="button" id="player1" onclick="PlayerOne();" value="Player 1 Roll">
    <input type="button" id="player2" onclick="PlayerTwo();" value="Player 2 Roll">

Player One rolled a ***

Player Two rolled a ***

Result: ***

Body:
What happens is that your script runs before the HTML has completely loaded. So the elements you want the innerHTML of arent yet created. Try the following this prevents this from happening.

    var playerOnetrew = false;
    var playerTwotrew = false;

    //Functions
    function rollDie(){
        //create a random integer between 1 and 6
        var randomSide = Math.floor( Math.random() * 6 ) + 1;
        return randomSide
    }

    function PlayerOne(){
        document.getElementById("playerOneResult").innerHTML = rollDie();
        playerOnetrew = true;
        playerplayed();
    }

    function PlayerTwo(){
        document.getElementById("playerTwoResult").innerHTML = rollDie();
        playerTwotrew = true;
        playerplayed();
    }

    function playerplayed(){
        if(playerOnetrew && playerTwotrew){
            if(document.getElementById("playerOneResult").innerHTML > document.getElementById("playerTwoResult").innerHTML){
                document.getElementById("message").innerHTML = "Player One wins";
            }
            else if(document.getElementById("playerOneResult").innerHTML < document.getElementById("playerTwoResult").innerHTML){
                document.getElementById("message").innerHTML = "Player Two wins";
            }
        }
    }

<body>
    <h2>Programming Project - Problem P</h2>
    <input type="button" id="player1" onclick="PlayerOne();" value="Player 1 Roll">
    <input type="button" id="player2" onclick="PlayerTwo();" value="Player 2 Roll">
    <p>Player One rolled a <span id="playerOneResult">***</span></p>
    <p>Player Two rolled a <span id="playerTwoResult">***</span></p>
    <p>Result: <span id="message">***</span></p>
    </body>

let me know if you have any questions i tried to keep it as simple as possible. :)


问:
Django: loosing form attribute when changing <select> options in form template
In my Django application, a template which displays the manually the form fields from a Model. In this template I have a few fields which are  and the options are set in my forms.py. One of the option is a tuple ('new','New...') and when it is selected a pop up windows appears (Bootstrap Modal) and the user can add an option which is added to the choices of the select.

But when the form is submited, I have an error as the form key for this field is missing: KeyError: 'country', and if I print the form, country key is absent:

```<code>{'genotype': '?', 'complete_genome': False, 'seq_tech': '?', 'isolation_source': 'te', 'mol_type': '?', 'NT_seq': 'TTG', 'source': '?', 'host': 'chicken', 'species': 'A', 'isolate': 'te1', 'sourceLink': '', 'subtyping_ref': '?', 'PK_idSequence': 'test', 'strain': 'te1_strain', 'comment': '', 'subtype': '?'}
</code>```

My forms.py:

```<code>UNKNOWN_START_LIST = [('?','?')]
NEW_END_LIST = [('new','New...')]

class SequenceForm(ModelForm):

    # create the form fields
    PK_idSequence = CharField(max_length=15, label='Sequence ID')

    # get the existing country values in the database
    tmpCountries = sorted(list(set([seq.country for seq in Sequence.objects.all() if seq.country is not None and seq.country != '?'])))
    countryChoices = UNKNOWN_START_LIST + [(tmpCountry, tmpCountry) for tmpCountry in tmpCountries] + NEW_END_LIST

    # the countryChoices will be [('?', '?'), ('France', 'France'), ('Germany', 'Germany'), ('Japan', 'Japan'), ('USA', 'USA'), ('new', 'New...')]
    country = ChoiceField(choices = countryChoices,
                    initial='?',
                    required = False)

    # ... more stuffs

    class Meta:
        model = Sequence
        fields = ['PK_idSequence', 'genotype', 'subtype', 'host', 'country', 'complete_genome', 'seq_tech', 'NT_seq', 'col_date',
                'isolation_source', 'isolate', 'strain', 'species', 'mol_type', 'subtyping_ref', 'source', 'sourceLink', 'comment']

    # custom clean form for Sequence
    def clean(self):
        cleaned_data = super(SequenceForm, self).clean()

        # where the error is raised
        if cleaned_data['country'] is not None:
            cleaned_data['country'] = cleaned_data.get('country').title()
</code>```

my template.html:

```<code>{# The modal window to record a new Country #}
<div id="modal_new_country" class="modal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Record a new country:</h5>
                </div>
                <div class="modal-body">
                    <input type="text" name="new_country_text" id="new_country_text">
                </div>
                <div class="modal-footer">
                    <button id="new_country_button" type="button" class="btn btn-primary">Submit</button>
                    <button id="new_country_cancel_button" type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                </div>
        </div>
    </div>
</div>

<form class="single_upload_form" action="{% url 'upload' dataType method %}" method="post">
    {% csrf_token %}
    <div class="container">
    <div class="row">
        <div class="col">
            <div class="{{form.name.css_classes}}">
                {{form.PK_idSequence.label_tag}}{{ form.PK_idSequence.errors }}</br><span class="form_field">{{ form.PK_idSequence }}</span>
            </div>
        </div>
        <div class="col">
            <div class="{{form.name.css_classes}}">
                {{ form.country.label_tag }}{{ form.country.errors }}</br><span class="form_field">{{ form.country }}</span>
            </div>
        </div>
    <div class="row">
        <div class="col">
            <input type="submit" value="Submit"/>
        </div>
    </div>
</form>
</code>```

my jQuery.js:

```<code>jQuery(document).ready(function() {
/* ############### Country dropdown select ############### */

    // in upload form if Country dropdown is set to New... create a modal to get the new country
    $("#id_country").change(function(){
        var selectedValue = $(this).find("option:selected").attr("value");
        switch (selectedValue){
            case "new":
                $('#modal_new_country').modal('show');
                break;
        }
    });

    // Add the new Country to the select options
    $("#new_country_button").click(function() {
        var newCountry = $("#new_country_text").val();
        newCountry = newCountry.substr(0,1).toUpperCase() + newCountry.substr(1);
        $('#id_country').append('<option value="'+newCountry+'" selected="selected">'+newCountry+'</option>');
        $('#modal_new_country').modal('hide');
    });

    // cancel button for modal Country set selected option to '?'
    $("#new_country_cancel_button").click(function() {
        $('#id_country').val('?');
        $('#modal_new_country').modal('hide');
    });

})
</code>```

I guess the problem comes from that the new value in the select id_country is not part of the initial options coming from the form, how could I fix this issue?

答:
If it can help, I found a way to add a new <option> to the <select> #id_country. In my forms.py I replaced the ChoiceField by a CharField which widget is a forms.Select where I put the countryChoices:

```<code>country = ChoiceField(choices = countryChoices, initial='?', required = False)
</code>```

by

```<code>country = CharField(max_length=50, widget=forms.Select(choices=countryChoices), required=False)
</code>```

So, as the country attribute is a CharField, there is no more validation error raised by invalid_choice and the form cleaned_data has now the new value for the key 'country'.

Body:
In my Django application, a template which displays the manually the form fields from a Model. In this template I have a few fields which are  and the options are set in my forms.py. One of the option is a tuple ('new','New...') and when it is selected a pop up windows appears (Bootstrap Modal) and the user can add an option which is added to the choices of the select.

But when the form is submited, I have an error as the form key for this field is missing: KeyError: 'country', and if I print the form, country key is absent:

{'genotype': '?', 'complete_genome': False, 'seq_tech': '?', 'isolation_source': 'te', 'mol_type': '?', 'NT_seq': 'TTG', 'source': '?', 'host': 'chicken', 'species': 'A', 'isolate': 'te1', 'sourceLink': '', 'subtyping_ref': '?', 'PK_idSequence': 'test', 'strain': 'te1_strain', 'comment': '', 'subtype': '?'}

My forms.py:

UNKNOWN_START_LIST = [('?','?')]
NEW_END_LIST = [('new','New...')]

class SequenceForm(ModelForm):

    # create the form fields
    PK_idSequence = CharField(max_length=15, label='Sequence ID')

    # get the existing country values in the database
    tmpCountries = sorted(list(set([seq.country for seq in Sequence.objects.all() if seq.country is not None and seq.country != '?'])))
    countryChoices = UNKNOWN_START_LIST + [(tmpCountry, tmpCountry) for tmpCountry in tmpCountries] + NEW_END_LIST

    # the countryChoices will be [('?', '?'), ('France', 'France'), ('Germany', 'Germany'), ('Japan', 'Japan'), ('USA', 'USA'), ('new', 'New...')]
    country = ChoiceField(choices = countryChoices,
                    initial='?',
                    required = False)

    # ... more stuffs

    class Meta:
        model = Sequence
        fields = ['PK_idSequence', 'genotype', 'subtype', 'host', 'country', 'complete_genome', 'seq_tech', 'NT_seq', 'col_date',
                'isolation_source', 'isolate', 'strain', 'species', 'mol_type', 'subtyping_ref', 'source', 'sourceLink', 'comment']

    # custom clean form for Sequence
    def clean(self):
        cleaned_data = super(SequenceForm, self).clean()

        # where the error is raised
        if cleaned_data['country'] is not None:
            cleaned_data['country'] = cleaned_data.get('country').title()

my template.html:

{# The modal window to record a new Country #}

Record a new country:

                    <input type="text" name="new_country_text" id="new_country_text">

                    <button id="new_country_button" type="button" class="btn btn-primary">Submit</button>
                    <button id="new_country_cancel_button" type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

<form class="single_upload_form" action="{% url 'upload' dataType method %}" method="post">
    {% csrf_token %}

                {{form.PK_idSequence.label_tag}}{{ form.PK_idSequence.errors }}
{{ form.PK_idSequence }}

                {{ form.country.label_tag }}{{ form.country.errors }}
{{ form.country }}

            <input type="submit" value="Submit"/>

</form>

my jQuery.js:

jQuery(document).ready(function() {
/* ############### Country dropdown select ############### */

    // in upload form if Country dropdown is set to New... create a modal to get the new country
    $("#id_country").change(function(){
        var selectedValue = $(this).find("option:selected").attr("value");
        switch (selectedValue){
            case "new":
                $('#modal_new_country').modal('show');
                break;
        }
    });

    // Add the new Country to the select options
    $("#new_country_button").click(function() {
        var newCountry = $("#new_country_text").val();
        newCountry = newCountry.substr(0,1).toUpperCase() + newCountry.substr(1);
        $('#id_country').append('<option value="'+newCountry+'" selected="selected">'+newCountry+'</option>');
        $('#modal_new_country').modal('hide');
    });

    // cancel button for modal Country set selected option to '?'
    $("#new_country_cancel_button").click(function() {
        $('#id_country').val('?');
        $('#modal_new_country').modal('hide');
    });

})

I guess the problem comes from that the new value in the select id_country is not part of the initial options coming from the form, how could I fix this issue?

Body:
If it can help, I found a way to add a new <option> to the <select> #id_country. In my forms.py I replaced the ChoiceField by a CharField which widget is a forms.Select where I put the countryChoices:

country = ChoiceField(choices = countryChoices, initial='?', required = False)

by

country = CharField(max_length=50, widget=forms.Select(choices=countryChoices), required=False)

So, as the country attribute is a CharField, there is no more validation error raised by invalid_choice and the form cleaned_data has now the new value for the key 'country'.


问:
FacebookSDK 4.x Crash Case
I use FacebookSDKs-iOS-4.28.0 and developer facebook page suggest this lines of code to sharing;

```<code>FBSDKShareLinkContent *content = [[FBSDKShareLinkContent alloc] init];
content.contentURL = [NSURL URLWithString:@"www.lcwaikiki.com"];
[FBSDKShareDialog showFromViewController:self withContent:content delegate:self];
</code>```

However when code comes to [FBSDKShareDialog showFromViewController:self withContent:content delegate:self]; code line application CRASH with SIGABRT

Anyone has any information to solve above mentioned CRASH case?

Thanks All.

答:
I found solution about above mentioned CRASH problem.

If your iOS application base SDK<=iOS9, you must add "fbauth2","fbapi" etc. under the LSApplicationQueriesSchemes into .plist file.

You can deep into Facebook SDK iOS9 guide

Title: FacebookSDK 4.x Crash Case

Body:
I use FacebookSDKs-iOS-4.28.0 and developer facebook page suggest this lines of code to sharing;

FBSDKShareLinkContent *content = [[FBSDKShareLinkContent alloc] init];
content.contentURL = [NSURL URLWithString:@"www.lcwaikiki.com"];
[FBSDKShareDialog showFromViewController:self withContent:content delegate:self];

However when code comes to [FBSDKShareDialog showFromViewController:self withContent:content delegate:self]; code line application CRASH with SIGABRT

Anyone has any information to solve above mentioned CRASH case?

Thanks All.