问:
How can I send information from NodeJS server to client side?
For example, I want to signal to the client side that a username sent via the POST method in an HTML form already exists in my database.

I know how to recuperate POST data with body-parser and I know how to look it up in a MySQL database.

I know that I could use Ajax to write an error message directly on the form. What does my NodeJS server need to send and how does it send this information?

I've searched through numerous tutorials and I just found solutions where they send a new HTML page. I want to keep my web page the same and use functions like appendChild() to post the error message.

答:
There are a couple of ways you could send data from server-side, so NodeJS, to client-side - which I assume in your case would be some JavaScript file like main.js that handles DOM manimulation.

So, the 1st way you could send data is through a templating engine like Handlebars, for example. There is an easy to use module for express you could get here: hbs.

Now to quickly summarize how an engine like that works, we are basically sending an HTML file like you probably saw in the tutorials, however, a templating engine like Handlebars allows us to send actual data with that file dynamically, so what we would do is render a specific Handlebars template (which in core is just HTML), and pass in a JavaScript object to the render call which would contain all the data you want to pass into that file and then access it in the .hbs file.

So on the server-side, we would write something like this, assuming we have a file called home.hbs and set up Handlebars as the templating engine:

```<code>router.get('/home', function(req,res) {
   var dataToSendObj = {'title': 'Your Website Title', 'message': 'Hello'};
   res.render('home',dataToSendObj);
});
</code>```

And access in home.hbs like this:

```<code><html>
   <header>
      {{title}}
   </header>
   <body>
      message from server: {{message}}
   </body>
</html>
</code>```

Now, the issue with this approach is that if you wanted to update the data on the page dynamically, without having to reload the page, using a templating engine would not be ideal. Instead, like you said, you would use AJAX.

So, the 2nd way you could send data from your NodeJS server to the front-end of your website, is using an asynchronous AJAX call.

First, add a route to whatever route handler you are using for AJAX to make a call to. This where you have some logic to perhaps access the database, make some checks and return some useful information back to client.

```<code>router.get('/path/for/ajax/call', function(req,res) {
   // make some calls to database, fetch some data, information, check state, etc...
   var dataToSendToClient = {'message': 'error message from server'};
   // convert whatever we want to send (preferably should be an object) to JSON
   var JSONdata = JSON.stringify(dataToSendToClient);
   res.send(JSONdata);
});
</code>```

Assuming you have some file such as main.js, create an AJAX request with callbacks to listen to certain event responses like this:

```<code>var req = new XMLHttpRequest();
var url = '/path/for/ajax/call';

req.open('GET',url,true); // set this to POST if you would like
req.addEventListener('load',onLoad);
req.addEventListener('error',onError);

req.send();

function onLoad() {
   var response = this.responseText;
   var parsedResponse = JSON.parse(response);

   // access your data newly received data here and update your DOM with appendChild(), findElementById(), etc...
   var messageToDisplay = parsedResponse['message'];

   // append child (with text value of messageToDisplay for instance) here or do some more stuff
}

function onError() {
  // handle error here, print message perhaps
  console.log('error receiving async AJAX call');
}
</code>```

To summarize the above approach using AJAX, this would be the flow of the interaction:

Action is triggered on client-side (like button pressed)

The event handler for that creates a new AJAX request, sets up the callback so it knows what to do when the response comes back from the server, and sends the request

The GET or POST request sent is caught by our route handler on the server

Server side logic is executed to get data from database, state, etc...

The new data is fetched, placed into a JSON object, and sent back by the server

The client AJAX's event listener for either load or error catches the response and executes the callback

In the case of a successful response load, we parse the response, and update the client-side UI

Hope this is helpful!

Body:
There are a couple of ways you could send data from server-side, so NodeJS, to client-side - which I assume in your case would be some JavaScript file like main.js that handles DOM manimulation.

So, the 1st way you could send data is through a templating engine like Handlebars, for example. There is an easy to use module for express you could get here: hbs.

Now to quickly summarize how an engine like that works, we are basically sending an HTML file like you probably saw in the tutorials, however, a templating engine like Handlebars allows us to send actual data with that file dynamically, so what we would do is render a specific Handlebars template (which in core is just HTML), and pass in a JavaScript object to the render call which would contain all the data you want to pass into that file and then access it in the .hbs file.

So on the server-side, we would write something like this, assuming we have a file called home.hbs and set up Handlebars as the templating engine:

router.get('/home', function(req,res) {
   var dataToSendObj = {'title': 'Your Website Title', 'message': 'Hello'};
   res.render('home',dataToSendObj);
});

And access in home.hbs like this:

<html>
   <header>
      {{title}}
   </header>
   <body>
      message from server: {{message}}
   </body>
</html>

Now, the issue with this approach is that if you wanted to update the data on the page dynamically, without having to reload the page, using a templating engine would not be ideal. Instead, like you said, you would use AJAX.

So, the 2nd way you could send data from your NodeJS server to the front-end of your website, is using an asynchronous AJAX call.

First, add a route to whatever route handler you are using for AJAX to make a call to. This where you have some logic to perhaps access the database, make some checks and return some useful information back to client.

router.get('/path/for/ajax/call', function(req,res) {
   // make some calls to database, fetch some data, information, check state, etc...
   var dataToSendToClient = {'message': 'error message from server'};
   // convert whatever we want to send (preferably should be an object) to JSON
   var JSONdata = JSON.stringify(dataToSendToClient);
   res.send(JSONdata);
});

Assuming you have some file such as main.js, create an AJAX request with callbacks to listen to certain event responses like this:

var req = new XMLHttpRequest();
var url = '/path/for/ajax/call';

req.open('GET',url,true); // set this to POST if you would like
req.addEventListener('load',onLoad);
req.addEventListener('error',onError);

req.send();

function onLoad() {
   var response = this.responseText;
   var parsedResponse = JSON.parse(response);

   // access your data newly received data here and update your DOM with appendChild(), findElementById(), etc...
   var messageToDisplay = parsedResponse['message'];

   // append child (with text value of messageToDisplay for instance) here or do some more stuff
}

function onError() {
  // handle error here, print message perhaps
  console.log('error receiving async AJAX call');
}

To summarize the above approach using AJAX, this would be the flow of the interaction:

Action is triggered on client-side (like button pressed)

The event handler for that creates a new AJAX request, sets up the callback so it knows what to do when the response comes back from the server, and sends the request

The GET or POST request sent is caught by our route handler on the server

Server side logic is executed to get data from database, state, etc...

The new data is fetched, placed into a JSON object, and sent back by the server

The client AJAX's event listener for either load or error catches the response and executes the callback

In the case of a successful response load, we parse the response, and update the client-side UI

Hope this is helpful!


来源: stackexchange

问:
Convert.DateTime
What Convert.DateTime will convert the date 7/25/2010 12:00:00 it's current format is(MM/dd/yyyy HH:mm:ss)?

When I convert this string format to date time I am getting the error "string was not recognized as valid DateTime"

答:
If you need to use Convert.DateTime, I'll assume you're working with a string you want to convert to a date. So you might try this:

```<code>DateTime date = Convert.DateTime("7/25/2010 12:00:00 am");
string formattedDateString = date.ToString("MM/dd/yyyy HH:mm:ss")
</code>```

I'm making no assumptions as to why you'd want to do this, except that, well, you have your reasons.

ContentLicense: CC BY-SA 3.0

Title: Convert.DateTime

Body:
If you need to use Convert.DateTime, I'll assume you're working with a string you want to convert to a date. So you might try this:

DateTime date = Convert.DateTime("7/25/2010 12:00:00 am");
string formattedDateString = date.ToString("MM/dd/yyyy HH:mm:ss")

I'm making no assumptions as to why you'd want to do this, except that, well, you have your reasons.

ContentLicense: CC BY-SA 2.5


问:
'undefined' getting appended to a specific Web API call
'Undefined' is getting appended to a specific WebAPI call in my angular application where as other calls succeed without issue.

Both registerUser and login call fails because of 'Undefined' character:

Request URL: http://localhost:25971/undefined/api/Account/Register

Request URL: http://localhost:25971/undefined/Token

Here is my code:

```<code>    (function () {
    "use strict";
    angular
        .module("userManagement")
        .controller("mainCtrl", ["userAccount", mainCtrl])

    function mainCtrl(userAccount) {
        var vm = this;
        vm.isLoggedIn = false;
        vm.message = '';
        vm.userData = {
            userName: '',
            email: '',
            password: '',
            confirmPassword: ''
        };

        vm.registerUser = function () {
            vm.userData.confirmPassword = vm.userData.password;
            userAccount.registration.registerUser(vm.userData, function (data) {
                vm.confirmPassword = "";
                vm.message = "...Registration successful";
                // vm.login();
            });
        }
        vm.login = function () {
            vm.userData.grant_type = "password";
            vm.userData.userName = vm.userData.email;
            userAccount.login.loginUser(vm.userData, function (data) {
                vm.isLoggedIn = true;
                vm.password = "";
                vm.message = "";
                vm.token = data.access_token;
            });
        }
    }
}());
</code>```

