问:
Getting input from form to use in JSON
So, I am pretty new when it comes to messing with JSON, AJAX and that kind of stuff...
I have this one assignment which I am supposed to have 4 input fields: "Start city", "Start state", "Destination city" and "Destination state".
It is basically supposed to get the distance between city A to city B. It was given a file with the information behind that, the thing I need to do is get the inputs, and get the data from the file if that makes sense.

I thought about having a javascript function something like this:

```<code>function getData()
{
    var xhttpData = new XMLHttpRequest();
    var url = "http://localhost/cgi-
        bin/ercanbracks/mileage/mileageAjaxJSON";

    xhttpData.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            var parseData = this.responseText;
            console.log(parseData);
            var trip = parseData.trip;
            document.getElementsByName("startCity")[0].value =
                trip.startcity;
            document.getElementsByName("startState")[0].value =
                trip.startstate;
            document.getElementsByName("endCity")[0].value =  trip.endcity;
            document.getElementsByName("endState")[0].value =
                trip.endstate;

            document.getElementById("demo").innerHTML =  trip.startcity + ",
                " + trip.startstate + ", " + trip.miles + " miles to " +
                trip.endcity + ", " + trip.endstate + ".";
        }
    };

    xhttpData.open("GET", url, true);
    xhttpData.send();
}
document.addEventListener("DOMContentLoaded", function(event) { getData();
});
</code>```

Here is the form:

```<code><!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript"
            src="http://localhost/~arthurfig/week11.js"></script>
        <title></title>

    </head>
    <body>
        <form action="" onsubmit="getData()">
            <p>Start City: </p>
            <input type="text" name="startCity">
            <p>Start State: </p>
            <input type="text" name="startState">
            <p>Destination City: </p>
            <input type="text" name="endCity">
            <p>Destination State: </p>
            <input type="text" name="endState">
            <input type="submit" value="Check">
        </form>
        <p id="demo"></p>
    </body>
</html>
</code>```

And here is what is in the file:

```<code>{"trip" :
  { "startcity" : "",
    "startstate" : "",
    "endcity" : "",
    "endstate" : "",
    "miles" : "Unknown"
  }
}
</code>```

My problem is that I'm not sure how to get the value of the text fields from the form to set as the value of the variables and make it get the distance(miles) using these values.

答:
```<code>    function getData(){
var city=document.getElementById("startCity").value;
var State=document.getElementById("startState").value;
var endCity=document.getElementById("endCity").value;
var endState=document.getElementById("endState").value;
console.log(city);
var s=   document.getElementById("demo").innerHTML = endState;
}
First you get value from form like this or you can serialize the form , then you emebed your logic
</code>```

Title: Getting input from form to use in JSON

Body:
So, I am pretty new when it comes to messing with JSON, AJAX and that kind of stuff...
I have this one assignment which I am supposed to have 4 input fields: "Start city", "Start state", "Destination city" and "Destination state".
It is basically supposed to get the distance between city A to city B. It was given a file with the information behind that, the thing I need to do is get the inputs, and get the data from the file if that makes sense.

I thought about having a javascript function something like this:

function getData()
{
    var xhttpData = new XMLHttpRequest();
    var url = "http://localhost/cgi-
        bin/ercanbracks/mileage/mileageAjaxJSON";

    xhttpData.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            var parseData = this.responseText;
            console.log(parseData);
            var trip = parseData.trip;
            document.getElementsByName("startCity")[0].value =
                trip.startcity;
            document.getElementsByName("startState")[0].value =
                trip.startstate;
            document.getElementsByName("endCity")[0].value =  trip.endcity;
            document.getElementsByName("endState")[0].value =
                trip.endstate;

            document.getElementById("demo").innerHTML =  trip.startcity + ",
                " + trip.startstate + ", " + trip.miles + " miles to " +
                trip.endcity + ", " + trip.endstate + ".";
        }
    };

    xhttpData.open("GET", url, true);
    xhttpData.send();
}
document.addEventListener("DOMContentLoaded", function(event) { getData();
});

Here is the form:

<!DOCTYPE html>

        <title></title>

        <form action="" onsubmit="getData()">

Start City:

            <input type="text" name="startCity">

Start State:

            <input type="text" name="startState">

Destination City:

            <input type="text" name="endCity">

Destination State:

            <input type="text" name="endState">
            <input type="submit" value="Check">
        </form>

And here is what is in the file:

{"trip" :
  { "startcity" : "",
    "startstate" : "",
    "endcity" : "",
    "endstate" : "",
    "miles" : "Unknown"
  }
}

My problem is that I'm not sure how to get the value of the text fields from the form to set as the value of the variables and make it get the distance(miles) using these values.


来源: stackexchange

问:
Insert unique values in Array in Javascript
I have one array. The function gets called continuously from backend service.
I want to push unique values in one object. My code is

```<code>currentValue =  pointerToVisconCtrl.MappedVariableObj.value;
var seconds = new Date().getSeconds();
seconds = parseInt(seconds);
graphDataObject.push({timestamp : seconds, value : currentValue});
</code>```

Please guide me to enter only unique currentValue and seconds value in graphDataObject

答:
you can use filter function in the javascript array like below to check if a particular object exists or not:</p>

```<code>var dataObject = graphDataObject.filter(function(el){
      return el.timestamp == seconds && el.value == currentValue; //you can check only one object if you want here
 });
if(dataObject.length > 0)
{
  //the object exists in the array
}
else{
 graphDataObject.push({timestamp : seconds, value : currentValue}); //push object to the array.
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have one array. The function gets called continuously from backend service.
I want to push unique values in one object. My code is

currentValue =  pointerToVisconCtrl.MappedVariableObj.value;
var seconds = new Date().getSeconds();
seconds = parseInt(seconds);
graphDataObject.push({timestamp : seconds, value : currentValue});

Please guide me to enter only unique currentValue and seconds value in graphDataObject

Body:
you can use filter function in the javascript array like below to check if a particular object exists or not:

var dataObject = graphDataObject.filter(function(el){
      return el.timestamp == seconds && el.value == currentValue; //you can check only one object if you want here
 });
if(dataObject.length > 0)
{
  //the object exists in the array
}
else{
 graphDataObject.push({timestamp : seconds, value : currentValue}); //push object to the array.
}


问:
Django IntegrityError null value in column "author_id" violates not-null constraint
I am trying to save a form where I take user inputs. I am getting Integrity error. Can anyone please help me out here? I see that people have used request.user.username but I don't see how to use this in my forms. Please don't mind the code as I am still trying to figure out things in Django.

Below are my files:

```<code>models.py

class CommonModel(models.Model):

    author = models.ForeignKey('auth.User')
    title = models.CharField(max_length=400)
    comments = models.TextField(blank=True)
    requirements = JSONField(default = {})
    specs = JSONField(default= {})
    created_date = models.DateTimeField(default=timezone.now)
    updated_date = models.DateTimeField(blank=True, null=True)

    class Meta:
       abstract = True

    def update(self):
        self.updated_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

class Item(CommonModel):

    HW = 'HW'
    NW = 'NW'
    SW = 'SW'
    VM = 'VM'
    WI = 'WI'
    SI = 'SI'
    ITEM_TYPES = (
        (HW, 'Hardware'),
        (NW, 'Network'),
        (SW, 'Software'),
        (VM, 'Virtual Machine'),
        (WI, 'Work Item'),
        (SI, 'Support Item'),
    )

    UNIT_LOE = 'LOE'
    UNIT_USD = 'USD'
    UNIT_TYPES = (
        (UNIT_LOE, 'LOE,MD'),
        (UNIT_USD, 'USD'),
    )

    item_type = models.CharField(default='HW', max_length=5, choices=ITEM_TYPES)
    unit_type = models.CharField(default='USD', max_length=5, choices=UNIT_TYPES)
    otc_price = models.DecimalField(default='0.0', max_digits=10, decimal_places=2)
    annual_price = models.DecimalField(default='0.0', max_digits=10, decimal_places=2)
    gp_code = models.TextField(default='Unknown')
    class Meta:
       abstract = True

