问:
Recommended word order of names?
From my perspective there can be (at least) two aproaches how to create a name for a variable, function, class etc.

Structured:

```<code>history_clear()
history_save_to_file()
cache_remove_entry()
cache_find()
browser_window_url_trim()
</code>```

Readable for humans:

```<code>clear_history()
save_history_to_file()
remove_entry_from_cache()
find_in_cache()
check_for_updates()
</code>```

What is the preferred word order? Is there any?
I'm quite new to the programming but I'd like to acquire the good coding habits from the beginning. I've briefly read the PEP 8 Style Guide but I didn't find the answer there.

答:
While this question is hard to answer objectively, I think you should go to my favorite python standard library module for this, courtesy of Tim Peters.

```<code>>>> import this
</code>```

The Zen of Python, by Tim Peters

Beautiful is better than ugly. Explicit is better than implicit.
  Simple is better than complex. Complex is better than complicated.
  Flat is better than nested. Sparse is better than dense. Readability
  counts. Special cases aren't special enough to break the rules.
  Although practicality beats purity. Errors should never pass silently.
  Unless explicitly silenced. In the face of ambiguity, refuse the
  temptation to guess. There should be one-- and preferably only one
  --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often
  better than right now. If the implementation is hard to explain,
  it's a bad idea. If the implementation is easy to explain, it may be a
  good idea. Namespaces are one honking great idea -- let's do more of
  those!

I believe Readability counts. is the most relevant here. With little exception, code is to be written and maintained by other humans, not machines. It should be "readable for humans" as you suggested.

Title: Recommended word order of names?

Body:
From my perspective there can be (at least) two aproaches how to create a name for a variable, function, class etc.

Structured:

history_clear()
history_save_to_file()
cache_remove_entry()
cache_find()
browser_window_url_trim()

Readable for humans:

clear_history()
save_history_to_file()
remove_entry_from_cache()
find_in_cache()
check_for_updates()

What is the preferred word order? Is there any?
I'm quite new to the programming but I'd like to acquire the good coding habits from the beginning. I've briefly read the PEP 8 Style Guide but I didn't find the answer there.

Body:
While this question is hard to answer objectively, I think you should go to my favorite python standard library module for this, courtesy of Tim Peters.

>>> import this

The Zen of Python, by Tim Peters

Beautiful is better than ugly. Explicit is better than implicit.
  Simple is better than complex. Complex is better than complicated.
  Flat is better than nested. Sparse is better than dense. Readability
  counts. Special cases aren't special enough to break the rules.
  Although practicality beats purity. Errors should never pass silently.
  Unless explicitly silenced. In the face of ambiguity, refuse the
  temptation to guess. There should be one-- and preferably only one
  --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often
  better than right now. If the implementation is hard to explain,
  it's a bad idea. If the implementation is easy to explain, it may be a
  good idea. Namespaces are one honking great idea -- let's do more of
  those!

I believe Readability counts. is the most relevant here. With little exception, code is to be written and maintained by other humans, not machines. It should be "readable for humans" as you suggested.


来源: stackexchange

问:
Get coordinates from multiple taps and return them in an array for use in another function
I have set up an empty UIView on my app. I would like to be able to tap two points on the view, get the coordinates of the taps, and append them to an array. Then I would like to pass this array to another function for use (to draw a line between them). I know how to access the locations, but I do not know how I can return them to another function for use. Here is what I have so far:

```<code>var coordinates = [CGPoint]()
override func touchesBegan (_ touches: Set <UITouch>, with event: UIEvent?){
let touch = touches.first!
let location= touch.locaition(in:self)
coordinates.append(location)
}
</code>```

I am not able to modify the touchesBegan function so that it can return the array. If I try to, it will no longer be overriding UIKit's touchesBegan function and Xcode will be reading it as my own function. Thanks!

答: You don't need to return them at all I think. Your coordinates array is a property on your class and you should be able to access that anywhere inside your class, or even by your superclass. If it needs to be private or fileprivate, then you can use delegates to pass information backwards/upwards as needed. </p>

ContentLicense: CC BY-SA 3.0

Body:
I have set up an empty UIView on my app. I would like to be able to tap two points on the view, get the coordinates of the taps, and append them to an array. Then I would like to pass this array to another function for use (to draw a line between them). I know how to access the locations, but I do not know how I can return them to another function for use. Here is what I have so far:

var coordinates = [CGPoint]()
override func touchesBegan (_ touches: Set <UITouch>, with event: UIEvent?){
let touch = touches.first!
let location= touch.locaition(in:self)
coordinates.append(location)
}

I am not able to modify the touchesBegan function so that it can return the array. If I try to, it will no longer be overriding UIKit's touchesBegan function and Xcode will be reading it as my own function. Thanks!


问:
How do I write a unit test that verifies a subroutine is called?
```<code>Public Class Class1

Public OutPut As String = ""
Public StoreThis As String = ""

Public Function GiveOutPut(ByVal s As String) As String

    OutPut = s + " OutPut"

    If s = "S" Then
        CallThis()
    End If

    Return OutPut

End Function

Public Sub CallThis()

    ///pretend something useful is going on here

End Sub

End Class
</code>```

Granted this example is pretty weak, but how could I write a test method that to prove that CallThis() gets called everytime that the input parameter s = "S"?

答:
Not sure this is the best approach, but I would set a class-level boolean variable which the second subroutine would set, and then check that variable in the test.  Something like this: </p>

```<code>Public Class Class1

Public OutPut As String = ""
Public StoreThis As String = ""
Public Success as Boolean = False

   Public Function GiveOutPut(ByVal s As String) As String
       OutPut = s + " OutPut"
       If s = "S" Then
         CallThis()
       End If
       Return OutPut
   End Function

   Public Sub CallThis()
     ///pretend something useful is going on here
     Success = True
   End Sub

End Class
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Public Class Class1

Public OutPut As String = ""
Public StoreThis As String = ""

Public Function GiveOutPut(ByVal s As String) As String

    OutPut = s + " OutPut"

    If s = "S" Then
        CallThis()
    End If

    Return OutPut

End Function

Public Sub CallThis()

    ///pretend something useful is going on here

End Sub

End Class

Granted this example is pretty weak, but how could I write a test method that to prove that CallThis() gets called everytime that the input parameter s = "S"?

Body:
Not sure this is the best approach, but I would set a class-level boolean variable which the second subroutine would set, and then check that variable in the test.  Something like this:

Public Class Class1

Public OutPut As String = ""
Public StoreThis As String = ""
Public Success as Boolean = False

   Public Function GiveOutPut(ByVal s As String) As String
       OutPut = s + " OutPut"
       If s = "S" Then
         CallThis()
       End If
       Return OutPut
   End Function

   Public Sub CallThis()
     ///pretend something useful is going on here
     Success = True
   End Sub

End Class


问:
Weird error in multi-line Batch-file printing

I've been working on a project for myself, that produces a grid in batch, that can have specific points accessed and altered for better graphics with batch games and the like.

@echo off
setlocal ENABLEDELAYEDEXPANSION

!x!
:::::::::::
:: ALIAS ::
:::::::::::
:@alias
    set x=exit/b
    goto:@main
    !x!
:::::::::::
:: MAIN  ::
:::::::::::
:@main
call:$Canvas _canvas 16 16 .
set px=%~1
set py=%~2
set _canvas_point[!px!][!py!]=#
!_canvas#draw!

!x!
:::::::::::
::OBJECTS::
:::::::::::
:@objects
!x!
:$Canvas
    set this=%~1
    set /a !this!_width=%~2
    set /a !this!_height=%~3
    set !this!_default_char=%~4
    set !this!#draw=call:#$canvas_proto_draw !this!
    for /L %%i in (1, 1, !%this%_height!) do (
        for /L %%j in (1, 1, !%this%_width!) do (
            set !this!_point[%%j][%%i]=!%this%_default_char!
            set !this!_row[%%i]=!%this%_row[%%i]!!%this%_point[%%j][%%i]!
            )
        )
    !x!
    :#$Canvas_proto_draw
        set this=%~1
        for /L %%i in (1, 1, !%this%_height!) do (
        for /L %%j in (1, 1, !%this%_width!) do (
            set !this!_row[%%i]=!%this%_row[%%i]!!%this%_point[%%j][%%i]!
            )
        )
        for /L %%i in (1, 1, !%this%_height!) do (
            echo !%this%_row[%%i]!
            )
    !x!
```

<p>My problem occurs with the final output: giving it <code>1, 1</code> will result in a point showing up roughly halfway across the top row. I have no idea why this occurs, and need help. I've combed through all of the output with echo turned on and the value <code>_canvas_point[1][1]</code> does get the value of <code>#</code> on the update.</p>

<p>Here is the output:</p>

<pre class="lang-batch-file prettyprint-override"><code>C:\Home>canvas 1 1
................#...............
................................
................................
................................
................................
................................
................................
................................
................................
................................
................................
................................
................................
................................
................................
................................