Here is the code in userAccount factory method:

```<code> (function () {
    "use strict";
    angular.module("common.services")
    .factory("userAccount", ["$resource", "appsettings", userAccount])
    function userAccount($resource, appsettings) {
        return {
            registration: $resource(appsettings.serverPath + "/api/Account/Register", null,
                {
                    'registerUser': { method: 'POST' }
                }),
            login: $resource(appsettings.serverPath + "/Token", null,
                {
                    'loginUser': {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        transformRequest: function (data, headersGetter) {
                        var str = [];
                        for (var d in data) {
                            str.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
                            return str.join("&")
                        }
                    }
                }
            })
        }
    }

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

Appsettings is defined like this:

```<code>(function () {
   "use strict";
    angular.module("common.services", ["ngResource"]).constant("appsettings", {
        serverpath:"http://localhost:25879/"
    });
}());
</code>```

I am new to Angular and WebAPI, any help or direction to find the issue would be appreciated!

答: Check for serverPath in apiSettings

Body:
'Undefined' is getting appended to a specific WebAPI call in my angular application where as other calls succeed without issue.

Both registerUser and login call fails because of 'Undefined' character:

Request URL: http://localhost:25971/undefined/api/Account/Register

Request URL: http://localhost:25971/undefined/Token

Here is my code:

    (function () {
    "use strict";
    angular
        .module("userManagement")
        .controller("mainCtrl", ["userAccount", mainCtrl])

    function mainCtrl(userAccount) {
        var vm = this;
        vm.isLoggedIn = false;
        vm.message = '';
        vm.userData = {
            userName: '',
            email: '',
            password: '',
            confirmPassword: ''
        };

        vm.registerUser = function () {
            vm.userData.confirmPassword = vm.userData.password;
            userAccount.registration.registerUser(vm.userData, function (data) {
                vm.confirmPassword = "";
                vm.message = "...Registration successful";
                // vm.login();
            });
        }
        vm.login = function () {
            vm.userData.grant_type = "password";
            vm.userData.userName = vm.userData.email;
            userAccount.login.loginUser(vm.userData, function (data) {
                vm.isLoggedIn = true;
                vm.password = "";
                vm.message = "";
                vm.token = data.access_token;
            });
        }
    }
}());

Here is the code in userAccount factory method:

 (function () {
    "use strict";
    angular.module("common.services")
    .factory("userAccount", ["$resource", "appsettings", userAccount])
    function userAccount($resource, appsettings) {
        return {
            registration: $resource(appsettings.serverPath + "/api/Account/Register", null,
                {
                    'registerUser': { method: 'POST' }
                }),
            login: $resource(appsettings.serverPath + "/Token", null,
                {
                    'loginUser': {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        transformRequest: function (data, headersGetter) {
                        var str = [];
                        for (var d in data) {
                            str.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
                            return str.join("&")
                        }
                    }
                }
            })
        }
    }

})();

Appsettings is defined like this:

(function () {
   "use strict";
    angular.module("common.services", ["ngResource"]).constant("appsettings", {
        serverpath:"http://localhost:25879/"
    });
}());

I am new to Angular and WebAPI, any help or direction to find the issue would be appreciated!

Body: Check for serverPath in apiSettings


问:
Python decoding error on Excel with xlrd
I know this is a recurrent subject but I'm facing a encoding/decoding error when trying to parse an Excel file (.xlsx) opened with xlrd

```<code>    value = sheet.cell(row,col).value
    value = value.decode('utf-8') // also tried cp1252 and iso-8859-15
</code>```

WARNING: 'ascii' codec can't encode character u'\xe9' in position xx: ordinal not in range(128)

xlrd doc says that From Excel 97 onwards, the text in Excel spreadsheets has been stored as Unicode. So decoding should not even be necessary.

Any idea what should be done ?

P.S. My Excel file has some é and à inside.

答:
Still using Python 2? :(

If what you're trying to do is convert from unicode to UTF-8 encoded str, you need to value.encode('utf-8'), not decode.

Body:
I know this is a recurrent subject but I'm facing a encoding/decoding error when trying to parse an Excel file (.xlsx) opened with xlrd

    value = sheet.cell(row,col).value
    value = value.decode('utf-8') // also tried cp1252 and iso-8859-15

WARNING: 'ascii' codec can't encode character u'\xe9' in position xx: ordinal not in range(128)

xlrd doc says that From Excel 97 onwards, the text in Excel spreadsheets has been stored as Unicode. So decoding should not even be necessary.

Any idea what should be done ?

P.S. My Excel file has some é and à inside.


问:
Sort columns in a matrix
I have a matrix (or a multidimensional array) of non unique values like this one:

```<code>var matrix = [
                [1, 3, 2, 4, 1],
                [2, 4, 1, 3, 2],
                [4, 3, 2, 1, 4]
             ]
</code>```

I want to sort a row of this matrix but the others rows should reorder the same in order to keep the column like organization.

```<code>//matrix sorted by the row 0
var sorted_matrix = [
                      [1, 1, 2, 3, 4],
                      [2, 2, 1, 4, 3],
                      [4, 4, 2, 3, 1]
                    ]
</code>```

I would prefer a lodash solution if possible.

答:
You could use an array with the indices and sort it with the values of matrix[0]. Then build a new array with sorted elements.

var matrix = [[1, 3, 2, 4, 1], [2, 4, 1, 3, 2], [4, 3, 2, 1, 4]],
    indices = matrix[0].map((_, i) => i);

indices.sort((a, b) => matrix[0][a] - matrix[0][b]);

result = matrix.map(a => indices.map(i => a[i]));

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: Sort columns in a matrix

Body:
I have a matrix (or a multidimensional array) of non unique values like this one:

var matrix = [
                [1, 3, 2, 4, 1],
                [2, 4, 1, 3, 2],
                [4, 3, 2, 1, 4]
             ]

I want to sort a row of this matrix but the others rows should reorder the same in order to keep the column like organization.

//matrix sorted by the row 0
var sorted_matrix = [
                      [1, 1, 2, 3, 4],
                      [2, 2, 1, 4, 3],
                      [4, 4, 2, 3, 1]
                    ]

I would prefer a lodash solution if possible.

Body:
You could use an array with the indices and sort it with the values of matrix[0]. Then build a new array with sorted elements.

var matrix = [[1, 3, 2, 4, 1], [2, 4, 1, 3, 2], [4, 3, 2, 1, 4]],
    indices = matrix[0].map((_, i) => i);

indices.sort((a, b) => matrix[0][a] - matrix[0][b]);

result = matrix.map(a => indices.map(i => a[i]));

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
SuggestBox override addSelectionHandler
I have a custom Oracle with Objects to pass to the SuggestBox. Then I need get back a object when it's selected from de SuggestBox.

```<code>public HandlerRegistration addSelectionHandler(SelectionHandler<SuggestOracle.Suggestion> handler)
</code>```

The problem is that I don't have Suggestion. I have "CustomSuggestion". I read de API and I try to write a Custom SuggestBox implementing the interface HasSelectionHandlers but I can't because the SuggestBox have a implementation of the interface. I get the error:

```<code>The interface HasSelectionHandlers cannot be implemented more than once with different arguments: HasSelectionHandlers<SuggestOracle.Suggestion> and HasSelectionHandlers<CustomSuggestion>
</code>```

Can you help me? Sorry for my bad english.

答:
Not sure I understand your problem. Have a look at the following example (really basic but you should get an idea on how to deal with custom suggestions). Hope that helps:</p>

```<code>public void onModuleLoad() {
    SuggestBox box = new SuggestBox(new CustomOracle<CustomSuggestion>());

    box.addSelectionHandler(new SelectionHandler<SuggestOracle.Suggestion>() {

        @Override
        public void onSelection(SelectionEvent<Suggestion> event) {
            String value = ((CustomSuggestion) event.getSelectedItem()).fSomeOtherValue;
            Window.alert(value);
        }
    });
    RootPanel.get().add(box);
}

private class CustomOracle<CustomSuggestion> extends SuggestOracle {

    private LinkedList<Starter.CustomSuggestion> fStore;

    public CustomOracle() {
        fStore = new LinkedList<Starter.CustomSuggestion>();
        fStore.add(new Starter.CustomSuggestion("2", "two", "foo"));
        fStore.add(new Starter.CustomSuggestion("22", "twenty-two", "bar"));
        fStore.add(new Starter.CustomSuggestion("222", "two-hundred twenty-two", "w000t"));
    }