class ItemTemplate(Item):
    pass
   # Need ID here to relate to estimate

class ItemObject(Item):
    pass
</code>```

Here is my admin.py

```<code>class CommonAdmin(admin.ModelAdmin):

    formfield_overrides = {
        JSONField:{ 'widget':JSONEditor },
    }

    def otc_price(self,obj):
        return json_prettified(obj.otc_price)
    def annual_price(self,obj):
        return json_prettified(obj.annual_price)

from reversion.admin import VersionAdmin

@admin.register(ItemTemplate)
class ItemTemplateAdmin(VersionAdmin):
     list_display = ('title', 'item_type', 'unit_type', 'otc_price','annual_price')
     formfield_overrides = {
        JSONField:{ 'widget':JSONEditor },
     }

@admin.register(ItemObject)
class ItemObjectAdmin(VersionAdmin):
     list_display = ('title', 'item_type', 'unit_type', 'otc_price','annual_price')
     formfield_overrides = {
        JSONField:{ 'widget':JSONEditor },
     }
</code>```

And finally the views.py.

```<code>def order_create(request):
        cart = ItemObject.objects.all()

        if request.method == 'POST':
            form = ItemObjectCreateForm(request.POST)
            if form.is_valid():
                form.save()
                for item in cart:
                    annual_price = 122
                    otc_price=100
                    # Logic to calculate the price and put it in estimate table
                    ItemObject.objects.create(
                                             requirements=item.requirements,
                                             specs=item.specs,
                                             annual_price = annual_price,

                    )
                # clear the cart
                #cart.clear()
                order_created()
                # redirect to the payment
                return redirect('success.html')

        else:
            form = ItemObjectCreateForm()
        return render(request,
                      'index.html',
                      {'cart': cart, 'form': form})
</code>```

Here I am trying to store data to ItemObject but while submitting the form, I am getting error.

```<code>IntegrityError: null value in column "author_id" violates not-null constraint
DETAIL:  Failing row contains
</code>```

Also my forms.py is like below

```<code>class ItemObjectCreateForm(forms.ModelForm):
    class Meta:
        model = ItemObject
        fields = ['title','requirements', 'gp_code', 'specs','author', 'item_type', 'unit_type','comments', 'id'
                  ]
</code>```

Attaching DB

答:
In your definition of CommonModel you've required that author not be null. Is that correct? Must every instance of CommonModel have an author? If not, you can alter the definition to allow null values:

```<code>author = models.ForeignKey('auth.User', default=None, null=True, blank=True)
</code>```

Body:
I am trying to save a form where I take user inputs. I am getting Integrity error. Can anyone please help me out here? I see that people have used request.user.username but I don't see how to use this in my forms. Please don't mind the code as I am still trying to figure out things in Django.

Below are my files:

models.py

class CommonModel(models.Model):

    author = models.ForeignKey('auth.User')
    title = models.CharField(max_length=400)
    comments = models.TextField(blank=True)
    requirements = JSONField(default = {})
    specs = JSONField(default= {})
    created_date = models.DateTimeField(default=timezone.now)
    updated_date = models.DateTimeField(blank=True, null=True)

    class Meta:
       abstract = True

    def update(self):
        self.updated_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

class Item(CommonModel):

    HW = 'HW'
    NW = 'NW'
    SW = 'SW'
    VM = 'VM'
    WI = 'WI'
    SI = 'SI'
    ITEM_TYPES = (
        (HW, 'Hardware'),
        (NW, 'Network'),
        (SW, 'Software'),
        (VM, 'Virtual Machine'),
        (WI, 'Work Item'),
        (SI, 'Support Item'),
    )

    UNIT_LOE = 'LOE'
    UNIT_USD = 'USD'
    UNIT_TYPES = (
        (UNIT_LOE, 'LOE,MD'),
        (UNIT_USD, 'USD'),
    )

    item_type = models.CharField(default='HW', max_length=5, choices=ITEM_TYPES)
    unit_type = models.CharField(default='USD', max_length=5, choices=UNIT_TYPES)
    otc_price = models.DecimalField(default='0.0', max_digits=10, decimal_places=2)
    annual_price = models.DecimalField(default='0.0', max_digits=10, decimal_places=2)
    gp_code = models.TextField(default='Unknown')
    class Meta:
       abstract = True

class ItemTemplate(Item):
    pass
   # Need ID here to relate to estimate

class ItemObject(Item):
    pass

Here is my admin.py

class CommonAdmin(admin.ModelAdmin):

    formfield_overrides = {
        JSONField:{ 'widget':JSONEditor },
    }

    def otc_price(self,obj):
        return json_prettified(obj.otc_price)
    def annual_price(self,obj):
        return json_prettified(obj.annual_price)

from reversion.admin import VersionAdmin

@admin.register(ItemTemplate)
class ItemTemplateAdmin(VersionAdmin):
     list_display = ('title', 'item_type', 'unit_type', 'otc_price','annual_price')
     formfield_overrides = {
        JSONField:{ 'widget':JSONEditor },
     }

@admin.register(ItemObject)
class ItemObjectAdmin(VersionAdmin):
     list_display = ('title', 'item_type', 'unit_type', 'otc_price','annual_price')
     formfield_overrides = {
        JSONField:{ 'widget':JSONEditor },
     }

And finally the views.py.

def order_create(request):
        cart = ItemObject.objects.all()

        if request.method == 'POST':
            form = ItemObjectCreateForm(request.POST)
            if form.is_valid():
                form.save()
                for item in cart:
                    annual_price = 122
                    otc_price=100
                    # Logic to calculate the price and put it in estimate table
                    ItemObject.objects.create(
                                             requirements=item.requirements,
                                             specs=item.specs,
                                             annual_price = annual_price,

                    )
                # clear the cart
                #cart.clear()
                order_created()
                # redirect to the payment
                return redirect('success.html')

        else:
            form = ItemObjectCreateForm()
        return render(request,
                      'index.html',
                      {'cart': cart, 'form': form})

Here I am trying to store data to ItemObject but while submitting the form, I am getting error.

IntegrityError: null value in column "author_id" violates not-null constraint
DETAIL:  Failing row contains

Also my forms.py is like below

class ItemObjectCreateForm(forms.ModelForm):
    class Meta:
        model = ItemObject
        fields = ['title','requirements', 'gp_code', 'specs','author', 'item_type', 'unit_type','comments', 'id'
                  ]

Attaching DB

Body:
In your definition of CommonModel you've required that author not be null. Is that correct? Must every instance of CommonModel have an author? If not, you can alter the definition to allow null values:

author = models.ForeignKey('auth.User', default=None, null=True, blank=True)


问:
count the number of negatives in an array using recursion?
I have written a code which counts negative numbers in an array and now need to write the same code using the recursion technique. I am new to recursion so I'm not sure if i am on the right track with this code.

```<code>public int countNeg (int[ ] nums, int n)
{
    int neg = 0;
    for (int index = 0; index < n; index ++)
        if (nums[index] < 0)
            neg++;
    return neg;
}
</code>```

for the recursive code, this is what i did:

```<code>public int countNeg (int[ ] nums, int n)
{
     if (n < 0)
         return 0;
     else {
         int neg = countNeg (nums, n-1);
         if (nums[n-1] < 0)
             return neg + 1;
         else
             return neg;
      }
}
</code>```

答:
@Bilghen's answer already provides the required solution.

I will however offer a solution which uses Tail Recursion technique.

```<code>public int countNeg (int[ ] nums, int index) {
  return countNegTailRecur(nums, index, 0);
}

