问:
Twig Dynamic Variable Assignment
I am trying to dynamically assign variables in Twig inside a loop. For example, this is the JSON being passed into the template:

```<code>[{
   "name": "firstName",
   "value": "Adam",
 },
 {
   "name": "Lastname",
   "value": "Human",
 }]
</code>```

It's worth noting, I do not have the ability to modify this JSON formatting, as it's coming from a third party, so I need to solve this problem on the template side.

I want to loop through this json and create variables for each object, like so:

```<code>{% for item in json %}
    {% set {{item.name}} = item.value %}
{% endfor %}
</code>```

The challenge is Twig is assumes I'm assigning a value to a literal, when I want to assign the value to a evaluated variable name. This way I can just reference each item in the array like {{firstName}} and get back "Adam" in the template.

I've tried a number of different ways to force Twig to dynamically create a variable array, such as:

{% set (item.name) = item.value %}

and

```<code>{% set options = {} %}
{% for item in json %}
    {% set options[item.name] = item.value %}
{% endfor %}
</code>```

With no luck.

Any ideas on dynamically creating variables? This is straight forward in most programming languages, so I'm struggling to understand how this is handled in a template engine like Twig.

答:
If the values are actually iterateable and not a single json string you can put them in an array like:

```<code>{% set values = [] %}
{% for item in json %}
    {% set values = values|merge({(item.name): item.value}) %}
{% endfor %}
</code>```

Then you can use values.firstName.

If it is a json string and thus can't be looped through like this. You need to write a basic string parser in twig. I've written something similar like that last week in this answer however. Its a very bad idea in general as it fails on so many occasions.

Title: Twig Dynamic Variable Assignment

Body:
I am trying to dynamically assign variables in Twig inside a loop. For example, this is the JSON being passed into the template:

[{
   "name": "firstName",
   "value": "Adam",
 },
 {
   "name": "Lastname",
   "value": "Human",
 }]

It's worth noting, I do not have the ability to modify this JSON formatting, as it's coming from a third party, so I need to solve this problem on the template side.

I want to loop through this json and create variables for each object, like so:

{% for item in json %}
    {% set {{item.name}} = item.value %}
{% endfor %}

The challenge is Twig is assumes I'm assigning a value to a literal, when I want to assign the value to a evaluated variable name. This way I can just reference each item in the array like {{firstName}} and get back "Adam" in the template.

I've tried a number of different ways to force Twig to dynamically create a variable array, such as:

{% set (item.name) = item.value %}

and

{% set options = {} %}
{% for item in json %}
    {% set options[item.name] = item.value %}
{% endfor %}

With no luck.

Any ideas on dynamically creating variables? This is straight forward in most programming languages, so I'm struggling to understand how this is handled in a template engine like Twig.

Body:
If the values are actually iterateable and not a single json string you can put them in an array like:

{% set values = [] %}
{% for item in json %}
    {% set values = values|merge({(item.name): item.value}) %}
{% endfor %}

Then you can use values.firstName.

If it is a json string and thus can't be looped through like this. You need to write a basic string parser in twig. I've written something similar like that last week in this answer however. Its a very bad idea in general as it fails on so many occasions.


来源: stackexchange

问:
Validate select box
I'm using the jQuery plugin Validation to validate a form. I have a select list looking like this:

```<code><select id="select">
<option value="">Choose an option</option>
<option value="option1">Option1</option>
<option value="option2">Option2</option>
<option value="option3">Option3</option>
</select>
</code>```

Now, I want to make sure that the user selects anything but "Choose an option" (which is the default one). So that it won't validate if you choose the first option. How can this be done?

答:
Perhaps there is a shorter way but this works for me.</p>

```<code><script language='JavaScript' type='text/javascript'>
    function validateThisFrom(thisForm) {
        if (thisForm.FIELDNAME.value == "") {
            alert("Please make a selection");
            thisForm.FIELDNAME.focus();
            return false;
        }
        if (thisForm.FIELDNAME2.value == "") {
            alert("Please make a selection");
            thisForm.FIELDNAME2.focus();
            return false;
        }
    }
</script>
<form onSubmit="return validateThisFrom (this);">
    <select name="FIELDNAME" class="form-control">
        <option value="">- select -</option>
        <option value="value 1">Visible info of Value 1</option>
        <option value="value 2">Visible info of Value 2</option>
    </select>
    <select name="FIELDNAME2" class="form-control">
        <option value="">- select -</option>
        <option value="value 1">Visible info of Value 1</option>
        <option value="value 2">Visible info of Value 2</option>
    </select>
</form>
</code>```

ContentLicense: CC BY-SA 2.5

Title: Validate select box

Body:
I'm using the jQuery plugin Validation to validate a form. I have a select list looking like this:

<select id="select">
<option value="">Choose an option</option>
<option value="option1">Option1</option>
<option value="option2">Option2</option>
<option value="option3">Option3</option>
</select>

Now, I want to make sure that the user selects anything but "Choose an option" (which is the default one). So that it won't validate if you choose the first option. How can this be done?

Body:
Perhaps there is a shorter way but this works for me.

<script language='JavaScript' type='text/javascript'>
    function validateThisFrom(thisForm) {
        if (thisForm.FIELDNAME.value == "") {
            alert("Please make a selection");
            thisForm.FIELDNAME.focus();
            return false;
        }
        if (thisForm.FIELDNAME2.value == "") {
            alert("Please make a selection");
            thisForm.FIELDNAME2.focus();
            return false;
        }
    }
</script>
<form onSubmit="return validateThisFrom (this);">
    <select name="FIELDNAME" class="form-control">
        <option value="">- select -</option>
        <option value="value 1">Visible info of Value 1</option>
        <option value="value 2">Visible info of Value 2</option>
    </select>
    <select name="FIELDNAME2" class="form-control">
        <option value="">- select -</option>
        <option value="value 1">Visible info of Value 1</option>
        <option value="value 2">Visible info of Value 2</option>
    </select>
</form>

ContentLicense: CC BY-SA 3.0


问:
Util class for accesing a Service in Spring 3
In Spring 3 it is not possible to set @Autowired in either static fields or methods, so since I want to declare an utility class such as:

```<code>public class SchoolYearServiceUtil {
    private static SchoolYearService schoolYearService;

    public static SchoolYear getSchoolYear(Long id) {
        return schoolYearService.get(id);
    }
}
</code>```

to avoid having to inject the schoolYearService everywhere (jsp, command class...) in which I need it. In this case, I don't need an interface to be implemented by SchoolYearServiceUtil.

I don't want to have to initialize the object through code but getting the same instance as the Spring's one.

Which would be the best option to implement the getSchoolYear as a static method?

Thanks.

Would this be conceptually wrong?:

```<code>@Component
public class SchoolYearServiceUtil {

private static SchoolYearService schoolYearService;

@Autowired(required = true)
private SchoolYearServiceUtil(@Qualifier("schoolYearServiceImpl") SchoolYearService schoolYearService) {
    SchoolYearServiceUtil.schoolYearService = schoolYearService;
}

public static SchoolYearService getSchoolYearService() {
    return schoolYearService;
}

public static SchoolYear getSchoolYear(Long id) {

    return getSchoolYearService().get(id);
}
}
</code>```

I would have to make sure that only Spring calls once the constructor and the constructor is called nowhere else, that's why I declared the constructor as private.

答:
I fully support skaffman's comment. You don't need static fields with DI. You just define a bean of scope singleton (default).

There is a way to obtain a bean statically, but you should be aware that it is not to be used in regular situations. (there are some valid applications). It is to use the WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext)

You notice that you need to pass a ServletContext argument.

OwnerDisplayName: anon

LastEditorDisplayName: anon

Body:
In Spring 3 it is not possible to set @Autowired in either static fields or methods, so since I want to declare an utility class such as:

public class SchoolYearServiceUtil {
    private static SchoolYearService schoolYearService;

    public static SchoolYear getSchoolYear(Long id) {
        return schoolYearService.get(id);
    }
}

to avoid having to inject the schoolYearService everywhere (jsp, command class...) in which I need it. In this case, I don't need an interface to be implemented by SchoolYearServiceUtil.

I don't want to have to initialize the object through code but getting the same instance as the Spring's one.

Which would be the best option to implement the getSchoolYear as a static method?

Thanks.

Would this be conceptually wrong?:

@Component
public class SchoolYearServiceUtil {

private static SchoolYearService schoolYearService;

@Autowired(required = true)
private SchoolYearServiceUtil(@Qualifier("schoolYearServiceImpl") SchoolYearService schoolYearService) {
    SchoolYearServiceUtil.schoolYearService = schoolYearService;
}

public static SchoolYearService getSchoolYearService() {
    return schoolYearService;
}

public static SchoolYear getSchoolYear(Long id) {

    return getSchoolYearService().get(id);
}
}

I would have to make sure that only Spring calls once the constructor and the constructor is called nowhere else, that's why I declared the constructor as private.


问:
Knockout JS visible based on select value
I am trying to show or hide a paragraph based on the value of a select. I have reviewed the various posts that seem the same as my question however, I am new to knockout.js and none of them seem to give a basic simple example of what I am trying to do.

Here is the fiddle:
http://jsfiddle.net/scooke/ub8ozbvf/

答:
You have some mistakes on your code:

Javascript: on json objects, the key-value pairs are separated by comma not by semicolons

```<code>var testing = {
  currentSelect: ko.observable("apples"),
  otherKey: ko.observable("otherValue"),
}
</code>```

HTML data-bind tags: as you are using a ko.observable to test equality, you have to call it as a function and you don't have to break the simple quotation mark inside double quotation mark

Apples Shown!

I've update your fiddle

Body:
You have some mistakes on your code:

Javascript: on json objects, the key-value pairs are separated by comma not by semicolons

var testing = {
  currentSelect: ko.observable("apples"),
  otherKey: ko.observable("otherValue"),
}

HTML data-bind tags: as you are using a ko.observable to test equality, you have to call it as a function and you don't have to break the simple quotation mark inside double quotation mark

<p data-bind="visible:currentSelect() === 'apples'">Apples Shown!</p>