    @Override
    public void requestSuggestions(Request request, Callback callback) {
        String query = request.getQuery();
        LinkedList<Starter.CustomSuggestion> result = new LinkedList<Starter.CustomSuggestion>();
        for (Starter.CustomSuggestion entry : fStore) {
            if (entry.fDisplay.contains(query)) {
                result.add(entry);
            }
        }
        callback.onSuggestionsReady(request, new Response(result));
    }

}

private class CustomSuggestion implements Suggestion {

    private String fReplace;
    private String fDisplay;
    private String fSomeOtherValue;

    public CustomSuggestion(String display, String replace, String someOtherValue) {
        fDisplay = display;
        fReplace = replace;
        fSomeOtherValue = someOtherValue;
    }

    @Override
    public String getDisplayString() {
        return fDisplay;
    }

    @Override
    public String getReplacementString() {
        return fReplace;
    }
}
</code>```

Title: SuggestBox override addSelectionHandler

Body:
I have a custom Oracle with Objects to pass to the SuggestBox. Then I need get back a object when it's selected from de SuggestBox.

public HandlerRegistration addSelectionHandler(SelectionHandler<SuggestOracle.Suggestion> handler)

The problem is that I don't have Suggestion. I have "CustomSuggestion". I read de API and I try to write a Custom SuggestBox implementing the interface HasSelectionHandlers but I can't because the SuggestBox have a implementation of the interface. I get the error:

The interface HasSelectionHandlers cannot be implemented more than once with different arguments: HasSelectionHandlers<SuggestOracle.Suggestion> and HasSelectionHandlers<CustomSuggestion>

Can you help me? Sorry for my bad english.

Body:
Not sure I understand your problem. Have a look at the following example (really basic but you should get an idea on how to deal with custom suggestions). Hope that helps:

public void onModuleLoad() {
    SuggestBox box = new SuggestBox(new CustomOracle<CustomSuggestion>());

    box.addSelectionHandler(new SelectionHandler<SuggestOracle.Suggestion>() {

        @Override
        public void onSelection(SelectionEvent<Suggestion> event) {
            String value = ((CustomSuggestion) event.getSelectedItem()).fSomeOtherValue;
            Window.alert(value);
        }
    });
    RootPanel.get().add(box);
}

private class CustomOracle<CustomSuggestion> extends SuggestOracle {

    private LinkedList<Starter.CustomSuggestion> fStore;

    public CustomOracle() {
        fStore = new LinkedList<Starter.CustomSuggestion>();
        fStore.add(new Starter.CustomSuggestion("2", "two", "foo"));
        fStore.add(new Starter.CustomSuggestion("22", "twenty-two", "bar"));
        fStore.add(new Starter.CustomSuggestion("222", "two-hundred twenty-two", "w000t"));
    }

    @Override
    public void requestSuggestions(Request request, Callback callback) {
        String query = request.getQuery();
        LinkedList<Starter.CustomSuggestion> result = new LinkedList<Starter.CustomSuggestion>();
        for (Starter.CustomSuggestion entry : fStore) {
            if (entry.fDisplay.contains(query)) {
                result.add(entry);
            }
        }
        callback.onSuggestionsReady(request, new Response(result));
    }

}

private class CustomSuggestion implements Suggestion {

    private String fReplace;
    private String fDisplay;
    private String fSomeOtherValue;

    public CustomSuggestion(String display, String replace, String someOtherValue) {
        fDisplay = display;
        fReplace = replace;
        fSomeOtherValue = someOtherValue;
    }

    @Override
    public String getDisplayString() {
        return fDisplay;
    }

    @Override
    public String getReplacementString() {
        return fReplace;
    }
}


问:
How can I exclude nearly duplicated values in a sql table based off a rule?
Consider this table:

I have data giving a person's ID and their citizenships.  Some people appear twice on the table because they have dual citizenship.

I would like help doing two things:

1) If someone has US citizenship and another citizenship, I would like to remove the line with the non-US citizenship

2) If someone has two non-US citizenships, I would like to remove one of them--no preference which.

Any suggestions how to do this?

答:
Something like this should do:

```<code>select id, name, citizenship
from (
  select id, name, citizenship,
         row_number() over (partition by id
                              order by case
                                         when citizenship = 'US' then 1
                                         else 2
                                       end) as rn
  from the_table
) t
where rn = 1
order by id;
</code>```

Another option is to use Postgres' distinct on () operator

```<code>select distinct on (id) *
from the_table
order by id, by case
                  when citizenship = 'US' then 1
                  else 2
                end
</code>```

Body:
Something like this should do:

select id, name, citizenship
from (
  select id, name, citizenship,
         row_number() over (partition by id
                              order by case
                                         when citizenship = 'US' then 1
                                         else 2
                                       end) as rn
  from the_table
) t
where rn = 1
order by id;

Another option is to use Postgres' distinct on () operator

select distinct on (id) *
from the_table
order by id, by case
                  when citizenship = 'US' then 1
                  else 2
                end


问:
Swift Modeling Friend System
I'm making a simple app in swift, and have users, photos, and friends table in Postgres and store photos in S3. The app functions with simple REST calls. I'm having an issue with the following:
User A sends a friend request to User B
    Friend Table: sender_id: UserA_id, receiver_id: UserB_id, status: 'pending'
Now, on the device, UserB is added to UserA's pendingFromMe's friends. Now, how at the same time do I update UserB's pendingToMe's friends on a separate device?

A couple options I have thought of

Postgres Listen - This is bad as 500 connection limit means this won't work

APN would send a Push Notification to UserB and run a function to re-download friends list

Any other options? How would I go about doing this? There are NO tutorials outside of Parse/Firebase and I don't want to use BaaS since I've built my own REST server.

Thanks!

Will accept links to tutorials for this, github repos, etc

答:
If you orchestrate, your facade should call your user service to update the status on both users then invoke the notification service to push to both devices.

If you're event-based, your user service should probably listen to status update events and update the other user's status then fire an event which your notification service should handle to push to the involved devices.

ContentLicense: CC BY-SA 4.0

Title: Swift Modeling Friend System


问:
Angular Form Required doesn't work
I put a simple form input in my form but required doesn't work for me and from with empty input submitted.
Here is my code:

```<code><div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
      <input type="text" class="form-control" id="inputEmail3" placeholder="test"
        required
        name="test">
    </div>
  </div>
</code>```

Here is my form tag:

```<code><form class="form-horizontal" (ngSubmit)="onSubmit()">
</code>```

Here is my submit button tag:

```<code><button type="submit" class="btn btn-default">Save</button>
</code>```

答:
Add ngNativeValidate in your form tag:</p>

```<code><form ngNativeValidate class="form-horizontal" (ngSubmit)="onSubmit()">
</code>```

Title: Angular Form Required doesn't work

Body:
I put a simple form input in my form but required doesn't work for me and from with empty input submitted.
Here is my code:

      <input type="text" class="form-control" id="inputEmail3" placeholder="test"
        required
        name="test">

Here is my form tag:

<form class="form-horizontal" (ngSubmit)="onSubmit()">

Here is my submit button tag:

<button type="submit" class="btn btn-default">Save</button>

Body:
Add ngNativeValidate in your form tag:

<form ngNativeValidate class="form-horizontal" (ngSubmit)="onSubmit()">


问:
Dagger2 error: Kotlin: Unresolved reference: DaggerSOMETHINGComponent

source code

I'm building a gradle project of Kotlin and Dagger2 which runs well half year ago in macOS:

GitHub:Kotlin-Tutorials13

you can get it by

```<code>git clone https://github.com/enbandari/Kotlin-Tutorials.git
cd Kotlin-Tutorials/code/Kt13
</code>```

you can open it in IntelliJ IDEA

building enviroment

My building enviroment is listed as below:

IntelliJ IDEA 2017.1.3

JRE: 1.8.0_112-release-736-b21 amd64

JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o

Windows 10 10.0

building result

It tuens out an error:

```<code>C:\Users\xiang\IdeaProjects\Kotlin-Tutorials-master\code\Kt13\src\main\kotlin\net\println\kt13\Service.kt
Error:(3, 25) Kotlin: Unresolved reference: DaggerRESTFulComponent
Error:(19, 9) Kotlin: Unresolved reference: DaggerRESTFulComponent
</code>```

decompile

So, I decompile RESTFulComponent.class

the source file of it is RESTFulComponent.kt

```<code>package net.println.kt13

import dagger.Component
import net.println.kt13.module.RetrofitModule
import retrofit2.Retrofit
import javax.inject.Singleton

/**
 * Created by benny on 12/11/16.
 */
@Singleton
@Component(modules = arrayOf(RetrofitModule::class))
interface RESTFulComponent {
    fun retrofit(): Retrofit
}
</code>```

decompile RESTFulComponent.class we get

```<code>// IntelliJ API Decompiler stub source generated from a class file
// Implementation of methods is not available