public int countNegTailRecur (int[ ] nums, int index, int total) {
  if(index >= nums.length)
    return total;
  else
    return countNeg(nums, index+1, nums[index] < 0 ? total + 1 : total);
}
</code>```

Call it like so -

```<code>int numberOfNegativeNumbers = countNeg(nums, 0);
</code>```

Body:
I have written a code which counts negative numbers in an array and now need to write the same code using the recursion technique. I am new to recursion so I'm not sure if i am on the right track with this code.

public int countNeg (int[ ] nums, int n)
{
    int neg = 0;
    for (int index = 0; index < n; index ++)
        if (nums[index] < 0)
            neg++;
    return neg;
}

for the recursive code, this is what i did:

public int countNeg (int[ ] nums, int n)
{
     if (n < 0)
         return 0;
     else {
         int neg = countNeg (nums, n-1);
         if (nums[n-1] < 0)
             return neg + 1;
         else
             return neg;
      }
}

Body:
@Bilghen's answer already provides the required solution.

I will however offer a solution which uses Tail Recursion technique.

public int countNeg (int[ ] nums, int index) {
  return countNegTailRecur(nums, index, 0);
}

public int countNegTailRecur (int[ ] nums, int index, int total) {
  if(index >= nums.length)
    return total;
  else
    return countNeg(nums, index+1, nums[index] < 0 ? total + 1 : total);
}

Call it like so -

int numberOfNegativeNumbers = countNeg(nums, 0);


问:
View will not rotate
I have 2 views in my uiwindow which we will call view A and view B,

if I have view A on top view B and rotate the phone view A will not rotate unless i remove view B. Is there a way for the willrotate method to get called in view A without having to remove view B from the UIWINDOW?

Thanks.

答:
Ok I found out that this is not possible.

http://developer.apple.com/library/ios/#qa/qa2010/qa1688.html

ContentLicense: CC BY-SA 2.5

Title: View will not rotate


问:
Java - How to mention protocol family?
In C, protocol family is mentioned as first parameter.

For ex:

socket(AF_INET,,) for ipv4

socket(AF_PACKET,,) used for packet sniffing

Python supports three address families, AF_INET, AF_INET6 & AF_UNIX

In Java, below syntax does not allow mentioning protocol family,

```<code>ServerSocket()
ServerSocket(int port)
ServerSocket(int port, int backlog)
ServerSocket(int port, int backlog, InetAddress bindAddr)

Socket()
Socket(InetAddress address, int port)
Socket(InetAddress address, int port, InetAddress localAddr, int localPort)
Socket(Proxy proxy)
Socket(SocketImpl impl)
Socket(String host, int port)
Socket(String host, int port, InetAddress localAddr, int localPort)
</code>```

1) On which protocol family stack, does Java enable socket communication?

2) Does Java allow explicit mentioning of protocol family for socket communication?

答: Java does not support AF_UNIX or AF_PACKET at all. All the socket classes support AF_INET and AF_INET6 only, and do so automatically depending on whether an AF_INET6 stack exists or not.</p>

Title: Java - How to mention protocol family?

Body:
In C, protocol family is mentioned as first parameter.

For ex:

socket(AF_INET,,) for ipv4

socket(AF_PACKET,,) used for packet sniffing

Python supports three address families, AF_INET, AF_INET6 & AF_UNIX

In Java, below syntax does not allow mentioning protocol family,

ServerSocket()
ServerSocket(int port)
ServerSocket(int port, int backlog)
ServerSocket(int port, int backlog, InetAddress bindAddr)

Socket()
Socket(InetAddress address, int port)
Socket(InetAddress address, int port, InetAddress localAddr, int localPort)
Socket(Proxy proxy)
Socket(SocketImpl impl)
Socket(String host, int port)
Socket(String host, int port, InetAddress localAddr, int localPort)

1) On which protocol family stack, does Java enable socket communication?

2) Does Java allow explicit mentioning of protocol family for socket communication?


问:
Meteor MongoDB return single object
```<code>{
    "_id" : "R9zbu8oTWwgxT5eCR",
    "practiceSetup" : {
        "operatoriesSettings" : [
            {
                "name" : "Operatory 1",
                "description" : "Room 1",
                "status" : true
            },
                            {
                "name" : "Operatory 2",
                "description" : "Room B",
                "status" : true
            }
        ],

}
</code>```

I'm trying to lookup object that has name "Operatory 1" and only return that object.

Here is what I have tried,

```<code>Practice.findOne({ _id: 'R9zbu8oTWwgxT5eCR' }, { "$elemMatch": { "practiceSetup.operatoriesSettings": { "name": "Operatory 1" } } } );
</code>```

However this will return the whole document, not that particular object, not sure what I'm doing wrong here.

答:
You can try out this,

```<code>Practice.findOne({ _id: 'R9zbu8oTWwgxT5eCR' }).map(function(u){
        return u.practiceSetup
                .operatoriesSettings
                .filter( m => m.name == "Operatory 1");
    })
</code>```

This will return:

```<code>[
 [
    {
        "name" : "Operatory 1",
        "description" : "Room 1",
        "status" : true
    }
 ]
]
</code>```

Title: Meteor MongoDB return single object

Body:
{
    "_id" : "R9zbu8oTWwgxT5eCR",
    "practiceSetup" : {
        "operatoriesSettings" : [
            {
                "name" : "Operatory 1",
                "description" : "Room 1",
                "status" : true
            },
                            {
                "name" : "Operatory 2",
                "description" : "Room B",
                "status" : true
            }
        ],

}

I'm trying to lookup object that has name "Operatory 1" and only return that object.

Here is what I have tried,

Practice.findOne({ _id: 'R9zbu8oTWwgxT5eCR' }, { "$elemMatch": { "practiceSetup.operatoriesSettings": { "name": "Operatory 1" } } } );

However this will return the whole document, not that particular object, not sure what I'm doing wrong here.

Body:
You can try out this,

Practice.findOne({ _id: 'R9zbu8oTWwgxT5eCR' }).map(function(u){
        return u.practiceSetup
                .operatoriesSettings
                .filter( m => m.name == "Operatory 1");
    })

This will return:

[
 [
    {
        "name" : "Operatory 1",
        "description" : "Room 1",
        "status" : true
    }
 ]
]


问:
How to validate read only field in Django Rest Framework
I'm trying to add a vote functionality to the code found in tutorial of Django Rest Framework. On top of Snippet model, I added a Vote model:

```<code>class Vote(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    voter = models.ForeignKey(User, on_delete=models.CASCADE)
    snippet = models.ForeignKey(Snippet, related_name='votes', on_delete=models.CASCADE)

    class Meta:
        ordering = ('created',)
</code>```

In my serializer, I'm trying to validate the fact that user cannot vote more than once and cannot vote for his own snippet:

```<code>class VoteSerializer(serializers.HyperlinkedModelSerializer):
    voter = serializers.ReadOnlyField(source='voter.username',validators=[UniqueValidator(queryset=Vote.objects.all(), message=already_voted)])
    snippet = serializers.PrimaryKeyRelatedField(queryset=Snippet.objects.all())

    def validate(self, data):
        snippet = data.get('snippet')
        voter = data.get('voter')
        if voter==data['snippet'].owner:
            raise serializers.ValidationError(u"Voter cannot vote for himself.")
        return data
</code>```

Voter field must be read-only. Problem is that ReadOnlyField is not available in data structure. How can I validate with read only field?

EDIT: here is my view

```<code>class VoteViewSet(viewsets.ModelViewSet):
    """
    This viewset automatically provides `list`, `create`, `retrieve`,
    `update` and `destroy` actions.
    """

    queryset = Vote.objects.all()
    serializer_class = VoteSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,
                      IsOwnerOrReadOnly,)

    def perform_create(self, serializer):
        serializer.save(voter=self.request.user)
</code>```

答:
In your serializer you already have access to current user with self.context['request'].user:

so your code should be something like this:

```<code>if self.context['request'].user == data['snippet'].owner:
        raise serializers.ValidationError(u"Voter cannot vote for himself.")
</code>```

so you can remove the perform_create and use this istead

Body:
I'm trying to add a vote functionality to the code found in tutorial of Django Rest Framework. On top of Snippet model, I added a Vote model:

class Vote(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    voter = models.ForeignKey(User, on_delete=models.CASCADE)
    snippet = models.ForeignKey(Snippet, related_name='votes', on_delete=models.CASCADE)

    class Meta:
        ordering = ('created',)

In my serializer, I'm trying to validate the fact that user cannot vote more than once and cannot vote for his own snippet:

class VoteSerializer(serializers.HyperlinkedModelSerializer):
    voter = serializers.ReadOnlyField(source='voter.username',validators=[UniqueValidator(queryset=Vote.objects.all(), message=already_voted)])
    snippet = serializers.PrimaryKeyRelatedField(queryset=Snippet.objects.all())

    def validate(self, data):
        snippet = data.get('snippet')
        voter = data.get('voter')
        if voter==data['snippet'].owner:
            raise serializers.ValidationError(u"Voter cannot vote for himself.")
        return data

Voter field must be read-only. Problem is that ReadOnlyField is not available in data structure. How can I validate with read only field?

EDIT: here is my view

class VoteViewSet(viewsets.ModelViewSet):
    """
    This viewset automatically provides `list`, `create`, `retrieve`,
    `update` and `destroy` actions.
    """

    queryset = Vote.objects.all()
    serializer_class = VoteSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,
                      IsOwnerOrReadOnly,)

    def perform_create(self, serializer):
        serializer.save(voter=self.request.user)

Body:
In your serializer you already have access to current user with self.context['request'].user:

so your code should be something like this:

if self.context['request'].user == data['snippet'].owner:
        raise serializers.ValidationError(u"Voter cannot vote for himself.")

so you can remove the perform_create and use this istead


问:
Laravel 5.5 Multi Authentication Routing wrong login form showing
I am Trying to get Laravel multiple authentication to work on one of my projects. I've tried multiple things but I keep getting stuck. I currently have two guards defined, two models, two login controllers, etc.

If I go to /login - works as expected

If I go to /home (without being logged in) - I get redirected to the login page  as expected

If I go to /register- works as expected

If I go to /admin/login - I am presented with the default login form instead of the admin login form

If I go to /admin/admin/login - I am presented with the correct admin login form

My routes file:

```<code>    Auth::routes();
    Route::get('/home', 'HomeController@index')->name('home');
    Route::prefix('admin')->group(function() {
    Route::get('/login', 'Auth\AdminLoginController@showLoginForm')->name('admin.login');
    Route::post('/login', 'Auth\AdminLoginController@login')->name('admin.login.submit');
   Route::get('/', 'AdminController@index')->name('admin.dashboard');
});
</code>```

And this is my Auth file:

```<code>    return [

    // Authentication Defaults

    'defaults' => [
    'guard' => 'web',
    'passwords' => 'users',
    ],
    // Authentication Guards

    'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'api' => [
        'driver' => 'token',
        'provider' => 'users',
    ],
    'admin' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],
    'admin-api' => [
        'driver' => 'token',
        'provider' => 'admins',
    ],
],
// User Providers

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],
    'admins' => [
        'driver' => 'eloquent',
        'model' => App\Admin::class,
    ],

],
      // Resetting Passwords

