问:
fabric.textbox is not working for google chrome?
I am deleting all the text in text box or i am removing each letter by using backspace.After removing all letters again am  doing typing but its blocked.Its not allowed to move.   </p>

答:
A data URI (or data URL) is a string, which contains the data of a small file, prefixed by a data: scheme and the MIME type of the file.

For binary data, the file is often converted to base64 in order to be able to represent all the bytes in a format which is compatible with URI rules.

The Blob constructor expects as first argument a list of data that will be appended in the resulting Blob.

Here you are trying to create a Blob from a dataURI directly, this means that your file will hold data:image/png;base64,iVB0Rw0... as text/plain, literally.

You can check this by opening the resulting file in a TextEditor, since yes, this is just a text file that you did create.

var blob = new Blob([c.toDataURL()], {type: 'image/png'});
var f = new FileReader();
f.onload = function(){console.log(f.result)};
f.readAsText(blob);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="c"></canvas></code>```

What you want is to extract the data contained in this dataURI, before appending it to your Blob.

The easy solution when available, is to use the Fetch API:

var dataURI = c.toDataURL();
fetch(dataURI)
.then(r=>r.blob())
.then(blob=>{
  // here blob is a good old png file
  var f = new FileReader();
  f.onload = function(){console.log(f.result)};
  f.readAsText(blob);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="c"></canvas></code>```

You can achieve the same with XMLHttpRequest.responseType = 'blob' for older browsers.

But if you don't like asynchronicity, you may also convert it manually, by first removing the dataURI header, and then decode the base64 data and feed an Uint8Array with the correct byte values.

var dataURI = c.toDataURL();

var byteString = atob(dataURI.split(',')[1]);
var arr = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
  arr[i] = byteString.charCodeAt(i);
}
var blob = new Blob([arr]);

var f = new FileReader();
f.onload = function(){console.log(f.result)};
f.readAsText(blob);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="c"></canvas></code>```

And note that I didn't talked about HTMLCanvasElement.toBlob() yet, because if I'm not mistaken, fabricjs still doesn't have this method, but if you weren't using the multiplier option, that would be the best solution.

Body:
A data URI (or data URL) is a string, which contains the data of a small file, prefixed by a data: scheme and the MIME type of the file.

For binary data, the file is often converted to base64 in order to be able to represent all the bytes in a format which is compatible with URI rules.

The Blob constructor expects as first argument a list of data that will be appended in the resulting Blob.

Here you are trying to create a Blob from a dataURI directly, this means that your file will hold data:image/png;base64,iVB0Rw0... as text/plain, literally.

You can check this by opening the resulting file in a TextEditor, since yes, this is just a text file that you did create.

var blob = new Blob([c.toDataURL()], {type: 'image/png'});
var f = new FileReader();
f.onload = function(){console.log(f.result)};
f.readAsText(blob);

<canvas id="c"></canvas>

What you want is to extract the data contained in this dataURI, before appending it to your Blob.

The easy solution when available, is to use the Fetch API:

var dataURI = c.toDataURL();
fetch(dataURI)
.then(r=>r.blob())
.then(blob=>{
  // here blob is a good old png file
  var f = new FileReader();
  f.onload = function(){console.log(f.result)};
  f.readAsText(blob);
});

<canvas id="c"></canvas>

You can achieve the same with XMLHttpRequest.responseType = 'blob' for older browsers.

But if you don't like asynchronicity, you may also convert it manually, by first removing the dataURI header, and then decode the base64 data and feed an Uint8Array with the correct byte values.

var dataURI = c.toDataURL();

var byteString = atob(dataURI.split(',')[1]);
var arr = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
  arr[i] = byteString.charCodeAt(i);
}
var blob = new Blob([arr]);

var f = new FileReader();
f.onload = function(){console.log(f.result)};
f.readAsText(blob);

<canvas id="c"></canvas>

And note that I didn't talked about HTMLCanvasElement.toBlob() yet, because if I'm not mistaken, fabricjs still doesn't have this method, but if you weren't using the multiplier option, that would be the best solution.


来源: stackexchange

问:
AppleScript to open URL in Safari crashes for Flash-based websites
I'm trying to open a URL in Safari. It works fine for websites without Flash embedded, but crashes Safari for Flash sites.

Example (this WORKS):

```<code>tell application "Safari" to open location "http://google.com"
</code>```

This CRASHES when Safari is not already running:

```<code>tell application "Safari" to open location "http://grooveshark.com"
</code>```

Two things I noticed:

Safari only crashes for websites with embedded Flash

The script above only crashes if a new instance of Safari is created (i.e. Safari was not running before)

From the second observation I assume that it could be a permission issue of some sort. Maybe the Safari instance launched from the AppleScript has a problem loading plugins?

答:
I had come across a similar issue some time back while working on Xcode. I realized later that it was caused by an asset in Flash. If you turn your applescript into an application, the problem should be solved.

On Xcode, go to Run -> Stop on Debugger()/DebugStr() and uncheck the option if it is on and build your application again.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to open a URL in Safari. It works fine for websites without Flash embedded, but crashes Safari for Flash sites.

Example (this WORKS):

tell application "Safari" to open location "http://google.com"

This CRASHES when Safari is not already running:

tell application "Safari" to open location "http://grooveshark.com"

Two things I noticed:

Safari only crashes for websites with embedded Flash

The script above only crashes if a new instance of Safari is created (i.e. Safari was not running before)

From the second observation I assume that it could be a permission issue of some sort. Maybe the Safari instance launched from the AppleScript has a problem loading plugins?


问:
How do I get a .net standard 2.0 project to build on TFS2015
I have a .net standard 2.0 class library in a .net 4.7.1 web solution.

Building the solution locally works fine, but when the TFS server builds the solution it is unable to compile the .net 2.0 standard library. It crashes during compilation and complains that system.object etc is not defined or imported.

It's a TFS 2015 running the old tfsbuild.proj style xml files.
The build server is otherwise up to date with .net 4.7.1, latest .net core 2.0.3, latest visual studio, latest build tools.

I can see that it generates a csc.exe command to compile the .net standard 2.0 project that crashes. If I simply was to run "dotnet build", it works great.

Watching the logs of the build I can see that the CoreCompile step when running in VS or "dotnet build" contains a "References" Task Parameter with references to the .net standard 2 library. This Task Parameter is missing in the CoreCompile step when the build server is running the build.

Does anyone have a suggestion on how to best proceed to get msbuild on the tfs server to successfully compile the .net standard 2.0 project?

Could I get msbuild to generate the necessary "References" task parameter?

Is my best option to turn off automatic building of .net standard projects and try to do everything manually as build steps with "dotnet build" instead, since dotnet build correctly identifies the necessary references?

答:
Seems you are trying to use the VS2015 MSBuild tools to build a solution which includes a .NET Standard 2.0 project.

The .NET team changed the project file structure (first announced
  here) for new .NET Core and .NET Standard projects along with the
  release of Visual Studio 2017.

Support for building .NET Core/Standard came with the TFS 2017 Update 2 update.

.NET Core tasks support project files

With the current update, we are enhancing .NET core tasks to support *.csproj files in addition to project.json. You can now use Visual
  Studio 2017 on your build agents to build .NET core applications using
  csproj files.

As a workaround, you could try to give up of using the TFS 2015 build task MSBUILD and Visual Studio Build, and now use the Command Line step.  In general, if you can perform a task on the commandline you can also do it in TFS/VSTS. More detail steps please refer this blog: Building .NET Core and .NET Standard Projects in TFS 2015

ContentLicense: CC BY-SA 3.0


问:
Write to a FIFO from a Python program
I a trying to control the volume of mplayer from a python program. The mplayer program gets started from a bash script:

```<code>#!/bin/bash
mkfifo /home/administrator/files/mplayer-control.pipe
/usr/bin/mplayer -slave -input file=/home/administrator/files/mplayer-control.pipe /home/administrator/music/file.mp3
</code>```

Then I have a GUI written in Python that is supposed to be able to control the volume of the instance of mplayer that is being played. I have tried the following:

```<code>os.system('echo "set_property volume $musicvol" > /home/administrator/files/mplayer-control.pipe')
</code>```

That works if i substitute $musicvol with the numeric value instead, but that is unfortunately of no use. I need to be able to pass the variable.

I would also be able to solve it by invoking a bash script from the Python application, but I can not get that to work either:

```<code>subprocess.call("/home/administrator/files/setvolume.sh", executable="bash", shell=True)
</code>```

答:
You don't need to call os.system and invoke a shell to write that line to the FIFO from your Python script- you can just do:

```<code>new_volume = 50
with open("/home/administrator/files/mplayer-control.pipe","w") as fp:
    fp.write("set_property volume %d\n" % (new_volume,))