package net.println.kt13.module

@dagger.Module public final class RxAdapterModule public constructor() {
    @javax.inject.Singleton @dagger.Provides public final fun adapter(): retrofit2.CallAdapter.Factory { /* compiled code */ }
}
</code>```

reason

The error result from annotation of dagger's not working.

How can I fix this error?

答:
wrong operation

I use Ctrl+F9 to compile and this error arises。

right operation

We should click View -> Tool Windows -> Gradle to open Gradle projects Window

Then click Tasks -> build -> build

reason

Ctrl+F9 isn't invoking gradle build, we should use gradle build in Gradle projects Window

Body:
source code

I'm building a gradle project of Kotlin and Dagger2 which runs well half year ago in macOS:

GitHub:Kotlin-Tutorials13

you can get it by

git clone https://github.com/enbandari/Kotlin-Tutorials.git
cd Kotlin-Tutorials/code/Kt13

you can open it in IntelliJ IDEA

building enviroment

My building enviroment is listed as below:

IntelliJ IDEA 2017.1.3

JRE: 1.8.0_112-release-736-b21 amd64

JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o

Windows 10 10.0

building result

It tuens out an error:

C:\Users\xiang\IdeaProjects\Kotlin-Tutorials-master\code\Kt13\src\main\kotlin\net\println\kt13\Service.kt
Error:(3, 25) Kotlin: Unresolved reference: DaggerRESTFulComponent
Error:(19, 9) Kotlin: Unresolved reference: DaggerRESTFulComponent

decompile

So, I decompile RESTFulComponent.class

the source file of it is RESTFulComponent.kt

package net.println.kt13

import dagger.Component
import net.println.kt13.module.RetrofitModule
import retrofit2.Retrofit
import javax.inject.Singleton

/**
 * Created by benny on 12/11/16.
 */
@Singleton
@Component(modules = arrayOf(RetrofitModule::class))
interface RESTFulComponent {
    fun retrofit(): Retrofit
}

decompile RESTFulComponent.class we get

// IntelliJ API Decompiler stub source generated from a class file
// Implementation of methods is not available

package net.println.kt13.module

@dagger.Module public final class RxAdapterModule public constructor() {
    @javax.inject.Singleton @dagger.Provides public final fun adapter(): retrofit2.CallAdapter.Factory { /* compiled code */ }
}

reason

The error result from annotation of dagger's not working.

How can I fix this error?


问:
CRF++/Wapiti include category of entire sentence as feature
How can I represent category of sentence predicted from Naive Bayes as a feature in CRF++ or Wapiti?

For instance, if the sentence, Tumblr merges with Yahoo., is classified as Business, then while composing the training file for crf, where can I indicate the label Business as a feature? And how should then the template be modeled?

Should the train file be like this

```<code>Tumblr    business    ORG
merges    business    O
with     business    O
Yahoo    business    ORG
</code>```

Or only include the category with the ORG label? How so? And the template file?

答:
Method 1:
You can add business as a feature in the same way you have shown or you can simply write 1 instead of business. Similarly, for category sports you can add another column and the value in this column shall be 1 for words belonging to sports sentence.
You'll have to add each column in the template file too, respectively.

```<code>U42:%x[0,1] #for business
U43:%x[0,2] #for sports
</code>```

Method 2:
Including category with ORG might not be a good idea because the same ORG can appear in different categories.

Body:
How can I represent category of sentence predicted from Naive Bayes as a feature in CRF++ or Wapiti?

For instance, if the sentence, Tumblr merges with Yahoo., is classified as Business, then while composing the training file for crf, where can I indicate the label Business as a feature? And how should then the template be modeled?

Should the train file be like this

Tumblr    business    ORG
merges    business    O
with     business    O
Yahoo    business    ORG

Or only include the category with the ORG label? How so? And the template file?

Body:
Method 1:
You can add business as a feature in the same way you have shown or you can simply write 1 instead of business. Similarly, for category sports you can add another column and the value in this column shall be 1 for words belonging to sports sentence.
You'll have to add each column in the template file too, respectively.

U42:%x[0,1] #for business
U43:%x[0,2] #for sports

Method 2:
Including category with ORG might not be a good idea because the same ORG can appear in different categories.


问:
Undefined reference to timeGetTime() in g++
I'm using g++ command line under Windows 10 to build a basic timing loop and am getting the error: " undefined reference to `timeGetTime@0' " when attempting to compile.

The code, itself, is pretty simple:

```<code>#include <windows.h>
#include <iostream>
using namespace std;

int main(){
   int start = timeGetTime();
   int finish = 10000;
   int benchmarks [9] = {1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000};
   int i = 0;
   int time = timeGetTime() - start;
   while( time < finish){
       if(time > benchmarks[i]){
           cout << benchmarks[i] / 1000 << endl;
           i++;
       }

   return 0;
}
</code>```

Not sure what I need to do to get g++ to play nicely with the WinAPI. I can't help but wonder if it's an issue with the linker.

答:
You have to link libwinmm.

Undefined reference is an error which occures when your compiler knows that the function exist, it knows its prototype, but can't find its corpse. When it is not one of your functions, it surely means you miss to link a library.

Body:
I'm using g++ command line under Windows 10 to build a basic timing loop and am getting the error: " undefined reference to `timeGetTime@0' " when attempting to compile.

The code, itself, is pretty simple:

#include <windows.h>
#include <iostream>
using namespace std;