'passwords' => [
    'users' => [
        'provider' => 'users',
        'table' => 'password_resets',
        'expire' => 60,
    ],
    'admins' => [
        'provider' => 'admins',
        'table' => 'password_resets',
        'expire' => 30,
        ],
    ],
];
</code>```

Here is my adminLoginController file:

```<code><?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class AdminLoginController extends Controller
{
public function __construct() {
    $this->middleware('guest:admin');
}
public function showLoginForm() {
    return view('auth.admin-login');
}
public function login(){
    //validate the form data

    // atttempt to log in the user

    // if successful redirect to their admin dashboard

     // if unsuccessful then redirect back to the login
    }
}
</code>```

I'm sure I'm missing something. It may be simple but it is delaying my progress. Every other thing works. It's just getting the /admin route to use the right middleware...I think...maybe?

答:
I had the same problem before and later got a solution for it.
Actually the mistake I had commited which I think you may have done too was to have a folder named Admin and in it there was no login file in it so typing /admin/login made laravel to look for the file in there, miss it and then go to the default login file. What solved my problem was renaming the folder and everything worked. Try that if you have done the same mistake</p>

Body:
I am Trying to get Laravel multiple authentication to work on one of my projects. I've tried multiple things but I keep getting stuck. I currently have two guards defined, two models, two login controllers, etc.

If I go to /login - works as expected

If I go to /home (without being logged in) - I get redirected to the login page  as expected

If I go to /register- works as expected

If I go to /admin/login - I am presented with the default login form instead of the admin login form

If I go to /admin/admin/login - I am presented with the correct admin login form

My routes file:

    Auth::routes();
    Route::get('/home', 'HomeController@index')->name('home');
    Route::prefix('admin')->group(function() {
    Route::get('/login', 'Auth\AdminLoginController@showLoginForm')->name('admin.login');
    Route::post('/login', 'Auth\AdminLoginController@login')->name('admin.login.submit');
   Route::get('/', 'AdminController@index')->name('admin.dashboard');
});

And this is my Auth file:

    return [

    // Authentication Defaults

    'defaults' => [
    'guard' => 'web',
    'passwords' => 'users',
    ],
    // Authentication Guards

    'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],
    'api' => [
        'driver' => 'token',
        'provider' => 'users',
    ],
    'admin' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],
    'admin-api' => [
        'driver' => 'token',
        'provider' => 'admins',
    ],
],
// User Providers

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],
    'admins' => [
        'driver' => 'eloquent',
        'model' => App\Admin::class,
    ],

],
      // Resetting Passwords

'passwords' => [
    'users' => [
        'provider' => 'users',
        'table' => 'password_resets',
        'expire' => 60,
    ],
    'admins' => [
        'provider' => 'admins',
        'table' => 'password_resets',
        'expire' => 30,
        ],
    ],
];

Here is my adminLoginController file:

<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class AdminLoginController extends Controller
{
public function __construct() {
    $this->middleware('guest:admin');
}
public function showLoginForm() {
    return view('auth.admin-login');
}
public function login(){
    //validate the form data

    // atttempt to log in the user

    // if successful redirect to their admin dashboard

     // if unsuccessful then redirect back to the login
    }
}

I'm sure I'm missing something. It may be simple but it is delaying my progress. Every other thing works. It's just getting the /admin route to use the right middleware...I think...maybe?


问:
Apply formatting for nested tables
In my document, I have table style called "Small". And here is the macro, which will change the font size in each table of this style:

```<code>Sub FormatTables()
    Dim t As Table
    For Each t In ActiveDocument.Tables
        If t.Style = "Small" Then
            t.Range.Font.Size = 8
        End If
    Next