I've update your fiddle


问:
Active Record callbacks with has_many association
I want to run a before_save or after_add callback every time I add a child object to a parent object (has_many association). In the callback I want to set the end_date property on the parent (cohort) based on the end_date properties of all the children (courses).

```<code>class Cohort < ActiveRecord::Base
  has_many :courses
  before_save :update_end_date

  def update_end_date
    self.end_date = courses.order(:end_date).last.try(:end_date)
  end
end
</code>```

The problem I'm experiencing is that the courses are not yet persisted to the database in the before_save callback, so courses.order(:end_date) does not return the newly added course(s).

There are several workarounds I could use (e.g. using the Ruby courses.sort_by method or using after_save with update), but my impression is that using the Active Record order method, if possible, would be preferable in terms of efficiency and best practice. Is there a way to do this with Active Record in before_save, or what might be best practice for this? It seems like something that would come up a lot, but I'm having trouble finding solutions that work for me, so I feel like I must be thinking about it wrong. Thanks!

答:
You could do an after save on the courses that may update the cohort if their end date is later than the cohorts end date. and an after destroy on the course, that tells the cohort to update its end date to correspond to the remaining courses.

```<code>class Course < ActiveRecord::Base
  belongs_to :cohort
  after_save :maybe_update_cohort_end_date
  after_destroy :update_cohort_end_date

  def maybe_update_cohort_end_date
    if cohort && self.end_date > cohort.end_date
      cohort.end_date = self.end_date
      cohort.save
    end
  end

  def update_cohort_end_date
    cohort.update_end_date if cohort
  end
end

class Cohort < ActiveRecord::Base
  has_many :courses

  def update_end_date
    self.end_date = courses.order(:end_date).last.try(:end_date)
  end
end
</code>```

This way you only make an update if the new or updated course's end date would change the the cohorts end date.  But also catches if a course is removed then check what the end date should be

Body:
I want to run a before_save or after_add callback every time I add a child object to a parent object (has_many association). In the callback I want to set the end_date property on the parent (cohort) based on the end_date properties of all the children (courses).

class Cohort < ActiveRecord::Base
  has_many :courses
  before_save :update_end_date

  def update_end_date
    self.end_date = courses.order(:end_date).last.try(:end_date)
  end
end

The problem I'm experiencing is that the courses are not yet persisted to the database in the before_save callback, so courses.order(:end_date) does not return the newly added course(s).

There are several workarounds I could use (e.g. using the Ruby courses.sort_by method or using after_save with update), but my impression is that using the Active Record order method, if possible, would be preferable in terms of efficiency and best practice. Is there a way to do this with Active Record in before_save, or what might be best practice for this? It seems like something that would come up a lot, but I'm having trouble finding solutions that work for me, so I feel like I must be thinking about it wrong. Thanks!

Body:
You could do an after save on the courses that may update the cohort if their end date is later than the cohorts end date. and an after destroy on the course, that tells the cohort to update its end date to correspond to the remaining courses.

class Course < ActiveRecord::Base
  belongs_to :cohort
  after_save :maybe_update_cohort_end_date
  after_destroy :update_cohort_end_date

  def maybe_update_cohort_end_date
    if cohort && self.end_date > cohort.end_date
      cohort.end_date = self.end_date
      cohort.save
    end
  end

  def update_cohort_end_date
    cohort.update_end_date if cohort
  end
end

class Cohort < ActiveRecord::Base
  has_many :courses

  def update_end_date
    self.end_date = courses.order(:end_date).last.try(:end_date)
  end
end

This way you only make an update if the new or updated course's end date would change the the cohorts end date.  But also catches if a course is removed then check what the end date should be


问:
Python Pandas Accessing values from second index in multi-indexed dataframe
I am not really sure how multi indexing works, so I maybe simply be trying to do the wrong things here. If I have a dataframe with

```<code>        Value
A  B
1  1    5.67
1  2    6.87
1  3    7.23
2  1    8.67
2  2    9.87
2  3    10.23
</code>```

If I want to access the elements where B=2, how would I do that? df.ix[2] gives me the A=2. To get a particular value it seems df.ix[(1,2)] but that is the purpose of the B index if you can't access it directly?

答:
Just as an alternative, you could use df.loc:

```<code>>>> df.loc[(slice(None),2),:]
     Value
A B
1 2   6.87
2 2   9.87
</code>```

The tuple accesses the indexes in order. So, slice(None) grabs all values from index 'A', the second position limits based on the second level index, where 'B'=2 in this example. The : specifies that you want all columns, but you could subet the columns there as well.

Body:
I am not really sure how multi indexing works, so I maybe simply be trying to do the wrong things here. If I have a dataframe with

        Value
A  B
1  1    5.67
1  2    6.87
1  3    7.23
2  1    8.67
2  2    9.87
2  3    10.23

If I want to access the elements where B=2, how would I do that? df.ix[2] gives me the A=2. To get a particular value it seems df.ix[(1,2)] but that is the purpose of the B index if you can't access it directly?

Body:
Just as an alternative, you could use df.loc:

>>> df.loc[(slice(None),2),:]
     Value
A B
1 2   6.87
2 2   9.87

The tuple accesses the indexes in order. So, slice(None) grabs all values from index 'A', the second position limits based on the second level index, where 'B'=2 in this example. The : specifies that you want all columns, but you could subet the columns there as well.


问:
Javascript array object Output
Can anybody help me I am new to javascript. I am not able to understand the below line of code. I spend hours to debug this code but I am not able to rectify.

```<code>var data = [
    {"name":"123123123123"},
    {"name":"123123123124"},
    {"name":"123123123125"},
    {"name":"123123123126"}
];
var x1 = {}
var basicS = {
    "question":[]
}
data.forEach(function(val,i){
   x1[val.name]=basicS;
});

console.log(x1);
data.forEach(function(val,i){
 x1[val.name].question.push('insert');
});
console.log(x1);
</code>```

Output:

```<code>{
 123123123123:{
    question:[
      0:"insert"
      1:"insert"
      2:"insert"
      3:"insert"
    ]
},
123123123124:{
    question:[
      0:"insert"
      1:"insert"
      2:"insert"
      3:"insert"
    ]
},
123123123125:{
    question:[
      0:"insert"
      1:"insert"
      2:"insert"
      3:"insert"
    ]
},
123123123126:{
    question:[
      0:"insert"
      1:"insert"
      2:"insert"
      3:"insert"
    ]
}
}
</code>```

Expected Output should be:

```<code>{
  123123123123:{
    question:[
      0:"insert"
    ]
},
123123123124:{
    question:[
      0:"insert"
    ]
},
123123123125:{
    question:[
      0:"insert"
              ]
},
123123123126:{
    question:[
      0:"insert"
    ]
}
}
</code>```

Not able to understand from where four values are inserted inside the each question array while i am inserting only  one in each question
array object.

Is there any alternative to solve this type of prblem.

Please help me out. I am totally confused. Thanks in advance.

答:
You may want to create multiple objects:

```<code>data.forEach(function(val,i){
   x1[val.name]={
      "question":[]
    };
});
</code>```

Or both loops in one O(n) instead of O(2n):

```<code>data.forEach(function(val,i){
   (x1[val.name]=x1[val.name] || {question:[]}).question.push(val);
});
</code>```

Title: Javascript array object Output

Body:
Can anybody help me I am new to javascript. I am not able to understand the below line of code. I spend hours to debug this code but I am not able to rectify.

var data = [
    {"name":"123123123123"},
    {"name":"123123123124"},
    {"name":"123123123125"},
    {"name":"123123123126"}
];
var x1 = {}
var basicS = {
    "question":[]
}
data.forEach(function(val,i){
   x1[val.name]=basicS;
});

console.log(x1);
data.forEach(function(val,i){
 x1[val.name].question.push('insert');
});
console.log(x1);

Output:

{
 123123123123:{
    question:[
      0:"insert"
      1:"insert"
      2:"insert"
      3:"insert"
    ]
},
123123123124:{
    question:[
      0:"insert"
      1:"insert"
      2:"insert"
      3:"insert"
    ]
},
123123123125:{
    question:[
      0:"insert"
      1:"insert"
      2:"insert"
      3:"insert"
    ]
},
123123123126:{
    question:[
      0:"insert"
      1:"insert"
      2:"insert"
      3:"insert"
    ]
}
}

Expected Output should be:

{
  123123123123:{
    question:[
      0:"insert"
    ]
},
123123123124:{
    question:[
      0:"insert"
    ]
},
123123123125:{
    question:[
      0:"insert"
              ]
},
123123123126:{
    question:[
      0:"insert"
    ]
}
}

Not able to understand from where four values are inserted inside the each question array while i am inserting only  one in each question
array object.

Is there any alternative to solve this type of prblem.

Please help me out. I am totally confused. Thanks in advance.

Body:
You may want to create multiple objects:

data.forEach(function(val,i){
   x1[val.name]={
      "question":[]
    };
});

Or both loops in one O(n) instead of O(2n):

data.forEach(function(val,i){
   (x1[val.name]=x1[val.name] || {question:[]}).question.push(val);
});


问:
AngularJS disable double click
I have a problem with a button which contacts server on click. If you do a double click (or any number of clicks for that matter) you will call the server that number of times.

```<code><div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">{{ 'ADMIN.CONTENT.DELIVERIES.BODY.CLOSE' | translate }}</button>
    <a class="btn btn-danger" ng-click="vm.markDelivered()" ng-dblclick="return" ng-disabled="flag">{{ 'MANAGER.CONTENT.DELIVERIES.BODY.DELETE_PANEL.CONFIRM' | translate }}</a>
</div>
</code>```

I have tried with ng-disabled but for some reason it doesn't work, as it is saying that that element is not allowed there. I tried changing a to button, but that seems the same. ng-dblclick="return" does nothing also.

答:
I see a couple of issues here.

First, change the anchor tag to a button.

Second, you seem to be using 'controller as' syntax. So, you are probably setting your flag in the vm. But, in your html, you are looking for the flag in the $scope. Change ng-disabled="flag" to ng-disabled="vm.flag"