int main(){
   int start = timeGetTime();
   int finish = 10000;
   int benchmarks [9] = {1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000};
   int i = 0;
   int time = timeGetTime() - start;
   while( time < finish){
       if(time > benchmarks[i]){
           cout << benchmarks[i] / 1000 << endl;
           i++;
       }

   return 0;
}

Not sure what I need to do to get g++ to play nicely with the WinAPI. I can't help but wonder if it's an issue with the linker.


问:
problems with closure in JS
I have a problem with understanding closure when I have 3 level of scopes

https://jsfiddle.net/Ar2zee/wLy8rkyL/1/

How I can get access to parameter "g" in level3 function,

var a = 10;

function level1(b) {
  var c = 1;

  function level2(f) {
    var d = 2;

    function level3(g) {
      return a + b + c + d + f + g;
    }
    return level3()
  }
  return level2;
}
var temp = level1(10);
var temp2 = temp(10);
var temp3 = temp2(10);
console.log(temp3(10)); // or level(10)();  without variable```

Thank you !

答:
Line:1 invokes level1 fn and get back fn level2 stored in alias temp.

Line:2 invokes temp fn and get back fn level3 stored in alias temp2.

Line:3 now when invoking temp2 fn you execute fn level3 getting back the result of addition operation.

So temp3 is not a function but a value.

var a = 10;

function level1(b) {
  var c = 1;

  function level2(f) {
    var d = 2;

    function level3(g) {
      return a + b + c + d + f + g;
    }
    return level3;
  }
  return level2;
}
var temp = level1(10);
var temp2 = temp(10);
var temp3 = temp2(10);
console.log(temp3); // or level(10)();  without variable```

Title: problems with closure in JS

Body:
I have a problem with understanding closure when I have 3 level of scopes

https://jsfiddle.net/Ar2zee/wLy8rkyL/1/

How I can get access to parameter "g" in level3 function,

var a = 10;

function level1(b) {
  var c = 1;

  function level2(f) {
    var d = 2;

    function level3(g) {
      return a + b + c + d + f + g;
    }
    return level3()
  }
  return level2;
}
var temp = level1(10);
var temp2 = temp(10);
var temp3 = temp2(10);
console.log(temp3(10)); // or level(10)();  without variable

Thank you !


问:
Is there something wrong with my form?
I have my form working and all of the errors and everything works.
But if you have an error, it refreshes the page and removes any text that was inserted before the submit button was clicked and you have to re-enter all of the information.
Anyway to fix this?

I think it has something to do with not using $_SERVER["PHP_SELF"] in the action of the form.
Instead I have action=""

I am doing this because the page that needs to be refreshed with the same info has a variable in its url (monthly_specials_info.php?date=Dec10) that was put there from the last page.

I tried using

```<code><form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
</code>```

and it produced the right url. but the text was all removed anyway when form was submitted (with errors).. any ideas?

Form code:

```<code>echo '    <div id="specialsForm"><h3>Interested in this coupon? Email us! </h3>
                                            <form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
                                              Name: <input name="name" type="text" /><br />
                                              Email: <input name="email" type="text" /><br />
                                              Phone Number: <input name="phone" type="text" /><br /><br />
                                              Comment: <br/>
                                              <textarea name="comment" rows="5" cols="30"></textarea><br /><br />
                                              <input type="submit" name="submit" value="Submit Email"/>
                                            </form></div>
                                            <div style="clear:both;"></div><br /><br />';
</code>```

and the vaildator:

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

                                                $errors = array();
                                                if (empty($name)) {
                                                    $errors[] = '<span class="error">ERROR: Missing Name </span><br/>';
                                                }
                                                if (empty($phone) || empty($email)) {
                                                    $errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
                                                }
                                                if (!is_numeric($phone)) {
                                                    $errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
                                                }
                                                if (!preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/', strtoupper($email))) {
                                                    $errors[] = '<span class="error">ERROR: Please Insert a valid Email</span><br/>';
                                                }
                                                if ($errors) {
                                                    echo '<p style="font-weight:bold;text-align:center;">There were some errors:</p> ';
                                                    echo '<ul><li>', implode('</li><li>', $errors), '</li></ul><br/>';
                                                } else {
                                                    mail( "email@hotmail.com", "Monthly Specials Email",
                                                        "Name: $name\n".
                                                        "Email: $email\n".
                                                        "Phone Number: $phone\n".
                                                        "Comment: $comment", "From: $email");
                                                    echo'<span id="valid">Message has been sent</span><br/>';
                                                }
}
</code>```

答:
First: you cannot trust '.$_SERVER it can be modified. Be carefull with that!

Second: you could(should?) use a hidden field instead of specifing it in the action?

But if you have an error, it refreshes
  the page and removes any text that was
  inserted before the submit button was
  clicked and you have to re-enter all
  of the information. Anyway to fix
  this?

You could use ajax to fix it(I believe plain old HTML has this side-effect?).

Title: Is there something wrong with my form?

Body:
I have my form working and all of the errors and everything works.
But if you have an error, it refreshes the page and removes any text that was inserted before the submit button was clicked and you have to re-enter all of the information.
Anyway to fix this?

I think it has something to do with not using $_SERVER["PHP_SELF"] in the action of the form.
Instead I have action=""

I am doing this because the page that needs to be refreshed with the same info has a variable in its url (monthly_specials_info.php?date=Dec10) that was put there from the last page.

I tried using

<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">

and it produced the right url. but the text was all removed anyway when form was submitted (with errors).. any ideas?

Form code:

echo '

Interested in this coupon? Email us!

                                            <form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
                                              Name: <input name="name" type="text" />

                                              Email: <input name="email" type="text" />

                                              Phone Number: <input name="phone" type="text" />

                                              Comment:

                                              <textarea name="comment" rows="5" cols="30"></textarea>

                                              <input type="submit" name="submit" value="Submit Email"/>
                                            </form>

';

and the vaildator:

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

                                                $errors = array();
                                                if (empty($name)) {
                                                    $errors[] = 'ERROR: Missing Name
';
                                                }
                                                if (empty($phone) || empty($email)) {
                                                    $errors[] = 'ERROR: You must insert a phone number or email
';
                                                }
                                                if (!is_numeric($phone)) {
                                                    $errors[] = 'ERROR: You must insert a phone number or email
';
                                                }
                                                if (!preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/', strtoupper($email))) {
                                                    $errors[] = 'ERROR: Please Insert a valid Email
';
                                                }
                                                if ($errors) {
                                                    echo '
There were some errors:
 ';
                                                    echo '

', implode('

', $errors), '

';
                                                } else {
                                                    mail( "email@hotmail.com", "Monthly Specials Email",
                                                        "Name: $name\n".
                                                        "Email: $email\n".
                                                        "Phone Number: $phone\n".
                                                        "Comment: $comment", "From: $email");
                                                    echo'Message has been sent
';
                                                }
}


问:
Access the parent object of an object in PHP
This is my test code:

```<code>class Base
{
    public $property;

    public function method() {
        return 456;
    }

    public function setProperty($value) {
        $this->property = $value;
    }
}

class Derived extends Base
{
    public function method() {
        return 789;
    }
}

$derived = new Derived;
$derived->setProperty(123);

$base = getParentInstance($derived);

echo $base->property; // Should print 123
echo $base->method(); // Should print 456
</code>```

Looking around I found a lot of stuff related but nothing direct to the point. I just need to cast an instance to an ancestor class. Is this even possible on PHP?

Up to now I came out with this wrong code that (I think) just instantiate a new Base class:

```<code>function getParentInstance($object)
{
    $reflection = new ReflectionObject($object);
    $parent_class = $reflection->getParentClass();
    return $parent_class->newInstanceWithoutConstructor();
}
</code>```

Another complication is I can only modify Derived... Base is provided by an external framework.

Addendum

Here is the proof what I'm requesting is not absurd. Same code in C++:

```<code>class Base
{
public:
    int property;

    int method() {
        return 456;
    }

    void setProperty(int value) {
        this->property = value;
    }
};

class Derived: public Base
{
public:
    int method() {
        return 789;
    }
};

#include <iostream>
int main()
{
    Derived *derived = new Derived;
    derived->setProperty(123);

    Base *base = (Base *) derived; // Is **this** possible in PHP?

    std::cout << base->property; // It prints 123
    std::cout << base->method(); // It prints 456

    return 0;
}
</code>```

答:
As many mentioned, you shouldn't do it, and technically speaking you can't.

You can simulate the behaviour to get the results you expect as following:

```<code>class Derived extends Base
{
    protected $isProxy = false;

    public function method() {
        return $this->isProxy ? parent::method() : 'def';
    }

    /**
     * not really a parent. The same class, which behave like a parent in this specific case
     */
    public function getParent()
    {
      $this->isProxy = true;
      $base = clone $this;
      $this->isProxy = false;
      return $base;
    }
}

$derived = new Derived;
$derived->setProperty(123);

$base = $derived->getParent();

echo $base->property; // prints 123
echo $base->method(); // prints 456
</code>```

EDIT:

a simplified example of what else you can do:

```<code>function getParentInstance($child) {
  $base = new Base();
  $base->property = $child->property;
  return $base;
}
</code>```

This works with public properties only.
Private/Protected properties should be accessed/assigned using Reflection.

Body:
This is my test code:

class Base
{
    public $property;

    public function method() {
        return 456;
    }

    public function setProperty($value) {
        $this->property = $value;
    }
}

class Derived extends Base
{
    public function method() {
        return 789;
    }
}

$derived = new Derived;
$derived->setProperty(123);

$base = getParentInstance($derived);

echo $base->property; // Should print 123
echo $base->method(); // Should print 456

Looking around I found a lot of stuff related but nothing direct to the point. I just need to cast an instance to an ancestor class. Is this even possible on PHP?

Up to now I came out with this wrong code that (I think) just instantiate a new Base class:

function getParentInstance($object)
{
    $reflection = new ReflectionObject($object);
    $parent_class = $reflection->getParentClass();
    return $parent_class->newInstanceWithoutConstructor();
}

Another complication is I can only modify Derived... Base is provided by an external framework.

Addendum

Here is the proof what I'm requesting is not absurd. Same code in C++:

class Base
{
public:
    int property;

    int method() {
        return 456;
    }

    void setProperty(int value) {
        this->property = value;
    }
};

class Derived: public Base
{
public:
    int method() {
        return 789;
    }
};

#include <iostream>
int main()
{
    Derived *derived = new Derived;
    derived->setProperty(123);

    Base *base = (Base *) derived; // Is **this** possible in PHP?

    std::cout << base->property; // It prints 123
    std::cout << base->method(); // It prints 456

    return 0;
}

Body:
As many mentioned, you shouldn't do it, and technically speaking you can't.

You can simulate the behaviour to get the results you expect as following:

class Derived extends Base
{
    protected $isProxy = false;

    public function method() {
        return $this->isProxy ? parent::method() : 'def';
    }

    /**
     * not really a parent. The same class, which behave like a parent in this specific case
     */
    public function getParent()
    {
      $this->isProxy = true;
      $base = clone $this;
      $this->isProxy = false;
      return $base;
    }
}

$derived = new Derived;
$derived->setProperty(123);

$base = $derived->getParent();

echo $base->property; // prints 123
echo $base->method(); // prints 456

EDIT:

a simplified example of what else you can do:

function getParentInstance($child) {
  $base = new Base();
  $base->property = $child->property;
  return $base;
}

This works with public properties only.
Private/Protected properties should be accessed/assigned using Reflection.


问:
Cakephp 3 save associations dose not work
I try to make a blog with articles and tags but for some reason my tags wont save when creating articles.
I did followed some ideas from official cake blog and from here but no luck for me .. Maybe something I do wrong and I dont see.

Tables for keywords

```<code>CREATE TABLE `keywords` (
  `id` int(11) NOT NULL,
  `article_id` int(11) DEFAULT NULL,
  `tag` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
</code>```

Table model
Keywords:

```<code>class KeywordsTable extends Table
{
......................
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->table('keywords');
        $this->displayField('id');
        $this->primaryKey('id');

        $this->belongsTo('Article', [
            'foreignKey' => 'article_id',
            'joinType' => 'INNER'
        ]);
    }
....................
}
</code>```

Article

```<code>class ArticleTable extends Table
{
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->table('article');
        $this->displayField('id');
        $this->primaryKey('id');

        $this->addBehavior('Timestamp');

        $this->belongsTo('Users', [
            'foreignKey' => 'user_id',
            'joinType' => 'INNER'
        ]);

        $this->hasMany('Keywords', [
            'foreignKey' => 'article_id'
        ]);
    }