End Sub
</code>```

The problem is, that it doesn't work for nested tables. In picture shown below, black table is "Normal", blue table is "Small". How it could be fixed?

答:
This should process every table, even those tables nested to arbitrary depth.</p>

```<code>Sub FormatTables()

    Dim t As Table, col As New Collection
    Dim n As Table

    'add all top-level table(s) to collection
    For Each t In ActiveDocument.Tables
        col.Add t
    Next

    'process each table from the collection
    Do While col.Count > 0
        Set t = col(1) '<< reference the first table from the collection
        col.Remove 1   '<< remove it from collection
        Debug.Print "Table has " & t.Rows.Count & " rows", t.Style

        If t.Style = "Small" Then t.Range.Font.Size = 8

        'gather any nested table(s) for checking
        For Each n In t.Tables
            col.Add n
        Next n
    Loop

End Sub
</code>```

Title: Apply formatting for nested tables

Body:
In my document, I have table style called "Small". And here is the macro, which will change the font size in each table of this style:

Sub FormatTables()
    Dim t As Table
    For Each t In ActiveDocument.Tables
        If t.Style = "Small" Then
            t.Range.Font.Size = 8
        End If
    Next
End Sub

The problem is, that it doesn't work for nested tables. In picture shown below, black table is "Normal", blue table is "Small". How it could be fixed?

Body:
This should process every table, even those tables nested to arbitrary depth.

Sub FormatTables()

    Dim t As Table, col As New Collection
    Dim n As Table

    'add all top-level table(s) to collection
    For Each t In ActiveDocument.Tables
        col.Add t
    Next

    'process each table from the collection
    Do While col.Count > 0
        Set t = col(1) '<< reference the first table from the collection
        col.Remove 1   '<< remove it from collection
        Debug.Print "Table has " & t.Rows.Count & " rows", t.Style

        If t.Style = "Small" Then t.Range.Font.Size = 8

        'gather any nested table(s) for checking
        For Each n In t.Tables
            col.Add n
        Next n
    Loop

End Sub


问:
Nuget.exe update vs Update-Package in Visual Studio and Web/App.configs
When updating a package version for a project via the command line using "nuget update (projectFile|packages.config) -Id (packageName) -NonInteractive" I have a bunch of web.configs generated (with transforms), and the existing app.configs are not transformed.

When updating the same package version for the same project via VS (Update-Package -Id (packageName)), there are no web.configs generated and the appropriate app.configs are transformed.

I realize the web.config's that are created have no adverse effect, but the extra file clutter bothers me.

Why is the behavior inconsistent? And is there a way for the CLI to adhere to the VS behavior (which I want)?

Using the latest version of nuget.exe 4.4.1

答:
Why is the behavior inconsistent?

That because the different behavior of nuget install command between NuGet CLI  and Visual Studio.

As we know, config transformations provide a simple way for a package to modify a web.config or app.config when the package is installed. And when we update a NuGet package, NuGet will uninstall the old version nuget package, then install the latest nuget package to the project.

However, the behavior of nuget install command between NuGet CLI  and Visual Studio are different.

The operation nuget install packages on NuGet CLI:

Obviously, NuGet will not re-transform app.configs when you using the update-packages operation on the NuGet CLI.

Conversely, operation nuget-install packages on Visual Studio:

Installs a package and its dependencies into a project

So using update-package on Visual Studio can appropriately transform app.configs file.

And is there a way for the CLI to adhere to the VS behavior (which I
  want)?

To my knowledge, I am afraid the answer is not. Because package manager console is providing is access to visual studio objects. We could not use it with NuGet CLI without Visual Studio:

https://github.com/NuGet/Home/issues/1512


问:
Does gmail addon support jquery/angularjs?
I am trying to create an addon in my gmail. I was wondering whether it supports jquery/angularjs etc., Or it's just only plain javascript.

How can we achieve deferred concept in gmail addon?

答:
Everything you wanted to know could have been found out in a simple google search. http://code.google.com/apis/gmail/
This link will be able to answer both of your questions.

TL:DR

It has a javascript library and an early stage node.js (alpha) library

EDIT: As stated above the two main supported libraries which i feel would be of use to you are a javascript and node.js library. The other libraries are as follows: Java, Python, PHP (Beta), .NET, Objective-C, Dart(Beta), Ruby (Alpha) and finally Go (Alpha).

You enquire about whether it has Angular support although not officially supported you can find an angular-google-gapi on github that:

An AngularJS module for using all Google Apis and your Google Cloud
  Endpoints (Google App Engine) with OAuth. This module uses Google APIs
  Client Library for JavaScript, available for all GApis.

it was created by the github user maximepvrt and is available here: https://github.com/maximepvrt/angular-google-gapi

This might be what you are looking for.


问:
how to split a file to list of lists TCL
I'm coding TCL and I would like to split a file into two lists of lists,
the file contain:

```<code>(1,2) (3,4) (5,6)
(7,8) (9,10) (11,12)
</code>```

and I would like to get two list
one for each line, that contain lists that each one contain to two number

for example:

```<code>puts $list1                 #-> {1 2} {3 4} {5 6}
puts [lindex $list1 0]      #-> 1 2
puts [lindex $list2 2]      #-> 11 12
</code>```

I tried to use regexp and split but no success

答:
The code works for windows :

TCL file code is :

proc captureImage {} {

 #open the image config file.
 set configFile [open "C:/main/image_config.txt" r]

 #To retrive the values from the config file.
 while {![eof $configFile]} {
  set part [split [gets $configFile] "="]
  set props([string trimright [lindex $part 0]]) [string trimleft [lindex $part 1]]
 }
 close $configFile

 set time [clock format [clock seconds] -format %Y%m%d_%H%M%S]
 set date [clock format [clock seconds] -format %Y%m%d]

 #create the folder with the current date
 set folderPath $props(folderPath)
 append folderDate $folderPath "" $date "/"
 set FolderCreation [file mkdir $folderDate]
 while {0} {
    if { [file exists $date] == 1} {
    }
    break
    }

 #camera selection to capture image.
 set camera "video"
 append cctv $camera "=" $props(cctv)

 #set the image resolution (XxY).
 set resolutionX $props(resolutionX)
 set resolutionY $props(resolutionY)
 append resolution $resolutionX "x" $resolutionY

 #set the name to the save image
 set imagePrefix $props(imagePrefix)
 set imageFormat $props(imageFormat)
 append filename $folderDate "" $imagePrefix "_" $time "." $imageFormat

 set logPrefix "Image_log"
 append logFile $folderDate "" $logPrefix "" $date ".txt"

 #ffmpeg command to capture image in background
 exec ffmpeg -f dshow -benchmark -i $cctv -s $resolution $filename >& $logFile &

 after 3000

 }

}
captureImage```
</div>
</div>
</p>

<p>thext file code is :</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-html lang-html prettyprint-override"><code>cctv=Integrated Webcam

resolutionX=1920
resolutionY=1080

imagePrefix=ImageCapture
imageFormat=jpg
folderPath=c:/test/

//camera=video=Integrated Webcam,Logitech HD Webcam C525</code>```

This code works for me me accept the code from text file were list of parameters are passed.