</code>```

It's not clear to me what you expect to happen in your original python, though - is musicvol set in the environment?  If instead it's a Python variable that you want to insert into the string that you're passing, the easiest way is to use the string interpolation operator (%) as I've done in the example above.

In your example of using subprocess.call you don't need the executable or shell keyword arguments if setvolume.sh is executable and has a #! line - you could just do:

```<code>subprocess.call("/home/administrator/files/setvolume.sh")
</code>```

However, it's better to just use open and write in Python as above, I think.

Title: Write to a FIFO from a Python program

Body:
I a trying to control the volume of mplayer from a python program. The mplayer program gets started from a bash script:

#!/bin/bash
mkfifo /home/administrator/files/mplayer-control.pipe
/usr/bin/mplayer -slave -input file=/home/administrator/files/mplayer-control.pipe /home/administrator/music/file.mp3

Then I have a GUI written in Python that is supposed to be able to control the volume of the instance of mplayer that is being played. I have tried the following:

os.system('echo "set_property volume $musicvol" > /home/administrator/files/mplayer-control.pipe')

That works if i substitute $musicvol with the numeric value instead, but that is unfortunately of no use. I need to be able to pass the variable.

I would also be able to solve it by invoking a bash script from the Python application, but I can not get that to work either:

subprocess.call("/home/administrator/files/setvolume.sh", executable="bash", shell=True)

Body:
You don't need to call os.system and invoke a shell to write that line to the FIFO from your Python script- you can just do:

new_volume = 50
with open("/home/administrator/files/mplayer-control.pipe","w") as fp:
    fp.write("set_property volume %d\n" % (new_volume,))

It's not clear to me what you expect to happen in your original python, though - is musicvol set in the environment?  If instead it's a Python variable that you want to insert into the string that you're passing, the easiest way is to use the string interpolation operator (%) as I've done in the example above.

In your example of using subprocess.call you don't need the executable or shell keyword arguments if setvolume.sh is executable and has a #! line - you could just do:

subprocess.call("/home/administrator/files/setvolume.sh")

However, it's better to just use open and write in Python as above, I think.


问:
Using Chrome, how to find to which events are bound to an element
Lets suppose I've a link on my page:

```<code><a href="#" id="foo">Click Here</a>
</code>```

I don't know anything else, but when I click on the link, an alert("bar") is displayed.
So I know that somewhere, some code is getting bound to #foo.

How can I find the code that is binding the alert("bar") to the click event?
I'm looking for a solution with Chrome.

Ps.: The example is fictive, so I'm not looking for solution like: "Use XXXXXX and search the whole project for "alert(\"bar\")". I want a real debugging/tracing solution.

答:
(Latest as of 2022) For version Chrome Version Version 99:

Select the element you want to inspect

Choose the Event Listeners tab

Make sure to check the Framework listeners to show the real javascript file instead of the jquery function.

ContentLicense: CC BY-SA 4.0

Body:
Lets suppose I've a link on my page:

Click Here

I don't know anything else, but when I click on the link, an alert("bar") is displayed.
So I know that somewhere, some code is getting bound to #foo.

How can I find the code that is binding the alert("bar") to the click event?
I'm looking for a solution with Chrome.

Ps.: The example is fictive, so I'm not looking for solution like: "Use XXXXXX and search the whole project for "alert(\"bar\")". I want a real debugging/tracing solution.


问:
NGRX: TypeError: Actions must have a type property
Being new to ngrx I am facing an exception and not sure why...

I am trying to dispatch an action and handle it in an effect, but I keep getting the error: TypeError: Actions must have a type property

Actions:

```<code>export const TEST_ACTION = 'test_action';
export class TryTest implements Action {
    readonly type = TEST_ACTION;

    constructor(public playload: any) {
    }
}
export type MyActions = TryTest;
</code>```

Effects:

```<code>import * as MyActions from "./myactions.actions";

@Injectable()
export class MyEffects {
    @Effect()
    testEffect = this.actions$
        .ofType(MyActions.TEST_ACTION)
        .map((action: MyActions.TryTest) => {
            return 'something'
        });

    constructor(private actions$: Actions) {}
}
</code>```

Component:

```<code>this.store.dispatch(new MyActions.TryTest({ name: 'test' }));
</code>```

I am using:

effects: 4.0.5 and store: 4.0.3

答:
because effect must return an action at the end.
so you have two choices:

return a {type: string} object

return a new Action()

```<code>import * as MyActions from "./myactions.actions";

@Injectable()
export class MyEffects {
    @Effect()
    testEffect = this.actions$
        .ofType(MyActions.TEST_ACTION)
        .map((action: MyActions.TryTest) => {
            return {type:'your_action'}
        });