Your final button line would look like this:
<button class="btn btn-danger" ng-click="vm.markDelivered()" ng-dblclick="return" ng-disabled="vm.flag">{{ 'MANAGER.CONTENT.DELIVERIES.BODY.DELETE_PANEL.CONFIRM' | translate }}</button>

Adding a working plunker here demonstrating ng-disabled

Title: AngularJS disable double click

Body:
I have a problem with a button which contacts server on click. If you do a double click (or any number of clicks for that matter) you will call the server that number of times.

    <button type="button" class="btn btn-default" data-dismiss="modal">{{ 'ADMIN.CONTENT.DELIVERIES.BODY.CLOSE' | translate }}</button>
    {{ 'MANAGER.CONTENT.DELIVERIES.BODY.DELETE_PANEL.CONFIRM' | translate }}

I have tried with ng-disabled but for some reason it doesn't work, as it is saying that that element is not allowed there. I tried changing a to button, but that seems the same. ng-dblclick="return" does nothing also.


问:
golang initialize member with struct itself for sync.Mutex and sync.Cond
Here is go code:

```<code>type someThing struct {
    sync.Mutex
    cv      *sync.Cond
    num     int
}

func NewSomething() *someThing {
    // how do you do this ?
    return &someThing{cv:sync.NewCond(sync.Mutex)}
}
</code>```

This code fails to compile:

```<code>sync.Mutex (type) is not an expression
</code>```

So basically the question is how to refer to the struct itself (because it has an embedded member sync.Mutex) while initializing it ? (c++ has this, for example).

答:
You can create a new instance first, and then refer to the embedded field:

```<code>type SomeThing struct {
    sync.Mutex
    cv  *sync.Cond
    num int
}

func NewSomething() *SomeThing {
    st := &SomeThing{}
    st.cv = sync.NewCond(&st.Mutex)
    return st
}
</code>```

GoPlay here: https://play.golang.org/p/BlnHMi1EKT

Body:
Here is go code:

type someThing struct {
    sync.Mutex
    cv      *sync.Cond
    num     int
}

func NewSomething() *someThing {
    // how do you do this ?
    return &someThing{cv:sync.NewCond(sync.Mutex)}
}

This code fails to compile:

sync.Mutex (type) is not an expression

So basically the question is how to refer to the struct itself (because it has an embedded member sync.Mutex) while initializing it ? (c++ has this, for example).

Body:
You can create a new instance first, and then refer to the embedded field:

type SomeThing struct {
    sync.Mutex
    cv  *sync.Cond
    num int
}

func NewSomething() *SomeThing {
    st := &SomeThing{}
    st.cv = sync.NewCond(&st.Mutex)
    return st
}

GoPlay here: https://play.golang.org/p/BlnHMi1EKT


问:
iPhone - Creating Home Screen for App that show icons to launch other app with in app
I just wanted to know how can I create Home Screen after launching my App, that shows multiple icons/app buttons to launch other apps, just like the way iPhone home screen has multiple icons/pages that list app icons.

My app will have different features like map,dining, weather etc.

Thanks

答:
This type of functionality is not allowed by Apple.  That is any sort of desktop replacement or dashboard system is explicitly prohibited.

However, if you check out the Facebook iPhone app, you can see that  you could do something similar.  That is one app showing a grid of icons.  Each of the icon buttons launches a different view within the app itself.

This type functionality is allowed and is provided by the three20 library:

https://github.com/facebook/three20

This library was spun off from code created in the Facebook App.


问:
Debugging file transfer using pscp executed from PowerShell
I am trying to use PowerShell to send a file from a Windows 10 dev box to a CentOS 7 server across a local area network.

When I run the following command from PowerShell in the Windows 10 dev box, Putty opens, but then closes before asking for password.  And then the test file (index.html) is not present in the intended destination folder on the CentOS 7 server.

```<code>Start-Process 'C:\Program Files (x86)\PuTTY\pscp.exe' -ArgumentList ("-scp -pw password C:\projects\temp\junk\index.html some_user_name@192.168.1.5:/home/some_user_name/")
</code>```

How can I diagnose what problem is causing this command to fail?  And what specific steps need to be taken in order for the file to be successfully transferred from the devbox to the server?

I have double checked the obvious things, like the file paths, the user name, and the IP.

The above command is derived from this suggestion by @GrahamGold.

答:
In general, there's nothing wrong with your command. It should work (if all arguments are correct).

To diagnose the problem, first test the command on Windows command-line (cmd.exe):

"C:\Program Files (x86)\PuTTY\pscp.exe" -scp -pw password C:\projects\temp\junk\index.html some_user_name@192.168.1.5:/home/some_user_name/
```

<p>This way, the output is preserved and you will see, what went wrong (if anything).</p>

<p>The next step is to do the same in PowerShell script using call operator <code>&</code> (though the result should be the same):</p>

```& "C:\Program Files (x86)\PuTTY\pscp.exe" -scp -pw password C:\projects\temp\junk\index.html some_user_name@192.168.1.5:/home/some_user_name/
```

If that works, it's time to replace & with the Start-Process cmdlet, if you really want that. But in general, I do not see a point of that, unless you want to run the transfer asynchronously.

Though if you want to make you command portable, you need to add -hostkey switch.

See my answer to Using echo y as an automated response to a pcp hostkey prompt.

Body:
I am trying to use PowerShell to send a file from a Windows 10 dev box to a CentOS 7 server across a local area network.

When I run the following command from PowerShell in the Windows 10 dev box, Putty opens, but then closes before asking for password.  And then the test file (index.html) is not present in the intended destination folder on the CentOS 7 server.

Start-Process 'C:\Program Files (x86)\PuTTY\pscp.exe' -ArgumentList ("-scp -pw password C:\projects\temp\junk\index.html some_user_name@192.168.1.5:/home/some_user_name/")

How can I diagnose what problem is causing this command to fail?  And what specific steps need to be taken in order for the file to be successfully transferred from the devbox to the server?

I have double checked the obvious things, like the file paths, the user name, and the IP.

The above command is derived from this suggestion by @GrahamGold.

Body:
In general, there's nothing wrong with your command. It should work (if all arguments are correct).

To diagnose the problem, first test the command on Windows command-line (cmd.exe):

"C:\Program Files (x86)\PuTTY\pscp.exe" -scp -pw password C:\projects\temp\junk\index.html some_user_name@192.168.1.5:/home/some_user_name/

This way, the output is preserved and you will see, what went wrong (if anything).

The next step is to do the same in PowerShell script using call operator & (though the result should be the same):

& "C:\Program Files (x86)\PuTTY\pscp.exe" -scp -pw password C:\projects\temp\junk\index.html some_user_name@192.168.1.5:/home/some_user_name/

If that works, it's time to replace & with the Start-Process cmdlet, if you really want that. But in general, I do not see a point of that, unless you want to run the transfer asynchronously.

Though if you want to make you command portable, you need to add -hostkey switch.

See my answer to Using echo y as an automated response to a pcp hostkey prompt.


问:
Bootstrap form not in the center of the div
I have a bootstraap form where two field I have added the class .d-inline-block so that it comes next to each other and I have another field where I have not added the class so that It comes below of the two field.

I want this to be in the center of the div which I am not able to do it. Only the first two fields are coming to center but not the last div.

Can someone point out the mistake?

@import url( 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css' );

.d-inline-block {

  width: 40%;
}

.message {
  width: 80%;
}

.formClass {
  margin-left: auto !important;
  margin-right: auto !important;
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="formClass ">
  <div class="form-group d-inline-block">
    <input type="text" class="form-control" id="nameInput">
    <div class="form-control-placeholder"> Name </div>
  </div>
  <div class="form-group d-inline-block">
    <input type="text" class="form-control" id="phoneInput">
    <div class="form-control-placeholder"> Phone </div>
  </div>

  <div class="form-group message">
    <input type="text" class="form-control" id="phoneInput">
    <div class="form-control-placeholder"> Phone </div>
  </div>
</form></code>```

https://jsfiddle.net/97avbgsq/

答:
While you're free to create your own custom CSS classes to control form field sizes and position, I would like to suggest using the built in grid system column classes to control the size and position of the input fields.

Bootstrap 4 Grid System