Body:
I'm coding TCL and I would like to split a file into two lists of lists,
the file contain:

(1,2) (3,4) (5,6)
(7,8) (9,10) (11,12)

and I would like to get two list
one for each line, that contain lists that each one contain to two number

for example:

puts $list1                 #-> {1 2} {3 4} {5 6}
puts [lindex $list1 0]      #-> 1 2
puts [lindex $list2 2]      #-> 11 12

I tried to use regexp and split but no success

Body:
The code works for windows :

TCL file code is :

proc captureImage {} {

 #open the image config file.
 set configFile [open "C:/main/image_config.txt" r]

 #To retrive the values from the config file.
 while {![eof $configFile]} {
  set part [split [gets $configFile] "="]
  set props([string trimright [lindex $part 0]]) [string trimleft [lindex $part 1]]
 }
 close $configFile

 set time [clock format [clock seconds] -format %Y%m%d_%H%M%S]
 set date [clock format [clock seconds] -format %Y%m%d]

 #create the folder with the current date
 set folderPath $props(folderPath)
 append folderDate $folderPath "" $date "/"
 set FolderCreation [file mkdir $folderDate]
 while {0} {
    if { [file exists $date] == 1} {
    }
    break
    }

 #camera selection to capture image.
 set camera "video"
 append cctv $camera "=" $props(cctv)

 #set the image resolution (XxY).
 set resolutionX $props(resolutionX)
 set resolutionY $props(resolutionY)
 append resolution $resolutionX "x" $resolutionY

 #set the name to the save image
 set imagePrefix $props(imagePrefix)
 set imageFormat $props(imageFormat)
 append filename $folderDate "" $imagePrefix "_" $time "." $imageFormat

 set logPrefix "Image_log"
 append logFile $folderDate "" $logPrefix "" $date ".txt"

 #ffmpeg command to capture image in background
 exec ffmpeg -f dshow -benchmark -i $cctv -s $resolution $filename >& $logFile &

 after 3000

 }

}
captureImage

thext file code is :

cctv=Integrated Webcam

resolutionX=1920
resolutionY=1080

imagePrefix=ImageCapture
imageFormat=jpg
folderPath=c:/test/

//camera=video=Integrated Webcam,Logitech HD Webcam C525

This code works for me me accept the code from text file were list of parameters are passed.


问:
How to filter out 2 ids in c#?
I have below code which is filtering out menu id value 8

```<code>oListVM = oListVM.Where(x => x.MenuID != 8).ToList();  //filter out menu id 8
</code>```

But I wanted to filter out menu id 8 and 13 so I decided to write the code like this. Is this the right way to filter out both 8 and 13 menu id? I recently started working with c# and
.net.

```<code>oListVM = oListVM.Where(x => (x.MenuID != 8 && x.MenuID!=13)).ToList();  //filter out menu id 8 and 13
</code>```

答:
You are right

```<code>oListVM = oListVM.Where(x => (x.MenuID != 8 && x.MenuID!=13)).ToList();  //filter out menu id 8 and 13
</code>```

is a valid way to do. In additional, say you have more than 2 ids, just use Array or List:

```<code>int[] filterArray = new int[6] {1,5,6,8,13,14};
oListVM = oListVM.Where(x => !filterArray.Contains(x)).ToList();
</code>```

Title: How to filter out 2 ids in c#?

Body:
I have below code which is filtering out menu id value 8

oListVM = oListVM.Where(x => x.MenuID != 8).ToList();  //filter out menu id 8

But I wanted to filter out menu id 8 and 13 so I decided to write the code like this. Is this the right way to filter out both 8 and 13 menu id? I recently started working with c# and
.net.

oListVM = oListVM.Where(x => (x.MenuID != 8 && x.MenuID!=13)).ToList();  //filter out menu id 8 and 13

Body:
You are right

oListVM = oListVM.Where(x => (x.MenuID != 8 && x.MenuID!=13)).ToList();  //filter out menu id 8 and 13

is a valid way to do. In additional, say you have more than 2 ids, just use Array or List:

int[] filterArray = new int[6] {1,5,6,8,13,14};
oListVM = oListVM.Where(x => !filterArray.Contains(x)).ToList();


问:
Initialize and declare variable in if-else condition in JAVA
I'm trying to initialize and declare variable in if-else condition in JAVA, but it is not executing, can someone please help me in below code?

This is the method, which I'm calling from main method. But it's not executing the initialization under if condition and failing.

```<code>    public static void getData(String funct) {
            try {
                    if ("lob".equals(funct)) {
                            String sql1= String.format("select distinct lob_name from BPUSH_lobs order by lob_name");
                    }
                    else {
                            String sql1= String.format("select distinct env_type from BPUSH_environments order by env_type");
                    }
                    Connection conn=DriverManager.getConnection
                    ("jdbc:oracle:thin:@172.23.240.41:1521:BCTOOLS","AMCOPR","AMCOPR");

                    Statement stmt = conn.createStatement();
                    ResultSet rst;

                    System.out.println(funct);

                    rst = stmt.executeQuery(sql1);

                    while (rst.next()) {
                            String lobName = rst.getString("lob_name");
                            System.out.format("%s\n",lobName);
                    }

                    conn.close();
            }
            catch (Exception e) {
                    System.err.println("Got an exception! ");
                    System.err.println(e.getMessage());
            }
    }
</code>```

}

PLEASE HELP :)
Thanks,

答: Define the variable "String sql1" out side the try block and initialize it with null "String sql1=null;" This must solve your problem.

Body:
I'm trying to initialize and declare variable in if-else condition in JAVA, but it is not executing, can someone please help me in below code?

This is the method, which I'm calling from main method. But it's not executing the initialization under if condition and failing.

    public static void getData(String funct) {
            try {
                    if ("lob".equals(funct)) {
                            String sql1= String.format("select distinct lob_name from BPUSH_lobs order by lob_name");
                    }
                    else {
                            String sql1= String.format("select distinct env_type from BPUSH_environments order by env_type");
                    }
                    Connection conn=DriverManager.getConnection
                    ("jdbc:oracle:thin:@172.23.240.41:1521:BCTOOLS","AMCOPR","AMCOPR");

                    Statement stmt = conn.createStatement();
                    ResultSet rst;

                    System.out.println(funct);

                    rst = stmt.executeQuery(sql1);

                    while (rst.next()) {
                            String lobName = rst.getString("lob_name");
                            System.out.format("%s\n",lobName);
                    }

                    conn.close();
            }
            catch (Exception e) {
                    System.err.println("Got an exception! ");
                    System.err.println(e.getMessage());
            }
    }

}

PLEASE HELP :)
Thanks,


问:
Angular js directive controller function bind issue when using ng repeat
I have a code like this

JS

```<code>var app = angular.module('app',[]);

app.controller('ctrl',function($scope){
  $scope.hello = "hello";
  $scope.check = [1,2];

  $scope.focus1 = function(){
    $scope.setFocusInput0();
  };
  $scope.focus2 = function(){
    $scope.setFocusInput1();
  };
});

app.directive('rfocus',function(){
  return {
    restrict: 'A',
    controller: function($scope, $element, $attrs){
        var fooName = 'setFocus' + $attrs.rfocus;
        $scope[fooName] = function(){alert(1)
            $element.focus();
        }
    },
  }
});
</code>```

HTML

```<code><div ng-app="app" ng-controller="ctrl">
<input ng-repeat="i in check" type="checkbox" rfocus="Input{{$index}}"/>
<button ng-click="focus1()">set focus 1</button>
<button ng-click="focus2()">set focus 2</button>
</code>```