C:\Home>
</code>```

Here is a pastebin link with the output having @echo on

Quick things:
Yes, this is a feeble attempt at object oriented programming in batch-file
Yes, I know other languages are better for this kind of thing, I just want to do it with batch-file
Yes, I have weird stylistic choices with names and labels and such. It's so I can read it better, seeing as labels are used for both goto locations and function labels.

答:
In :#$Canvas_proto_draw

```<code>:#$Canvas_proto_draw
set this=%~1
for /L %%i in (1, 1, !%this%_height!) do (
 SET "!this!_row[%%i]="
 for /L %%j in (1, 1, !%this%_width!) do (
...
</code>```

You may observe that your displayed data is 32 columns x 16 rows. This is caused by not clearing out each of the rows before appending the values.

Body:
I've been working on a project for myself, that produces a grid in batch, that can have specific points accessed and altered for better graphics with batch games and the like.

@echo off
setlocal ENABLEDELAYEDEXPANSION

!x!
:::::::::::
:: ALIAS ::
:::::::::::
:@alias
    set x=exit/b
    goto:@main
    !x!
:::::::::::
:: MAIN  ::
:::::::::::
:@main
call:$Canvas _canvas 16 16 .
set px=%~1
set py=%~2
set _canvas_point[!px!][!py!]=#
!_canvas#draw!

!x!
:::::::::::
::OBJECTS::
:::::::::::
:@objects
!x!
:$Canvas
    set this=%~1
    set /a !this!_width=%~2
    set /a !this!_height=%~3
    set !this!_default_char=%~4
    set !this!#draw=call:#$canvas_proto_draw !this!
    for /L %%i in (1, 1, !%this%_height!) do (
        for /L %%j in (1, 1, !%this%_width!) do (
            set !this!_point[%%j][%%i]=!%this%_default_char!
            set !this!_row[%%i]=!%this%_row[%%i]!!%this%_point[%%j][%%i]!
            )
        )
    !x!
    :#$Canvas_proto_draw
        set this=%~1
        for /L %%i in (1, 1, !%this%_height!) do (
        for /L %%j in (1, 1, !%this%_width!) do (
            set !this!_row[%%i]=!%this%_row[%%i]!!%this%_point[%%j][%%i]!
            )
        )
        for /L %%i in (1, 1, !%this%_height!) do (
            echo !%this%_row[%%i]!
            )
    !x!

My problem occurs with the final output: giving it 1, 1 will result in a point showing up roughly halfway across the top row. I have no idea why this occurs, and need help. I've combed through all of the output with echo turned on and the value _canvas_point[1][1] does get the value of # on the update.

Here is the output:

C:\Home>canvas 1 1
................#...............
................................
................................
................................
................................
................................
................................
................................
................................
................................
................................
................................
................................
................................
................................
................................

C:\Home>

Here is a pastebin link with the output having @echo on

Quick things:
Yes, this is a feeble attempt at object oriented programming in batch-file
Yes, I know other languages are better for this kind of thing, I just want to do it with batch-file
Yes, I have weird stylistic choices with names and labels and such. It's so I can read it better, seeing as labels are used for both goto locations and function labels.

Body:
In :#$Canvas_proto_draw

:#$Canvas_proto_draw
set this=%~1
for /L %%i in (1, 1, !%this%_height!) do (
 SET "!this!_row[%%i]="
 for /L %%j in (1, 1, !%this%_width!) do (
...

You may observe that your displayed data is 32 columns x 16 rows. This is caused by not clearing out each of the rows before appending the values.


问:
Getting parameters from query string
I am creating a web page using ASP.Net WebAPi, MVC and Knockout.

I have a normal MVC controller that loads the pages when I need them:

```<code> [Authorize]
    public class AdminController : Controller
    {
        public ActionResult Clients()
        {
            return View();
        }

        public ActionResult ClientEdit(int? Id)
        {
            return View();
        }
    }
</code>```

And once the page is loaded, my Knockout model takes care of the loading of the data. So, the 'Clients' controller simply loads a list of all clients. When on that screen, a user can click 'Edit' next to a client, and the page is navigated to the 'ClientEdit' controller, which takes an id.

So, my knockout click event looks like this in my knockout view model:

```<code>self.EditClick = function () {
        if (this.ClientId && typeof this.ClientId !== 'undefined') {
            window.location.href = "/Admin/ClientEdit/" + this.ClientId;
        }
        else
            window.location.href = "/Admin/ClientEdit/";
    }
</code>```

(It handles the 'Create New' button and the edit button, hence the 'if')

Once I redirect, the MVC controller loads the page, and the URL is:

http://localhost:49389/Admin/ClientEdit/1

I then load the knockout model, and would like to make an API call to get the data...

After my page loads, I want to bind the view model to the page. Here's my view model at the moment:

```<code>function AdminClientEditor() {
    var self = this;

    self.Name = ko.observable("");
    self.ContactName = ko.observable("");

ko.applyBindings(new AdminClientEditor(), $("#clienteditor")[0]);
</code>```

So, I will create a $.get method that calls a webAPI method that will return me data based on the id. I just need to get the ID somehow.

But, how do I get the Id (In this case, '1', from the URL?
And, is this the right way to achieve what I am trying to do?

答:
I've come up with this solution which works, but I am unsure if it's the best way. It seems pretty good.

I created a MVC ViewModel class in my application code, called 'GenericParameteModel', which at the moment, has a single parameter, "Id".

I then modified my page loading MVC method:

```<code>public ActionResult ClientEdit(int? Id)
{
     var mv = new GenericParameteModel { Id = Id };
     return View(mv);
}
</code>```

On my View page, I added the model 'GenericParameteModel' to the View.

I created a hidden field, called 'ClientId' on the view.

```<code><input type="hidden" id="clientId" value="@model.Id">
</code>```

Then, within my knockout view model, I check if $("#clientId").val() has a value. If so, I do the $.get call, using that value, and populate my view model.

In doing so, all my initial page loads from MVC will have the ability to you the GenericParameteModel, and it will be a pattern for other pages. As it's a model, I can add new fields as my application requires.

This seems to work well. I'm unsure if this is an acceptable way as I am new to this (MVC to load views and the Knockout/WebApi to get the data after loading). But it seems neat and manageable.

Title: Getting parameters from query string

Body:
I am creating a web page using ASP.Net WebAPi, MVC and Knockout.

I have a normal MVC controller that loads the pages when I need them:

 [Authorize]
    public class AdminController : Controller
    {
        public ActionResult Clients()
        {
            return View();
        }

        public ActionResult ClientEdit(int? Id)
        {
            return View();
        }
    }

And once the page is loaded, my Knockout model takes care of the loading of the data. So, the 'Clients' controller simply loads a list of all clients. When on that screen, a user can click 'Edit' next to a client, and the page is navigated to the 'ClientEdit' controller, which takes an id.

So, my knockout click event looks like this in my knockout view model:

self.EditClick = function () {
        if (this.ClientId && typeof this.ClientId !== 'undefined') {
            window.location.href = "/Admin/ClientEdit/" + this.ClientId;
        }
        else
            window.location.href = "/Admin/ClientEdit/";
    }

(It handles the 'Create New' button and the edit button, hence the 'if')

Once I redirect, the MVC controller loads the page, and the URL is:

http://localhost:49389/Admin/ClientEdit/1

I then load the knockout model, and would like to make an API call to get the data...

After my page loads, I want to bind the view model to the page. Here's my view model at the moment:

function AdminClientEditor() {
    var self = this;

    self.Name = ko.observable("");
    self.ContactName = ko.observable("");

ko.applyBindings(new AdminClientEditor(), $("#clienteditor")[0]);

So, I will create a $.get method that calls a webAPI method that will return me data based on the id. I just need to get the ID somehow.

But, how do I get the Id (In this case, '1', from the URL?
And, is this the right way to achieve what I am trying to do?

Body:
I've come up with this solution which works, but I am unsure if it's the best way. It seems pretty good.

I created a MVC ViewModel class in my application code, called 'GenericParameteModel', which at the moment, has a single parameter, "Id".

I then modified my page loading MVC method:

public ActionResult ClientEdit(int? Id)
{
     var mv = new GenericParameteModel { Id = Id };
     return View(mv);
}

On my View page, I added the model 'GenericParameteModel' to the View.

I created a hidden field, called 'ClientId' on the view.

<input type="hidden" id="clientId" value="@model.Id">

Then, within my knockout view model, I check if $("#clientId").val() has a value. If so, I do the $.get call, using that value, and populate my view model.

In doing so, all my initial page loads from MVC will have the ability to you the GenericParameteModel, and it will be a pattern for other pages. As it's a model, I can add new fields as my application requires.

This seems to work well. I'm unsure if this is an acceptable way as I am new to this (MVC to load views and the Knockout/WebApi to get the data after loading). But it seems neat and manageable.


问:
Securing connection strings and app settings in an Azure App - how to use them locally
In my web app which is hosted as an Azure App Service, I have the following in my web.config for testing:

```<code><connectionStrings>
    <add name="ProductionConnection" providerName="System.Data.SqlClient" connectionString="Data Source=tcp:something.database.windows.net,1433;Initial Catalog=DatabaseName;User Id=admin@sssdddr;Password=Pass@word1;Trusted_Connection=False;Encrypt=True;Connection Timeout=30; MultipleActiveResultSets=True" />
</connectionStrings>
</code>```

I'm trying to follow some basic security best practices here, so I've moved my connection string up to the Application Settings section of my web app:

This particular setting is a bad example because ideally I'd only ever have ProductionConnection stored in Azure and never used locally - but for other connection strings and appSettings used both locally and in production that should should be protected, how should I handle the values when developing locally?

答:
I mean the connection string value / app setting should not be baked
  into the application's bin directory

Connection strings are normally located inside web.config file. web.config will never be inside bin folder; we normally place it inside application's root folder.

I believe you mean storing sensitive information like username and password to access SQL Server. You cannot hide connection string and settings from developers who is debugging the application.

In corporate environment, we (developers) use Windows Authentication to access SQL Server.

Body:
In my web app which is hosted as an Azure App Service, I have the following in my web.config for testing:

<connectionStrings>
    <add name="ProductionConnection" providerName="System.Data.SqlClient" connectionString="Data Source=tcp:something.database.windows.net,1433;Initial Catalog=DatabaseName;User Id=admin@sssdddr;Password=Pass@word1;Trusted_Connection=False;Encrypt=True;Connection Timeout=30; MultipleActiveResultSets=True" />
</connectionStrings>

I'm trying to follow some basic security best practices here, so I've moved my connection string up to the Application Settings section of my web app:

This particular setting is a bad example because ideally I'd only ever have ProductionConnection stored in Azure and never used locally - but for other connection strings and appSettings used both locally and in production that should should be protected, how should I handle the values when developing locally?


问:
Write a char macro to a binary file
I've been working on some code that basically just tries to write a struct to a binary file in the form of a list, which isn't a problem, but I also need to write a macro at the end of every structure, the which is a char (I called it END_CHAR). What I use trying to do was:

```<code>#define END_CHAR 'F'
/*Some irrelevant code here*/
fwrite(&END_CHAR,sizeof(char),1,file_output);
</code>```

I understand that this doesn't work because I'm asking the memory address of a char that isn't stored in any variable. So, what is the proper way to do what I want to do?

答:
In C, 'F' is just a way of writing the number 70 (assuming ASCII), so it's just a number, and you can't take the address of a number, only a variable. #define doesn't change that. So make a variable:

```<code>char endchar = 'F';

fwrite(&endchar, ...
</code>```

Title: Write a char macro to a binary file

Body:
I've been working on some code that basically just tries to write a struct to a binary file in the form of a list, which isn't a problem, but I also need to write a macro at the end of every structure, the which is a char (I called it END_CHAR). What I use trying to do was:

#define END_CHAR 'F'
/*Some irrelevant code here*/
fwrite(&END_CHAR,sizeof(char),1,file_output);

I understand that this doesn't work because I'm asking the memory address of a char that isn't stored in any variable. So, what is the proper way to do what I want to do?

Body:
In C, 'F' is just a way of writing the number 70 (assuming ASCII), so it's just a number, and you can't take the address of a number, only a variable. #define doesn't change that. So make a variable:

char endchar = 'F';

fwrite(&endchar, ...


问:
Java 8 cyclic inference warning
My knowledge about list operations is from scripting languages. So in Java I stopped on something strange in case of finding cookie with particular name.

```<code>List<Cookie> cookies = Arrays.asList(request.getCookies());
        String auth = cookies.stream()
                .filter(c -> c.getName().equals("auth"))
                .map(Cookie::getValue);
</code>```

On the map method IntelliJ is showing me "Cyclic inference".

Java compiler Error:(52, 25) java: incompatible types: no instance(s) of type variable(s) R exist so that java.util.stream.Stream conforms to java.lang.String

答:
In essence, what this rather cryptic error message is saying is "the output of the stream sequence doesn't match what you are assigning it to in the end", ex:

```<code>String s = list.stream().map(s -> s); // this doesn't result in a String...
</code>```

.findFirst().get()
So to debug compilation, remove the assignment (temporarily), or, as the other answer says, add something that makes it return a String by collecting (ex: .collect(Collectors.joining(","))) or (getting like .findFirst().get()), or change the assignment, like Stream<String> stream = list.stream().map(...)

Title: Java 8 cyclic inference warning

Body:
My knowledge about list operations is from scripting languages. So in Java I stopped on something strange in case of finding cookie with particular name.

List<Cookie> cookies = Arrays.asList(request.getCookies());
        String auth = cookies.stream()
                .filter(c -> c.getName().equals("auth"))
                .map(Cookie::getValue);

On the map method IntelliJ is showing me "Cyclic inference".

Java compiler Error:(52, 25) java: incompatible types: no instance(s) of type variable(s) R exist so that java.util.stream.Stream conforms to java.lang.String

Body:
In essence, what this rather cryptic error message is saying is "the output of the stream sequence doesn't match what you are assigning it to in the end", ex:

String s = list.stream().map(s -> s); // this doesn't result in a String...

.findFirst().get()
So to debug compilation, remove the assignment (temporarily), or, as the other answer says, add something that makes it return a String by collecting (ex: .collect(Collectors.joining(","))) or (getting like .findFirst().get()), or change the assignment, like Stream<String> stream = list.stream().map(...)


问:
Deploy multiple applications to a single EC2 instance using AWS Elastic Beanstalk
I am have deployed a .Net website to AWS Elastic Beanstalk.  I want to now deploy another .Net web project (a web service) to the same EC2 instance that was created by AWS Elastic Beanstalk, but the selection to "use and existing environment" in the Environment page of the publishing wizard is greyed out.

Is there a way to do this?

答: Maybe this package can help you running multiple apps/websites on a single Elastic Beanstalk instance (Apache): https://github.com/tscheiki/ElasticDeploy</p>


问:
C++ syntax of 2D vector
Can someone explain below c++ syntax with example ?

```<code>vector <vector <int> > s(n,vector <int> ());
</code>```

especially this part inside the constructor:

```<code>vector <int> ()
</code>```

答:
```<code>#include <vector>
using namespace std;

int main()
{
    int N = 10;
    std::vector< std::vector<int> vector2DA(N, std::vector< int>(N));
    return 0;

}
</code>```

This code create vector2D 10x10, first parameter constructor is size basic vector(vector2DA(size, objectWhichIsContain)), which contain other vector, which have size 10 (std::vector< int>(size)). We have vector2D 10x10.

Title: C++ syntax of 2D vector

Body:
Can someone explain below c++ syntax with example ?

vector <vector <int> > s(n,vector <int> ());

especially this part inside the constructor:

vector <int> ()

Body:
#include <vector>
using namespace std;

int main()
{
    int N = 10;
    std::vector< std::vector<int> vector2DA(N, std::vector< int>(N));
    return 0;

}

This code create vector2D 10x10, first parameter constructor is size basic vector(vector2DA(size, objectWhichIsContain)), which contain other vector, which have size 10 (std::vector< int>(size)). We have vector2D 10x10.


问:
POSTing JsonObject With HttpClient From Web API
I'm trying to POST a JsonObject using HttpClient from Web API. I'm not quite sure how to go about this and can't find much in the way of sample code.

Here's what I have so far:

```<code>var myObject = (dynamic)new JsonObject();
myObject.Data = "some data";
myObject.Data2 = "some more data";

HttpClient httpClient = new HttpClient("myurl");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

HttpResponseMessage response = httpClient.Post("", ???);
</code>```

I think I need to cast my JsonObject as a StreamContent but I'm getting hung up on that step.

答:
If using Newtonsoft.Json:

```<code>using Newtonsoft.Json;
using System.Net.Http;
using System.Text;

public static class Extensions
{
    public static StringContent AsJson(this object o)
        => new StringContent(JsonConvert.SerializeObject(o), Encoding.UTF8, "application/json");
}
</code>```

Example:

```<code>var httpClient = new HttpClient();
var url = "https://www.duolingo.com/2016-04-13/login?fields=";
var data = new { identifier = "username", password = "password" };
var result = await httpClient.PostAsync(url, data.AsJson())
</code>```

Body:
I'm trying to POST a JsonObject using HttpClient from Web API. I'm not quite sure how to go about this and can't find much in the way of sample code.

Here's what I have so far:

var myObject = (dynamic)new JsonObject();
myObject.Data = "some data";
myObject.Data2 = "some more data";

HttpClient httpClient = new HttpClient("myurl");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

HttpResponseMessage response = httpClient.Post("", ???);

I think I need to cast my JsonObject as a StreamContent but I'm getting hung up on that step.

Body:
If using Newtonsoft.Json:

using Newtonsoft.Json;
using System.Net.Http;
using System.Text;

public static class Extensions
{
    public static StringContent AsJson(this object o)
        => new StringContent(JsonConvert.SerializeObject(o), Encoding.UTF8, "application/json");
}

Example:

var httpClient = new HttpClient();
var url = "https://www.duolingo.com/2016-04-13/login?fields=";
var data = new { identifier = "username", password = "password" };
var result = await httpClient.PostAsync(url, data.AsJson())

ContentLicense: CC BY-SA 4.0


答: Tools like NCover or TFS Code Coverage will anaysis what bits of your code have been called.  You could also use debug.writeline for ouput in your test.</p>

Title: How do I write a unit test that verifies a subroutine is called?


问:
AWS ELB and GoDaddy Domain working
I have registered a domain in goDaddy.com and want the traffic to be sent to AWS route53. I have a ELB created I did the following steps

In Route 53, created a HostedZone for my godaddy domain name which in turn gave me a NS record with 4 amazon DNS server names and an SOA record.

Created a new "A" record with just the naked domain and Aliased it with Elastic LB

In godaddy , in DNS management, If I use the ELB DNS name for "A" record, I get an error "Enter a valid IP address" where as if I give the EC2 public IP address for "A" record  , I can see the index page . I have still not given the 4 NS record DNS server names in godaddy.

Questions :

How do I use ELB instead of using EC2 Public IP.

If I use the NS values, does that means the domain is ported to AWS Route53 and I will be charged every month at AWS? If I use the EC2 IP address only in goDaddy ,then I will not be charged by AWS ?

Hope I am clear on my question, if not please let me know I can explain further

答:
First of all AWS ELB does not provide a A record with an IP address and instead it provides a CName. Unfortunately a CName cannot be mapped to a naked domain in DNS configurations and as a work around, AWS provides an Alias for A record.

However using Godaddy DNS, Alias to AWS resources such as ELB is not possible which limits using naked domain mappings to ELB. Therefore you need to delegate DNS management to Route53 hosted zone(Or atleast for the naked domain) having the name server forwarding which cost you around $0.5 per hosted zone month for the first 25 hosted zones.

Since an IP address is available for an EC2, if you directly point an A record in Godaddy, it won't cost for DNS at AWS.

Title: AWS ELB and GoDaddy Domain working


答: I think there isn't really any preferred order out there and you should use the one that makes working easy and more smooth. For example, if you had a lot of variables/classes/functions with the key word "history" and "cache", with repeatable words (like "history_add" and "cache_add") using the structured version would probably be better. But in any other cases, the readable version is going to be good solution.</p>

Title: Recommended word order of names?

Body:
From my perspective there can be (at least) two aproaches how to create a name for a variable, function, class etc.

Structured:

history_clear()
history_save_to_file()
cache_remove_entry()
cache_find()
browser_window_url_trim()

Readable for humans:

clear_history()
save_history_to_file()
remove_entry_from_cache()
find_in_cache()
check_for_updates()

What is the preferred word order? Is there any?
I'm quite new to the programming but I'd like to acquire the good coding habits from the beginning. I've briefly read the PEP 8 Style Guide but I didn't find the answer there.


问:
Splice() function not working as expected
I'm trying to remove a particular element from an array in JavaScript using splice() function but I'm not able to delete the target element.

```<code>    var a = [];
    a.push("cs");
    a.push("ac");
    var curr2 = a.indexOf("ac");
    if(curr2 != -1){
        a = a.splice(curr2,1);
    }
    console.log(a);
</code>```

Expected result : ["cs"] Actual Result : ["ac"]

Can someone explain this behaviour. Thanks!

答: splice returns the item you have deleted in a array. In short, change a = a.splice(curr2,1); to a.splice(curr2,1); and your code will work as expected. Since splice modifies the array you will get an array without the desired element. Where as before you were reassigning a to the return value of splice

Body:
I'm trying to remove a particular element from an array in JavaScript using splice() function but I'm not able to delete the target element.

    var a = [];
    a.push("cs");
    a.push("ac");
    var curr2 = a.indexOf("ac");
    if(curr2 != -1){
        a = a.splice(curr2,1);
    }
    console.log(a);

Expected result : ["cs"] Actual Result : ["ac"]

Can someone explain this behaviour. Thanks!


问:
How to Call Ajax With Same Div Multiple Times
I am calling ajax with below code in my index.php file.

```<code><script type="text/javascript">
    $(document).ready(function(){
        $("#counting").click(function(){
            $.ajax({
                type: 'POST',
                url: 'https://example.com/update.php',
                data: {url: '<?=$url?>'},
                success: function(data) {
                   // alert(data);
                    //$("p").text(data);

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

It's working perfectly, but the issue is
I have div called counting multiple times on the page.
example

```<code> <div id="counting">
<a href="example.com">example</a>
</div>

 <div id="counting">
<a href="example.com">example</a>
</div>
</code>```

Issue - Ajax call only works with first div, not below divs.
How to make it work with all divs with id counting

答:
Id attributes are supposed to be unique. You're only ever going to get the first div called because once the DOM sees that, it's met it's requirement and doesn't search further. I suggest you give you divs unique ids and then use a class that is the same for all of them.

```<code> <div id="div1" class="counting_class">
<a href="example.com">example</a>
</div>

<div id="div2" class="counting_class">
<a href="example.com">example</a>
</div>
</code>```

Then your jQuery would look something like this:

```<code>$(".counting_class").click(function(){
  var id = $(this).attr('id');
//then call ajax based on the individual ID
}
</code>```

Body:
I am calling ajax with below code in my index.php file.

It's working perfectly, but the issue is
I have div called counting multiple times on the page.
example

example

example

Issue - Ajax call only works with first div, not below divs.
How to make it work with all divs with id counting

Body:
Id attributes are supposed to be unique. You're only ever going to get the first div called because once the DOM sees that, it's met it's requirement and doesn't search further. I suggest you give you divs unique ids and then use a class that is the same for all of them.

 <div id="div1" class="counting_class">
<a href="example.com">example</a>
</div>

<div id="div2" class="counting_class">
<a href="example.com">example</a>
</div>

Then your jQuery would look something like this:

$(".counting_class").click(function(){
  var id = $(this).attr('id');
//then call ajax based on the individual ID
}


问:
How do I create a PHP array with 2 variables for each element without using an object?
I'm new to PHP and would require some assistance if possible.

I have the array

```<code>array("Name" => $userName, "Age" => $userAge);
</code>```

This works for one user but lets say I wanted to add multiple users that will all have a Name and Age how would I do that? Instead of passing is $userName would I have to pass it an array of user names and instead of $userage an array of user ages hence making it multidimesional?

Also for my purposes I cannot put the username and userage in an object and then simply add it to the array.

答:
One way is:</p>

```<code>array(
    array("Name" => $userName, "Age" => $userAge),
    array("Name" => $userName1, "Age" => $userAge1),
    array("Name" => $userName2, "Age" => $userAge2)
    ...
);
</code>```

Body:
I'm new to PHP and would require some assistance if possible.

I have the array

array("Name" => $userName, "Age" => $userAge);

This works for one user but lets say I wanted to add multiple users that will all have a Name and Age how would I do that? Instead of passing is $userName would I have to pass it an array of user names and instead of $userage an array of user ages hence making it multidimesional?

Also for my purposes I cannot put the username and userage in an object and then simply add it to the array.

Body:
One way is:

array(
    array("Name" => $userName, "Age" => $userAge),
    array("Name" => $userName1, "Age" => $userAge1),
    array("Name" => $userName2, "Age" => $userAge2)
    ...
);


问:
Spring test context best practice
I'm trying to cover a huge Spring Boot application with integration tests. There are lots of Spring beans within the app. It takes a while to load the Spring context.

So I'm wondering -

Is Spring clever enough to share the same context between multiple integration tests located in different classes? I mean to avoid initializing the heavy-weight context for each test class.

What happens when tests 1,2,4 use TestContextOne and tests 3,5 use TestContextTwo? Does Spring launch them in 1,2,4,3,5 order? Or does Spring keep two contexts in memory?

P.S. In other words, is the common practice to use a single "full" Spring Context for all integration tests, instead of writing separate ones for each test?

答:
Another trick that you can use in your integration tests is to force all the beans in the context to be "lazy". This is really useful when running just one integration test, as you do not have to wait for the entire application context to be loaded and initialized. This can significantly improve the time it takes to run a single test.

You may run into situations where beans are being implicitly created (Example: Spring IntegrationFlow). The flow is never directly injected into anything but your classes may have references to beans that the flow creates. In this case you either need to @Autowire your flow (to insure the implicit beans get created) or you can get creative with a BeanPostProcessor.

I created the following post processor and you just have to add it to your testing spring context.

```<code>public class LazyInitBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

    private Class<?>[] exclusionList;

    public LazyInitBeanFactoryPostProcessor() {
    }

    public LazyInitBeanFactoryPostProcessor(Class<?>[] exclusionList) {
        this.exclusionList = exclusionList;
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

        //Iterate over all bean, mark them as lazy if they are not in the exclusion list.
        for (String beanName : beanFactory.getBeanDefinitionNames()) {
            if (isLazy(beanName, beanFactory)) {
                BeanDefinition definition = beanFactory.getBeanDefinition(beanName);
                definition.setLazyInit(true);
            }
        }
    }

    private boolean isLazy(String beanName, ConfigurableListableBeanFactory beanFactory) {
        if (exclusionList == null || exclusionList.length == 0) {
            return true;
        }
        for (Class<?> clazz : exclusionList) {
            if (beanFactory.isTypeMatch(beanName,clazz)) {
                return false;
            }
        }
        return true;
    }
}
</code>```

And to use it:

```<code>@SpringBootTest(webEnvironment = WebEnvironment.NONE)
public class MyTest {
.
.
.
@TestConfiguration
protected static class TestConfiguration {

    @Bean
    public BeanFactoryPostProcessor lazyBeanPostProcessor() {
        return new LazyInitBeanFactoryPostProcessor();
    }
}
</code>```

Or you extend it with exclusions (In this example, any bean that is assignable to a Spring Integration flow will NOT be marked as lazy:

```<code>@TestConfiguration
protected static class TestConfiguration {
    @Bean
    public BeanFactoryPostProcessor lazyBeanPostProcessor() {
        return new ExtendedTestLazyBeanFactoryPostProcessor();
    }

    static private class ExtendedTestLazyBeanFactoryPostProcessor extends LazyInitBeanFactoryPostProcessor {
        public ServiceTestLazyBeanFactoryPostProcessor() {
            super(new Class<?>[] {IntegrationFlow.class});
        }
    }
</code>```

Title: Spring test context best practice

Body:
Another trick that you can use in your integration tests is to force all the beans in the context to be "lazy". This is really useful when running just one integration test, as you do not have to wait for the entire application context to be loaded and initialized. This can significantly improve the time it takes to run a single test.

You may run into situations where beans are being implicitly created (Example: Spring IntegrationFlow). The flow is never directly injected into anything but your classes may have references to beans that the flow creates. In this case you either need to @Autowire your flow (to insure the implicit beans get created) or you can get creative with a BeanPostProcessor.

I created the following post processor and you just have to add it to your testing spring context.

public class LazyInitBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

    private Class<?>[] exclusionList;

    public LazyInitBeanFactoryPostProcessor() {
    }

    public LazyInitBeanFactoryPostProcessor(Class<?>[] exclusionList) {
        this.exclusionList = exclusionList;
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

        //Iterate over all bean, mark them as lazy if they are not in the exclusion list.
        for (String beanName : beanFactory.getBeanDefinitionNames()) {
            if (isLazy(beanName, beanFactory)) {
                BeanDefinition definition = beanFactory.getBeanDefinition(beanName);
                definition.setLazyInit(true);
            }
        }
    }

    private boolean isLazy(String beanName, ConfigurableListableBeanFactory beanFactory) {
        if (exclusionList == null || exclusionList.length == 0) {
            return true;
        }
        for (Class<?> clazz : exclusionList) {
            if (beanFactory.isTypeMatch(beanName,clazz)) {
                return false;
            }
        }
        return true;
    }
}

And to use it:

@SpringBootTest(webEnvironment = WebEnvironment.NONE)
public class MyTest {
.
.
.
@TestConfiguration
protected static class TestConfiguration {

    @Bean
    public BeanFactoryPostProcessor lazyBeanPostProcessor() {
        return new LazyInitBeanFactoryPostProcessor();
    }
}

Or you extend it with exclusions (In this example, any bean that is assignable to a Spring Integration flow will NOT be marked as lazy:

@TestConfiguration
protected static class TestConfiguration {
    @Bean
    public BeanFactoryPostProcessor lazyBeanPostProcessor() {
        return new ExtendedTestLazyBeanFactoryPostProcessor();
    }

    static private class ExtendedTestLazyBeanFactoryPostProcessor extends LazyInitBeanFactoryPostProcessor {
        public ServiceTestLazyBeanFactoryPostProcessor() {
            super(new Class<?>[] {IntegrationFlow.class});
        }
    }


问:
processBuilder failing to load data on different host?
On host 'A' I start a transaction by inserting values to a table in DB. As soon as I insert, I call processBuilder to refresh host 'B' which in-turn should load the updated values from same DB table to cache. But the values are not getting loaded.

Is there any relation between processBuilder and transaction? Because the transaction is yet to complete on the host from where I am calling processBuilder.

I tried fetching values from DB before calling processBuilder on host 'A' and it is returning the values which was recently inserted (result set returns 10 rows) where as on host 'B' which is calling same select statement return 9 rows.

答:
"as soon as I insert" red flag.

Yes, there is a relationship between the transaction and processBuilder. If the transaction is not committed, then all other sessions will not be able to see the changes. If you're used to programming in a DB app environment where autocommit is enabled and switch to a DB app environment where autocommit is disabled, then you are likely to run across this kind of problem.


问:
Triggering Instance methods by firing the Parent method
What is the best way to fire a method in many children by calling the parent's method?

For example, lets say I have a parent object Foo which has many instances: BarX, BarY, etc.

```<code>Foo = function(){
   x = null;
   y = null;
   move = function(){
      x += 1;
      y += 1;
   };
}

BarX = new Foo();
BarX.x = 50;
BarX.y = 50;

BarY = new Foo();
BarY.x = 200;
BarY.y = 200;
</code>```

Is there any easy way to fire off the move function in all instances? Am I limited to looping through the instances and firing off the function like that or can I somehow fire the function in Foo and have it trickle down and fire off all instances who extend Foo?

答:
No. But you could be more clever about it. Make a static moveAll function on Foo. Examples make things clearer. Here is the fiddle.

```<code>var Foo = function(x, y){
   this.x = x;
   this.y = y;
   this.move = function(){
      x += 1;
      y += 1;
      alert(x + ' ' + ' ' + y);
   };
   Foo.instances.push(this); // add the instance to Foo collection on init
};
Foo.instances = [];
Foo.moveAll = function(){
    for(var i = 0; i < Foo.instances.length; i++)
        Foo.instances[i].move();
}

var a = new Foo(5, 6);
var b = new Foo(3, 4);

Foo.moveAll();
</code>```

Body:
What is the best way to fire a method in many children by calling the parent's method?

For example, lets say I have a parent object Foo which has many instances: BarX, BarY, etc.

Foo = function(){
   x = null;
   y = null;
   move = function(){
      x += 1;
      y += 1;
   };
}

BarX = new Foo();
BarX.x = 50;
BarX.y = 50;

BarY = new Foo();
BarY.x = 200;
BarY.y = 200;

Is there any easy way to fire off the move function in all instances? Am I limited to looping through the instances and firing off the function like that or can I somehow fire the function in Foo and have it trickle down and fire off all instances who extend Foo?

Body:
No. But you could be more clever about it. Make a static moveAll function on Foo. Examples make things clearer. Here is the fiddle.

var Foo = function(x, y){
   this.x = x;
   this.y = y;
   this.move = function(){
      x += 1;
      y += 1;
      alert(x + ' ' + ' ' + y);
   };
   Foo.instances.push(this); // add the instance to Foo collection on init
};
Foo.instances = [];
Foo.moveAll = function(){
    for(var i = 0; i < Foo.instances.length; i++)
        Foo.instances[i].move();
}

var a = new Foo(5, 6);
var b = new Foo(3, 4);

Foo.moveAll();


问:
In-app purchase was successful, however, it did not run my code.Why?
I am new to in-app purchase system. I just watched some tutorials, then implemented in-app purchase. However, when my in-app purchase was successful, it did not run my code. Does it have to run the following code?:</p>

```<code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1001) {
        String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");

        if (resultCode == RESULT_OK) {
            try {
                JSONObject jo = new JSONObject(purchaseData);
                String sku = jo.getString(inappid);
                Toast.makeText(
                        MainActivity.this,
                        "You have bought the " + sku
                                + ". Excellent choice,adventurer!",
                        Toast.LENGTH_LONG).show();
                writeInApp("1");
                playGroundMain.bonus_pop_up(R.drawable.rich_big, "\"VIP Монстр\"");
                playGroundMain.reWriteBonus("1", 6);

            } catch (JSONException e) {
                System.out.println("Failed to parse purchase data.");
                e.printStackTrace();
            }
        }
    }
}
</code>```

答:
I've made a fair few apps with the payment system, you should take a look at this listener

IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener()
    {
        public void onConsumeFinished(Purchase purchase, IabResult result) {

            Log.d(TAG, "Consumption finished. JSON: " + purchase.getOriginalJson() + ", signature: " + purchase.getSignature());

            if (mHelper == null) return;

            if (result.isSuccess())
            {
                    Log.i(TAG, "BOUGHT THE ITEM :-)")
            }
            else
            {
                Log.e(TAG, "Error while consuming: " + result);
            }
            Log.d(TAG, "End consumption flow.");
        }
    };
```

<p>you could add this listener in the consumeAsync function of the IabHelper like so:</p>

<pre class="lang-java prettyprint-override"><code>IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener()
{
        public void onIabPurchaseFinished(IabResult result, Purchase purchase)
        {

            if (purchase.getSku().equals(SKU_21500))
            {
                // bought 21500 credits
                Log.d(TAG, "Purchase is 21500 credits. Starting credits consumption.");
                try
                {
                    mHelper.consumeAsync(purchase, mConsumeFinishedListener);
                }
                catch (IabHelper.IabAsyncInProgressException e)
                {
                    Log.d(TAG, "Error consuming 21500 credits. Another async operation in progress.");
                    return;
                }
            }
        }
}
</code>```

And then you can put the "mPurchaseFinishedListener" in the "launchPurchaseFlow " function as so:

mHelper.launchPurchaseFlow(activity, item, REQUEST_CODE, mPurchaseFinishedListener);
```

REQUEST_CODE being 10001

Hope this helps!

Body:
I am new to in-app purchase system. I just watched some tutorials, then implemented in-app purchase. However, when my in-app purchase was successful, it did not run my code. Does it have to run the following code?:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1001) {
        String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");

        if (resultCode == RESULT_OK) {
            try {
                JSONObject jo = new JSONObject(purchaseData);
                String sku = jo.getString(inappid);
                Toast.makeText(
                        MainActivity.this,
                        "You have bought the " + sku
                                + ". Excellent choice,adventurer!",
                        Toast.LENGTH_LONG).show();
                writeInApp("1");
                playGroundMain.bonus_pop_up(R.drawable.rich_big, "\"VIP Монстр\"");
                playGroundMain.reWriteBonus("1", 6);

            } catch (JSONException e) {
                System.out.println("Failed to parse purchase data.");
                e.printStackTrace();
            }
        }
    }
}

Body:
I've made a fair few apps with the payment system, you should take a look at this listener

IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener()
    {
        public void onConsumeFinished(Purchase purchase, IabResult result) {

            Log.d(TAG, "Consumption finished. JSON: " + purchase.getOriginalJson() + ", signature: " + purchase.getSignature());

            if (mHelper == null) return;

            if (result.isSuccess())
            {
                    Log.i(TAG, "BOUGHT THE ITEM :-)")
            }
            else
            {
                Log.e(TAG, "Error while consuming: " + result);
            }
            Log.d(TAG, "End consumption flow.");
        }
    };

you could add this listener in the consumeAsync function of the IabHelper like so:

IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener()
{
        public void onIabPurchaseFinished(IabResult result, Purchase purchase)
        {

            if (purchase.getSku().equals(SKU_21500))
            {
                // bought 21500 credits
                Log.d(TAG, "Purchase is 21500 credits. Starting credits consumption.");
                try
                {
                    mHelper.consumeAsync(purchase, mConsumeFinishedListener);
                }
                catch (IabHelper.IabAsyncInProgressException e)
                {
                    Log.d(TAG, "Error consuming 21500 credits. Another async operation in progress.");
                    return;
                }
            }
        }
}

And then you can put the "mPurchaseFinishedListener" in the "launchPurchaseFlow " function as so:

mHelper.launchPurchaseFlow(activity, item, REQUEST_CODE, mPurchaseFinishedListener);

REQUEST_CODE being 10001

Hope this helps!


问:
Optionally descend a nested struct
Assuming a class template Optional exists:

```<code>template <class T>
class Optional
{
public:
  ...
  bool isPresent(void) const {...}
  const T& value(void) {...} // throws if !isPresent()
  ...
};
</code>```

Also, some structs with nested Optional fields are defined:

```<code>struct A;
struct B;
struct C;
struct D;

struct A
{
   Optional<B> b1_;
   int i_;
};

struct B
{
   Optional<C> c1_;
   int j_;
};

struct C
{
   Optional<D> d1_;
   int k_;
};

struct D
{
   int l_;
   int m_;
   int n_;
};
</code>```

I'm looking for a programming idiom that provides the following behavior without the ugliness.

```<code>int get_l_OrDefault(const A& a, int def)
{
  if (!a.b_.isPresent()) return def;
  else if (!a.b_.value().c_.isPresent()) return def;
  else if (!a.b_.value().c_.value().d_.isPresent()) return def;
  else return a.b_.value().c_.value().d_.value().l_;
}
</code>```

Given an A a;, can I define something that takes some representation of the path to the non-optional leaf field and a default value?

```<code>getValueOrDefault(a.b.j_, 0);
getValueOrDefault(a.b.c.k_, 0);
... etc
</code>```

答:
You can do something like

```<code>template <typename Class, typename Def, typename M>
Def getValueOrDefault(const Class& c, Def, M m)
{
    return c.*m;
}

template <typename Class, typename Def, typename  M, typename ... Ms>
Def getValueOrDefault(const Class& c, Def def, M m, Ms... ms)
{
    if (c.*m) {
        return getValueOrDefault(*(c.*m), def, ms...);
    } else {
        return def;
    }
}
</code>```

With usage:

```<code>std::cout << getValueOrDefault(a, 0, &A::b, &B::j) << std::endl;
std::cout << getValueOrDefault(a, 0, &A::b, &B::c, &C::k) << std::endl;
</code>```

Demo

Title: Optionally descend a nested struct

Body:
Assuming a class template Optional exists:

template <class T>
class Optional
{
public:
  ...
  bool isPresent(void) const {...}
  const T& value(void) {...} // throws if !isPresent()
  ...
};

Also, some structs with nested Optional fields are defined:

struct A;
struct B;
struct C;
struct D;

struct A
{
   Optional b1_;
   int i_;
};

struct B
{
   Optional<C> c1_;
   int j_;
};

struct C
{
   Optional<D> d1_;
   int k_;
};

struct D
{
   int l_;
   int m_;
   int n_;
};

I'm looking for a programming idiom that provides the following behavior without the ugliness.

int get_l_OrDefault(const A& a, int def)
{
  if (!a.b_.isPresent()) return def;
  else if (!a.b_.value().c_.isPresent()) return def;
  else if (!a.b_.value().c_.value().d_.isPresent()) return def;
  else return a.b_.value().c_.value().d_.value().l_;
}

Given an A a;, can I define something that takes some representation of the path to the non-optional leaf field and a default value?

getValueOrDefault(a.b.j_, 0);
getValueOrDefault(a.b.c.k_, 0);
... etc

Body:
You can do something like

template <typename Class, typename Def, typename M>
Def getValueOrDefault(const Class& c, Def, M m)
{
    return c.*m;
}

template <typename Class, typename Def, typename  M, typename ... Ms>
Def getValueOrDefault(const Class& c, Def def, M m, Ms... ms)
{
    if (c.*m) {
        return getValueOrDefault(*(c.*m), def, ms...);
    } else {
        return def;
    }
}

With usage:

std::cout << getValueOrDefault(a, 0, &A::b, &B::j) << std::endl;
std::cout << getValueOrDefault(a, 0, &A::b, &B::c, &C::k) << std::endl;

Demo


问:
Spring annotation @Autowired inside methods
@Autowired can be used with constructors, setter and class variables.

How can I use the @Autowired annotation inside a method or any other scope.? I tried the following, but it produces compilation errors. For example

```<code>public classs TestSpring {
  public void method(String param){
    @Autowired
    MyCustomObjct obj;

    obj.method(param);
  }
}
</code>```

If this is impossible, is there any other way to achieve ? (I used Spring 4.)

答:
If what you are looking for is IoC in method you can do this:

Helper2.java class

```<code>public class Helper2 {

    @Autowired
    ApplicationContext appCxt;

    public void tryMe() {
        Helper h = (Helper) appCxt.getBean("helper");
        System.out.println("Hello: "+h);
    }
}
</code>```

spring.xml file notice the user of <context:annotation-config />

```<code><beans ...>
    <context:annotation-config />
    <bean id="helper" class="some_spring.Helper" />
    <bean id="helper2" class="some_spring.Helper2" />
</beans>
</code>```

log output

```<code>2017-07-06 01:37:05 DEBUG DefaultListableBeanFactory:249 - Returning cached instance of singleton bean 'helper2'
2017-07-06 01:37:05 DEBUG DefaultListableBeanFactory:249 - Returning cached instance of singleton bean 'helper'
Hello: some_spring.Helper@431e34b2
</code>```

Body:
@Autowired can be used with constructors, setter and class variables.

How can I use the @Autowired annotation inside a method or any other scope.? I tried the following, but it produces compilation errors. For example

public classs TestSpring {
  public void method(String param){
    @Autowired
    MyCustomObjct obj;

    obj.method(param);
  }
}

If this is impossible, is there any other way to achieve ? (I used Spring 4.)

Body:
If what you are looking for is IoC in method you can do this:

Helper2.java class

public class Helper2 {

    @Autowired
    ApplicationContext appCxt;

    public void tryMe() {
        Helper h = (Helper) appCxt.getBean("helper");
        System.out.println("Hello: "+h);
    }
}

spring.xml file notice the user of <context:annotation-config />

<beans ...>
    <context:annotation-config />
    <bean id="helper" class="some_spring.Helper" />
    <bean id="helper2" class="some_spring.Helper2" />
</beans>

log output

2017-07-06 01:37:05 DEBUG DefaultListableBeanFactory:249 - Returning cached instance of singleton bean 'helper2'
2017-07-06 01:37:05 DEBUG DefaultListableBeanFactory:249 - Returning cached instance of singleton bean 'helper'
Hello: some_spring.Helper@431e34b2


问:
EditText added is not a TextInputEditText. Please switch to using that class instead
I'm using an EditText inside a TextInputLayout, but after upgrading the support library to 23.2.0, I get this warning in the logcat, What's the difference between a regular EditText and a TextInputEditText? I can't seem to find any documentation for it.

答:
I had this problem and just deleted this line in my xml file:

```<code>android: fitsSystemWindows = "true"
</code>```

and the error disappeared.

Body:
I had this problem and just deleted this line in my xml file:

android: fitsSystemWindows = "true"

and the error disappeared.


问:
Invalid Argument - Interfaces inherited, as works, implicit casting does not. What gives?
I have a function that has a signature of

```<code>Update(IEnumberable<INotifyPropertyChanging> things)
</code>```

and a class

```<code>doohickey : INotifyPropertyChanging, INotifyPropertyChanging{}
</code>```

When I try to do

```<code>List<doohickey> doohickeys = new List<doohickey>();
Update(doohickeys);
</code>```

An exception gets thrown stating:

```<code>cannot convert from 'System.Collections.Generic.List<doohickey>' to 'System.Collections.Generic.IEnumerable<System.ComponentModel.INotifyPropertyChanging>'
</code>```

What gives?  Doohickey inherits the INotifyPropertyChanging interface and List inherits the IEnumerable interface!  How come simply passing the object and expecting it to get cast down doesn't?

I've included the references to INotifyPropertyChanging to signify that doohickey is actually a linq-to-sql class; in case that bit of context matters.

答:
This won't work because there is no implicit conversion between List<doohickey> and IEnumerable<NotifyPropertyChanging>. You need to call:

```<code>Update(doohickeys.Cast<INotifyPropertyChanging>());
</code>```

The reason behind this is type safety. In C#4, co-/contravariance was added to the language, which generally helps making these type of conversions valid. There are some limitations though, since the type involved needs to be declared co-/contravariant, and it only applies to interfaces and delegates.

The reason why you can't implicitly convert List<T> to List<TBase> is, that it would make this code valid:

```<code>List<T> values = new List<T>();
// add some values...
List<TBase> bases = values;
bases.Add(new TBase());  // Woops. We broke type safety by adding a TBase to a list of T's
</code>```

Now, if you tried to do this when values was of type IEnumerable<T>, it would be valid in C#4. This is because you can only get values out of IEnumerable<T>, so we don't need to worry about lesser types being added. Therefore IEnumerable<T> is covariant, and is declared as:

```<code>IEnumerable<out T>
</code>```

Where out means "covariant". (The keywords is actually the best way to remember which way values may go in a variant type.

Co-/contravariance is a rather large subject, but this article does a good job of explaining the most important parts. And if you want to learn more, Eric Lippert has an 11-part blog post series about the feature. Eric is one of the language designers.

Body:
I have a function that has a signature of

Update(IEnumberable<INotifyPropertyChanging> things)

and a class

doohickey : INotifyPropertyChanging, INotifyPropertyChanging{}

When I try to do

List<doohickey> doohickeys = new List<doohickey>();
Update(doohickeys);

An exception gets thrown stating:

cannot convert from 'System.Collections.Generic.List<doohickey>' to 'System.Collections.Generic.IEnumerable<System.ComponentModel.INotifyPropertyChanging>'

What gives?  Doohickey inherits the INotifyPropertyChanging interface and List inherits the IEnumerable interface!  How come simply passing the object and expecting it to get cast down doesn't?

I've included the references to INotifyPropertyChanging to signify that doohickey is actually a linq-to-sql class; in case that bit of context matters.

Body:
This won't work because there is no implicit conversion between List<doohickey> and IEnumerable<NotifyPropertyChanging>. You need to call:

Update(doohickeys.Cast<INotifyPropertyChanging>());

The reason behind this is type safety. In C#4, co-/contravariance was added to the language, which generally helps making these type of conversions valid. There are some limitations though, since the type involved needs to be declared co-/contravariant, and it only applies to interfaces and delegates.

The reason why you can't implicitly convert List<T> to List<TBase> is, that it would make this code valid:

List<T> values = new List<T>();
// add some values...
List<TBase> bases = values;
bases.Add(new TBase());  // Woops. We broke type safety by adding a TBase to a list of T's

Now, if you tried to do this when values was of type IEnumerable<T>, it would be valid in C#4. This is because you can only get values out of IEnumerable<T>, so we don't need to worry about lesser types being added. Therefore IEnumerable<T> is covariant, and is declared as:

IEnumerable<out T>

Where out means "covariant". (The keywords is actually the best way to remember which way values may go in a variant type.

Co-/contravariance is a rather large subject, but this article does a good job of explaining the most important parts. And if you want to learn more, Eric Lippert has an 11-part blog post series about the feature. Eric is one of the language designers.


问:
Issues with nested forms
I'm trying to create a fully manageable website where the user can fill some skills ('css', 'php', 'ruby', you name it). Next to it, they fill how good they think they are with this, in a percentage.

I intend to display the result in graphs but right now I'm stuck with this nested form, I can't make them show up.

So as I said earlier, you can add your skills in a page named settings, so here is how I linked them together:

skill.rb and setting.rb

```<code>class Skill < ApplicationRecord
  belongs_to :settings, optional: true
end

class Setting < ApplicationRecord
    has_many :skills, dependent: :destroy
      accepts_nested_attributes_for :skills, allow_destroy: true,
      reject_if: proc { |att| att['name'].blank? }
# Other lines...
</code>```

ApplicationHelper.rb

```<code>def link_to_add_row(name, f, association, **args)
    new_object = f.object.send(association).klass.new
    id = new_object.object_id
    fields = f.fields_for(association, new_object, child_index: id) do |builder|
      render(association.to_s.singularize, f: builder)
    end
    link_to name, '#', class: 'add_fields' + args[:class], data: { id: id, fields: fields.gsub('\n', '') }
  end
</code>```

application.js

```<code>$(document).on('turbolinks:load', function() {

    $('form').on('click', '.remove_skill', function(event) {
        $(this).prev('input[type="hidden"]').val('1');
        $(this).closest('div').hide();
        return event.preventDefault();
    });

    $('form').on('click', '.add_fields', function(event) {
       let regexp, time;
       time = new Date().getTime();
       regexp = new RegExp($(this).data('id'), 'g');
       $('.skills').append($(this).data('skills').replace(regexp, time));
       return event.preventDefault();
    });
});
</code>```

views/settings/_form.html.erb

```<code>  <!-- Some other fields -->
  <table>
    <thead>
      <tr>
        <th></th>
        <th>Compétence</th>
        <th>Maîtrise</th>
      </tr>
    </thead>
    <tbody class="fields">
      <%= fields_for :skills do |builder| %>
        <%= render 'skill', f: builder %>
      <% end %>

      <%= link_to_add_row('Ajouter skill', f, :skills, class: 'add_skill') %>

    </tbody>
  </table>
  <!-- Some other fields -->
</code>```

**views/settings/_skill.html.erb

```<code><tr>
  <td>
    <%= f.input_field :_destroy, as: :hidden %>
    <%= link_to 'Delete', '#', class: 'remove_record' %>
  </td>
  <td><%= f.input :name, label: false %></td>
  <td><%= f.input :completed, label: false %></td>
  <td><%= f.input :due, label: false, as: :string %></td>
</tr>
</code>```

I followed this video's instruction, and so far when I click on "add skill", I can see my nested form being rendered in my rails console, but that's all.

I think this is just something I didn't see, but I redid the tutorial twice and each time a bit different but nothing shows when i click on "add skill".

Any help is welcomed!

答:
A few things to look at.  first, this function:

```<code>$('form').on('click', '.add_fields', function(event) {
   let regexp, time;
   time = new Date().getTime();
   regexp = new RegExp($(this).data('id'), 'g');
   $('.skills').append($(this).data('skills').replace(regexp, time));
   return event.preventDefault();
});
</code>```

Is looking for an element with a 'skills' class on it and will append the records there.  I didn't see an element with it above unless I missed it.

Next, try disabling turbolinks, at least when debugging - I have had problems with that before.

Remove the gem 'turbolinks' line from your Gemfile.

Remove the //= require turbolinks from your app/assets/javascripts/application.js.

Remove the two "data-turbolinks-track" => true hash key/value pairs from your app/views/layouts/application.html.erb.

(from blog.steveklabnik.com/posts/2013-06-25-removing-turbolinks-from-rails-4

After that, throw in a wad of

```<code>console.log()
</code>```

statements in to verify expected values are what you expect, elements exist etc at runtime.

Finally, I have a post about something similar here:
Javascript nested forms for has_many relationships
Which might be of use.

Title: Issues with nested forms

Body:
I'm trying to create a fully manageable website where the user can fill some skills ('css', 'php', 'ruby', you name it). Next to it, they fill how good they think they are with this, in a percentage.

I intend to display the result in graphs but right now I'm stuck with this nested form, I can't make them show up.

So as I said earlier, you can add your skills in a page named settings, so here is how I linked them together:

skill.rb and setting.rb

class Skill < ApplicationRecord
  belongs_to :settings, optional: true
end

class Setting < ApplicationRecord
    has_many :skills, dependent: :destroy
      accepts_nested_attributes_for :skills, allow_destroy: true,
      reject_if: proc { |att| att['name'].blank? }
# Other lines...

ApplicationHelper.rb

def link_to_add_row(name, f, association, **args)
    new_object = f.object.send(association).klass.new
    id = new_object.object_id
    fields = f.fields_for(association, new_object, child_index: id) do |builder|
      render(association.to_s.singularize, f: builder)
    end
    link_to name, '#', class: 'add_fields' + args[:class], data: { id: id, fields: fields.gsub('\n', '') }
  end

application.js

$(document).on('turbolinks:load', function() {

    $('form').on('click', '.remove_skill', function(event) {
        $(this).prev('input[type="hidden"]').val('1');
        $(this).closest('div').hide();
        return event.preventDefault();
    });

    $('form').on('click', '.add_fields', function(event) {
       let regexp, time;
       time = new Date().getTime();
       regexp = new RegExp($(this).data('id'), 'g');
       $('.skills').append($(this).data('skills').replace(regexp, time));
       return event.preventDefault();
    });
});

views/settings/_form.html.erb

        Compétence
        Maîtrise

      <%= fields_for :skills do |builder| %>
        <%= render 'skill', f: builder %>
      <% end %>

      <%= link_to_add_row('Ajouter skill', f, :skills, class: 'add_skill') %>

**views/settings/_skill.html.erb

    <%= f.input_field :_destroy, as: :hidden %>
    <%= link_to 'Delete', '#', class: 'remove_record' %>

  <%= f.input :name, label: false %>
  <%= f.input :completed, label: false %>
  <%= f.input :due, label: false, as: :string %>

I followed this video's instruction, and so far when I click on "add skill", I can see my nested form being rendered in my rails console, but that's all.

I think this is just something I didn't see, but I redid the tutorial twice and each time a bit different but nothing shows when i click on "add skill".

Any help is welcomed!

Body:
A few things to look at.  first, this function:

$('form').on('click', '.add_fields', function(event) {
   let regexp, time;
   time = new Date().getTime();
   regexp = new RegExp($(this).data('id'), 'g');
   $('.skills').append($(this).data('skills').replace(regexp, time));
   return event.preventDefault();
});

Is looking for an element with a 'skills' class on it and will append the records there.  I didn't see an element with it above unless I missed it.

Next, try disabling turbolinks, at least when debugging - I have had problems with that before.

Remove the gem 'turbolinks' line from your Gemfile.

Remove the //= require turbolinks from your app/assets/javascripts/application.js.

Remove the two "data-turbolinks-track" => true hash key/value pairs from your app/views/layouts/application.html.erb.

(from blog.steveklabnik.com/posts/2013-06-25-removing-turbolinks-from-rails-4

After that, throw in a wad of

console.log()

statements in to verify expected values are what you expect, elements exist etc at runtime.

Finally, I have a post about something similar here:
Javascript nested forms for has_many relationships
Which might be of use.


问:
Access private members of a class instantiated using interface
I have a class derived from an interface and a friend class of the derived class. I want to access the members of derived class which is instantiated as interface. It looks like this:

Interface:

```<code>class AInterface
{
public:
   virtual ~AInterface() = default;
   virtual void set(int a) = 0;
};
</code>```

Derived class A with friend class B:

```<code>class B;
class A : public AInterface
{
public:
   ~A() override {}
   void set(int a) override
   {
      mem = a;
   }
private:
   friend class B;

   int mem = 0;
};
</code>```

class B:

```<code>class B
{
public:
   B()
   {
     a = new A();
     a->set(3);
   }

   int get_a()
   {
      // Access mem since it's a friend class
      return a->mem;
   }

private:
    AInterface *a;
}
</code>```

main:

```<code>int main()
{
    B *b = new B();
    std::cout << b->get_a() << std::endl;
    return 0;
}
</code>```

The program does not compile saying AInterface has no member named 'mem'.
Do I need getter functions in the interface and implement it in A to achieve this or is there any other way to do it?

答:
In your class B.

```<code>class B
{
  //...
   int get_a()
   {
      return a->mem;   // but a is a AInterface*  !!!
   }

private:
    AInterface *a;     // That's not an A*, but an AInterface*
};
</code>```

You have 2 options.

use dynamic_cast<>

```<code> int B::get_a()
 {
     A* p = dynamic_cast<A*>(a);
     if (p)
       return p->mem;
     // a is not an A*, it's another AInterface*-type object !!!
                                   // What should you do?
     throw something_or_other();   // throw?
     return -1;                    // return an error code?
   }
   // or maybe add..  so you can check for errors before calling get_a()
   A* B::get_A_ptr() const
   {
      return dynamic_cast<A*>(a);
   }
</code>```

dynamic_cast works fine, but can slow down your app if you need to make frequent reads of a->mem.

Store a in an A*, which is probably what you meant to do from the start...

```<code>class B
{
  // ...
private:
  A* a;    // now a->A::mem is visible.
};
</code>```

Since you explicitly call new A in B's constructor, I think option 2 is better for your case.

Body:
I have a class derived from an interface and a friend class of the derived class. I want to access the members of derived class which is instantiated as interface. It looks like this:

Interface:

class AInterface
{
public:
   virtual ~AInterface() = default;
   virtual void set(int a) = 0;
};

Derived class A with friend class B:

class B;
class A : public AInterface
{
public:
   ~A() override {}
   void set(int a) override
   {
      mem = a;
   }
private:
   friend class B;

   int mem = 0;
};

class B:

class B
{
public:
   B()
   {
     a = new A();
     a->set(3);
   }

   int get_a()
   {
      // Access mem since it's a friend class
      return a->mem;
   }

private:
    AInterface *a;
}

main:

int main()
{
    B *b = new B();
    std::cout <get_a() << std::endl;
    return 0;
}

The program does not compile saying AInterface has no member named 'mem'.
Do I need getter functions in the interface and implement it in A to achieve this or is there any other way to do it?

Body:
In your class B.

class B
{
  //...
   int get_a()
   {
      return a->mem;   // but a is a AInterface*  !!!
   }

private:
    AInterface *a;     // That's not an A*, but an AInterface*
};

You have 2 options.

use dynamic_cast<>

 int B::get_a()
 {
     A* p = dynamic_cast<A*>(a);
     if (p)
       return p->mem;
     // a is not an A*, it's another AInterface*-type object !!!
                                   // What should you do?
     throw something_or_other();   // throw?
     return -1;                    // return an error code?
   }
   // or maybe add..  so you can check for errors before calling get_a()
   A* B::get_A_ptr() const
   {
      return dynamic_cast<A*>(a);
   }

dynamic_cast works fine, but can slow down your app if you need to make frequent reads of a->mem.

Store a in an A*, which is probably what you meant to do from the start...

class B
{
  // ...
private:
  A* a;    // now a->A::mem is visible.
};

Since you explicitly call new A in B's constructor, I think option 2 is better for your case.


问:
Design time slider
I wish to add this design as a time slider in my dashboard.

Has anyone ever designed this using React, HTML? Any help is appreciated.

答:
If those circles, lines are based on your returned json data, it is quite straightforward with React / Redux. You can follow the steps:

You need to add event listeners on your timeline either click or mouseover

Define the state variable mapData in the constructor

trigger the event and retrieve different data via http request

make sure you call setState() with the new data and bind them into your state variables

Bind the state variable into the render() elements and you will see the change.

Hopefully it can help you out.

Title: Design time slider


问:
Cannot 'GET' mLab Data b/c of CORS
I can't execute the 'GET' request with the getTasks() function.

```<code>$(document).ready(function(){
    getTasks();
});

const apiKey = 'xxxxxxx';

function getTasks(){
    $.ajax({
        type: 'GET',
        url: 'https://api.mlab.com/api/1/databases/taskmanager/collections/tasks?apiKey='+apiKey,
        contentType: 'application/json',
        xhrFields: {
            withCredentials: true
        },
        success: function(data){
            console.log(data);
        },
        error: function(){
            console.log('FAIL')
        }
    })
}
</code>```

The error that I get is:

api.mlab.com/api/1/databases/taskmanager/collections/tasks?apiKey=xxxxxxx
  Failed to load resource: the server responded with a status of 400
  (Bad Request)

Response to preflight request doesn't pass access control check: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'null' is therefore not allowed access. The response
  had HTTP status code 400.

I understand that Google-Chrome on Windows is CORS enabled, and will not (by default) allow communication with a different domain.  I'm not sure what a preflight request is. Regardless, I tried to implement what I saw from Using CORS - HTML5 Rocks (from the CORS from jQuery section), but to no avail.

答:
CORS is there to protect you. If you want some more info on it, wikipedia has a good entry on it.

It appears the issue here is that you're trying to access your mongodb hosted by mlab directly from your web app. As you can see in your code, you're providing credentials/api keys to make that request.

My guess is that mlab's intent of not allowing CORS is to prevent you from doing this. You should never put your private API keys in html to be hosted on a web page, as it's easily accessible by reading source code. Then someone would have direct access to your mongodb.

Instead, you should create a server-side application (node, or... ** Whatever **) that exposes an api you control on the same domain (or a domain you give permission to via CORS).

As far as the "preflight" request, if you look in your chrome debugging tools, you should see an additional request go out with the "OPTIONS" method. This is the request that chrome (and most other http clients) send out first to a server hosted on a different domain. it's looking for the Access-Control-Allow-Origin header to find out whether it's allowed to make the request. Pretty interesting stuff if you ever have some time to dig into it.

Title: Cannot 'GET' mLab Data b/c of CORS

Body:
I can't execute the 'GET' request with the getTasks() function.

$(document).ready(function(){
    getTasks();
});

const apiKey = 'xxxxxxx';

function getTasks(){
    $.ajax({
        type: 'GET',
        url: 'https://api.mlab.com/api/1/databases/taskmanager/collections/tasks?apiKey='+apiKey,
        contentType: 'application/json',
        xhrFields: {
            withCredentials: true
        },
        success: function(data){
            console.log(data);
        },
        error: function(){
            console.log('FAIL')
        }
    })
}

The error that I get is:

api.mlab.com/api/1/databases/taskmanager/collections/tasks?apiKey=xxxxxxx
  Failed to load resource: the server responded with a status of 400
  (Bad Request)

Response to preflight request doesn't pass access control check: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'null' is therefore not allowed access. The response
  had HTTP status code 400.

I understand that Google-Chrome on Windows is CORS enabled, and will not (by default) allow communication with a different domain.  I'm not sure what a preflight request is. Regardless, I tried to implement what I saw from Using CORS - HTML5 Rocks (from the CORS from jQuery section), but to no avail.


问:
Windows server 2016 datacenter vpn installation fails
I have a VPS with Windows Server 2016 Datacenter, which I access through Remote Desktop. I would like to access it through VPN, so I tried to repeat the working configuration I have in another VPS with Windows Server 2008 Standard.

Both servers have a single Network Interface with a public address and a second internal address (10.1.0.1/255.255.255.248). As I said, VPN works perfectly on 2008.

The procedure I followed is described perfectly with screenshots in an article by Thomas Mauer
http://www.thomasmaurer.ch/2016/10/how-to-install-vpn-on-windows-server-2016/

So, briefly, I added the Remote Access role with the Remote Access and Routing features. The role and features get installed without any problem and then I am directed to a wizard, though which I try to initialize the VPN-only feature with a custom configuration. When I finally get into the "old" Routing and Remote Access Management console and try to right-click on the server node to "Configure and Enable Routing and Remote Access" this procedure never ends. A rotating clock icon stays there forever, so I have to kill the management console from the task manager.

When I reopen the management console, either with or without restarting the server, the server looks like running. Then I right-click on the server and select "Properties" in order to define the tunneling protocol for VPN as well as the internal address range that will be provided to the connected clients. The problem here is that this properties popup never gets saved. The "Apply" button does nothing, the "OK" button does not close the form and only the "Cancel" button closes the form without changing anything.

Has anybody seen this behaviour? Am I missing something?

Best regards,
Alex

答:
I don't know why, but for this service to work the user "Network Service" needs to have "Logon as Service" permission, other services do not seam to require that...
You can grant this permission either by using secpol.msc or by just switching the service to run as e. g. "Local System" and back to "Network Service" (empty password fields).</p>


答:
Typecast the variables $userName and $userAge to array -

```<code>$userName = (array)$userName;
$userAge = (array)$userAge;
</code>```

Iterate over them for further processing. It would then make no difference if the size of array was one or many.

Title: How do I create a PHP array with 2 variables for each element without using an object?

Body:
I'm new to PHP and would require some assistance if possible.

I have the array

array("Name" => $userName, "Age" => $userAge);

This works for one user but lets say I wanted to add multiple users that will all have a Name and Age how would I do that? Instead of passing is $userName would I have to pass it an array of user names and instead of $userage an array of user ages hence making it multidimesional?

Also for my purposes I cannot put the username and userage in an object and then simply add it to the array.

Body:
Typecast the variables $userName and $userAge to array -

$userName = (array)$userName;
$userAge = (array)$userAge;

Iterate over them for further processing. It would then make no difference if the size of array was one or many.


问:
Pull button to the right of the panel header in primeng panel widget
I have a prime ng button on my panel header. I would like to pull it to the right of the panel header. Please can someone tell me

```<code>  <p-header>
    <h4>Data View</h4>
    <button pButton type="button" [style]="{'float':'right'}" label="New Data" icon="fa-plus" (click)="createData()" class="ui-button-danger"></button>
  </p-header>
</code>```

Also seems like button doesn't have a style class, is there a way to specify a css class to a primeng button widget?

答:
You could use plain HTML/CSS type styling.

So instead of doing [style]="..." you could do regular CSS.

```<code><button pButton type="button" style="float: right;" ....</button>
</code>```

Or if you don't want inline styling, you could do something like

```<code>.my-button {
    float: right;
    ....
}
</code>```

You have to remember that although PrimeNG does a lot of the work for you, it's just javascript/typescript and HTML/CSS under the hood. You can still do basic CSS styling on them. I've definitely had to do that to trim down buttons because they use too much screen space IMO.

Body:
I have a prime ng button on my panel header. I would like to pull it to the right of the panel header. Please can someone tell me

Data View

    <button pButton type="button" [style]="{'float':'right'}" label="New Data" icon="fa-plus" (click)="createData()" class="ui-button-danger"></button>

Also seems like button doesn't have a style class, is there a way to specify a css class to a primeng button widget?

Body:
You could use plain HTML/CSS type styling.

So instead of doing [style]="..." you could do regular CSS.

<button pButton type="button" style="float: right;" ....</button>

Or if you don't want inline styling, you could do something like

.my-button {
    float: right;
    ....
}

You have to remember that although PrimeNG does a lot of the work for you, it's just javascript/typescript and HTML/CSS under the hood. You can still do basic CSS styling on them. I've definitely had to do that to trim down buttons because they use too much screen space IMO.


问:
How to figure out the type parameter for nested type parameter
With the following code,new Box(10),  new Box("20") works well for me. But for the new Box(Seq(20)), new Box(Seq("20"))),
I would like to figure out the type of type parameter for the Seq, so that I could print Seq[Int], Seq[String]

```<code>      @Test
      def testClassTag(): Unit = {
        class Box[T:ClassTag](val data: T) {
          def printTypeParameter() = {
            val tag = implicitly[ClassTag[T]].runtimeClass
            tag match {
              case _ if tag == classOf[Int] => println("Int")
              case _ if tag == classOf[String] => println("String")
              case _ if tag == classOf[Seq[_]] => println( "Seq")
            }
          }
        }
        val boxes = Seq(new Box(10),  new Box("20"), new Box(Seq(20)), new Box(Seq("20")))
        boxes.foreach(_.printTypeParameter())

  }
</code>```

答:
The new proper way to do it is using TypeTag instead of ClassTag:

```<code>def foo[T : TypeTag](data: T) = typeOf[T] match {
  case t if t =:= typeOf[Int] => println("Int")
  case t if t =:= typeOf[String] => println("String")
  case t if t <:< typeOf[Seq[String]] => println("Seq[String]")
  // etc
}
</code>```

(If you just want to print it out, you can as well do  this:

```<code>def foo[T : TypeTag](data: T) = println(typeOf[T])`
</code>```

it does the same thing, but handles all types, not just the ones you could think of.

Body:
With the following code,new Box(10),  new Box("20") works well for me. But for the new Box(Seq(20)), new Box(Seq("20"))),
I would like to figure out the type of type parameter for the Seq, so that I could print Seq[Int], Seq[String]

      @Test
      def testClassTag(): Unit = {
        class Box[T:ClassTag](val data: T) {
          def printTypeParameter() = {
            val tag = implicitly[ClassTag[T]].runtimeClass
            tag match {
              case _ if tag == classOf[Int] => println("Int")
              case _ if tag == classOf[String] => println("String")
              case _ if tag == classOf[Seq[_]] => println( "Seq")
            }
          }
        }
        val boxes = Seq(new Box(10),  new Box("20"), new Box(Seq(20)), new Box(Seq("20")))
        boxes.foreach(_.printTypeParameter())

  }

Body:
The new proper way to do it is using TypeTag instead of ClassTag:

def foo[T : TypeTag](data: T) = typeOf[T] match {
  case t if t =:= typeOf[Int] => println("Int")
  case t if t =:= typeOf[String] => println("String")
  case t if t <:< typeOf[Seq[String]] => println("Seq[String]")
  // etc
}

(If you just want to print it out, you can as well do  this:

def foo[T : TypeTag](data: T) = println(typeOf[T])`

it does the same thing, but handles all types, not just the ones you could think of.


问:
Find common elements in two unsorted array
I try to find a solution to this problem:
I have two arrays A and B of integers (A and B can have different dimensions). I have to find the common elements in these two arrays. I have another condition: the maximum distance between the common elements is k.
So, this is my solution. I think is correct:

```<code>for (int i = 0; i<A.length; i++){
    for (int j=jlimit; (j<B.length) && (j <= ks); j++){
        if(A[i]==B[j]){
            System.out.println(B[j]);
            jlimit = j;
            ks = j+k;
        }//end if
    }
}
</code>```

Is there a way to make a better solution? Any suggestions? Thanks in advance!

答:
Solution using Java 8

```<code>static <T> Collection<T> intersection(Collection<T> c1, Collection<T> c2) {
    if (c1.size() < c2.size())
        return intersection(c2, c1);
    Set<T> c2set = new HashSet<>(c2);
    return c1.stream().filter(c2set::contains).distinct().collect(Collectors.toSet());
}
</code>```

Use Arrays::asList and boxed values of primitives:

```<code>Integer[] a =...
Collection<Integer> res = intersection(Arrays.asList(a),Arrays.asList(b));
</code>```

Body:
I try to find a solution to this problem:
I have two arrays A and B of integers (A and B can have different dimensions). I have to find the common elements in these two arrays. I have another condition: the maximum distance between the common elements is k.
So, this is my solution. I think is correct:

for (int i = 0; i<A.length; i++){
    for (int j=jlimit; (j<B.length) && (j <= ks); j++){
        if(A[i]==B[j]){
            System.out.println(B[j]);
            jlimit = j;
            ks = j+k;
        }//end if
    }
}

Is there a way to make a better solution? Any suggestions? Thanks in advance!

Body:
Solution using Java 8

static <T> Collection<T> intersection(Collection<T> c1, Collection<T> c2) {
    if (c1.size() < c2.size())
        return intersection(c2, c1);
    Set<T> c2set = new HashSet<>(c2);
    return c1.stream().filter(c2set::contains).distinct().collect(Collectors.toSet());
}

Use Arrays::asList and boxed values of primitives:

Integer[] a =...
Collection<Integer> res = intersection(Arrays.asList(a),Arrays.asList(b));


问:
Syntax highlighting of C function calls in emacs
I use a custom syntax highlighting theme for C in emacs, but I'm missing the possibility of highlighting function calls. For example:

```<code>int func(int foo)
{
    return foo;
}

void main()
{
    int bar = func(3);
}
</code>```

Is there any way to highlight the call to "func" in this example?
It doesn't matter if macros are highlighted too. Keywords like if, switch or sizeof should not match.

Thanks!

答:
The order of entries in the keyword list is significant. So if you put your entries after the ones that highlight keywords and function declarations, these won't be matched.

```<code>(font-lock-add-keywords 'c-mode
  '(("\\(\\w+\\)\\s-*\("
    (1 rumpsteak-font-lock-function-call-face)))
  t)
</code>```

Alternatively, you can use a function instead of a regexp as the MATCHER. Overkill for your question if you've stated your requirements exactly, but useful in harder cases. Untested (typed directly in the browser, in fact, so I don't even guarantee balanced parentheses).

```<code>(defun rumpsteak-match-function-call (&optional limit)
  (while (and (search-forward-regexp "\\(\\w+\\)\\s-*\(" limit 'no-error)
              (not (save-match-data
                     (string-match c-keywords-regexp (match-string 1))))
              (not (save-excursion
                     (backward-char)
                     (forward-sexp)
                     (c-skip-whitespace-forward)
                     (or (eobp) (= ?\{ (char-after (point)))))))))
(font-lock-add-keywords 'c-mode
  '((rumpsteak-match-function-call
    (1 rumpsteak-font-lock-function-call-face))))
</code>```

Body:
I use a custom syntax highlighting theme for C in emacs, but I'm missing the possibility of highlighting function calls. For example:

int func(int foo)
{
    return foo;
}

void main()
{
    int bar = func(3);
}

Is there any way to highlight the call to "func" in this example?
It doesn't matter if macros are highlighted too. Keywords like if, switch or sizeof should not match.

Thanks!

Body:
The order of entries in the keyword list is significant. So if you put your entries after the ones that highlight keywords and function declarations, these won't be matched.

(font-lock-add-keywords 'c-mode
  '(("\\(\\w+\\)\\s-*\("
    (1 rumpsteak-font-lock-function-call-face)))
  t)

Alternatively, you can use a function instead of a regexp as the MATCHER. Overkill for your question if you've stated your requirements exactly, but useful in harder cases. Untested (typed directly in the browser, in fact, so I don't even guarantee balanced parentheses).

(defun rumpsteak-match-function-call (&optional limit)
  (while (and (search-forward-regexp "\\(\\w+\\)\\s-*\(" limit 'no-error)
              (not (save-match-data
                     (string-match c-keywords-regexp (match-string 1))))
              (not (save-excursion
                     (backward-char)
                     (forward-sexp)
                     (c-skip-whitespace-forward)
                     (or (eobp) (= ?\{ (char-after (point)))))))))
(font-lock-add-keywords 'c-mode
  '((rumpsteak-match-function-call
    (1 rumpsteak-font-lock-function-call-face))))