@import url('https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>

  <div class="row">
    <div class="form-group col-sm-4 offset-sm-2">
      <input type="text" class="form-control" id="nameInput">
      <label class="d-block text-center" for="nameInput">Name</label>
    </div>
    <div class="form-group col-sm-4">
      <input type="text" class="form-control" id="phoneInput">
      <label class="d-block text-center" for="phoneInput">Phone</label>
    </div>
  </div>

  <div class="row">
    <div class="form-group col-sm-8 offset-sm-2">
      <input type="text" class="form-control" id="phoneInput">
      <label class="d-block text-center" for="phoneInput">Phone</label>
    </div>
  </div>

</form></code>```

Body:
I have a bootstraap form where two field I have added the class .d-inline-block so that it comes next to each other and I have another field where I have not added the class so that It comes below of the two field.

I want this to be in the center of the div which I am not able to do it. Only the first two fields are coming to center but not the last div.

Can someone point out the mistake?

@import url( 'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css' );

.d-inline-block {

  width: 40%;
}

.message {
  width: 80%;
}

.formClass {
  margin-left: auto !important;
  margin-right: auto !important;
  text-align: center;
}

<form class="formClass ">

    <input type="text" class="form-control" id="nameInput">

 Name

    <input type="text" class="form-control" id="phoneInput">

 Phone

    <input type="text" class="form-control" id="phoneInput">

 Phone

</form>

https://jsfiddle.net/97avbgsq/

Body:
While you're free to create your own custom CSS classes to control form field sizes and position, I would like to suggest using the built in grid system column classes to control the size and position of the input fields.

Bootstrap 4 Grid System

@import url('https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css');

<form>

  <div class="row">
    <div class="form-group col-sm-4 offset-sm-2">
      <input type="text" class="form-control" id="nameInput">
      <label class="d-block text-center" for="nameInput">Name</label>
    </div>
    <div class="form-group col-sm-4">
      <input type="text" class="form-control" id="phoneInput">
      <label class="d-block text-center" for="phoneInput">Phone</label>
    </div>
  </div>

  <div class="row">
    <div class="form-group col-sm-8 offset-sm-2">
      <input type="text" class="form-control" id="phoneInput">
      <label class="d-block text-center" for="phoneInput">Phone</label>
    </div>
  </div>

</form>


问:
Recursive hierarchical Oracle SQL query
I have a source table like below:

```<code>Emp_ID| Name| Manager_ID
001|abc|005
005|cde|010
010|xyz|050
050 | bcg| 100
100|sta|NULL
</code>```

My requirement is to populate the target table like below:

```<code>Emp_ID| Name| Manager_1| Manager_2| Manager_3| Manager_4
005|cde|xyz|bcg|sta|NULL
050|bcg|sta| NULL|NULL|NULL
100|sta|NULL|NULL|NULL
001|abc|cde|xyz|bcg|sta
</code>```

I am able to use recursive select through Connect by clause and populate the value for Manager_1 but not able to get through the logic to populate Manager_2, Manager_3 , Manager_4 values as different column values in a single row depending on how many level of hierarchy is present for a certain employee.
Please help.

答:
Pivot option:</p>

```<code>SELECT * FROM
(
  SELECT emp_id, name, manager_id
  FROM employees
)
PIVOT
(
  COUNT(manager_id)
  FOR manager_id IN ('005', '100', '050')
)
ORDER BY emp_id;
</code>```

Title: Recursive hierarchical Oracle SQL query

Body:
I have a source table like below:

Emp_ID| Name| Manager_ID
001|abc|005
005|cde|010
010|xyz|050
050 | bcg| 100
100|sta|NULL

My requirement is to populate the target table like below:

Emp_ID| Name| Manager_1| Manager_2| Manager_3| Manager_4
005|cde|xyz|bcg|sta|NULL
050|bcg|sta| NULL|NULL|NULL
100|sta|NULL|NULL|NULL
001|abc|cde|xyz|bcg|sta

I am able to use recursive select through Connect by clause and populate the value for Manager_1 but not able to get through the logic to populate Manager_2, Manager_3 , Manager_4 values as different column values in a single row depending on how many level of hierarchy is present for a certain employee.
Please help.

Body:
Pivot option:

SELECT * FROM
(
  SELECT emp_id, name, manager_id
  FROM employees
)
PIVOT
(
  COUNT(manager_id)
  FOR manager_id IN ('005', '100', '050')
)
ORDER BY emp_id;


问:
Xamarin Android (Visual Studio 2015) Could not connect to the debugger
I have a problem with the android debugger (Visual Studio 2015) as it always stops immediately after starting debug (it works just fine without debugging), I had my machine reset and reinstalled Visual Studio 2015 but it does not help.

Here is the log from logcat: monodroid-debug Error accepting stdout and stderr (127.0.0.1:8896) Address already in use

Here is the log from Xamarin log:

```<code>Mono.Debugging.Soft.ConnectionException: Could not connect to the debugger. ---> Mono.Debugger.Soft.VMDisconnectedException: Exception of type 'Mono.Debugger.Soft.VMDisconnectedException' was thrown.

Server stack trace:
at Mono.Debugger.Soft.Connection.SendReceive(CommandSet command_set, Int32 command, PacketWriter packet)
at Mono.Debugger.Soft.Connection.VM_GetVersion()
at Mono.Debugger.Soft.Connection.Connect()
at Mono.Debugger.Soft.VirtualMachine.connect()
at Mono.Debugger.Soft.VirtualMachineManager.Connect(Connection transport, StreamReader standardOutput, StreamReader standardError)
at Mono.Debugger.Soft.VirtualMachineManager.ConnectInternal(Socket dbg_sock, Socket con_sock, IPEndPoint dbg_ep, IPEndPoint con_ep)
at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs)
at System.Runtime.Remoting.Messaging.StackBuilderSink.AsyncProcessMessage(IMessage msg, IMessageSink replySink)

Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.EndInvokeHelper(Message reqMsg, Boolean bProxyCase)
at System.Runtime.Remoting.Proxies.RemotingProxy.Invoke(Object NotUsed, MessageData& msgData)
at Mono.Debugger.Soft.VirtualMachineManager.ConnectCallback.EndInvoke(IAsyncResult result)
at Mono.Debugger.Soft.VirtualMachineManager.EndConnect(IAsyncResult asyncResult)
at Mono.Debugging.Soft.SoftDebuggerSession.<>c__DisplayClass9.b__8(IAsyncResult ar)
--- End of inner exception stack trace ---
</code>```

Any help is much appreciated!

答:
Though the question is for VS 2015. Recently with visual studio 2017 version 15.2 has this issue.
 Uninstalling the visual studio and downgrading to  previous working VS helped in my case. Hope soon they will fix the bug.
https://forums.xamarin.com/discussion/95555/how-to-downgrade-visual-studio-2017-version-15-2-to-15-0</p>

Body:
I have a problem with the android debugger (Visual Studio 2015) as it always stops immediately after starting debug (it works just fine without debugging), I had my machine reset and reinstalled Visual Studio 2015 but it does not help.

Here is the log from logcat: monodroid-debug Error accepting stdout and stderr (127.0.0.1:8896) Address already in use

Here is the log from Xamarin log:

Mono.Debugging.Soft.ConnectionException: Could not connect to the debugger. ---> Mono.Debugger.Soft.VMDisconnectedException: Exception of type 'Mono.Debugger.Soft.VMDisconnectedException' was thrown.

Server stack trace:
at Mono.Debugger.Soft.Connection.SendReceive(CommandSet command_set, Int32 command, PacketWriter packet)
at Mono.Debugger.Soft.Connection.VM_GetVersion()
at Mono.Debugger.Soft.Connection.Connect()
at Mono.Debugger.Soft.VirtualMachine.connect()
at Mono.Debugger.Soft.VirtualMachineManager.Connect(Connection transport, StreamReader standardOutput, StreamReader standardError)
at Mono.Debugger.Soft.VirtualMachineManager.ConnectInternal(Socket dbg_sock, Socket con_sock, IPEndPoint dbg_ep, IPEndPoint con_ep)
at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs)
at System.Runtime.Remoting.Messaging.StackBuilderSink.AsyncProcessMessage(IMessage msg, IMessageSink replySink)

Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.EndInvokeHelper(Message reqMsg, Boolean bProxyCase)
at System.Runtime.Remoting.Proxies.RemotingProxy.Invoke(Object NotUsed, MessageData& msgData)
at Mono.Debugger.Soft.VirtualMachineManager.ConnectCallback.EndInvoke(IAsyncResult result)
at Mono.Debugger.Soft.VirtualMachineManager.EndConnect(IAsyncResult asyncResult)
at Mono.Debugging.Soft.SoftDebuggerSession.<>c__DisplayClass9.b__8(IAsyncResult ar)
--- End of inner exception stack trace ---

Any help is much appreciated!


问:
Can I build a list of Strings using each constructor of a class?
I have a simple data type such as:

```<code>data Class = Class1
           | Class2
           | Class3
           deriving (Show, Eq)
</code>```

Is there a simple way for me to build a list of Strings that contains the String version of each of these such that:

```<code>func Class = ["Class1", "Class2", "Class3"]
</code>```

答:
The answer is yes, but with a caveat. What is the type of func? It looks like its first argument would be a type, not a value. More on the later...

Deriving Enum gets you get the ability to list off successive constructors and deriving Bounded gets you the ability to get the "first" and "last" elements of this enumeration.

```<code>data Class = Class1
           | Class2
           | Class3
           deriving (Show, Eq, Enum, Bounded)