http://jsfiddle.net/2PJMQ/29/

When i removing ng-repeat and place checkboxes in static its working fine.

答:
At case of using directive with ng-repeat, you will have several nested scopes, so you should make some changes(plunker):

```<code>app.directive('rfocus',function(){
    return {
        scope:{
            rfocus:'@'
        },
        restrict: 'A',
        controller: function($scope, $element, $attrs){
            var fooName = 'setFocus' + $scope.rfocus;
            $scope.$parent.$parent[fooName] = function(){
                alert(1)
                $element.focus();
            }
        },
    }
});
</code>```

Or this variant:

```<code><input ng-repeat="i in check" type="checkbox" rfocus="'Input' + $index"/>
</code>```

Javascript:

```<code>app.directive('rfocus',function(){
    return {
        restrict: 'A',
        controller: function($scope, $element, $attrs){
            var fooName = 'setFocus' + $scope.$eval($attrs.rfocus);
            $scope.$parent.$parent[fooName] = function(){
                    alert(1)
                $element.focus();
            }
        },
    }
});
</code>```

But both of them will not work at plain situation. I think better solution is to change initial approach. You should pass to each directive it's identifier, i.e. rfocus and reference to variable focus, which determines current focused element, so you can change this variable in your controller and then directives will reflect it:

HTML:

```<code><div ng-app="app" ng-controller="ctrl">
    <input ng-repeat="i in check" type="checkbox" rfocus="{{$index}}" focus='{{focus}}'/>
    <button ng-click="focusClick(0)">set focus 1</button>
    <button ng-click="focusClick(1)">set focus 2</button>
    <input type="checkbox" rfocus="2" focus='{{focus}}'/>
    <button ng-click="focusClick(2)">set focus 3</button>
</div>
</code>```

Javascript:

```<code>var app = angular.module('app',[]);

app.controller('ctrl',function($scope){
    $scope.hello = "hello";
    $scope.check = [1,2];
    $scope.focus = 0;

    $scope.focusClick = function(index){
        $scope.focus = index;
    };
});

app.directive('rfocus',function(){
    return {
        scope:{
           rfocus:'@',
           focus:'@'
        },
        restrict: 'A',
        controller: function($scope, $element, $attrs){
            $scope.$watch('focus', function(){
                if($scope.rfocus == $scope.focus)
                    $element.focus();
            });
        },
    }
});
</code>```

Body:
I have a code like this

JS

var app = angular.module('app',[]);

app.controller('ctrl',function($scope){
  $scope.hello = "hello";
  $scope.check = [1,2];

  $scope.focus1 = function(){
    $scope.setFocusInput0();
  };
  $scope.focus2 = function(){
    $scope.setFocusInput1();
  };
});

app.directive('rfocus',function(){
  return {
    restrict: 'A',
    controller: function($scope, $element, $attrs){
        var fooName = 'setFocus' + $attrs.rfocus;
        $scope[fooName] = function(){alert(1)
            $element.focus();
        }
    },
  }
});

HTML

<input ng-repeat="i in check" type="checkbox" rfocus="Input{{$index}}"/>
<button ng-click="focus1()">set focus 1</button>
<button ng-click="focus2()">set focus 2</button>

http://jsfiddle.net/2PJMQ/29/

When i removing ng-repeat and place checkboxes in static its working fine.

Body:
At case of using directive with ng-repeat, you will have several nested scopes, so you should make some changes(plunker):

app.directive('rfocus',function(){
    return {
        scope:{
            rfocus:'@'
        },
        restrict: 'A',
        controller: function($scope, $element, $attrs){
            var fooName = 'setFocus' + $scope.rfocus;
            $scope.$parent.$parent[fooName] = function(){
                alert(1)
                $element.focus();
            }
        },
    }
});

Or this variant:

<input ng-repeat="i in check" type="checkbox" rfocus="'Input' + $index"/>

Javascript:

app.directive('rfocus',function(){
    return {
        restrict: 'A',
        controller: function($scope, $element, $attrs){
            var fooName = 'setFocus' + $scope.$eval($attrs.rfocus);
            $scope.$parent.$parent[fooName] = function(){
                    alert(1)
                $element.focus();
            }
        },
    }
});

But both of them will not work at plain situation. I think better solution is to change initial approach. You should pass to each directive it's identifier, i.e. rfocus and reference to variable focus, which determines current focused element, so you can change this variable in your controller and then directives will reflect it:

HTML:

<div ng-app="app" ng-controller="ctrl">
    <input ng-repeat="i in check" type="checkbox" rfocus="{{$index}}" focus='{{focus}}'/>
    <button ng-click="focusClick(0)">set focus 1</button>
    <button ng-click="focusClick(1)">set focus 2</button>
    <input type="checkbox" rfocus="2" focus='{{focus}}'/>
    <button ng-click="focusClick(2)">set focus 3</button>
</div>

Javascript:

var app = angular.module('app',[]);

app.controller('ctrl',function($scope){
    $scope.hello = "hello";
    $scope.check = [1,2];
    $scope.focus = 0;

    $scope.focusClick = function(index){
        $scope.focus = index;
    };
});

app.directive('rfocus',function(){
    return {
        scope:{
           rfocus:'@',
           focus:'@'
        },
        restrict: 'A',
        controller: function($scope, $element, $attrs){
            $scope.$watch('focus', function(){
                if($scope.rfocus == $scope.focus)
                    $element.focus();
            });
        },
    }
});


问:
Sending callback and response in same function
Is it bad practice if I write response and callback in same function(here in A) as in case of parameter missing (!a|| !b), the response will be sent, but the parent context will not receive any callback, as a result, the API will dangle and memory would be wasted?</p>

```<code>function practice (req, res){
    var a = req.body.a;
    var b = req.body.b;
    A(a,b, function(err, result){
        if(err){
            return err;
        }else{
            return res.send(c + "Action cmplete");
        }
    })
}

function A(a,b, callback){
  if(!a || !b){
      return res.send("param missing");
  }
  var c;
  c = a+b;
  return callback(null, c);
}
</code>```

答:
Your code examples seem a bit incomplete since you don't even define callbacka anywhere.

But, in general, if you are designing a function that carries out some asynchronous operation and accepts a callback, then you will nearly always want to provide the caller with feedback when the asynchronous operation is complete with an error or complete successfully (and perhaps with a return value).  The only way to do that is to ALWAYS call the callback when the operation is done.

If you don't, then the caller simply never knows or has any way of knowing when the asynchronous operation is done and that is often (not always) a problem.  So, any general purpose asynchronous API that notifies via a callback should ALWAYS call the callback when the async operation is done.

Think about it from the caller's perspective.  The caller needs to know what to check for after making the function call.  You'd like to make their life simple and consistent.  If they were to check for everything, they'd have to check for a synchronous return value, a synchronous exception and check for whether the callback was called.  That's a nightmare of an API that requires all that.  You really want an API that just consistently uses ONE of those mechanisms.  So, if you're going to notify via a callback sometimes, then you should always notify via the callback and never use the other two mechanisms.

This is where promises come in for managing asynchronous operations because they can be even simpler.  Just always return a promise from your function and then the caller can just always use .then() and .catch() on the promise.  Your internal function then just either resolves or reject that promise.

On the other hand, if you want to design a function whose contract with the caller is that, under these conditions I'm going to execute some other code and not call the callback and under these other conditions I'm going to not execute that other code and call the callback instead, you can do that.  It's not a very consistent interface and it's not very friendly to a caller who is not very well versed in what you're doing, but you could do it.