    constructor(private actions$: Actions) {}
}
</code>```

Body:
Being new to ngrx I am facing an exception and not sure why...

I am trying to dispatch an action and handle it in an effect, but I keep getting the error: TypeError: Actions must have a type property

Actions:

export const TEST_ACTION = 'test_action';
export class TryTest implements Action {
    readonly type = TEST_ACTION;

    constructor(public playload: any) {
    }
}
export type MyActions = TryTest;

Effects:

import * as MyActions from "./myactions.actions";

@Injectable()
export class MyEffects {
    @Effect()
    testEffect = this.actions$
        .ofType(MyActions.TEST_ACTION)
        .map((action: MyActions.TryTest) => {
            return 'something'
        });

    constructor(private actions$: Actions) {}
}

Component:

this.store.dispatch(new MyActions.TryTest({ name: 'test' }));

I am using:

effects: 4.0.5 and store: 4.0.3

Body:
because effect must return an action at the end.
so you have two choices:

return a {type: string} object

return a new Action()

import * as MyActions from "./myactions.actions";

@Injectable()
export class MyEffects {
    @Effect()
    testEffect = this.actions$
        .ofType(MyActions.TEST_ACTION)
        .map((action: MyActions.TryTest) => {
            return {type:'your_action'}
        });

    constructor(private actions$: Actions) {}
}


问:
keys in object are undefined but object is not (react-redux)
So I have a strange issue with the data I'm fetching from an API. In my reducer I've set the initial state to an empty object and in my component's render method I'm accessing this fetched data using this.props.data.value.one.

The actual fetched data from the API look like this:

```<code>{data:
  {value: {one: '1'}}
}
</code>```

However when I try to console.log(this.props.data) it will log {value: {one: '1'}} after logging undefined a couple of times but will log this.props.data.value.one as undefined.

I'm doing similar stuff in my other reducers which are getting data from other API's and they work fine.

App.js Component:

```<code>@connect(store => store)
...
componentWillMount = () => {//API Call here}
render = () => {
 return (
    <div><p>{this.props.data.value.one}</p><div>
 )
}
</code>```

reducer.js:

```<code>...
export default function reducer(state={data: {}}, action) {
  ...
  case 'FETCHED_DATA':
    return {...state, data: action.data}
</code>```

action.js:

```<code>...
fetchData = user => dispatch => {
  //request.get...
     .then(res => dispatch({type: 'FETCHED_DATA', data: res.body.data})
}
</code>```

答:
There are 2 issues i see here:

As mentioned in other answers and comments, you should always
conditionally access objects that are fetched asynchronously.

```<code>this.props.myObj && this.props.myObj.myValue
</code>```

By the way, don't fetch inside componentWillMount, instead do it
in componentDidMount.   You can read about the reasons for this in
the DOCS.

Avoid introducing any side-effects or subscriptions in this method.
  For those use cases, use componentDidMount() instead.

By the look of the shape of your reducer (state) it seems that the
data object is nested inside the reducer:

```<code>state={data: {}}
</code>```

So you can't access it directly from props (unless you are changing
the shape in mapStateToProps).

So i would expect to see this:

```<code>this.props.reducerName.data.value.one
</code>```

instead of this:

```<code>this.props.data.value.one
</code>```

Body:
So I have a strange issue with the data I'm fetching from an API. In my reducer I've set the initial state to an empty object and in my component's render method I'm accessing this fetched data using this.props.data.value.one.

The actual fetched data from the API look like this:

{data:
  {value: {one: '1'}}
}

However when I try to console.log(this.props.data) it will log {value: {one: '1'}} after logging undefined a couple of times but will log this.props.data.value.one as undefined.

I'm doing similar stuff in my other reducers which are getting data from other API's and they work fine.

App.js Component:

@connect(store => store)
...
componentWillMount = () => {//API Call here}
render = () => {
 return (

{this.props.data.value.one}

 )
}

reducer.js:

...
export default function reducer(state={data: {}}, action) {
  ...
  case 'FETCHED_DATA':
    return {...state, data: action.data}

action.js:

...
fetchData = user => dispatch => {
  //request.get...
     .then(res => dispatch({type: 'FETCHED_DATA', data: res.body.data})
}

Body:
There are 2 issues i see here:

As mentioned in other answers and comments, you should always
conditionally access objects that are fetched asynchronously.

this.props.myObj && this.props.myObj.myValue

By the way, don't fetch inside componentWillMount, instead do it
in componentDidMount.   You can read about the reasons for this in
the DOCS.

Avoid introducing any side-effects or subscriptions in this method.
  For those use cases, use componentDidMount() instead.

By the look of the shape of your reducer (state) it seems that the
data object is nested inside the reducer:

state={data: {}}

So you can't access it directly from props (unless you are changing
the shape in mapStateToProps).

So i would expect to see this:

this.props.reducerName.data.value.one

instead of this:

this.props.data.value.one


问:
Validating by attribute
I would like to check by attribute that value passed to method is correct, because adding if condition to method body make code less readable (in my opinion)

For example,

```<code>    public object GetSomething(int id)
    {
        // there could be more conditions
        if (id<= 0)
            throw new ArgumentOutOfRangeException(nameof(id), $"Forbiden value: '{id}'");
        // real logic
        ...
</code>```

I want to check it is such way

```<code>    [PossitiveValueAttr(id)]
    public object GetSomething(int id)
    {
        // real logic
</code>```

or (I would prefer that)

```<code>    public object GetSomething([PossitiveValueAttr] int id)
    {
        // real logic
</code>```

1) Do you know any similar existing solution?

2) How can I pass method's argument to my attribute?

答:
Attributes can't magically cause any behavioral change in your application unless you have code that looks for and acts on them.
Further, attributes can only be determined if you have reflection information, which you can't get for function arguments.
But for your particular example (must be positive), why not just used an unsigned int?</p>

Title: Validating by attribute

Body:
I would like to check by attribute that value passed to method is correct, because adding if condition to method body make code less readable (in my opinion)

For example,

    public object GetSomething(int id)
    {
        // there could be more conditions
        if (id<= 0)
            throw new ArgumentOutOfRangeException(nameof(id), $"Forbiden value: '{id}'");
        // real logic
        ...

I want to check it is such way

    [PossitiveValueAttr(id)]
    public object GetSomething(int id)
    {
        // real logic

or (I would prefer that)

    public object GetSomething([PossitiveValueAttr] int id)
    {
        // real logic

1) Do you know any similar existing solution?

2) How can I pass method's argument to my attribute?


问:
How to solve Delphi's [Pascal Fatal Error] F2084 Internal Error: LA33?
I'm really sick of this problem. Google searches always seem to suggest "delete all bpls for the package", "delete all dcus". Sometimes this just-does-not-work. Hopefully I can get some other ideas here.

I have a package written in-house, which had been installed without issue a few months ago. Having made a few changes to the source, I figured it was time to recompile/reinstall the package. Now I get two errors, the first if I choose "install" is

Access violation at address 02422108 in module 'dcc100.dll'. Read of address 00000000.

...or if I try to build/compile the package, I get

[Pascal Fatal Error] F2084 Internal Error: LA33

This is one of those Delphi problems that seems to occur time and time again for many of us. Would be great if we could collate a response something along the lines of "any one or combination of these steps might fix it, but if you do all these steps it will fix it...."

At the moment, I've removed all references to the bpl/dcp files for this package, but still getting the same error...

Using BDS2006 (Delphi)

Update 01-Oct-2008: I managed to solve this - see my post below. As I can't accept my own answer, I'm not entirely sure what to do here. Obviously these types of issues occur frequently for some people, so I'll leave it open for a while to get other suggestions. Then I guess if someone collates all the info into a super-post, I can accept the answer

答:
Maybe the following step will be a better solution:

Declare the array as a type and just define the class constant with this type, eg.

```<code>TMyArray = array[TErrEnum] of string;

TMyClass = class(TComponent)
private
  const ErrStrs: TMyArray
    = ('', //erOK
       'Invalid user name or password', //erInvUserPass
       'Trial Period has Expired'); //erTrialExp
protected
  ...
public
  ...
end;
</code>```

This makes the array declaration explicit.

OwnerDisplayName: Graza

LastEditorDisplayName: Graza

Body:
Maybe the following step will be a better solution:

Declare the array as a type and just define the class constant with this type, eg.

TMyArray = array[TErrEnum] of string;

TMyClass = class(TComponent)
private
  const ErrStrs: TMyArray
    = ('', //erOK
       'Invalid user name or password', //erInvUserPass
       'Trial Period has Expired'); //erTrialExp
protected
  ...
public
  ...
end;

This makes the array declaration explicit.


问:
Rails.application.routes.url_helpers crashing Heroku app
I'm building a Serializer for Collection+Json, and I'm writing an API as an example. I'm having an issue when using Rails.application.routes.url_helpers on the deployed app on Heroku.

I use this in one serializer:

Rails.application.routes.url_helpers.bills_url

In development, everything works fine. However, on Heroku this raises an error:

undefined method 'bills_url' for #<Module:0x007f3a1eab8d58> (NoMethodError).

If I dump Rails.application.routes.url_helpers.methods, no _url or _path methods are listed. However, they are if I run the same code in the console:

```<code>heroku run rails c --app myapp
> Rails.application.routes.url_helpers.methods
> # => :bills_url is present
</code>```

This is weird. Any clue on this? Does Heroku make url_helpers not available? I am absolutely lost. I've googled a lot but found nothing.

Here's the bug report for the complete trace.

Thank you.

答:
Craig's answer is on the right track.  So, because in config/environments/production.rb we have

```<code>config.eager_load = true
</code>```

We also need to add the following:

```<code>config.before_eager_load do
  Rails.application.reload_routes!
end
</code>```

Now anywhere in your code, you should be able to use Rails.application.routes.url_helpers.*_path and Rails.application.routes.url_helpers.*_url helpers.

In my case, I was trying to use the helpers in concerns, and having the same issue you were.  This works like a charm on heroku in production for me... of course it took me way too long to work it out! ;)

Body:
I'm building a Serializer for Collection+Json, and I'm writing an API as an example. I'm having an issue when using Rails.application.routes.url_helpers on the deployed app on Heroku.

I use this in one serializer:

Rails.application.routes.url_helpers.bills_url

In development, everything works fine. However, on Heroku this raises an error:

undefined method 'bills_url' for #<Module:0x007f3a1eab8d58> (NoMethodError).

If I dump Rails.application.routes.url_helpers.methods, no _url or _path methods are listed. However, they are if I run the same code in the console:

heroku run rails c --app myapp
> Rails.application.routes.url_helpers.methods
> # => :bills_url is present

This is weird. Any clue on this? Does Heroku make url_helpers not available? I am absolutely lost. I've googled a lot but found nothing.

Here's the bug report for the complete trace.

Thank you.

Body:
Craig's answer is on the right track.  So, because in config/environments/production.rb we have

config.eager_load = true

We also need to add the following:

config.before_eager_load do
  Rails.application.reload_routes!
end

Now anywhere in your code, you should be able to use Rails.application.routes.url_helpers.*_path and Rails.application.routes.url_helpers.*_url helpers.

In my case, I was trying to use the helpers in concerns, and having the same issue you were.  This works like a charm on heroku in production for me... of course it took me way too long to work it out! ;)


问:
TestNG Assert showing error in selenium project
Assert is showing error even though testng is imported. error is "Assert cannot be resolved" and in the import of Assert the error is "The import org.testng.Assert cannot be resolved" .. Please help me to resolve this issue..

答: This might be because the TestNG plugin is not installed on eclipse. Try to install the TestNG plugin, then this should get resolved.</p>


问:
Hibernate - Handle multiple definitions of a table
I am creating a REST service in Java using Resteasy and Hibernate. This API is supposed to support both older and newer versions of an existing database schema.

In version 1.0 of the database I have a table defined like below:

Later in version 2.0 the table was renamed, two new columns were added and length of one of the columns was increased. This table now looks like:

I am planning to create two separate entity classes and based on the version of the connected database use the corresponding entity class.

I would like to know if this approach is OK. If so then is there some better approach for this type of situation.

答:
I ended up creating two separate entity classes and based on the version of the connected database, I use the corresponding entity class.

Still open to any better solution.


问:
Http get method showing json file not found
I am totally new in angular 4 and trying to call web api httpGet method. I create a json file named student.json . When I run my code in console I can see below Error :

```<code> http://localhost:4200/src/data/students.json 404 (Not Found)
</code>```

My Code :

```<code>fetchData(){
    this.http.get("src/data/students.json").subscribe(
        (data)=>console.log(data)
    );
}
</code>```

enter image description here

What am I wrong? Thanks in advance.

答:
use below code in your service</p>

```<code>export class MyDataService {

  constructor(private http: Http) { }

  fetchData() {
    this.http.get('../assets/data/students.json').subscribe(
      (data)=>console.log(data)
    );
  }

}
</code>```

Body:
I am totally new in angular 4 and trying to call web api httpGet method. I create a json file named student.json . When I run my code in console I can see below Error :

 http://localhost:4200/src/data/students.json 404 (Not Found)

My Code :

fetchData(){
    this.http.get("src/data/students.json").subscribe(
        (data)=>console.log(data)
    );
}

enter image description here

What am I wrong? Thanks in advance.

Body:
use below code in your service

export class MyDataService {

  constructor(private http: Http) { }

  fetchData() {
    this.http.get('../assets/data/students.json').subscribe(
      (data)=>console.log(data)
    );
  }

}


问:
'gulp' is not recognized as an internal or external command
I am trying to use Gulp and Node.Js to stream my process for minifying and concatenating CSS/JS files for production.

Here is what I have done.

I installed Node.Js on my Windows 7 machine.

Installed Gulp globally using this command npm install -g gulp

Then I added a new User variable called NODE_PATH set it to %AppData%\npm\node_modules

After closing and re-opening my command line, I tried to run a gulp task from the command line (i.e. gulp css). But that give me the following error

```<code>'gulp' is not recognized as an internal or external command
</code>```

How can I get this to work?

When I opened the following path using the search bar in windows,
%AppData%\npm\node_modules I see the following two folders

```<code>gulp
gulp-cli
</code>```

I've tried to add %AppData%\npm\node_modules to the Path variable on my system variable, but it did not take it because that variable reached it's max allowed character limit.

I removed couple of paths from my Path variable and added ;C:\Users\[MyWindowsUserName]\AppData\Roaming\npm\node_modules

but still not working.

I even tried to set the path at run time using this command

PATH=%PATH%;C:\Users\[MyWindowsUserName]\AppData\Roaming\npm\node_modules
then run gulp and still the same issues.

What am I missing here? What else do I need in order to get this to work?

答: In my case, this problem occured because I did npm install with another system user in my project folder before. Gulp was already installed globally. After deleting folder /node_modules/ in my project, and running npm install with the current user, it worked.

Body:
I am trying to use Gulp and Node.Js to stream my process for minifying and concatenating CSS/JS files for production.

Here is what I have done.

I installed Node.Js on my Windows 7 machine.

Installed Gulp globally using this command npm install -g gulp

Then I added a new User variable called NODE_PATH set it to %AppData%\npm\node_modules

After closing and re-opening my command line, I tried to run a gulp task from the command line (i.e. gulp css). But that give me the following error

'gulp' is not recognized as an internal or external command

How can I get this to work?

When I opened the following path using the search bar in windows,
%AppData%\npm\node_modules I see the following two folders

gulp
gulp-cli

I've tried to add %AppData%\npm\node_modules to the Path variable on my system variable, but it did not take it because that variable reached it's max allowed character limit.

I removed couple of paths from my Path variable and added ;C:\Users\[MyWindowsUserName]\AppData\Roaming\npm\node_modules

but still not working.

I even tried to set the path at run time using this command

PATH=%PATH%;C:\Users\[MyWindowsUserName]\AppData\Roaming\npm\node_modules
then run gulp and still the same issues.

What am I missing here? What else do I need in order to get this to work?


问:
ReformAlign executable not stable.
I have compiled and executable (ReformAlign) from a makefile, however, on launching it, it opens and closes immediately.

Is there something I failed to do or should do to enable work properly.
Any suggestions and help is greatly appreciated.

答:
Maybe you should try to run the executable from the command window.

On Windows: start cmd.exe then inside the cmd go to the directory where your ReformAlign.exe file is saved. You can change directories with the cd command.

After that you can simply type the name of your executable and it should start running.

Example:

C:\Users\Nabi> cd YourFileDirectory\MaybeSomeSubdirectory

Press Enter, then type the name of your *.exe file.

C:\Users\Nabi\YourFileDirectory\MaybeSomeSubdirectory> ReformAlign.exe

Again press Enter, and your file should start.

Title: ReformAlign executable not stable.


问:
GroupBy performs slowly
I have the following query and is super slow for 3000 records and produces 370 entries. How can I improve performance on it?</p>

```<code>dealerResults = _results.GroupBy(x => new { x.DealerName, x.DealerId })
                                      .Select(x => new MarketingReportResults()
                                      {
                                          DealerId = x.Key.DealerId,
                                          DealerName = x.Key.DealerName,
                                          LinkedTotal = linkedLeadCores.Count(y => y.DealerId == x.Key.DealerId),
                                          LeadsTotal = x.Count(),
                                          SalesTotal = x.Count(y => y.IsSold),
                                          Percent = (decimal)(x.Count() * 100) / count,
                                          ActiveTotal = x.Count(y => y.IsActive),
                                      }).ToList();
</code>```

答:
I think the linkedLeadCores.Count() is the bottleneck here as you loop though the entire linkedLeadCores list each time a entry of _results is processed. This assumption seems to be confirmed by your comments also.

So to remove the bottleneck you could create a map (aka dictionary) that holds the count for each dealer before doing anything with _results like this ...

```<code>var linkedLeadCoresCountMap = linkedLeadCores
    .GroupBy(y => y.DealerId )
    .ToDictionary(y => y.Key, y => y.Count());
</code>```

... and then you could write

```<code>LinkedTotal = linkedLeadCoresCountMap.ContainsKey(x.Key.DealerId) ?
    linkedLeadCoresCountMap[x.Key.DealerId] : 0,
</code>```

Title: GroupBy performs slowly

Body:
I have the following query and is super slow for 3000 records and produces 370 entries. How can I improve performance on it?

dealerResults = _results.GroupBy(x => new { x.DealerName, x.DealerId })
                                      .Select(x => new MarketingReportResults()
                                      {
                                          DealerId = x.Key.DealerId,
                                          DealerName = x.Key.DealerName,
                                          LinkedTotal = linkedLeadCores.Count(y => y.DealerId == x.Key.DealerId),
                                          LeadsTotal = x.Count(),
                                          SalesTotal = x.Count(y => y.IsSold),
                                          Percent = (decimal)(x.Count() * 100) / count,
                                          ActiveTotal = x.Count(y => y.IsActive),
                                      }).ToList();

Body:
I think the linkedLeadCores.Count() is the bottleneck here as you loop though the entire linkedLeadCores list each time a entry of _results is processed. This assumption seems to be confirmed by your comments also.

So to remove the bottleneck you could create a map (aka dictionary) that holds the count for each dealer before doing anything with _results like this ...

var linkedLeadCoresCountMap = linkedLeadCores
    .GroupBy(y => y.DealerId )
    .ToDictionary(y => y.Key, y => y.Count());

... and then you could write

LinkedTotal = linkedLeadCoresCountMap.ContainsKey(x.Key.DealerId) ?
    linkedLeadCoresCountMap[x.Key.DealerId] : 0,


问:
NodeJS : Parse not saving record
I have the following code for saving data to the table.

```<code>let Parse = require('parse').Parse;

export const gameInsert = async (data) => {
  try {
      const game = Parse.Object.extend('Table');
      const query = new game();
    data.forEach((item) => {
      query.set('name', 'NewName');
      query.save();
    }, this);
  } catch (e) {
    console.log(e);
  }
};
</code>```

But it gives me no warning or error and the record is not saving. What am i missing ?

答: Have you try, query.save(null); ?</p>

Title: NodeJS : Parse not saving record

Body:
I have the following code for saving data to the table.

let Parse = require('parse').Parse;

export const gameInsert = async (data) => {
  try {
      const game = Parse.Object.extend('Table');
      const query = new game();
    data.forEach((item) => {
      query.set('name', 'NewName');
      query.save();
    }, this);
  } catch (e) {
    console.log(e);
  }
};

But it gives me no warning or error and the record is not saving. What am i missing ?

Body: Have you try, query.save(null); ?


问:
using wp_get_attachment_image_src in foreach loop
I have 10 images added to a post via Advanced Custom Fields, they're named from 1 to 10 e.g 'image_*', ACF is set to return the ID.

I'm trying to get the full size image URL of each image in the loop and use it as a href attribute to open a full size popup of the image, however I don't understand how wp_get_attachment_image_src works.

Since I am unable to use Advanced Custom Field's Repeater, this is the loop i'm using to get an array of the images with a custom image size of scaled, it works fine to generate the responsive image markup that I need:

```<code>// args

$sizeHuge = 'scaled'; // scaled image
$images = array(); // img array

for($x = 1; $x <= 10; $x++) {
        $img = get_field('image_' . $x);
   if($img) {
        $images[] = $img;
   } else {
        break;
   }
 }

<?php foreach($images as $image) { ?>

    <a href="" class="open-viewer">

        <?php echo wp_get_attachment_image( $image, $sizeHuge ); ?>

    </a>

<?php } ?>
</code>```

I need to set the href attribute of the parent a element with the URL of the image. This is what I have tried with wp_get_attachment_image_src, it doesn't work, it sets every href with image_10's URL.

```<code>// args

$sizeFull = 'full'; // full size image
$sizeHuge = 'scaled'; // scaled image
$images = array(); // img array

for($x = 1; $x <= 10; $x++) {
        $img = get_field('image_' . $x);
        $image_array = wp_get_attachment_image_src($img, $sizeFull);
        $link = $image_array[0];
   if($img) {
        $images[] = $img;
   } else {
        break;
   }
 }

<?php foreach($images as $image) { ?>

    <a href="<?php echo $link; ?>" class="open-viewer">

        <?php echo wp_get_attachment_image( $image, $sizeHuge ); ?>

    </a>

<?php } ?>
</code>```

My question is: How can I set the href of a.open-viewer with the correct URL?, and secondly, why does my code fail? (debug is switched on but no errors appear).

I realise I've horribly misunderstood something here, I'm a PHP novice so any advice about my approach would be appreciated.

答:
Following is the updated/corrected code which will work for you:</p>

```<code> <?php

   // args

    $sizeFull = 'full'; // full size image
    $sizeHuge = 'scaled'; // scaled image
    $images = array(); // img array

    for($x = 1; $x <= 10; $x++) {
            $img = get_field('image_' . $x);
       if($img) {
            $images[] = $img;
       } else {
            break;
       }
     }

    <?php foreach($images as $image) {
          $image_array = wp_get_attachment_image_src($image, $sizeFull);
          $link = $image_array[0];
         ?>

        <a href="<?php echo $link; ?>" class="open-viewer">

            <?php echo wp_get_attachment_image( $image, $sizeHuge ); ?>
            // or Rather than calling above function, why don't you write <img> tag as you already have image url ? Like:
            <img src="<?php echo $link; ?>" class="">

        </a>

    <?php } ?>
</code>```

Body:
I have 10 images added to a post via Advanced Custom Fields, they're named from 1 to 10 e.g 'image_*', ACF is set to return the ID.

I'm trying to get the full size image URL of each image in the loop and use it as a href attribute to open a full size popup of the image, however I don't understand how wp_get_attachment_image_src works.

Since I am unable to use Advanced Custom Field's Repeater, this is the loop i'm using to get an array of the images with a custom image size of scaled, it works fine to generate the responsive image markup that I need:

// args

$sizeHuge = 'scaled'; // scaled image
$images = array(); // img array

for($x = 1; $x <= 10; $x++) {
        $img = get_field('image_' . $x);
   if($img) {
        $images[] = $img;
   } else {
        break;
   }
 }

<?php foreach($images as $image) { ?>

        <?php echo wp_get_attachment_image( $image, $sizeHuge ); ?>

<?php } ?>

I need to set the href attribute of the parent a element with the URL of the image. This is what I have tried with wp_get_attachment_image_src, it doesn't work, it sets every href with image_10's URL.

// args

$sizeFull = 'full'; // full size image
$sizeHuge = 'scaled'; // scaled image
$images = array(); // img array

for($x = 1; $x <= 10; $x++) {
        $img = get_field('image_' . $x);
        $image_array = wp_get_attachment_image_src($img, $sizeFull);
        $link = $image_array[0];
   if($img) {
        $images[] = $img;
   } else {
        break;
   }
 }

<?php foreach($images as $image) { ?>

    <a href="<?php echo $link; ?>" class="open-viewer">

        <?php echo wp_get_attachment_image( $image, $sizeHuge ); ?>

<?php } ?>

My question is: How can I set the href of a.open-viewer with the correct URL?, and secondly, why does my code fail? (debug is switched on but no errors appear).

I realise I've horribly misunderstood something here, I'm a PHP novice so any advice about my approach would be appreciated.

Body:
Following is the updated/corrected code which will work for you:

 <?php

   // args

    $sizeFull = 'full'; // full size image
    $sizeHuge = 'scaled'; // scaled image
    $images = array(); // img array

    for($x = 1; $x <= 10; $x++) {
            $img = get_field('image_' . $x);
       if($img) {
            $images[] = $img;
       } else {
            break;
       }
     }

    <?php foreach($images as $image) {
          $image_array = wp_get_attachment_image_src($image, $sizeFull);
          $link = $image_array[0];
         ?>

        <a href="<?php echo $link; ?>" class="open-viewer">

            <?php echo wp_get_attachment_image( $image, $sizeHuge ); ?>
            // or Rather than calling above function, why don't you write <img> tag as you already have image url ? Like:
            <img src="<?php echo $link; ?>" class="">

        </a>

    <?php } ?>


问:
Function inside component - ReactJS
Pretty new to  React and I have this issue: I want to get URL+ImageUrl from coinData.

In Vue, I would just create a method in the component:

```<code>getCoinImage: function(symbol) {
  return CRYPTOCOMPARE_API_URI + this.coinData[symbol].ImageUrl;
}
</code>```

Then call the function in the view template and it would return full URL of the image I'm looking for.

How do I do it in React?

```<code>class App extends Component {

  constructor(props) {
    super(props);

this.state = {
  cryptos: [],
  coinData: {},
};
}

componentDidMount() {
 axios.get('https://api.coinmarketcap.com/v1/ticker/?limit=0')
.then(res => {
  const cryptos = res.data;
  this.setState({cryptos: cryptos});
  console.log(this.state.cryptos);

})

axios.get('https://min-api.cryptocompare.com/data/all/coinlist')
.then(res => {
const coinData = res.data.Data;
this.setState({coinData: coinData});
//console.log(coinData["BTC"].ImageUrl);
})
}

render() {
return (

    <table className="table is-striped is-narrow is-fullwidth"><thead>
        <tr>
          <td>Rank</td>
          <td>Name</td>
          <td>Symbol</td>
          <td>Price (USD)</td>
          <td>1h</td>
          <td>24h</td>
          <td>1 Week</td>
          <td>Market Cap</td>
        </tr>
      </thead>
      <tbody>{Object.keys(this.state.cryptos).map((key) => (
        <tr>
          <td>{this.state.cryptos[key].rank}</td>
          <td>{this.state.cryptos[key].name}</td>
          <td>{this.state.cryptos[key].symbol}</td>
          <td>{this.state.cryptos[key].price_usd}</td>
          <td>{this.state.cryptos[key].percent_change_1h}</td>
          <td>{this.state.cryptos[key].percent_change_24h}</td>
          <td>{this.state.cryptos[key].percent_change_7d}</td>
          <td>{this.state.cryptos[key].market_cap_usd}</td>
        </tr>
 ))};
      </tbody>
    </table>

);
}
}
</code>```

答:
You can write a similar function inside the component and call it when you need it, like

```<code>getCoinImage(imageUrl) {
 return `${CRYPTOCOMPARE_API_URI}${imageUrl}`;
}
</code>```

Just write this like any other method(like render). Then in the place you need, you need to call it like this this.getCoinImage(this.coinData[symbol].ImageUrl). I assume you will have the required data in the variable CRYPTOCOMPARE_API_URI.

Assuming you would need it inside your map, you can call like this

```<code><td><img src={this.getCoinImage(this.state.cryptos[key].imageUrl)} /></td>
</code>```

Title: Function inside component - ReactJS

Body:
Pretty new to  React and I have this issue: I want to get URL+ImageUrl from coinData.

In Vue, I would just create a method in the component:

getCoinImage: function(symbol) {
  return CRYPTOCOMPARE_API_URI + this.coinData[symbol].ImageUrl;
}

Then call the function in the view template and it would return full URL of the image I'm looking for.

How do I do it in React?

class App extends Component {

  constructor(props) {
    super(props);

this.state = {
  cryptos: [],
  coinData: {},
};
}

componentDidMount() {
 axios.get('https://api.coinmarketcap.com/v1/ticker/?limit=0')
.then(res => {
  const cryptos = res.data;
  this.setState({cryptos: cryptos});
  console.log(this.state.cryptos);

})

axios.get('https://min-api.cryptocompare.com/data/all/coinlist')
.then(res => {
const coinData = res.data.Data;
this.setState({coinData: coinData});
//console.log(coinData["BTC"].ImageUrl);
})
}

render() {
return (

          Rank
          Name
          Symbol
          Price (USD)
          1h
          24h
          1 Week
          Market Cap

{Object.keys(this.state.cryptos).map((key) => (

          {this.state.cryptos[key].rank}
          {this.state.cryptos[key].name}
          {this.state.cryptos[key].symbol}
          {this.state.cryptos[key].price_usd}
          {this.state.cryptos[key].percent_change_1h}
          {this.state.cryptos[key].percent_change_24h}
          {this.state.cryptos[key].percent_change_7d}
          {this.state.cryptos[key].market_cap_usd}

 ))};

);
}
}

Body:
You can write a similar function inside the component and call it when you need it, like

getCoinImage(imageUrl) {
 return `${CRYPTOCOMPARE_API_URI}${imageUrl}`;
}

Just write this like any other method(like render). Then in the place you need, you need to call it like this this.getCoinImage(this.coinData[symbol].ImageUrl). I assume you will have the required data in the variable CRYPTOCOMPARE_API_URI.

Assuming you would need it inside your map, you can call like this

<td><img src={this.getCoinImage(this.state.cryptos[key].imageUrl)} /></td>


问:
notificationManager get notification by Id
Anyone know any way to get a notification by id? It's I want when get a new notification if it is still being shown in the status bar of Android want to get the information and add it to a new notification. Thank you.</p>

答:
You can get active notification list from NotificationManager.</p>

```<code>@RequiresApi(api = Build.VERSION_CODES.M)
public Notification getActiveNotification(int notificationId) {
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    StatusBarNotification[] barNotifications = notificationManager.getActiveNotifications();
    for(StatusBarNotification notification: barNotifications) {
        if (notification.getId() == notificationId) {
            return notification.getNotification();
        }
    }
    return null;
}
</code>```

Body:
You can get active notification list from NotificationManager.

@RequiresApi(api = Build.VERSION_CODES.M)
public Notification getActiveNotification(int notificationId) {
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    StatusBarNotification[] barNotifications = notificationManager.getActiveNotifications();
    for(StatusBarNotification notification: barNotifications) {
        if (notification.getId() == notificationId) {
            return notification.getNotification();
        }
    }
    return null;
}


问:
Quote needed: Preprocessor usage is bad OO practice
I believe, that the usage of preprocessor directives like #if UsingNetwork is bad OO practice - other coworkers do not.
I think, when using an IoC container (e.g. Spring), components can be easily configured if programmed accordingly. In this context either a propery IsUsingNetwork can be set by the IoC container or, if the "using network" implementation behaves differently, another implementation of that interface should be implemented and injected (e.g.: IService, ServiceImplementation, NetworkingServiceImplementation).

Can somebody please provide citations of OO-Gurus or references in books which basically reads "Preprocessor usage is bad OO practice if you try to configure behaviour which should be configured via an IoC container"?

I need this citations to convince coworkers to refactor...

Edit: I do know and agree that using preprocessor directives to change targetplatform specific code during compilation is fine and that is what preprocessor directives are made for. However, I think that runtime-configuration should be used rather than compiletime-configuration to get good designed and testable classes and components. In other words: Using #defines and #if's beyond what they are meant for will lead to difficult to test code and badly designed classes.

Has anybody read something along these lines and can give me so I can refer to?

答:
IMHO, you talk about C and C++, not about OO practice in general. And C is not Object-oriented. In both languages the preprocessor is actually useful. Just use it correctly.

I think this answer belongs to C++ FAQ: [29.8] Are you saying that the preprocessor is evil?.

Yes, that's exactly what I'm saying:
  the preprocessor is evil.

Every #define macro effectively
  creates a new keyword in every source
  file and every scope until that symbol
  is #undefd. The preprocessor lets
  you create a #define symbol that is
  always replaced independent of the
  {...} scope where that symbol
  appears.

Sometimes we need the preprocessor,
  such as the #ifndef/#define wrapper
  within each header file, but it should
  be avoided when you can. "Evil"
  doesn't mean "never use." You will use
  evil things sometimes, particularly
  when they are "the lesser of two
  evils." But they're still evil :-)

I hope this source is authoritative enough :-)

OwnerDisplayName: tobsen

LastEditorDisplayName: tobsen

OwnerDisplayName: jetxee


问:
I want to add two columns in a dataframe with incremental values
I want to add two columns in a dataframe, let say we have 50 rows in the dataframe, so my Column 1 values should be 1 to 50, and Column 2 values should be 51 to 100.

```<code>def insertId(new_df, str):
    df.insertId(0, str, range(1, 1 + len(df)))
    return df
</code>```

The above function needs correction in order to meet my requirement, but unable to do so, as i am a beginner in Python.

Body:
I want to add two columns in a dataframe, let say we have 50 rows in the dataframe, so my Column 1 values should be 1 to 50, and Column 2 values should be 51 to 100.

def insertId(new_df, str):
    df.insertId(0, str, range(1, 1 + len(df)))
    return df

The above function needs correction in order to meet my requirement, but unable to do so, as i am a beginner in Python.

Body:
# Create sample data for initial dataframe.
np.random.seed(0)
df = pd.DataFrame(np.random.randn(5, 3), columns=list('ABC'))
>>> df
          A         B         C
0  1.764052  0.400157  0.978738
1  2.240893  1.867558 -0.977278
2  0.950088 -0.151357 -0.103219
3  0.410599  0.144044  1.454274
4  0.761038  0.121675  0.443863

# Add new columns in sequential order.
n = len(df)
new_cols = ['a', 'b']  # Desired names for new columns.
new_col_count = len(new_cols)
df2 = pd.DataFrame(
    np.arange(1, n * new_col_count + 1).reshape(n, new_col_count, order='F')
    columns=new_cols,
    index=df.index)
>>> pd.concat([df, df2], axis=1)
          A         B         C  a   b
0  1.764052  0.400157  0.978738  1   6
1  2.240893  1.867558 -0.977278  2   7
2  0.950088 -0.151357 -0.103219  3   8
3  0.410599  0.144044  1.454274  4   9
4  0.761038  0.121675  0.443863  5  10


问:
Django Framework: wrong confirmation email
So guys this is what I have in my reset_password_email.html file:

```<code>> {{ protocol }}://{{ domain }}{% url 'accounts:reset_password_confirm'uidb64=uid token=token %}
</code>```

This is my urls.py file:

```<code>url(r'^reset-password/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', password_reset_confirm, {'template_name': 'accounts/reset_password_confirm.html', 'post_reset_redirect': '/account/reset-password/complete/'}, name='password_reset_confirm'),
</code>```

And this is the E-Mail-Link that I reveive and doesn't work(example):

http://127.0.0.1:8000/accounts/reset-password/confirm/Mg/4r7-e49456caf2260a8ed103/

If I change the link to account instead of accounts (see below), it works:

http://127.0.0.1:8000/account/reset-password/confirm/Mg/4r7-e49456caf2260a8ed103/

答:
Wrong namespace in my other urls.py

It was:

```<code>url(r'^account/', include('accounts.urls', namespace='account**s**'))
</code>```

Instead of:

```<code>url(r'^account/', include('accounts.urls', namespace='account'))
</code>```

Body:
So guys this is what I have in my reset_password_email.html file:

> {{ protocol }}://{{ domain }}{% url 'accounts:reset_password_confirm'uidb64=uid token=token %}

This is my urls.py file:

url(r'^reset-password/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', password_reset_confirm, {'template_name': 'accounts/reset_password_confirm.html', 'post_reset_redirect': '/account/reset-password/complete/'}, name='password_reset_confirm'),

And this is the E-Mail-Link that I reveive and doesn't work(example):

http://127.0.0.1:8000/accounts/reset-password/confirm/Mg/4r7-e49456caf2260a8ed103/

If I change the link to account instead of accounts (see below), it works:

http://127.0.0.1:8000/account/reset-password/confirm/Mg/4r7-e49456caf2260a8ed103/

Body:
Wrong namespace in my other urls.py

It was:

url(r'^account/', include('accounts.urls', namespace='account**s**'))

Instead of:

url(r'^account/', include('accounts.urls', namespace='account'))


问:
Program gets stuck in an infinite loop when using entering default during switch statement
So I am currently writing a program in C that using a switch statement can allow a string to be entered then depending on the value you choose from the menu determine what to do with it.

Here is my code,

```<code>#include <stdio.h>

int main()
{
    int menu, end, i;
    char string[100];
    end = 0;

    do
    {
        printf("Welcome to the string operations program.\n\n");

        printf("1 - Enter a string\n");
        printf("2 - Display the message using the string\n");
        printf("3 - Count the number of characters in the string\n");
        printf("4 - Display the string backwards\n");
        printf("5 - Exit\n\n");

        printf("Option: ");
        scanf("%d", &menu);

        switch (menu)
        {
            case 1:
                printf("String: ");
                scanf("%s", string);
                break;

            case 2:
                printf("This is a message: Hello %s\n", string);
                break;

            case 3:
                printf("There are %d characters in %s\n", strlen(string), string);
                break;

            case 4:
                printf("string reversed gives: ");
                for (i = strlen(string) - 1; i >= 0; i--)
                    printf("%c", string[i]);
                printf("\n");
                break;

            case 5:
                printf("Exit");
                return 1;
                break;

            default:
                printf("Invalid input, try again.\n");
                break;

        }
    }while (end != 1);
    return 0;
}
</code>```

It seems to work for everything when I run it through 1,2,3,4,5 as that is the requirement for the question. However when i enter a letter for example 't' it goes to the default section as expected. When it enters this it goes into an infinite loop.

Can anyone help me and show me how to not make this an infinite loop but just have it return to the start as the user input was not allowed?

答:
Like Anton mentioned the problem is because of the scanf statement. You can add a getchar(); before break; in default: to solve this problem. Two more suggestions:
* You can remove the do-while loop here as it serves no special purpose and it's better to use while(1) loop.
* Also the break; statement in case 5 is not needed.</p>

Body:
So I am currently writing a program in C that using a switch statement can allow a string to be entered then depending on the value you choose from the menu determine what to do with it.

Here is my code,

#include <stdio.h>

int main()
{
    int menu, end, i;
    char string[100];
    end = 0;

    do
    {
        printf("Welcome to the string operations program.\n\n");

        printf("1 - Enter a string\n");
        printf("2 - Display the message using the string\n");
        printf("3 - Count the number of characters in the string\n");
        printf("4 - Display the string backwards\n");
        printf("5 - Exit\n\n");

        printf("Option: ");
        scanf("%d", &menu);

        switch (menu)
        {
            case 1:
                printf("String: ");
                scanf("%s", string);
                break;

            case 2:
                printf("This is a message: Hello %s\n", string);
                break;

            case 3:
                printf("There are %d characters in %s\n", strlen(string), string);
                break;

            case 4:
                printf("string reversed gives: ");
                for (i = strlen(string) - 1; i >= 0; i--)
                    printf("%c", string[i]);
                printf("\n");
                break;

            case 5:
                printf("Exit");
                return 1;
                break;

            default:
                printf("Invalid input, try again.\n");
                break;

        }
    }while (end != 1);
    return 0;
}

It seems to work for everything when I run it through 1,2,3,4,5 as that is the requirement for the question. However when i enter a letter for example 't' it goes to the default section as expected. When it enters this it goes into an infinite loop.

Can anyone help me and show me how to not make this an infinite loop but just have it return to the start as the user input was not allowed?


问:
getting data from localstorage in ngOnInit in Angular 4 but it reset its value on refresh
I am using localstorage to store data in it and retreiving from it in constructor, I want that check varaible retain its value on refresh of page and compare its value with the 0, after getting updated value if check == 0 then it should go inside that function.

I am stuck on it how this can be possible?

```<code>check=0;

ngOnInit() {

    if(this.check==0)
    {
        this.list =new Array();
        this.list.push("Purchase a ring for my beautiful wife","get new GALAXY Note 150","Complete kevin's work ASAP","Buy 2 dozen eggs","Get milk on my way to home");
        localStorage.setItem('list', JSON.stringify(this.list));
        this.check++;
        localStorage.setItem('incre', JSON.stringify(this.check));
    }

    this.check=JSON.parse( localStorage.getItem('incre'));
    this.list=JSON.parse( localStorage.getItem('list'));
}
</code>```

答:
You don't even set initital 0 like dr.nio's  code.

```<code>public check: number = 0;
ngOnInit() {
  this.check = JSON.parse(localStorage.getItem('incre'))
  if (!this.check) {}

}
</code>```

Be clear and readability.

Body:
I am using localstorage to store data in it and retreiving from it in constructor, I want that check varaible retain its value on refresh of page and compare its value with the 0, after getting updated value if check == 0 then it should go inside that function.

I am stuck on it how this can be possible?

check=0;

ngOnInit() {

    if(this.check==0)
    {
        this.list =new Array();
        this.list.push("Purchase a ring for my beautiful wife","get new GALAXY Note 150","Complete kevin's work ASAP","Buy 2 dozen eggs","Get milk on my way to home");
        localStorage.setItem('list', JSON.stringify(this.list));
        this.check++;
        localStorage.setItem('incre', JSON.stringify(this.check));
    }

    this.check=JSON.parse( localStorage.getItem('incre'));
    this.list=JSON.parse( localStorage.getItem('list'));
}

Body:
You don't even set initital 0 like dr.nio's  code.

public check: number = 0;
ngOnInit() {
  this.check = JSON.parse(localStorage.getItem('incre'))
  if (!this.check) {}

}

Be clear and readability.


问:
etcd error when trying to start service rejected send message
I am using ubuntu 14.04 and Im configuring etcd for use with calico, but the service does not work.

This is my etcd.conf file:

```<code># vim:set ft=upstart ts=2 et:
description "etcd"
author "etcd maintainers"

start on stopped rc RUNLEVEL=[2345]
stop on runlevel [!2345]

respawn

setuid etcd

env ETCD_DATA_DIR=/var/lib/etcd
export ETCD_DATA_DIR

exec /usr/bin/etcd --name="uno" \
--advertise-client-urls="http://172.16.8.241:2379,http://172.16.8.241:4001" \
--listen-client-urls="http://0.0.0.0:2379,http://0.0.0.0:4001" \
--listen-peer-urls "http://0.0.0.0:2380" \
--initial-advertise-peer-urls "http://172.16.8.241:2380" \
--initial-cluster-token $(uuidgen) \
--initial-cluster "node1=http://172.16.8.241:2380" \
--initial-cluster-state "new"
</code>```

When I try to start:

```<code>ikerlan@uno:~$ service etcd start

start: Rejected send message, 1 matched rules; type="method_call", sender=":1.128" (uid=1000 pid=7374 comm="start etcd ") interface="com.ubuntu.Upstart0_6.Job" member="Start" error name="(unset)" requested_reply="0" destination="com.ubuntu.Upstart" (uid=0 pid=1 comm="/sbin/init")
</code>```

What could be the problem?

答:
Etcd flags "name" and "initial-cluster" must be match together.

```<code>....
    --name="keukenhof" \
    --initial-cluster="keukenhof=http://localhost:2380"
....
</code>```

Body:
I am using ubuntu 14.04 and Im configuring etcd for use with calico, but the service does not work.

This is my etcd.conf file:

# vim:set ft=upstart ts=2 et:
description "etcd"
author "etcd maintainers"

start on stopped rc RUNLEVEL=[2345]
stop on runlevel [!2345]

respawn

setuid etcd

env ETCD_DATA_DIR=/var/lib/etcd
export ETCD_DATA_DIR

exec /usr/bin/etcd --name="uno" \
--advertise-client-urls="http://172.16.8.241:2379,http://172.16.8.241:4001" \
--listen-client-urls="http://0.0.0.0:2379,http://0.0.0.0:4001" \
--listen-peer-urls "http://0.0.0.0:2380" \
--initial-advertise-peer-urls "http://172.16.8.241:2380" \
--initial-cluster-token $(uuidgen) \
--initial-cluster "node1=http://172.16.8.241:2380" \
--initial-cluster-state "new"

When I try to start:

ikerlan@uno:~$ service etcd start

start: Rejected send message, 1 matched rules; type="method_call", sender=":1.128" (uid=1000 pid=7374 comm="start etcd ") interface="com.ubuntu.Upstart0_6.Job" member="Start" error name="(unset)" requested_reply="0" destination="com.ubuntu.Upstart" (uid=0 pid=1 comm="/sbin/init")

What could be the problem?

Body:
Etcd flags "name" and "initial-cluster" must be match together.

....
    --name="keukenhof" \
    --initial-cluster="keukenhof=http://localhost:2380"
....


问:
Using JavaCompiler API in a Spring Boot app - unable to properly set the compilation classpath
We have an app that's been migrated from a traditional WAR Spring web application to what we had hoped would be a modern Spring Boot executable Jar.

One of the app modules uses the JavaCompiler API to generate Java code and compile it in runtime.

The generated code requires dependencies that reside in the web app classpath, and so we had roughly the following code:

StandardJavaFileManager standardFileManager = compiler.getStandardFileManager(null, null, null);

List<String> optionList = new ArrayList<String>();

    // set compiler's classpath to be same as the runtime's
    String classpathString = System.getProperty("java.class.path");
    optionList.addAll(Arrays.asList("-nowarn",
                                    "-classpath",
                                    classpathString,
                                    "-g",
                                    "-source",
                                    javaVersion,
                                    "-target",
                                    javaVersion));

    Collection classpathFiles = getClasspathJars(classpathString);
    addPreviousCompiledClassesToClasspathFiles(rootClassPath, classpathFiles);

    try {
        File file = new File(getTargetRoot(tempClassPath));
        file.mkdirs();
        standardFileManager.setLocation(StandardLocation.CLASS_OUTPUT, Lists.newArrayList(file));
        standardFileManager.setLocation(StandardLocation.CLASS_PATH, classpathFiles);

        // adding current dir to the source path, to find the compiled DV
        if (generateSeparateJarsForEachDecision.equals(NO_JAR)) {
            standardFileManager.setLocation(StandardLocation.SOURCE_PATH, Lists.newArrayList(file));
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

        List<CharSequenceJavaFileObject> compilationUnits = Lists
                .newArrayList(new CharSequenceJavaFileObject(   StringUtils.capitalize(filename),
                                                                toString(javaCode)));
        JavaCompiler.CompilationTask task = compiler
                .getTask(writer, standardFileManager, listener, optionList, null, compilationUnits);
        status = task.call();
```

<p>```

However, that doesn't work with Boot.
The classpath only contains my-app.jar, and I can't add any of the nested jars to the -cp of the task - it just won't those nested jars.
I've also attempted to manually add the to the -cp parameter them like so: {absolute-path}/my-app.jar!/BOOT-INF/lib/my-dep.jar
{absolute-path}/my-app.jar!/BOOT-INF/lib/*.jar

None of those worked.
Thought about using the <requiresUnpack> tag on build too, but that didn't seem to help because I couldn't get a hold of the expanded dir in order to add it to the classpath.

答:
Faced similar issue.

Looks like a limitation with spring boot.

So created a standalone application with Jersey and Tomcat embedded.

Now jar contains all libraries and able to set it as class path to Java Compiler

Body:
We have an app that's been migrated from a traditional WAR Spring web application to what we had hoped would be a modern Spring Boot executable Jar.

One of the app modules uses the JavaCompiler API to generate Java code and compile it in runtime.

The generated code requires dependencies that reside in the web app classpath, and so we had roughly the following code:

StandardJavaFileManager standardFileManager = compiler.getStandardFileManager(null, null, null);

List<String> optionList = new ArrayList<String>();

    // set compiler's classpath to be same as the runtime's
    String classpathString = System.getProperty("java.class.path");
    optionList.addAll(Arrays.asList("-nowarn",
                                    "-classpath",
                                    classpathString,
                                    "-g",
                                    "-source",
                                    javaVersion,
                                    "-target",
                                    javaVersion));

    Collection classpathFiles = getClasspathJars(classpathString);
    addPreviousCompiledClassesToClasspathFiles(rootClassPath, classpathFiles);

    try {
        File file = new File(getTargetRoot(tempClassPath));
        file.mkdirs();
        standardFileManager.setLocation(StandardLocation.CLASS_OUTPUT, Lists.newArrayList(file));
        standardFileManager.setLocation(StandardLocation.CLASS_PATH, classpathFiles);

        // adding current dir to the source path, to find the compiled DV
        if (generateSeparateJarsForEachDecision.equals(NO_JAR)) {
            standardFileManager.setLocation(StandardLocation.SOURCE_PATH, Lists.newArrayList(file));
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

        List<CharSequenceJavaFileObject> compilationUnits = Lists
                .newArrayList(new CharSequenceJavaFileObject(   StringUtils.capitalize(filename),
                                                                toString(javaCode)));
        JavaCompiler.CompilationTask task = compiler
                .getTask(writer, standardFileManager, listener, optionList, null, compilationUnits);
        status = task.call();

```

However, that doesn't work with Boot.
The classpath only contains my-app.jar, and I can't add any of the nested jars to the -cp of the task - it just won't those nested jars.
I've also attempted to manually add the to the -cp parameter them like so: {absolute-path}/my-app.jar!/BOOT-INF/lib/my-dep.jar
{absolute-path}/my-app.jar!/BOOT-INF/lib/*.jar

None of those worked.
Thought about using the <requiresUnpack> tag on build too, but that didn't seem to help because I couldn't get a hold of the expanded dir in order to add it to the classpath.


问:
SQL Server Data Masking Minimum permissions needed to mask
I am in the process of masking some data in a SQL Server 2017 database. I have masked a column with this statement:

```<code>ALTER TABLE lEmployee
    ALTER COLUMN FirstName nvarchar(160)
          MASKED WITH (FUNCTION = 'partial(2,"xxx",2)')
</code>```

And I can see in sys.columns that this is now masked.

Now in the application, the data is not showing as masked (neither is it in the db when logged in as that user). I have also run the below to ensure the user does not have this permission.

```<code>REVOKE UNMASK TO testuser
</code>```

Can anyone advise what the minimum permissions are needed so that the data masking works as expected.

Thank you in advance

答:
You are not able to DENY UNMASK on sysadmin and db_owner. This is build-in limitation.

Also, as noted in the documentation, this is not a security feature if the user can query the table.

As it in the example of the documentation shows, you do not need to grant REVOKE UNMASK as it is set by default:

```<code>DROP TABLE IF EXISTS  [dbo].[StackOverflow];

CREATE TABLE [dbo].[StackOverflow]
  (MemberID int IDENTITY PRIMARY KEY,
   FirstName varchar(100) MASKED WITH (FUNCTION = 'partial(1,"XXXXXXX",0)') NULL,
   LastName varchar(100) NOT NULL,
   Phone# varchar(12) MASKED WITH (FUNCTION = 'default()') NULL,
   Email varchar(100) MASKED WITH (FUNCTION = 'email()') NULL);

INSERT [dbo].[StackOverflow] (FirstName, LastName, Phone#, Email) VALUES
('Roberto', 'Tamburello', '555.123.4567', 'RTamburello@contoso.com'),
('Janice', 'Galvin', '555.123.4568', 'JGalvin@contoso.com.co'),
('Zheng', 'Mu', '555.123.4569', 'ZMu@contoso.net');
SELECT * FROM [dbo].[StackOverflow]  ;

CREATE USER TestUser WITHOUT LOGIN;
GRANT SELECT ON [dbo].[StackOverflow]   TO TestUser;

EXECUTE AS USER = 'TestUser';
SELECT * FROM [dbo].[StackOverflow]  ;
REVERT;
</code>```

and you cannot REVOKE UNMASK to sysadmin and db_owner.

Body:
I am in the process of masking some data in a SQL Server 2017 database. I have masked a column with this statement:

ALTER TABLE lEmployee
    ALTER COLUMN FirstName nvarchar(160)
          MASKED WITH (FUNCTION = 'partial(2,"xxx",2)')

And I can see in sys.columns that this is now masked.

Now in the application, the data is not showing as masked (neither is it in the db when logged in as that user). I have also run the below to ensure the user does not have this permission.

REVOKE UNMASK TO testuser

Can anyone advise what the minimum permissions are needed so that the data masking works as expected.

Thank you in advance

Body:
You are not able to DENY UNMASK on sysadmin and db_owner. This is build-in limitation.

Also, as noted in the documentation, this is not a security feature if the user can query the table.

As it in the example of the documentation shows, you do not need to grant REVOKE UNMASK as it is set by default:

DROP TABLE IF EXISTS  [dbo].[StackOverflow];

CREATE TABLE [dbo].[StackOverflow]
  (MemberID int IDENTITY PRIMARY KEY,
   FirstName varchar(100) MASKED WITH (FUNCTION = 'partial(1,"XXXXXXX",0)') NULL,
   LastName varchar(100) NOT NULL,
   Phone# varchar(12) MASKED WITH (FUNCTION = 'default()') NULL,
   Email varchar(100) MASKED WITH (FUNCTION = 'email()') NULL);

INSERT [dbo].[StackOverflow] (FirstName, LastName, Phone#, Email) VALUES
('Roberto', 'Tamburello', '555.123.4567', 'RTamburello@contoso.com'),
('Janice', 'Galvin', '555.123.4568', 'JGalvin@contoso.com.co'),
('Zheng', 'Mu', '555.123.4569', 'ZMu@contoso.net');
SELECT * FROM [dbo].[StackOverflow]  ;

CREATE USER TestUser WITHOUT LOGIN;
GRANT SELECT ON [dbo].[StackOverflow]   TO TestUser;

EXECUTE AS USER = 'TestUser';
SELECT * FROM [dbo].[StackOverflow]  ;
REVERT;

and you cannot REVOKE UNMASK to sysadmin and db_owner.


问:
Retrieve company name with GoCardless webhook
I'm using GoCardless (sandbox account) webhook for a billing project. I want to recover the clients who choose to pay with GoCardless. The problem is that in the JSON that I get from GoCardless there is no such information.

I need the company name to put the mandate number into a sql database where all my clients are.

Is there a way to get the company name when a mandate is created ? Or to connect the mandate number to the company name ?

Here is my code :

<?php
putenv('GC_WEBHOOK_SECRET=my_secret...');
$token = getenv("GC_WEBHOOK_SECRET");
$raw_payload = file_get_contents('php://input');
$headers = getallheaders();
$provided_signature = $headers["Webhook-Signature"];
$calculated_signature = hash_hmac("sha256", $raw_payload, $token);
if ($provided_signature == $calculated_signature) {
  $payload = json_decode($raw_payload, true);
    foreach ($payload["events"] as $event) {
      if ($event["resource_type"]=="mandates" && $event["action"]=="created"){
                $mandates=$event["links"];
                $mandate=$mandates["mandate"];
                try
                {
                    $pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
                    $bdd = new PDO('sqlsrv...', $pdo_options);
                    $reqi="INSERT INTO goCardLess (client) VALUES ('".$mandate."')";
                    $req = $bdd->query($reqi);
                    $req->closeCursor();
                }
                catch (Exception $e)
                {
                    die('Erreur : ' . $e->getMessage());
                }
                header("HTTP/1.1 200 OK");
                }
              }
            }
 else {
    header("HTTP/1.1 498 Invalid Token test");
  }
?>```

答:
GoCardless webhook events don't contain any sensitive data - they provide resource IDs so you can retrieve them from the API if needed.

The "mandate created" event contains the mandate ID, and the API reference for mandates shows that mandate responses contain a customer ID (the customer resource is where you'll find their company name.)

This means you need to retrieve the mandate through the API, then retrieve the customer:

```<code>if ($event["resource_type"]=="mandates" && $event["action"]=="created") {
    $mandate_id = $event["links"]["mandate"];
    $mandate = $client->mandates()->get($mandate_id);

    $customer_id = $mandate->links->customer;
    $customer = $client->customers()->get($customer_id);

    $company_name = $customer->company_name;
}
</code>```

This assumes that you've already installed and initialised the client library as $client.

Body:
GoCardless webhook events don't contain any sensitive data - they provide resource IDs so you can retrieve them from the API if needed.

The "mandate created" event contains the mandate ID, and the API reference for mandates shows that mandate responses contain a customer ID (the customer resource is where you'll find their company name.)

This means you need to retrieve the mandate through the API, then retrieve the customer:

if ($event["resource_type"]=="mandates" && $event["action"]=="created") {
    $mandate_id = $event["links"]["mandate"];
    $mandate = $client->mandates()->get($mandate_id);

    $customer_id = $mandate->links->customer;
    $customer = $client->customers()->get($customer_id);

    $company_name = $customer->company_name;
}

This assumes that you've already installed and initialised the client library as $client.


问:
Error building with Maven: Compilation failure
I'm trying to build the OWASP Benchmark (source available at https://github.com/OWASP/benchmark) with Maven 3.5.2, and JDK/JRE 1.8.0_152. Upon an mvn compile, I'm getting the following error:

```<code>[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.3:compile (default-compile) on project benchmark: Compilation failure -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.3:compile (default-compile) on project benchmark: Compilation failure
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:213)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:154)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:146)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:51)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:309)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:194)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:107)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:955)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:290)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:194)
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (Unknown Source)
    at java.lang.reflect.Method.invoke (Unknown Source)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)
Caused by: org.apache.maven.plugin.compiler.CompilationFailureException: Compilation failure
    at org.apache.maven.plugin.compiler.AbstractCompilerMojo.execute (AbstractCompilerMojo.java:915)
    at org.apache.maven.plugin.compiler.CompilerMojo.execute (CompilerMojo.java:129)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:134)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:208)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:154)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:146)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:51)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:309)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:194)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:107)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:955)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:290)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:194)
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (Unknown Source)
    at java.lang.reflect.Method.invoke (Unknown Source)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)
[ERROR]
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
</code>```

Does anyone know what I'm doing wrong?

答: Turns out Maven was using JRE rather than JDK. It compiled successfully after I fixed this.</p>

Body:
I'm trying to build the OWASP Benchmark (source available at https://github.com/OWASP/benchmark) with Maven 3.5.2, and JDK/JRE 1.8.0_152. Upon an mvn compile, I'm getting the following error:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.3:compile (default-compile) on project benchmark: Compilation failure -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.3:compile (default-compile) on project benchmark: Compilation failure
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:213)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:154)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:146)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:51)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:309)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:194)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:107)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:955)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:290)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:194)
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (Unknown Source)
    at java.lang.reflect.Method.invoke (Unknown Source)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)
Caused by: org.apache.maven.plugin.compiler.CompilationFailureException: Compilation failure
    at org.apache.maven.plugin.compiler.AbstractCompilerMojo.execute (AbstractCompilerMojo.java:915)
    at org.apache.maven.plugin.compiler.CompilerMojo.execute (CompilerMojo.java:129)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:134)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:208)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:154)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:146)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:51)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:309)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:194)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:107)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:955)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:290)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:194)
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (Unknown Source)
    at java.lang.reflect.Method.invoke (Unknown Source)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)
[ERROR]
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

Does anyone know what I'm doing wrong?


问:
Error on Accessing Gridview EditItemTemplate
Below is my Error Message:

System.NullReferenceException: 'Object reference not set to an
  instance of an object.'

DueDateTB was null.

This happens during execution when I start updating the Date Column in Gridview. Below is my Code for both front and end side.

Back Side:

```<code>protected void PaymentsDueGV_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
  TextBox DueDateTB = (TextBox)((GridView)sender).FindControl("DueDateTB");
  string DueDate = DueDateTB.Text;
  DueDateTB.Text= (Convert.ToDateTime(DueDateTB.Text)).ToString("dddd, MMMM dd, yyyy h:mm tt");
  PaymentsDueDS.UpdateParameters["DueDate"].DefaultValue = DueDateTB.Text;
}
</code>```

Front Side:

```<code><asp:TemplateField HeaderText="Due Date" SortExpression="CreatedDate" ItemStyle-HorizontalAlign="Center">
  <EditItemTemplate>
    <asp:TextBox runat="server" Text='<%# Convert.ToDateTime(Eval("DueDate")).ToLocalTime().ToString("d") %>' ID="DueDateTB" CausesValidation="True" Columns="5" MaxLength="10"></asp:TextBox>
      <asp:RequiredFieldValidator ID="DueDateTBRValidator" runat="server" ErrorMessage="*"
           ForeColor="Black" ControlToValidate="DueDateTB">
      </asp:RequiredFieldValidator>
  <asp:CalendarExtender ID="DueDateCE" runat="server" Enabled="True" TargetControlID="DueDateTB" Format="MM/dd/yyyy"></asp:CalendarExtender>
  </EditItemTemplate>
  <ItemTemplate>
      <asp:Label ID="lblLocalTime" runat="server" Text='<%# Convert.ToDateTime(Eval("DueDate")).ToLocalTime().ToString("d") %>'></asp:Label>
  </ItemTemplate>
  <HeaderStyle CssClass="GridCells"></HeaderStyle>
  <ItemStyle CssClass="GridCells"></ItemStyle>
  <FooterStyle CssClass="GridCells"></FooterStyle>
</asp:TemplateField>
</code>```

答:
You've to cast the sender object into GridViewRow not into GridView as:

```<code>TextBox DueDateTB = (TextBox)((GridViewRow)sender).FindControl("DueDateTB");
</code>```

Body:
Below is my Error Message:

System.NullReferenceException: 'Object reference not set to an
  instance of an object.'

DueDateTB was null.

This happens during execution when I start updating the Date Column in Gridview. Below is my Code for both front and end side.

Back Side:

protected void PaymentsDueGV_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
  TextBox DueDateTB = (TextBox)((GridView)sender).FindControl("DueDateTB");
  string DueDate = DueDateTB.Text;
  DueDateTB.Text= (Convert.ToDateTime(DueDateTB.Text)).ToString("dddd, MMMM dd, yyyy h:mm tt");
  PaymentsDueDS.UpdateParameters["DueDate"].DefaultValue = DueDateTB.Text;
}

Front Side:

<asp:TemplateField HeaderText="Due Date" SortExpression="CreatedDate" ItemStyle-HorizontalAlign="Center">
  <EditItemTemplate>
    <asp:TextBox runat="server" Text='<%# Convert.ToDateTime(Eval("DueDate")).ToLocalTime().ToString("d") %>' ID="DueDateTB" CausesValidation="True" Columns="5" MaxLength="10"></asp:TextBox>
      <asp:RequiredFieldValidator ID="DueDateTBRValidator" runat="server" ErrorMessage="*"
           ForeColor="Black" ControlToValidate="DueDateTB">
      </asp:RequiredFieldValidator>
  <asp:CalendarExtender ID="DueDateCE" runat="server" Enabled="True" TargetControlID="DueDateTB" Format="MM/dd/yyyy"></asp:CalendarExtender>
  </EditItemTemplate>
  <ItemTemplate>
      <asp:Label ID="lblLocalTime" runat="server" Text='<%# Convert.ToDateTime(Eval("DueDate")).ToLocalTime().ToString("d") %>'></asp:Label>
  </ItemTemplate>
  <HeaderStyle CssClass="GridCells"></HeaderStyle>
  <ItemStyle CssClass="GridCells"></ItemStyle>
  <FooterStyle CssClass="GridCells"></FooterStyle>
</asp:TemplateField>

Body:
You've to cast the sender object into GridViewRow not into GridView as:

TextBox DueDateTB = (TextBox)((GridViewRow)sender).FindControl("DueDateTB");


问:
how to take large size array in java
i am new to java and i want to take large input size array in java. but in gives me some Runtime Error - NZEC, I don't know about it and i also did some research on this error but did'nt find anything related to my problem.

```<code>   long n=sc.nextLong();// n can be upto 10^9;
   long a[]=new long[n];// declaring array of n;
</code>```

also i am facing a compile time error which is :

```<code>error: incompatible types: possible lossy conversion from long to int
</code>```

can anyone please solve my this issue??

答:
Array sizes are limited to int size in java. so you need to create your array with int sizes always. you have to take n as int. and replace the long n=sc.nextLong();// n can be upto 10^9; by int n=sc.nextInt();// n can be upto 10^9;

It will work perfectly.

Title: how to take large size array in java

Body:
i am new to java and i want to take large input size array in java. but in gives me some Runtime Error - NZEC, I don't know about it and i also did some research on this error but did'nt find anything related to my problem.

   long n=sc.nextLong();// n can be upto 10^9;
   long a[]=new long[n];// declaring array of n;

also i am facing a compile time error which is :

error: incompatible types: possible lossy conversion from long to int

can anyone please solve my this issue??