</code>```

Then, we can get a list of all the elements via enumFromTo minBound maxBound (or just [minBound .. maxBound]).

However, back to the initial question on the type of func. You need to pass in a type as an argument. The usual way of doing this is using Proxy and ScopedTypeVariables.

```<code>{-# LANGUAGE ScopedTypeVariables #-}

import Data.Proxy (Proxy(..))

func :: forall a. (Enum a, Bounded a, Show a) => Proxy a -> [String]
func Proxy = map show $ enumFromTo minBound (maxBound :: a)
</code>```

Try this out at GHCi:

```<code>ghci> func (Proxy :: Proxy Class)
["Class1","Class2","Class3"]
ghci> func (Proxy :: Proxy Bool)
["True","False"]
</code>```

Body:
I have a simple data type such as:

data Class = Class1
           | Class2
           | Class3
           deriving (Show, Eq)

Is there a simple way for me to build a list of Strings that contains the String version of each of these such that:

func Class = ["Class1", "Class2", "Class3"]

Body:
The answer is yes, but with a caveat. What is the type of func? It looks like its first argument would be a type, not a value. More on the later...

Deriving Enum gets you get the ability to list off successive constructors and deriving Bounded gets you the ability to get the "first" and "last" elements of this enumeration.

data Class = Class1
           | Class2
           | Class3
           deriving (Show, Eq, Enum, Bounded)

Then, we can get a list of all the elements via enumFromTo minBound maxBound (or just [minBound .. maxBound]).

However, back to the initial question on the type of func. You need to pass in a type as an argument. The usual way of doing this is using Proxy and ScopedTypeVariables.

{-# LANGUAGE ScopedTypeVariables #-}

import Data.Proxy (Proxy(..))

func :: forall a. (Enum a, Bounded a, Show a) => Proxy a -> [String]
func Proxy = map show $ enumFromTo minBound (maxBound :: a)

Try this out at GHCi:

ghci> func (Proxy :: Proxy Class)
["Class1","Class2","Class3"]
ghci> func (Proxy :: Proxy Bool)
["True","False"]


问:
PHP - Store XML file onto server
I am new to PHP and I can't seem to find code snippets for storing posted data onto the server PHP is running on.

HOST :

I am using Xmapp/Apache to create a local server, as seen below:

GOAL :

The goal is to send a post request attaching a XML string as content to POST.php and the PHP script will parse the content into XML and store the .xml file into ./XML Files directory

Here is a markup of what the code would be:

```<code><?php
    if (isset($_POST["XML"]))
    {

        //put .xml file into server directory ./XML Files

        echo "success";
    }
    else echo "error";
?>
</code>```

答:
Use simplexml_load_string() to create SimpleXMLElement and then call asXML method on it to write the data to the file:</p>

```<code>if (isset($_POST["XML"])) {

    //put .xml file into server directory ./XML Files

    $simpleXMLElement = simplexml_load_string($_POST["XML"]);
    $simpleXMLElement->asXML('./XML Files/filename.xml');

    echo "success";
} else {
    echo "error";
}
</code>```

Title: PHP - Store XML file onto server

Body:
I am new to PHP and I can't seem to find code snippets for storing posted data onto the server PHP is running on.

HOST :

I am using Xmapp/Apache to create a local server, as seen below:

GOAL :

The goal is to send a post request attaching a XML string as content to POST.php and the PHP script will parse the content into XML and store the .xml file into ./XML Files directory

Here is a markup of what the code would be:

<?php
    if (isset($_POST["XML"]))
    {

        //put .xml file into server directory ./XML Files

        echo "success";
    }
    else echo "error";
?>

Body:
Use simplexml_load_string() to create SimpleXMLElement and then call asXML method on it to write the data to the file:

if (isset($_POST["XML"])) {

    //put .xml file into server directory ./XML Files

    $simpleXMLElement = simplexml_load_string($_POST["XML"]);
    $simpleXMLElement->asXML('./XML Files/filename.xml');

    echo "success";
} else {
    echo "error";
}


问:
Implementation of Service Broker API for Cassandra and Aerospike in open source Cloud Foundry
I need to use Cassandra and Aerospike as services with open source cloud foundry. Service Broker implementations with PCF i.e. Pivotal Cloud Foundry, are available as tiles for most DBs. Can these be used with open source cloud foundry? If yes, how? If not, how to go about implementing the service broker API for my use case? Are there any already available? </p>

答:
Aerospike is available on PCF - https://discuss.aerospike.com/t/aerospike-now-available-on-pivotal-cloud-foundry-pcf-aerospike-blog-post-october-19-2016/3524

the write up then refers to:

https://network.pivotal.io/products/aerospike


问:
How can a instance with Num type class coercion to Fractional implicitly?
I tested the numeric coercion by using GHCI:

```<code>>> let c = 1 :: Integer

>> 1 / 2
0.5

>> c / 2
<interactive>:15:1: error:
• No instance for (Fractional Integer) arising from a use of ‘/’
• In the expression: c / 2
  In an equation for ‘it’: it = c / 2

>> :t (/)
(/) :: Fractional a => a -> a -> a -- (/) needs Fractional type

>> (fromInteger c)  / 2
0.5

>>:t fromInteger
fromInteger :: Num a => Integer -> a  -- Just convert the Integer to Num not to Fractional
</code>```

I can use fromInteger function to convert a Integer type to Num (fromInteger has the type fromInteger :: Num a => Integer -> a), but I cannot understand that how can the type Num be converted to Fractional implicitly?

I know that if an instance has type Fractional it must have type Num (class Num a => Fractional a where), but does it necessary that if an instance has type Num it can be used as an instance with Fractional type?

@mnoronha Thanks for your detailed reply. There is only one question confuse me. I know the reason that type a cannot be used in function (/) is that type a is with type Integer which is not an instance of type class Fractional (the function (/) requires that the type of arguments must be instance of Fractional). What I don't understand is that even by calling fromInteger to convert the type integer to atype which be an instance of Num, it does not mean a type be an instance of Fractional (because Fractional type class is more constrained than Num type class, so a type may not implement some functions required by Fractional type class). If a type does not fully fit the condition Fractional type class requires, how can it be use in the function (/) which asks the arguments type be instance of Fractional. Sorry for not native speaker and really thanks for your patience!

I tested that if a type only fits the parent type class, it cannot be used in a function which requires more constrained type class.

```<code>{-# LANGUAGE OverloadedStrings #-}
module Main where

class ParentAPI a where
  printPar :: int -> a -> String

class (ParentAPI a) => SubAPI a where
  printSub :: a -> String

data ParentDT = ParentDT Int
instance ParentAPI ParentDT where
  printPar i p = "par"

testF :: (SubAPI a) => a -> String
testF a = printSub a

main = do
  let m = testF $ ParentDT 10000
  return ()
====
test-typeclass.hs:19:11: error:
• No instance for (SubAPI ParentDT) arising from a use of ‘testF’
• In the expression: testF $ ParentDT 10000
  In an equation for ‘m’: m = testF $ ParentDT 10000
  In the expression:
    do { let m = testF $ ParentDT 10000;
         return () }
</code>```

I have found a doc explaining the numeric overloading ambiguity very clearly and may help others with the same confusion.

https://www.haskell.org/tutorial/numbers.html

答:
The reason why this works comes down to the way universal quantification works. To help explain this I am going to add in explicit forall to the type signatures (which you can do yourself if you enable -XExplicitForAll or any other forall related extension), but if you just removed them (forall a. ... becomes just ...), everything will work fine.

The thing to remember is that when a function involves a type constrained by a typeclass, then what that means is that you can input/output ANY type within that typeclass, so it's actually better to have a less constrained typeclass.

So:

```<code>fromInteger :: forall a. Num a => Integer -> a

fromInteger 5 :: forall a. Num a => a
</code>```

Means that you have a value that is of EVERY Num type. So not only can you use it in a function taking it in a Fractional, you could use it in a function that only takes in MyWeirdTypeclass a => ... as long as there is one single type that implements both Num and MyWeirdTypeclass. Hence why you can get the following just fine:

```<code>fromInteger 5 / 2 :: forall a. Fractional a => a
</code>```

Now of course once you decide to divide by 2, it now wants the output type to be Fractional, and thus 5 and 2 will be interpreted as some Fractional type, so we won't run into issues where we try to divide Int values, as trying to make the above have type Int will fail to type check.

This is really powerful and awesome, but very much unfamiliar, as generally other languages either don't support this, or only support it for input arguments (e.g print in most languages can take in any printable type).

Now you may be curious when the whole superclass / subclass stuff comes into play, so when you are defining a function that takes in something of type Num a => a, then because a user can pass in ANY Num type, you are correct that in this situation you cannot use functions defined on some subclass of Num, only things that work on ALL Num values, like *:

```<code>double :: forall a. Num a => a -> a
double n = n * 2  -- in here `n` really has type `exists a. Num a => a`
</code>```

So the following does not type check, and it wouldn't type check in any language, because you don't know that the argument is a Fractional.

```<code>halve :: Num a => a -> a
halve n = n / 2  -- in here `n` really has type `exists a. Num a => a`
</code>```

What we have up above with fromInteger 5 / 2 is more equivalent to the following, higher rank function, note that the forall within parenthesis is required, and you need to use -XRankNTypes:

```<code>halve :: forall b. Fractional b => (forall a. Num a => a) -> b
halve n = n / 2 -- in here `n` has type `forall a. Num a => a`
</code>```

Since this time you are taking in EVERY Num type (just like the fromInteger 5 you were dealing with before), not just ANY Num type. Now the downside of this function (and one reason why no one wants it) is that you really do have to pass in something of EVERY Num type:

```<code>halve (2 :: Int) -- does not work

halve (3 :: Integer) -- does not work

halve (1 :: Double) -- does not work

halve (4 :: Num a => a) -- works!

halve (fromInteger 5) -- also works!
</code>```

I hope that clears things up a little. All you need for the fromInteger 5 / 2 to work is that there exists ONE single type that is both a Num and a Fractional, or in other words just a Fractional, since Fractional implies Num. Type defaulting doesn't help much with clearing up this confusion, as what you may not realize is that GHC is just arbitrarily picking Double, it could have picked any Fractional.

Body:
I tested the numeric coercion by using GHCI:

>> let c = 1 :: Integer

>> 1 / 2
0.5

>> c / 2
<interactive>:15:1: error:
• No instance for (Fractional Integer) arising from a use of ‘/’
• In the expression: c / 2
  In an equation for ‘it’: it = c / 2

>> :t (/)
(/) :: Fractional a => a -> a -> a -- (/) needs Fractional type

>> (fromInteger c)  / 2
0.5

>>:t fromInteger
fromInteger :: Num a => Integer -> a  -- Just convert the Integer to Num not to Fractional

I can use fromInteger function to convert a Integer type to Num (fromInteger has the type fromInteger :: Num a => Integer -> a), but I cannot understand that how can the type Num be converted to Fractional implicitly?

I know that if an instance has type Fractional it must have type Num (class Num a => Fractional a where), but does it necessary that if an instance has type Num it can be used as an instance with Fractional type?

@mnoronha Thanks for your detailed reply. There is only one question confuse me. I know the reason that type a cannot be used in function (/) is that type a is with type Integer which is not an instance of type class Fractional (the function (/) requires that the type of arguments must be instance of Fractional). What I don't understand is that even by calling fromInteger to convert the type integer to atype which be an instance of Num, it does not mean a type be an instance of Fractional (because Fractional type class is more constrained than Num type class, so a type may not implement some functions required by Fractional type class). If a type does not fully fit the condition Fractional type class requires, how can it be use in the function (/) which asks the arguments type be instance of Fractional. Sorry for not native speaker and really thanks for your patience!

I tested that if a type only fits the parent type class, it cannot be used in a function which requires more constrained type class.

{-# LANGUAGE OverloadedStrings #-}
module Main where

class ParentAPI a where
  printPar :: int -> a -> String

class (ParentAPI a) => SubAPI a where
  printSub :: a -> String

data ParentDT = ParentDT Int
instance ParentAPI ParentDT where
  printPar i p = "par"

testF :: (SubAPI a) => a -> String
testF a = printSub a

main = do
  let m = testF $ ParentDT 10000
  return ()
====
test-typeclass.hs:19:11: error:
• No instance for (SubAPI ParentDT) arising from a use of ‘testF’
• In the expression: testF $ ParentDT 10000
  In an equation for ‘m’: m = testF $ ParentDT 10000
  In the expression:
    do { let m = testF $ ParentDT 10000;
         return () }

I have found a doc explaining the numeric overloading ambiguity very clearly and may help others with the same confusion.

https://www.haskell.org/tutorial/numbers.html

Body:
The reason why this works comes down to the way universal quantification works. To help explain this I am going to add in explicit forall to the type signatures (which you can do yourself if you enable -XExplicitForAll or any other forall related extension), but if you just removed them (forall a. ... becomes just ...), everything will work fine.

The thing to remember is that when a function involves a type constrained by a typeclass, then what that means is that you can input/output ANY type within that typeclass, so it's actually better to have a less constrained typeclass.

So:

fromInteger :: forall a. Num a => Integer -> a

fromInteger 5 :: forall a. Num a => a

Means that you have a value that is of EVERY Num type. So not only can you use it in a function taking it in a Fractional, you could use it in a function that only takes in MyWeirdTypeclass a => ... as long as there is one single type that implements both Num and MyWeirdTypeclass. Hence why you can get the following just fine:

fromInteger 5 / 2 :: forall a. Fractional a => a

Now of course once you decide to divide by 2, it now wants the output type to be Fractional, and thus 5 and 2 will be interpreted as some Fractional type, so we won't run into issues where we try to divide Int values, as trying to make the above have type Int will fail to type check.

This is really powerful and awesome, but very much unfamiliar, as generally other languages either don't support this, or only support it for input arguments (e.g print in most languages can take in any printable type).

Now you may be curious when the whole superclass / subclass stuff comes into play, so when you are defining a function that takes in something of type Num a => a, then because a user can pass in ANY Num type, you are correct that in this situation you cannot use functions defined on some subclass of Num, only things that work on ALL Num values, like *:

double :: forall a. Num a => a -> a
double n = n * 2  -- in here `n` really has type `exists a. Num a => a`

So the following does not type check, and it wouldn't type check in any language, because you don't know that the argument is a Fractional.

halve :: Num a => a -> a
halve n = n / 2  -- in here `n` really has type `exists a. Num a => a`

What we have up above with fromInteger 5 / 2 is more equivalent to the following, higher rank function, note that the forall within parenthesis is required, and you need to use -XRankNTypes:

halve :: forall b. Fractional b => (forall a. Num a => a) -> b
halve n = n / 2 -- in here `n` has type `forall a. Num a => a`

Since this time you are taking in EVERY Num type (just like the fromInteger 5 you were dealing with before), not just ANY Num type. Now the downside of this function (and one reason why no one wants it) is that you really do have to pass in something of EVERY Num type:

halve (2 :: Int) -- does not work

halve (3 :: Integer) -- does not work

halve (1 :: Double) -- does not work

halve (4 :: Num a => a) -- works!

halve (fromInteger 5) -- also works!

I hope that clears things up a little. All you need for the fromInteger 5 / 2 to work is that there exists ONE single type that is both a Num and a Fractional, or in other words just a Fractional, since Fractional implies Num. Type defaulting doesn't help much with clearing up this confusion, as what you may not realize is that GHC is just arbitrarily picking Double, it could have picked any Fractional.


答:
This is happening because every value in x1 is referencing the same basicS array. So you are pushing insert into that array four times.

To avoid this, give each item in x1 a new array:

var data = [
    {"name":"123123123123"},
    {"name":"123123123124"},
    {"name":"123123123125"},
    {"name":"123123123126"}
];
var x1 = {}

data.forEach(function(val,i){
   x1[val.name]= { "question": [] };
});

data.forEach(function(val,i){
 x1[val.name].question.push('insert');
});
console.log(x1);```
</div>
</div>
</p>

<p>Or, depending on what you're ultimately trying to do, you could just populate the arrays with their initial value instead of looping twice:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var data = [
    {"name":"123123123123"},
    {"name":"123123123124"},
    {"name":"123123123125"},
    {"name":"123123123126"}
];
var x1 = {}

data.forEach(function(val,i){
   x1[val.name] = { "question": ["insert"] };
});

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

Title: Javascript array object Output

Body:
Can anybody help me I am new to javascript. I am not able to understand the below line of code. I spend hours to debug this code but I am not able to rectify.

var data = [
    {"name":"123123123123"},
    {"name":"123123123124"},
    {"name":"123123123125"},
    {"name":"123123123126"}
];
var x1 = {}
var basicS = {
    "question":[]
}
data.forEach(function(val,i){
   x1[val.name]=basicS;
});

console.log(x1);
data.forEach(function(val,i){
 x1[val.name].question.push('insert');
});
console.log(x1);

Output:

{
 123123123123:{
    question:[
      0:"insert"
      1:"insert"
      2:"insert"
      3:"insert"
    ]
},
123123123124:{
    question:[
      0:"insert"
      1:"insert"
      2:"insert"
      3:"insert"
    ]
},
123123123125:{
    question:[
      0:"insert"
      1:"insert"
      2:"insert"
      3:"insert"
    ]
},
123123123126:{
    question:[
      0:"insert"
      1:"insert"
      2:"insert"
      3:"insert"
    ]
}
}

Expected Output should be:

{
  123123123123:{
    question:[
      0:"insert"
    ]
},
123123123124:{
    question:[
      0:"insert"
    ]
},
123123123125:{
    question:[
      0:"insert"
              ]
},
123123123126:{
    question:[
      0:"insert"
    ]
}
}

Not able to understand from where four values are inserted inside the each question array while i am inserting only  one in each question
array object.

Is there any alternative to solve this type of prblem.

Please help me out. I am totally confused. Thanks in advance.

Body:
This is happening because every value in x1 is referencing the same basicS array. So you are pushing insert into that array four times.

To avoid this, give each item in x1 a new array:

var data = [
    {"name":"123123123123"},
    {"name":"123123123124"},
    {"name":"123123123125"},
    {"name":"123123123126"}
];
var x1 = {}

data.forEach(function(val,i){
   x1[val.name]= { "question": [] };
});

data.forEach(function(val,i){
 x1[val.name].question.push('insert');
});
console.log(x1);

Or, depending on what you're ultimately trying to do, you could just populate the arrays with their initial value instead of looping twice:

var data = [
    {"name":"123123123123"},
    {"name":"123123123124"},
    {"name":"123123123125"},
    {"name":"123123123126"}
];
var x1 = {}

data.forEach(function(val,i){
   x1[val.name] = { "question": ["insert"] };
});

console.log(x1);


问:
Implementing min function in C by using typeof compiler extension gives error
When i attempted to implement min function in C as C lacks this function the compiler gives an error. I've used type of for implementing it just like this

MIN and MAX in C

My code

For quick reference:

```<code>>#define min(a,b) \
  ({ typeof (a) _a = (a); \
  typeof (b) _b = (b); \        //Min defined
  _a < _b ? _a : _b; })
  .
  .
  .
  c= min(c+floor(1.0/f), bi.biWidth) ;
  r= min(r+floor(1.0/f),abs(bi.biHeight)) ;
</code>```

Error generated:

```<code> >make resize
 clang -fsanitize=integer -fsanitize=undefined -ggdb3 -O0 -std=c11 -Wall
 -Werror -Wextra -Wno-sign-compare -Wshadow    resize.c  -lcrypt -lcs50
 -lm  -o resize

resize.c:191:18: error: implicit declaration of function 'typeof' is
invalid in C99 [-Werror,-Wimplicit-function-declaration]
          c= min(c+floor(1.0/f), bi.biWidth) ;
             ^
resize.c:11:6: note: expanded from macro 'min'
({ typeof (a) _a = (a); \
 ^
 resize.c:191:18: error: expected ';' after expression
 resize.c:11:17: note: expanded from macro 'min'
 ({ typeof (a) _a = (a); \
            ^

 resize.c:191:18: error: use of undeclared identifier '_a'

 resize.c:11:17: note: expanded from macro 'min'
 ({ typeof (a) _a = (a); \
            ^

 resize.c:191:18: error: expected ';' after expression

 resize.c:12:18: note: expanded from macro 'min'
  typeof (b) _b = (b); \

                  ^

 resize.c:191:18: error: use of undeclared identifier '_b'

 resize.c:12:18: note: expanded from macro 'min'
  typeof (b) _b = (b); \
             ^

 resize.c:191:18: error: use of undeclared identifier '_a'

 resize.c:13:5: note: expanded from macro 'min'
 _a < _b ? _a : _b; })
 ^

 resize.c:191:18: error: use of undeclared identifier '_b'

 resize.c:13:10: note: expanded from macro 'min'
 _a < _b ? _a : _b; })
     ^

 resize.c:191:18: error: use of undeclared identifier '_b'

 resize.c:13:20: note: expanded from macro 'min'
 _a < _b ? _a : _b; })
               ^

 resize.c:193:13: error: expected ';' after expression
     r= min(r+floor(1.0/f),abs(bi.biHeight)) ;
        ^

 resize.c:11:17: note: expanded from macro 'min'
  ({ typeof (a) _a = (a); \
            ^

 resize.c:193:13: error: use of undeclared identifier '_a'

 resize.c:11:17: note: expanded from macro 'min'
 ({ typeof (a) _a = (a); \
            ^

 resize.c:193:13: error: expected ';' after expression

 resize.c:12:18: note: expanded from macro 'min'
  typeof (b) _b = (b); \
             ^

 resize.c:193:13: error: use of undeclared identifier '_b'

 resize.c:12:18: note: expanded from macro 'min'
  typeof (b) _b = (b); \
             ^

 resize.c:193:13: error: use of undeclared identifier '_a'

 resize.c:13:5: note: expanded from macro 'min'
 _a < _b ? _a : _b; })
 ^

 resize.c:193:13: error: use of undeclared identifier '_b'

 resize.c:13:10: note: expanded from macro 'min'
 _a < _b ? _a : _b; })
     ^

 resize.c:193:13: error: use of undeclared identifier '_b'

 resize.c:13:20: note: expanded from macro 'min'
 _a < _b ? _a : _b; })
               ^

 15 errors generated.
</code>```

答:
It should be:

```<code>#define min(a,b) \
   ({ __typeof__ (a) _a = (a); \
      __typeof__ (b) _b = (b); // Min defined \
      _a < _b ? _a : _b; })
</code>```

Your comment should not be after the \ but before it.
Also you write typeof without the underscores. It is recommended to use them, the explanation is given here at SO.

typeof(), __typeof__() and __typeof() are compiler-specific extensions to the C language, because standard C does not include such an operator.

Macro without typeof:

If your compiler does not support the typeof "operator", you could define the min macro without typeof:

```<code>#define min(a,b) (((a) < (b)) ? (a) : (b))
</code>```

But with that you will have side effects when using postfix or prefix in/decrement operators on variables, because a double evaluation will occur.

Inline function:

The other possibility to make it safe is an inline function. It will be typesafe and no double evaluation will happen:

```<code>inline int min(int a, int b)
{
   if (a < b)
   {
      return a;
   }
   return b;
}
</code>```

You loose type genericity, but there is no other way. You could also think of using double since integers will be implicitly casted. But remember the loose of precision.

Body:
When i attempted to implement min function in C as C lacks this function the compiler gives an error. I've used type of for implementing it just like this

MIN and MAX in C

My code

For quick reference:

>#define min(a,b) \
  ({ typeof (a) _a = (a); \
  typeof (b) _b = (b); \        //Min defined
  _a < _b ? _a : _b; })
  .
  .
  .
  c= min(c+floor(1.0/f), bi.biWidth) ;
  r= min(r+floor(1.0/f),abs(bi.biHeight)) ;

Error generated:

 >make resize
 clang -fsanitize=integer -fsanitize=undefined -ggdb3 -O0 -std=c11 -Wall
 -Werror -Wextra -Wno-sign-compare -Wshadow    resize.c  -lcrypt -lcs50
 -lm  -o resize

resize.c:191:18: error: implicit declaration of function 'typeof' is
invalid in C99 [-Werror,-Wimplicit-function-declaration]
          c= min(c+floor(1.0/f), bi.biWidth) ;
             ^
resize.c:11:6: note: expanded from macro 'min'
({ typeof (a) _a = (a); \
 ^
 resize.c:191:18: error: expected ';' after expression
 resize.c:11:17: note: expanded from macro 'min'
 ({ typeof (a) _a = (a); \
            ^

 resize.c:191:18: error: use of undeclared identifier '_a'

 resize.c:11:17: note: expanded from macro 'min'
 ({ typeof (a) _a = (a); \
            ^

 resize.c:191:18: error: expected ';' after expression

 resize.c:12:18: note: expanded from macro 'min'
  typeof (b) _b = (b); \

                  ^

 resize.c:191:18: error: use of undeclared identifier '_b'

 resize.c:12:18: note: expanded from macro 'min'
  typeof (b) _b = (b); \
             ^

 resize.c:191:18: error: use of undeclared identifier '_a'

 resize.c:13:5: note: expanded from macro 'min'
 _a < _b ? _a : _b; })
 ^

 resize.c:191:18: error: use of undeclared identifier '_b'

 resize.c:13:10: note: expanded from macro 'min'
 _a < _b ? _a : _b; })
     ^

 resize.c:191:18: error: use of undeclared identifier '_b'

 resize.c:13:20: note: expanded from macro 'min'
 _a < _b ? _a : _b; })
               ^

 resize.c:193:13: error: expected ';' after expression
     r= min(r+floor(1.0/f),abs(bi.biHeight)) ;
        ^

 resize.c:11:17: note: expanded from macro 'min'
  ({ typeof (a) _a = (a); \
            ^

 resize.c:193:13: error: use of undeclared identifier '_a'

 resize.c:11:17: note: expanded from macro 'min'
 ({ typeof (a) _a = (a); \
            ^

 resize.c:193:13: error: expected ';' after expression

 resize.c:12:18: note: expanded from macro 'min'
  typeof (b) _b = (b); \
             ^

 resize.c:193:13: error: use of undeclared identifier '_b'

 resize.c:12:18: note: expanded from macro 'min'
  typeof (b) _b = (b); \
             ^

 resize.c:193:13: error: use of undeclared identifier '_a'

 resize.c:13:5: note: expanded from macro 'min'
 _a < _b ? _a : _b; })
 ^

 resize.c:193:13: error: use of undeclared identifier '_b'

 resize.c:13:10: note: expanded from macro 'min'
 _a < _b ? _a : _b; })
     ^

 resize.c:193:13: error: use of undeclared identifier '_b'

 resize.c:13:20: note: expanded from macro 'min'
 _a < _b ? _a : _b; })
               ^

 15 errors generated.