I rather doubt you'd see an interface like that in a well known API because of the inconsistency.   But, you could do it for your own use if you really wanted.  I wouldn't consider it the best practice.

Body:
Is it bad practice if I write response and callback in same function(here in A) as in case of parameter missing (!a|| !b), the response will be sent, but the parent context will not receive any callback, as a result, the API will dangle and memory would be wasted?

function practice (req, res){
    var a = req.body.a;
    var b = req.body.b;
    A(a,b, function(err, result){
        if(err){
            return err;
        }else{
            return res.send(c + "Action cmplete");
        }
    })
}

function A(a,b, callback){
  if(!a || !b){
      return res.send("param missing");
  }
  var c;
  c = a+b;
  return callback(null, c);
}


问:
Run a function returning a set on a set, and get back a larger set
We can use list comprehensions on a list, and get back a list of each element run through a function. We can do the same thing with a set.

I'm looking to run each element of a set through a function, that could return another set, larger than the original input. Is this possible with comprehensions?

I could do something like this, but is there a one-liner for it?

```<code>ret = set()
q = { 1, 2, 3, 4 }
def doubleIt( t ):
    return { t, t**2 }

for w in q:
    ret.update( doubleIt( w ) )

ret
>> { 1, 2, 3, 4, 9, 16 }
</code>```

The returning function will be much more complex, and could possibly return a set of sets, which I'll have to reduce further, so a one-liner would be very useful.

EDIT: Note that the returning function might also return a set. See in the example that running 2 through the function returns {2, 4} and running 4 through it returns {4, 16}, yet 4 only appears in the desired output once.

答:
Two expressions yet, it's a one-liner which is not long:

```<code>q = { 1, 2, 3, 4 } # given
def f(x):
    return x * x
ret = q | set(f(x) for x in q)
</code>```

In case f(x) returns a set:

```<code>reduce(lambda a, b: a | b, map(lambda a: f(a), q))
</code>```

Body:
We can use list comprehensions on a list, and get back a list of each element run through a function. We can do the same thing with a set.

I'm looking to run each element of a set through a function, that could return another set, larger than the original input. Is this possible with comprehensions?

I could do something like this, but is there a one-liner for it?

ret = set()
q = { 1, 2, 3, 4 }
def doubleIt( t ):
    return { t, t**2 }

for w in q:
    ret.update( doubleIt( w ) )

ret
>> { 1, 2, 3, 4, 9, 16 }

The returning function will be much more complex, and could possibly return a set of sets, which I'll have to reduce further, so a one-liner would be very useful.

EDIT: Note that the returning function might also return a set. See in the example that running 2 through the function returns {2, 4} and running 4 through it returns {4, 16}, yet 4 only appears in the desired output once.

Body:
Two expressions yet, it's a one-liner which is not long:

q = { 1, 2, 3, 4 } # given
def f(x):
    return x * x
ret = q | set(f(x) for x in q)

In case f(x) returns a set:

reduce(lambda a, b: a | b, map(lambda a: f(a), q))


问:
How to validate special character from the textbox without using Validate plugin on jquery
How to validate special characters in a textbox without using Validate plugin on JQuery</p>

答:
Best is to use regular expression with basic javascript.
I will prefer something like http://www.9lessons.info/2009/03/perfect-javascript-form-validation.html</p>


问:
Cannot add a child that doesn't have a YogaNode to a parent without a measure function! (Trying to add a 'ReactRawTextShadowNode' to a 'LayoutShadow
According on this tutorial, this is my component which I use for a react base component as a side bar component, and its working very well, but the problem starts when I change list items from <Text> to <Button>

```<code>    import { Text, Container, Header, Content, List, ListItem, TextBody, Button } from 'native-base';
import { StackNavigator, DrawerNavigator } from 'react-navigation'

export default class SideBar extends Component {

    render() {
        return (
            <Content style={{ backgroundColor: '#ffffff' }}>
                <Container>

                    <Content>
                        <List>
                            <ListItem>
                                <Text>First</Text>
                            </ListItem>
                            <ListItem>
                                <Text>Secount</Text>
                            </ListItem>
                            <ListItem>
                                <Text>Third</Text>
                            </ListItem>
                        </List>
                    </Content>
                </Container>
            </Content>
        );
    }
}
</code>```

I get this error:

cant add a child that doesn't have a YogaNede to parent without the
  measure function !(Trying to Add a 'ReactRawTextshadow' to a
  'LayoutShadowNode' )

cant understand this error at all and didn't saw any thing about it on net!

```<code>> Cannot add a child that doesn't have a YogaNode to a parent without a
> measure function! (Trying to add a 'ReactRawTextShadowNode' to a
> 'LayoutShadowNode') addChildAt
>     ReactShadowNodeImpl.java:199 addChildAt
>     ReactShadowNodeImpl.java:54 setChildren
>     UIImplementation.java:472 setChildren
>     UIManagerModule.java:436 invoke
>     Method.java invoke
>     Method.java:372 invoke
>     JavaMethodWrapper.java:374 invoke
>     JavaModuleWrapper.java:162 run
>     NativeRunnable.java handleCallback
>     Handler.java:739 dispatchMessage
>     Handler.java:95 dispatchMessage
>     MessageQueueThreadHandler.java:31 loop
>     Looper.java:135 run
>     MessageQueueThreadImpl.java:194 run
>     Thread.java:818
</code>```

答:
You should Use <Text> to display text in <Button> like this

```<code><ListItem>
    <Button> <Text>First</Text> </Button>
</ListItem>
</code>```

Body:
According on this tutorial, this is my component which I use for a react base component as a side bar component, and its working very well, but the problem starts when I change list items from <Text> to <Button>

    import { Text, Container, Header, Content, List, ListItem, TextBody, Button } from 'native-base';
import { StackNavigator, DrawerNavigator } from 'react-navigation'

export default class SideBar extends Component {

    render() {
        return (
            <Content style={{ backgroundColor: '#ffffff' }}>
                <Container>

                    <Content>
                        <List>
                            <ListItem>
                                <Text>First</Text>
                            </ListItem>
                            <ListItem>
                                <Text>Secount</Text>
                            </ListItem>
                            <ListItem>
                                <Text>Third</Text>
                            </ListItem>
                        </List>
                    </Content>
                </Container>
            </Content>
        );
    }
}

I get this error:

cant add a child that doesn't have a YogaNede to parent without the
  measure function !(Trying to Add a 'ReactRawTextshadow' to a
  'LayoutShadowNode' )

cant understand this error at all and didn't saw any thing about it on net!

> Cannot add a child that doesn't have a YogaNode to a parent without a
> measure function! (Trying to add a 'ReactRawTextShadowNode' to a
> 'LayoutShadowNode') addChildAt
>     ReactShadowNodeImpl.java:199 addChildAt
>     ReactShadowNodeImpl.java:54 setChildren
>     UIImplementation.java:472 setChildren
>     UIManagerModule.java:436 invoke
>     Method.java invoke
>     Method.java:372 invoke
>     JavaMethodWrapper.java:374 invoke
>     JavaModuleWrapper.java:162 run
>     NativeRunnable.java handleCallback
>     Handler.java:739 dispatchMessage
>     Handler.java:95 dispatchMessage
>     MessageQueueThreadHandler.java:31 loop
>     Looper.java:135 run
>     MessageQueueThreadImpl.java:194 run
>     Thread.java:818

Body:
You should Use <Text> to display text in <Button> like this

<ListItem>
    <Button> <Text>First</Text> </Button>
</ListItem>