......................................
}
</code>```

And here is my controller:

```<code>public function add()
{

        //$this->autoRender = false;
        $article = $this->Article->newEntity();

        if ($this->request->is('post')) {

        $article = $this->Article->patchEntity($article, $this->request->data, ['associated'=>['Keywords']]);
        echo "```";
        print_r($this->Article->save($article));
        die();
        }
}
```

<p>And this is the code I use in my form</p>

```<?= $this->Form->input('article[keywords][]', ['label'=>false, 'class' => 'form-control', 'placeholder' => 'keywords', 'templates' => ['inputContainer' => '{{content}}']]); ?>
```

So if any one could help me out I will appreciate.

答:
in controller you should use associated array, more details-

```<code>$this->Article->save($article,['associated' => ['Keywords']]);
</code>```

and in view file, make input field like this -

```<code><?= $this->Form->input('keywords.0.title', ['label'=>false, 'class' => 'form-control', 'placeholder' => 'keywords', 'templates' => ['inputContainer' => '{{content}}']]); ?>
</code>```

more details

Body:
I try to make a blog with articles and tags but for some reason my tags wont save when creating articles.
I did followed some ideas from official cake blog and from here but no luck for me .. Maybe something I do wrong and I dont see.

Tables for keywords

CREATE TABLE `keywords` (
  `id` int(11) NOT NULL,
  `article_id` int(11) DEFAULT NULL,
  `tag` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Table model
Keywords:

class KeywordsTable extends Table
{
......................
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->table('keywords');
        $this->displayField('id');
        $this->primaryKey('id');

        $this->belongsTo('Article', [
            'foreignKey' => 'article_id',
            'joinType' => 'INNER'
        ]);
    }
....................
}

Article

class ArticleTable extends Table
{
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->table('article');
        $this->displayField('id');
        $this->primaryKey('id');

        $this->addBehavior('Timestamp');

        $this->belongsTo('Users', [
            'foreignKey' => 'user_id',
            'joinType' => 'INNER'
        ]);

        $this->hasMany('Keywords', [
            'foreignKey' => 'article_id'
        ]);
    }
......................................
}

And here is my controller:

public function add()
{

        //$this->autoRender = false;
        $article = $this->Article->newEntity();

        if ($this->request->is('post')) {

        $article = $this->Article->patchEntity($article, $this->request->data, ['associated'=>['Keywords']]);
        echo "
";
        print_r($this->Article->save($article));
        die();
        }
}

And this is the code I use in my form

<?= $this->Form->input('article[keywords][]', ['label'=>false, 'class' => 'form-control', 'placeholder' => 'keywords', 'templates' => ['inputContainer' => '{{content}}']]); ?>

So if any one could help me out I will appreciate.

Body:
in controller you should use associated array, more details-

$this->Article->save($article,['associated' => ['Keywords']]);

and in view file, make input field like this -

<?= $this->Form->input('keywords.0.title', ['label'=>false, 'class' => 'form-control', 'placeholder' => 'keywords', 'templates' => ['inputContainer' => '{{content}}']]); ?>

more details


问:
Java reflection update number
I am new to Java reflection. I am trying to make a program where addition of two numbers gives custom result. Below is the code:

```<code>public class MoreTest {

    public static void main(String[] args) {

        try {
            Field field = Integer.class.getDeclaredField( "value" );
            field.setAccessible( true );
            field.setInt(Integer.valueOf(2),2);

        } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
            e.printStackTrace();
        }

        System.out.println( 2 + 4 ); // should print 8
    }

}
</code>```

What I can do in the above code to print the output I need?

答:
Well you just rewrite 2 to... 2 instead of 4...

try replacing this :

```<code>field.setInt(Integer.valueOf(2), 2);
</code>```

by this

```<code>field.setInt(Integer.valueOf(2), 4);
</code>```

in your code

Then :

```<code>Integer a = 2;
System.out.println( a + 4 ); // will print 8
</code>```

This works because Integer a = 2; triggers autoboxing, the compiler replaces this with Integer a = Integer.valueOf(2);, which is the instance from the cache you doctored earlier to have value 4.

In the expression a + 4 auto-unboxing is used; the compiler replaces that with a.intValue() + 4.

In the expression 2 + 4 (using numeric int literals) the values are both primitives, and no Integerclass instances are used.

Title: Java reflection update number

Body:
I am new to Java reflection. I am trying to make a program where addition of two numbers gives custom result. Below is the code:

public class MoreTest {

    public static void main(String[] args) {

        try {
            Field field = Integer.class.getDeclaredField( "value" );
            field.setAccessible( true );
            field.setInt(Integer.valueOf(2),2);

        } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
            e.printStackTrace();
        }

        System.out.println( 2 + 4 ); // should print 8
    }

}

What I can do in the above code to print the output I need?

Body:
Well you just rewrite 2 to... 2 instead of 4...

try replacing this :

field.setInt(Integer.valueOf(2), 2);

by this

field.setInt(Integer.valueOf(2), 4);

in your code

Then :

Integer a = 2;
System.out.println( a + 4 ); // will print 8

This works because Integer a = 2; triggers autoboxing, the compiler replaces this with Integer a = Integer.valueOf(2);, which is the instance from the cache you doctored earlier to have value 4.

In the expression a + 4 auto-unboxing is used; the compiler replaces that with a.intValue() + 4.

In the expression 2 + 4 (using numeric int literals) the values are both primitives, and no Integerclass instances are used.


问:
Gradle not picking the libraries which are copied dynamically under lib folder
I have a requirement to load the different runtime libraries for a apk execution and unit test cases execution.

I am familiar with compile and testCompile scopes but problem is I don't want to load specific compile scope libraries while running the unit tests.

So I came up with some build.gradle like the below. I could able to copy the required jars/aars under the libs folder but these are not considered for class path.

Any thing wrong with this script?

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "24.0.2"
    defaultConfig {
        applicationId "example.com.myapplication"
        minSdkVersion 21
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

task getDynamicJars(type: Copy) {
        delete fileTree("$projectDir/libs/")
        if(project.gradle.startParameter.taskNames.contains("test")){
            println("Loading Unit test dependencies");
            from "$rootDir/runtimeLibs/test/"
            into "$projectDir/libs/"
            include '**/*.*'

        }else{
            println("Loading Execute dependencies from:"+"$projectDir/runtimeLibs/execution/"+" To:"+"$projectDir/libs/");
            from "$rootDir/runtimeLibs/execution/"
            into "$projectDir/libs/"
            include '**/*.*'
        }

}

dependencies {
    println("Loading dependencies");
    compile fileTree(dir: "libs", include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:24.2.0'
    testCompile 'junit:junit:4.12'
}

project.afterEvaluate {
    preBuild.dependsOn getDynamicJars
}
</code>```

答:
How do you like this solution:</p>

```<code>def libsFolder
// ..
  buildTypes {
    release {
      // ..
      libsFolder = "${releaseLibsDir}"
    }

    debug {
      // ..
      libsFolder = "${debugLibsDir}"
    }
  }
// ..
dependencies {
  compile fileTree(dir: "${libsFolder}", include: ['*.jar'])
}
</code>```

Body:
I have a requirement to load the different runtime libraries for a apk execution and unit test cases execution.

I am familiar with compile and testCompile scopes but problem is I don't want to load specific compile scope libraries while running the unit tests.

So I came up with some build.gradle like the below. I could able to copy the required jars/aars under the libs folder but these are not considered for class path.

Any thing wrong with this script?

apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "24.0.2"
    defaultConfig {
        applicationId "example.com.myapplication"
        minSdkVersion 21
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

task getDynamicJars(type: Copy) {
        delete fileTree("$projectDir/libs/")
        if(project.gradle.startParameter.taskNames.contains("test")){
            println("Loading Unit test dependencies");
            from "$rootDir/runtimeLibs/test/"
            into "$projectDir/libs/"
            include '**/*.*'

        }else{
            println("Loading Execute dependencies from:"+"$projectDir/runtimeLibs/execution/"+" To:"+"$projectDir/libs/");
            from "$rootDir/runtimeLibs/execution/"
            into "$projectDir/libs/"
            include '**/*.*'
        }

}

dependencies {
    println("Loading dependencies");
    compile fileTree(dir: "libs", include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:24.2.0'
    testCompile 'junit:junit:4.12'
}

project.afterEvaluate {
    preBuild.dependsOn getDynamicJars
}

Body:
How do you like this solution:

def libsFolder
// ..
  buildTypes {
    release {
      // ..
      libsFolder = "${releaseLibsDir}"
    }

    debug {
      // ..
      libsFolder = "${debugLibsDir}"
    }
  }
// ..
dependencies {
  compile fileTree(dir: "${libsFolder}", include: ['*.jar'])
}


问:
Why EditorBrowsable doesn't work?
I tried to hide inherited property in intellisense with EditorBrowsable (as said here Hiding user control properties from IntelliSense), when testing in client form though I can still see it why ?

```<code>[
Category("Main"),
Description("Text"),
Obsolete("Don't use this"),
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never)
]
public override String Text
{
    get { return null; }
}
</code>```

答:
I repro.  There is a Note in the MSDN article about this:

In Visual C#, EditorBrowsableAttribute
  does not suppress members from a class
  in the same assembly.

Oddly, I don't see it suppress it either when I put the UserControl in a different assembly in the same solution.
  You may want to ping connect.microsoft.com about this, something isn't right.

Title: Why EditorBrowsable doesn't work?

Body:
I tried to hide inherited property in intellisense with EditorBrowsable (as said here Hiding user control properties from IntelliSense), when testing in client form though I can still see it why ?

[
Category("Main"),
Description("Text"),
Obsolete("Don't use this"),
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never)
]
public override String Text
{
    get { return null; }
}


问:
How do I sort IList C # by date?
I have an IList:

```<code>IList[] info = new IList[2];
info[0] = Date;      //List<DateTime> item
info[1] = something; //List<double> item
</code>```

So, I want sort info by dates in info[0]. Like that:

```<code> Date.Sort((a, b) => a.CompareTo(b));
</code>```

But when i'm trying to do it:

```<code>IEnumerable[] sortedEnum = info.OrderBy(info[0].Sort((a, b) => a.CompareTo(b)));
</code>```

I get:

'System.Collections.IList' does not contain a definition for 'Sort' and no extension method 'Sort' accepting a first argument of type 'System.Collections.IList' could be found (are you missing a using directive or an assembly reference?).

Can someoene help me with this?

答:
Building on Marc's

```<code>List<(DateTime when, double value) list = info[0].Zip(info[1], (d,v)=> (d,v));
</code>```

And as Magnetron points out, if you don't have C#7 yet,

```<code>var list = info[0].Zip(info[1], (d,v)=> Tuple.Create(d,v));
list.Sort((x,y) => x.Item1.compareTo(y.Item1));
</code>```

Title: How do I sort IList C # by date?

Body:
I have an IList:

IList[] info = new IList[2];
info[0] = Date;      //List<DateTime> item
info[1] = something; //List<double> item

So, I want sort info by dates in info[0]. Like that:

 Date.Sort((a, b) => a.CompareTo(b));

But when i'm trying to do it:

IEnumerable[] sortedEnum = info.OrderBy(info[0].Sort((a, b) => a.CompareTo(b)));

I get:

'System.Collections.IList' does not contain a definition for 'Sort' and no extension method 'Sort' accepting a first argument of type 'System.Collections.IList' could be found (are you missing a using directive or an assembly reference?).

Can someoene help me with this?

Body:
Building on Marc's

List<(DateTime when, double value) list = info[0].Zip(info[1], (d,v)=> (d,v));

And as Magnetron points out, if you don't have C#7 yet,

var list = info[0].Zip(info[1], (d,v)=> Tuple.Create(d,v));
list.Sort((x,y) => x.Item1.compareTo(y.Item1));


问:
How to make Property Tax Calculator in Javascript
I am completely new to JavaScript and my employers would like me to create a Property Tax Calculator.

I know the calculation and I know some of the code I'll need (from researching this for 2 days), but I can't put them together to get it to work. I also need an input field on my page, as the client needs to input their own value to make the calculation work. The calculation is:

Fair Market Value X 45% = Portioned Assessment

Portioned Assessed value X 30.915/1000 = Gross Taxes

I know I need my function to look kind of like this:

```<code>function PortionedAssessment() {
    var GrossTax = var FMValue * .45 * .030915;
</code>```

My variables:

```<code>    var PortAssess;
    var GrossTax;
    var FMValue = document.getElementsByName("FMValue").value;
</code>```

And I have part of my form (no styling done yet, I'll do that afterwards):

```<code><form name="PropertyCalc">

    Enter your Fair Market Value: <input type="text" value="FMValue"> X 45% X 0.030915

    <input type="button" onclick="calculate(PortionedAssessment)" name="result"
    value="Calculate" class="calcButton">

    Gross Taxes = ;

</form>
</code>```

I'm not sure how to put the calculation together or how to input the answer into my form. How do you direct a console.log to a div? I know I'm missing a lot, but like I said, this is completely over my head and I don't know who else to ask.

答:
$('#Calculate').click(function() {
  var FMValue = document.getElementById('FMValue').value ? document.getElementById('FMValue').value : '0';
  var num = parseInt(FMValue); //convert to int
  var GrossTax = num * .45 * .030915;

  document.getElementById('result').innerHTML = GrossTax; //return value to id of result
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Enter your Fair Market Value: <input type="text" id="FMValue"> X 45% X 0.030915

<button class="calcButton" id="Calculate">Calculate</button>

<div>
  GrossTax:
  <div id="result"></div>
</div></code>```

Body:
I am completely new to JavaScript and my employers would like me to create a Property Tax Calculator.

I know the calculation and I know some of the code I'll need (from researching this for 2 days), but I can't put them together to get it to work. I also need an input field on my page, as the client needs to input their own value to make the calculation work. The calculation is:

Fair Market Value X 45% = Portioned Assessment

Portioned Assessed value X 30.915/1000 = Gross Taxes

I know I need my function to look kind of like this:

function PortionedAssessment() {
    var GrossTax = var FMValue * .45 * .030915;

My variables:

    var PortAssess;
    var GrossTax;
    var FMValue = document.getElementsByName("FMValue").value;

And I have part of my form (no styling done yet, I'll do that afterwards):

<form name="PropertyCalc">

    Enter your Fair Market Value: <input type="text" value="FMValue"> X 45% X 0.030915

    <input type="button" onclick="calculate(PortionedAssessment)" name="result"
    value="Calculate" class="calcButton">

    Gross Taxes = ;

</form>

I'm not sure how to put the calculation together or how to input the answer into my form. How do you direct a console.log to a div? I know I'm missing a lot, but like I said, this is completely over my head and I don't know who else to ask.

Body:
$('#Calculate').click(function() {
  var FMValue = document.getElementById('FMValue').value ? document.getElementById('FMValue').value : '0';
  var num = parseInt(FMValue); //convert to int
  var GrossTax = num * .45 * .030915;

  document.getElementById('result').innerHTML = GrossTax; //return value to id of result
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Enter your Fair Market Value: <input type="text" id="FMValue"> X 45% X 0.030915

<button class="calcButton" id="Calculate">Calculate</button>

<div>
  GrossTax:
  <div id="result"></div>
</div>


问:
Escaping backslash in .gitconfig
I am attempting to set up a filter into my .gitconfig which replaces a string including backslashes with another string, also including backslashes.

```<code>clean = sed 's|foo|bar|g'
smudge = sed 's|foo|bar|g'
</code>```

This example does work, as long as foo and bar do not include any \.

I am aware, that I should escape \, but I just can't get it to work properly.
Could somebody walk me through the process of getting this to work?

答:
In general, to escape a backslash, double it.  If \x becomes x, then \\ becomes \.  This backslash interpretation "eats" backslashes, but not if they are prefixed by backslash.

That gets it past Git, where the shell eats it (interprets backslash followed by some other character as special), so if this command is fed to a shell, double it again.  Now one backslash in the final result is represented by four in the input.

If the shell passes it to a command like sed that treats backslash specially, double it again.  Now one backslash is eight!

Should that command pass the string on to another command that does backslash interpretation, you would need to double it yet again, and so on.  For this reason, we have other quoting mechanisms in the shell (and in other languages): inside single quotes, backslash is no longer special (no longer eaten) so you can halve the number of backslashes required using single quotes.  (Compare with, e.g., "raw" strings in Python.)  For this particular case, though, eight backslashes is probably not that much worse than careful single-quoting and four backslashes.

Title: Escaping backslash in .gitconfig

Body:
I am attempting to set up a filter into my .gitconfig which replaces a string including backslashes with another string, also including backslashes.

clean = sed 's|foo|bar|g'
smudge = sed 's|foo|bar|g'

This example does work, as long as foo and bar do not include any \.

I am aware, that I should escape \, but I just can't get it to work properly.
Could somebody walk me through the process of getting this to work?


问:
Callback functions in C++
In C++, when and how do you use a callback function?

EDIT:

I would like to see a simple example to write a callback function.

答: Callback functions are part of the C standard, an therefore also part of C++. But if you are working with C++, I would suggest you use the observer pattern instead: http://en.wikipedia.org/wiki/Observer_pattern

Title: Callback functions in C++


问:
List of dates for given day of the week Swift
I need to get the List of dates for the given date of the week.

As an example :
If user select the random date from picker Like 2017-6-7,
I needs to get and display the dates of the week.
[2017-6-4, 2017-6-5, 2017-6-6, 2017-6-7, 2017-6-8, 2017-6-9, 2017-6-10]

I couldn't find any solution on the internet.

Thank you

答:
This is a starting point using the date math skills of Calendar

```<code>var calendar = Calendar.current
calendar.firstWeekday = 1 // adjust first weekday if necessary
var startOfWeek = Date()
var interval : TimeInterval = 0.0
_ = calendar.dateInterval(of:.weekOfYear, start: &startOfWeek, interval: &interval, for: Date())
for i in 0..<7 {
    print(calendar.date(byAdding: .day, value: i, to: startOfWeek)!)
}
</code>```

Body:
This is a starting point using the date math skills of Calendar

var calendar = Calendar.current
calendar.firstWeekday = 1 // adjust first weekday if necessary
var startOfWeek = Date()
var interval : TimeInterval = 0.0
_ = calendar.dateInterval(of:.weekOfYear, start: &startOfWeek, interval: &interval, for: Date())
for i in 0..<7 {
    print(calendar.date(byAdding: .day, value: i, to: startOfWeek)!)
}


问:
HTTPS and CORS with Sony Camera API
I am developing a web application which makes use of the Sony Camera API with an Alpha 6300.

The web-app needs to access the camera and internet at the same time. Therefore, I am using a laptop with two network adapters, one connecting to Wi-Fi and one to the camera access point. I got this to work without the discovery phase, which is not possible from a browser (that's ok, the IP address of the camera is always the same).

However, in order to get it working on the production server (which is secure), I need some ugly hacks, due to the camera endpoints being only available in HTTP (no HTTPS) and with no CORS headers:

I need to use a Chrome extension to bypass CORS

I need to click on 'load unsafe scripts' in Google Chrome

A quick solution would be to pack everything in an Electron app, thus overriding Chrome's (more than legitimate) security concerns. However, this would strongly complicate the deploying and testing process. I would rather go with a web-based solution, if possible.

Anybody knows if there's a way to enforce HTTPS and set Access-Control-Allow-Origin on the Camera server?

答:
You can use a local CORS proxy. That's what I've done for development.

I went the similar route of "Electron" for disabling the same origin policy, only I used PhoneGap because I needed this for a phone.

Title: HTTPS and CORS with Sony Camera API


问:
How to dynamically choose the configurations based on the environment in JAVA?
I have a utility class which has common configurations related to email-sender, the configurations changes based on the environment like Staging and Production. Now how can I dynamically choose the configurations based on the environment?

here is my code,

EmailUtility.java

```<code>package com.housecar.common;

public class EmailUtility {

 //For staging
 public static final String FROM_EMAIL_ID = "xx12@xyz.com";
 public static final String FROM_NAME = "xyz";
 static final String SMTP_USERNAME = "xx12@xyz.com";
 static final String SMTP_PASSWORD = "15sss67$";
 public static final String REPLY_EMAIL_ID = "xx12@xyz.com";
 public static final String MAIL_SMTP_PORT = "587";
 public static final String MAIL_SMTP_SOCKET_FACTORY_PORT = "587";
 public static final String SMTP_HOST = "smtp.gmail.com";
 public static final String MAIL_SMTP_SOCKETFACTORY_CLASS = "javax.net.ssl.SSLSocketFactory";

 //for production

 /*public static final String FROM_EMAIL_ID = "admin@xyz.com";
 public static final String FROM_NAME = "xyz";
 static final String SMTP_USERNAME = "AKYeeeELEQAGAA"; // Replace with
                                                            // your SMTP
                                                            // username.
 static final String SMTP_PASSWORD = "gvwwwwwbgpGm/C/LmUYUK5HosQar7mTSwjl5MFeBRR";
 public static final String REPLY_EMAIL_ID = "admin@xyz.com";
 public static final String MAIL_SMTP_PORT = "587";
 public static final String MAIL_SMTP_SOCKET_FACTORY_PORT = "587";
 public static final String SMTP_HOST = "email-smtp.us-east-1.amazonaws.com";
 public static final String MAIL_SMTP_SOCKETFACTORY_CLASS = "javax.net.ssl.SSLSocketFactory";*/

}
</code>```

In my code I'm manually commenting out the configuration!

答:
I have used both methods :

specifying the active profile(eg. application-{profile}.properties)
This is fine and pretty straight forward. The build process will resolve the environment specific properties file. Files for each env can be maintained in source control. Prod properties file(not accessible to dev/qe) can be secured in source control. The downside is that managing the different properties can get out of sync(aka configuration drift) (eg. a certain property key was added in dev but not in qe)

specifying the custom argument in running the app (eg. -Dapp.home)
You have to add code to customize the loading the of the properties file. Some customization can include handling of encrypted property values. Property key/values can be maintained in Chef (or equivalent tool). See sample code below:

```<code>@Configuration
public class MyExternalConfig {

    @Bean
    public static PropertyPlaceholderConfigurer configurer(){

        //this is an external file path
        String appHomeConfig = System.getProperty("app.home") + File.separatorChar + "config";

        PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
        final Resource extResource = new FileSystemResource( new File( appHomeConfig, "application.properties") );
        ppc.setLocations( new Resource[] { extResource } ); //add other properties file if needed
        ppc.setIgnoreUnresolvablePlaceholders( true );
        return ppc;
    }
}
</code>```

Body:
I have a utility class which has common configurations related to email-sender, the configurations changes based on the environment like Staging and Production. Now how can I dynamically choose the configurations based on the environment?

here is my code,

EmailUtility.java

package com.housecar.common;

public class EmailUtility {

 //For staging
 public static final String FROM_EMAIL_ID = "xx12@xyz.com";
 public static final String FROM_NAME = "xyz";
 static final String SMTP_USERNAME = "xx12@xyz.com";
 static final String SMTP_PASSWORD = "15sss67$";
 public static final String REPLY_EMAIL_ID = "xx12@xyz.com";
 public static final String MAIL_SMTP_PORT = "587";
 public static final String MAIL_SMTP_SOCKET_FACTORY_PORT = "587";
 public static final String SMTP_HOST = "smtp.gmail.com";
 public static final String MAIL_SMTP_SOCKETFACTORY_CLASS = "javax.net.ssl.SSLSocketFactory";

 //for production

 /*public static final String FROM_EMAIL_ID = "admin@xyz.com";
 public static final String FROM_NAME = "xyz";
 static final String SMTP_USERNAME = "AKYeeeELEQAGAA"; // Replace with
                                                            // your SMTP
                                                            // username.
 static final String SMTP_PASSWORD = "gvwwwwwbgpGm/C/LmUYUK5HosQar7mTSwjl5MFeBRR";
 public static final String REPLY_EMAIL_ID = "admin@xyz.com";
 public static final String MAIL_SMTP_PORT = "587";
 public static final String MAIL_SMTP_SOCKET_FACTORY_PORT = "587";
 public static final String SMTP_HOST = "email-smtp.us-east-1.amazonaws.com";
 public static final String MAIL_SMTP_SOCKETFACTORY_CLASS = "javax.net.ssl.SSLSocketFactory";*/

}

In my code I'm manually commenting out the configuration!

Body:
I have used both methods :

specifying the active profile(eg. application-{profile}.properties)
This is fine and pretty straight forward. The build process will resolve the environment specific properties file. Files for each env can be maintained in source control. Prod properties file(not accessible to dev/qe) can be secured in source control. The downside is that managing the different properties can get out of sync(aka configuration drift) (eg. a certain property key was added in dev but not in qe)

specifying the custom argument in running the app (eg. -Dapp.home)
You have to add code to customize the loading the of the properties file. Some customization can include handling of encrypted property values. Property key/values can be maintained in Chef (or equivalent tool). See sample code below:

@Configuration
public class MyExternalConfig {

    @Bean
    public static PropertyPlaceholderConfigurer configurer(){

        //this is an external file path
        String appHomeConfig = System.getProperty("app.home") + File.separatorChar + "config";

        PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
        final Resource extResource = new FileSystemResource( new File( appHomeConfig, "application.properties") );
        ppc.setLocations( new Resource[] { extResource } ); //add other properties file if needed
        ppc.setIgnoreUnresolvablePlaceholders( true );
        return ppc;
    }
}