Body:
It should be:

#define min(a,b) \
   ({ __typeof__ (a) _a = (a); \
      __typeof__ (b) _b = (b); // Min defined \
      _a < _b ? _a : _b; })

Your comment should not be after the \ but before it.
Also you write typeof without the underscores. It is recommended to use them, the explanation is given here at SO.

typeof(), __typeof__() and __typeof() are compiler-specific extensions to the C language, because standard C does not include such an operator.

Macro without typeof:

If your compiler does not support the typeof "operator", you could define the min macro without typeof:

#define min(a,b) (((a) < (b)) ? (a) : (b))

But with that you will have side effects when using postfix or prefix in/decrement operators on variables, because a double evaluation will occur.

Inline function:

The other possibility to make it safe is an inline function. It will be typesafe and no double evaluation will happen:

inline int min(int a, int b)
{
   if (a < b)
   {
      return a;
   }
   return b;
}

You loose type genericity, but there is no other way. You could also think of using double since integers will be implicitly casted. But remember the loose of precision.


问:
CSS spin button cross browser, work for Chrome but not for firefox/safari
I have this spin up/down button works perfectly in Google Chrome(mac os), but when I open it with Safari it is a little off the grid, and in Firefox it is completely disappeared.

Could anyone help with the CSS? Thanks for any help

Chrome (CSS working really well):

Safari (kind off from the input field):

Firefox (not showing at all?):

/* style input number spinner */

input[type="number"] {
  position: relative;
  height: 25px;
}

/* Spin Buttons modified */

input[type="number"]::-webkit-outer-spin-button,
input[type="number"]::-webkit-inner-spin-button {
  -webkit-appearance: none;
  background: #FFF url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAJCAYAAADgkQYQAAAAKUlEQVQYlWNgwAT/sYhhKPiPT+F/LJgEsHv37v+EMGkmkuImoh2NoQAANlcun/q4OoYAAAAASUVORK5CYII=) no-repeat center center;
  width: 1em;
  border-left: 1px solid #BBB;
  opacity: 0.7;
  /* shows Spin Buttons per default (Chrome >= 39) */
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
}

input[type="number"]::-webkit-inner-spin-button:hover,
input[type="number"]::-webkit-inner-spin-button:active {
  box-shadow: 0 0 2px #0CF;
  opacity: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  <td><input type="number" min="0.001" step="0.001" name="price" value="" required=""></td>
</form></code>```

答:
As per , MDN This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

Still you can do something like this for FireFox (this won't work for chrome):

div:before, div:after {
    display: block;
    position: absolute;
    width: 14px;
    height: 8px;
    line-height: 8px;
    background-color: #ccc;
    left: 136px;
    z-index: 1;
    font-size: 9px;
    text-align: center;
    pointer-events: none;
}

div:before {
    content: "▲ ";
    top: 11px;
}

div:after {
    content: "▼";
    top: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div><input type="number" value="55" min="0" max="100" step="5" /></div></code>```

Hope this helps!

Body:
I have this spin up/down button works perfectly in Google Chrome(mac os), but when I open it with Safari it is a little off the grid, and in Firefox it is completely disappeared.

Could anyone help with the CSS? Thanks for any help

Chrome (CSS working really well):

Safari (kind off from the input field):

Firefox (not showing at all?):

/* style input number spinner */

input[type="number"] {
  position: relative;
  height: 25px;
}

/* Spin Buttons modified */

input[type="number"]::-webkit-outer-spin-button,
input[type="number"]::-webkit-inner-spin-button {
  -webkit-appearance: none;
  background: #FFF url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAJCAYAAADgkQYQAAAAKUlEQVQYlWNgwAT/sYhhKPiPT+F/LJgEsHv37v+EMGkmkuImoh2NoQAANlcun/q4OoYAAAAASUVORK5CYII=) no-repeat center center;
  width: 1em;
  border-left: 1px solid #BBB;
  opacity: 0.7;
  /* shows Spin Buttons per default (Chrome >= 39) */
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
}

input[type="number"]::-webkit-inner-spin-button:hover,
input[type="number"]::-webkit-inner-spin-button:active {
  box-shadow: 0 0 2px #0CF;
  opacity: 1;
}

<form>
  <input type="number" min="0.001" step="0.001" name="price" value="" required="">
</form>

Body:
As per , MDN This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

Still you can do something like this for FireFox (this won't work for chrome):

div:before, div:after {
    display: block;
    position: absolute;
    width: 14px;
    height: 8px;
    line-height: 8px;
    background-color: #ccc;
    left: 136px;
    z-index: 1;
    font-size: 9px;
    text-align: center;
    pointer-events: none;
}

div:before {
    content: "▲ ";
    top: 11px;
}

div:after {
    content: "▼";
    top: 20px;
}

<div><input type="number" value="55" min="0" max="100" step="5" /></div>

Hope this helps!


问:
Are there any naming convention guidelines for REST APIs?
When creating REST APIs, are there any guidelines or defacto standards for naming conventions within the API (eg: URL endpoint path components, querystring parameters)?  Are camel caps the norm, or underscores? others?

For example:

```<code>api.service.com/helloWorld/userId/x
</code>```

or

```<code>api.service.com/hello_world/user_id/x
</code>```

Note: This is not a question of RESTful API design, rather the naming convention guidelines to use for the eventual path components and/or query string parameters used.

Any guidelines would be appreciated.

答:
If you authenticate your clients with Oauth2 I think you will need underscore for at least two of your parameter names:

client_id

client_secret

I have used camelCase in my (not yet published) REST API. While writing the API documentation I have been thinking of changing everything to snake_case so I don't have to explain why the Oauth params are snake_case while other params are not.

See: https://www.rfc-editor.org/rfc/rfc6749

Body:
When creating REST APIs, are there any guidelines or defacto standards for naming conventions within the API (eg: URL endpoint path components, querystring parameters)?  Are camel caps the norm, or underscores? others?

For example:

api.service.com/helloWorld/userId/x

or

api.service.com/hello_world/user_id/x

Note: This is not a question of RESTful API design, rather the naming convention guidelines to use for the eventual path components and/or query string parameters used.

Any guidelines would be appreciated.


问:
How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'
I'm using Bootstrap V4 and the following error is logged in the console;

Error: Bootstrap tooltips require Tether
  (http://github.hubspot.com/tether/)

I have tried to remove the error by installing Tether but it hasn't worked. I have 'installed' Tether by including the following lines of code;

```<code><link rel="stylesheet" href="http://www.atlasestateagents.co.uk/css/tether.min.css">
<script src="http://www.atlasestateagents.co.uk/javascript/tether.min.js"></script>
</code>```

Have I 'installed' tether correctly?

Can anyone help me remove this error?

If you wish to view the error on my site, please click here and load your console.

答:
Method #1: Download from Here and insert it to your projects, or
 Method #2: use below code before your bootstrap script source:

```<code><script src="https://npmcdn.com/tether@1.2.4/dist/js/tether.min.js"></script>
</code>```

Body:
I'm using Bootstrap V4 and the following error is logged in the console;

Error: Bootstrap tooltips require Tether
  (http://github.hubspot.com/tether/)

I have tried to remove the error by installing Tether but it hasn't worked. I have 'installed' Tether by including the following lines of code;

<link rel="stylesheet" href="http://www.atlasestateagents.co.uk/css/tether.min.css">

Have I 'installed' tether correctly?

Can anyone help me remove this error?

If you wish to view the error on my site, please click here and load your console.

Body:
Method #1: Download from Here and insert it to your projects, or
 Method #2: use below code before your bootstrap script source:

<script src="https://npmcdn.com/tether@1.2.4/dist/js/tether.min.js"></script>


问:
I am having trouble in reading date and time from an excel sheet using python
```<code>import xlwt
import xlrd, xlutils

wb = xlwt.Workbook()
outsheet = wb.add_sheet('Page 1')

files = [r'c:\file1', r'C:c:\file2',]

outrow = 0

for f in files:

insheet = xlrd.open_workbook(f,formatting_info=True).sheets()[0]
for row in range(insheet.nrows):
    for col in range(insheet.ncols):
        outsheet.write(outrow, col,insheet.cell_value(row, col))
    outrow += 1
wb.save(r'C:\combined.xls')
</code>```

i get output as

42753.61492

42753.61492

42753.61492

42753.61492

42753.61492

where i was looking something as this

                        2017-01-18 14:45:29 a

2017-01-18 14:45:29 a

2017-01-18 14:45:29 a

2017-01-18 14:45:29 a

2017-01-20 09:10:06 a

答:
```<code>>>> import datetime
>>> datetime.datetime(1899,12,30) + datetime.timedelta(days=42753.61492)
datetime.datetime(2017, 1, 18, 14, 45, 29, 88000)
</code>```

Body:
import xlwt
import xlrd, xlutils

wb = xlwt.Workbook()
outsheet = wb.add_sheet('Page 1')

files = [r'c:\file1', r'C:c:\file2',]

outrow = 0

for f in files:

insheet = xlrd.open_workbook(f,formatting_info=True).sheets()[0]
for row in range(insheet.nrows):
    for col in range(insheet.ncols):
        outsheet.write(outrow, col,insheet.cell_value(row, col))
    outrow += 1
wb.save(r'C:\combined.xls')

i get output as

42753.61492

42753.61492

42753.61492

42753.61492

42753.61492

where i was looking something as this

                        2017-01-18 14:45:29 a

2017-01-18 14:45:29 a

2017-01-18 14:45:29 a

2017-01-18 14:45:29 a

2017-01-20 09:10:06 a


问:
ExecutorService shutdown other threads when one of them returns not null
I have like 20 threads. Each of the threads just makes findOne query to MongoDB:

```<code>db.myCollection.findOne({"queryKey" : "queryValue"})
</code>```

So findOne is going to return either null of found document.

Whenever one of the threads returns found document instead of null, I want to shutdown other threads.

Is there any way to do this?

I tried using invokeAny in ExecutorService. But it's returning the result of one that has completed successfully. In my case successful  case is when findOne returns found document instead of null.

Note: My real example is more complicated than just findOne( that's why I'm using multithreading, instead of just sequential calls)

答: As per the definition of invokeAny, the first successful result is returned. To make this work in your use-case wrap findOne and throw an exception if it is null, making it non-successful.

Body:
I have like 20 threads. Each of the threads just makes findOne query to MongoDB:

db.myCollection.findOne({"queryKey" : "queryValue"})

So findOne is going to return either null of found document.

Whenever one of the threads returns found document instead of null, I want to shutdown other threads.

Is there any way to do this?

I tried using invokeAny in ExecutorService. But it's returning the result of one that has completed successfully. In my case successful  case is when findOne returns found document instead of null.

Note: My real example is more complicated than just findOne( that's why I'm using multithreading, instead of just sequential calls)


问:
implementing an abstract base class function in another template base class
I have a Visual Studio 2008 C++ project where I have a class that inherits from an abstract base class and another template class that implements a function in the abstract base class. For example:

```<code>class Foo;

struct Buzz
{
    virtual ~Buzz() {};
    virtual void Buzz_Do( Foo* ) = 0;
};

class Base
{
public:
    virtual ~Base() {};
    virtual void Base_Do( Buzz* ) = 0;
};

template< class T >
class Bar
{
public:
    virtual void Base_Do( Buzz* v )
    {
        v->Buzz_Do( static_cast< T* >( this ) );
    };
};

class Foo : public Base, public Bar< Foo >
{
};

int _tmain(int argc, _TCHAR* argv[])
{
    Foo c;
    return 0;
}
</code>```

Unfortunately, this yields the compiler error:

```<code>1>MyApp.cpp(39) : error C2259: 'Foo' : cannot instantiate abstract class
1>        due to following members:
1>        'void Base::Base_Do(Buzz *)' : is abstract
1>        MyApp.cpp(17) : see declaration of 'Base::Base_Do'
</code>```

I've tried adding a public using Bar< Foo >::Base_Do; to class Foo, but that did not help.

Is there a way to make this work or will I need to put a concrete Base_Do() implementation in Foo and not use Bar<>?

Thanks,
PaulH

答:
There is no way to cause a function defined in one base to override a function by the same name in another base when those bases are unrelated.  It doesn't work that way.  You either have to have your template base inherit from the abstract base, or write the function in your derived class to call the function in your non-abstract base.

Which you do depends greatly upon your problem.  I generally prefer the former but have run into situations where it is not possible (because the bases I need are simply not related) and use the latter.

Body:
I have a Visual Studio 2008 C++ project where I have a class that inherits from an abstract base class and another template class that implements a function in the abstract base class. For example:

class Foo;

struct Buzz
{
    virtual ~Buzz() {};
    virtual void Buzz_Do( Foo* ) = 0;
};

class Base
{
public:
    virtual ~Base() {};
    virtual void Base_Do( Buzz* ) = 0;
};

template< class T >
class Bar
{
public:
    virtual void Base_Do( Buzz* v )
    {
        v->Buzz_Do( static_cast< T* >( this ) );
    };
};

class Foo : public Base, public Bar< Foo >
{
};

int _tmain(int argc, _TCHAR* argv[])
{
    Foo c;
    return 0;
}

Unfortunately, this yields the compiler error:

1>MyApp.cpp(39) : error C2259: 'Foo' : cannot instantiate abstract class
1>        due to following members:
1>        'void Base::Base_Do(Buzz *)' : is abstract
1>        MyApp.cpp(17) : see declaration of 'Base::Base_Do'

I've tried adding a public using Bar< Foo >::Base_Do; to class Foo, but that did not help.

Is there a way to make this work or will I need to put a concrete Base_Do() implementation in Foo and not use Bar<>?

Thanks,
PaulH


问:
How to completely get rid of if-else with OOP in such a tree like structure?
Here is the psudeocode:

```<code>if (parttimeEmployee) {
    if (country == USA) {

    }
    if (country == UK {

    }
}

if (fullTimeEmployee) {
    if (country == USA) {

    }
    if (country == UK) {

    }
}
</code>```

Now,  partTime and fullTime employees can be subclassed from 'Employee' interface.

But we have another if-else repeated/replicated inside each of them for 'Country'

Which design-pattern can we use to completely replace such nested-conditions ?

答:
You can use composition, giving each employee a Country object, on which you can call a method, which would implement the correct behavior for that country, assuming the behavior is the same regardless of which subclass of Employee it is (full or part time). If you're operating on a combination of employee type and country to define the behavior, you'll have to either have the branches somewhere, or have a mess of FullTimeUSEmployee, PartTimeUSEmployee, FullTimeUKEmployee, etc and so on.

It's important to consider though if using any particular design pattern is actually improving your code; nested conditionals may be simpler and easier to work with than a big, complicated class hierarchy with composites. Personally, I'd keep the branches unless there's duplicate code within them, and if there is, move the duplicate code to a function/method so it can be reused - but I tend to care more about DRY than cyclomatic complexity.

Body:
Here is the psudeocode:

if (parttimeEmployee) {
    if (country == USA) {

    }
    if (country == UK {

    }
}

if (fullTimeEmployee) {
    if (country == USA) {

    }
    if (country == UK) {

    }
}

Now,  partTime and fullTime employees can be subclassed from 'Employee' interface.

But we have another if-else repeated/replicated inside each of them for 'Country'

Which design-pattern can we use to completely replace such nested-conditions ?