问:
Handling repetition for calculation in foreach PHP
I've chance in my code to handling repetition calculation in foreach
statement. the point is how to make recursive ?

in this code i always use same code, when there is "HSPK" the calculation will have same method (foreach), for this example i commend in "fifth calculation".

```<code>function sum_hspk($hspk_uraian_ssh_hspk_kode) {

        $ssh_total = 0;

        $ssh_total_2 = 0;

        $ssh_total_3 = 0;

        $harga_analisa_hspk = 0;

        $harga_analisa_satuan = 0;

        $hspk_reference = json_decode(get_hspk_reference_uraian_by_hspk_uraian_hspk_kode($hspk_uraian_ssh_hspk_kode));

        $hspk_uraian = json_decode(get_hspk_uraian_by_kegiatan($hspk_reference->hspk_kegiatan_kode));

        foreach($hspk_uraian as $row) { // first foreach

            $hspk_uraian_koefisien = $row->hspk_uraian_koefisien;

            if($row->hspk_uraian_ssh_hspk_sumber == "SSH") { // first if

                $hspk_uraian_koefisien_ssh = $hspk_uraian_koefisien;

                $ssh = json_decode(get_ssh_detail_by_kode($row->hspk_uraian_ssh_hspk_kode));

                $ssh_total += ($ssh->ssh_uraian_harga * $hspk_uraian_koefisien_ssh);

            } elseif($row->hspk_uraian_ssh_hspk_sumber == "HSPK") {

                $hspk_uraian_koefisien_hspk_2 = $hspk_uraian_koefisien;

                $hspk_uraian = json_decode(get_hspk_uraian_by_kegiatan($row->hspk_uraian_ssh_hspk_kode));

                foreach($hspk_uraian as $row) { // second foreach

                    $hspk_uraian_koefisien = $row->hspk_uraian_koefisien;

                    if($row->hspk_uraian_ssh_hspk_sumber == "SSH") { // second if

                        $hspk_uraian_koefisien_ssh = $hspk_uraian_koefisien;

                        $ssh = json_decode(get_ssh_detail_by_kode($row->hspk_uraian_ssh_hspk_kode));

                        $ssh_total_2 += ($ssh->ssh_uraian_harga * $hspk_uraian_koefisien_ssh);

                    }elseif($row->hspk_uraian_ssh_hspk_sumber == "HSPK") {

                        $hspk_uraian_koefisien_hspk_3 = $hspk_uraian_koefisien;

                        $hspk_uraian = json_decode(get_hspk_uraian_by_kegiatan($row->hspk_uraian_ssh_hspk_kode));

                        foreach($hspk_uraian as $row) { // third foreach

                            $hspk_uraian_koefisien = $row->hspk_uraian_koefisien;

                            if($row->hspk_uraian_ssh_hspk_sumber == "SSH") {

                                $hspk_uraian_koefisien_ssh = $hspk_uraian_koefisien;

                                $ssh = json_decode(get_ssh_detail_by_kode($row->hspk_uraian_ssh_hspk_kode));

                                $ssh_total_3 += ($ssh->ssh_uraian_harga * $hspk_uraian_koefisien_ssh);

                            }else if($row->hspk_uraian_ssh_hspk_sumber == "HSPK") {

                                $hspk_uraian_koefisien_hspk_4 = $hspk_uraian_koefisien;

                                $hspk_uraian = json_decode(get_hspk_uraian_by_kegiatan($row->hspk_uraian_ssh_hspk_kode));

                                foreach ($hspk_uraian as $row) { // fourth foreach

                                    $hspk_uraian_koefisien = $row->hspk_uraian_koefisien;

                                    if($row->hspk_uraian_ssh_hspk_sumber == "SSH") {

                                        $hspk_uraian_koefisien_ssh = $hspk_uraian_koefisien;

                                        $ssh = json_decode(get_ssh_detail_by_kode($row->hspk_uraian_ssh_hspk_kode));

                                        $ssh_total_4 += ($ssh->ssh_uraian_harga * $hspk_uraian_koefisien_ssh);

                                    }elseif($row->hspk_uraian_ssh_hspk_sumber == "HSPK") {

                                        // fifth handling

                                    } // end fourth if

                                } // end fourth foreach

                                $harga_analisa_satuan = ((($ssh_total_4) * 0.15) + ($ssh_total_4));

                                $harga_analisa_hspk = ($harga_analisa_satuan * $hspk_uraian_koefisien_hspk_3);

                                $ssh_total_3 += $harga_analisa_hspk;

                            } // end third if

                        } // end third foreach

                        $harga_analisa_satuan = ((($ssh_total_3) * 0.15) + ($ssh_total_3));

                        $harga_analisa_hspk = ($harga_analisa_satuan * $hspk_uraian_koefisien_hspk_3);

                        $ssh_total_2 += $harga_analisa_hspk;

                    }; // end second if

                } // end second foreach

                $harga_analisa_satuan = ((($ssh_total_2) * 0.15) + ($ssh_total_2));

                $harga_analisa_hspk = ($harga_analisa_satuan * $hspk_uraian_koefisien_hspk_2);

                $ssh_total += $harga_analisa_hspk;

            } // end first if

        } // end first foreach

        $harga_analisa_hspk = ((($ssh_total) * 0.15) + ($ssh_total));

        return $harga_analisa_hspk;

    } // end function
</code>```

example execution that function:

```<code>$test = sum_hspk('01.04');
echo $test;
</code>```

答:
To make a recursive function, you need to think about what is the base case, and what you want to obtain (ssh_total) from the function. In this case, sum_hspk calculates ssh_total from "SSH" & "HSPK". "SSH" is your base case and you directly calculate the value. But for the "HSPK", it depends on "SSH" and "HSPK", therefore, you need to make a top-down approach until the base case "SSH" found. You need to call sum_hspk in "HSPK" conditions.

You should make this change to make recursive.

```<code>function get_ssh_total($row) {

    $ssh_total = 0;

    $hspk_uraian_koefisien = $row->hspk_uraian_koefisien;

    if ($row->hspk_uraian_ssh_hspk_sumber == "SSH") {

        $hspk_uraian_koefisien_ssh = $hspk_uraian_koefisien;

        $ssh = json_decode(get_ssh_detail_by_kode($row->hspk_uraian_ssh_hspk_kode));

        $ssh_total = ($ssh->ssh_uraian_harga * $hspk_uraian_koefisien_ssh);

    }
    else if ($row->hspk_uraian_ssh_hspk_sumber == "HSPK") {

        $hspk_uraian_koefisien_hspk_2 = $hspk_uraian_koefisien;

        $hspk_uraian = json_decode(get_hspk_uraian_by_kegiatan($row->hspk_uraian_ssh_hspk_kode));

        foreach($hspk_uraian as $row) {

            $ssh_total_2 += get_ssh_total($row);

        }

        $harga_analisa_satuan = ((($ssh_total_2) * 0.15) + ($ssh_total_2));

        $harga_analisa_hspk = ($harga_analisa_satuan * $hspk_uraian_koefisien_hspk_2);

        $ssh_total += $harga_analisa_hspk;

    }

    return $ssh_total;

}

function sum_hspk($hspk_uraian_ssh_hspk_kode) {

    $ssh_total = 0;

    $ssh_total_2 = 0;

    $ssh_total_3 = 0;

    $harga_analisa_hspk = 0;

    $harga_analisa_satuan = 0;

    $hspk_reference = json_decode(get_hspk_reference_uraian_by_hspk_uraian_hspk_kode($hspk_uraian_ssh_hspk_kode));

    $hspk_uraian = json_decode(get_hspk_uraian_by_kegiatan($hspk_reference->hspk_kegiatan_kode));

    foreach($hspk_uraian as $row) { // first foreach

        $ssh_total += get_ssh_total($row);

    } // end first foreach

    $harga_analisa_hspk = ((($ssh_total) * 0.15) + ($ssh_total));

    return $harga_analisa_hspk;

} // end function
</code>```

Body:
I've chance in my code to handling repetition calculation in foreach
statement. the point is how to make recursive ?

in this code i always use same code, when there is "HSPK" the calculation will have same method (foreach), for this example i commend in "fifth calculation".

function sum_hspk($hspk_uraian_ssh_hspk_kode) {

        $ssh_total = 0;

        $ssh_total_2 = 0;

        $ssh_total_3 = 0;

        $harga_analisa_hspk = 0;

        $harga_analisa_satuan = 0;

        $hspk_reference = json_decode(get_hspk_reference_uraian_by_hspk_uraian_hspk_kode($hspk_uraian_ssh_hspk_kode));

        $hspk_uraian = json_decode(get_hspk_uraian_by_kegiatan($hspk_reference->hspk_kegiatan_kode));

        foreach($hspk_uraian as $row) { // first foreach

            $hspk_uraian_koefisien = $row->hspk_uraian_koefisien;

            if($row->hspk_uraian_ssh_hspk_sumber == "SSH") { // first if

                $hspk_uraian_koefisien_ssh = $hspk_uraian_koefisien;

                $ssh = json_decode(get_ssh_detail_by_kode($row->hspk_uraian_ssh_hspk_kode));

                $ssh_total += ($ssh->ssh_uraian_harga * $hspk_uraian_koefisien_ssh);

            } elseif($row->hspk_uraian_ssh_hspk_sumber == "HSPK") {

                $hspk_uraian_koefisien_hspk_2 = $hspk_uraian_koefisien;

                $hspk_uraian = json_decode(get_hspk_uraian_by_kegiatan($row->hspk_uraian_ssh_hspk_kode));

                foreach($hspk_uraian as $row) { // second foreach

                    $hspk_uraian_koefisien = $row->hspk_uraian_koefisien;

                    if($row->hspk_uraian_ssh_hspk_sumber == "SSH") { // second if

                        $hspk_uraian_koefisien_ssh = $hspk_uraian_koefisien;

                        $ssh = json_decode(get_ssh_detail_by_kode($row->hspk_uraian_ssh_hspk_kode));

                        $ssh_total_2 += ($ssh->ssh_uraian_harga * $hspk_uraian_koefisien_ssh);

                    }elseif($row->hspk_uraian_ssh_hspk_sumber == "HSPK") {

                        $hspk_uraian_koefisien_hspk_3 = $hspk_uraian_koefisien;

                        $hspk_uraian = json_decode(get_hspk_uraian_by_kegiatan($row->hspk_uraian_ssh_hspk_kode));

                        foreach($hspk_uraian as $row) { // third foreach

                            $hspk_uraian_koefisien = $row->hspk_uraian_koefisien;

                            if($row->hspk_uraian_ssh_hspk_sumber == "SSH") {

                                $hspk_uraian_koefisien_ssh = $hspk_uraian_koefisien;

                                $ssh = json_decode(get_ssh_detail_by_kode($row->hspk_uraian_ssh_hspk_kode));

                                $ssh_total_3 += ($ssh->ssh_uraian_harga * $hspk_uraian_koefisien_ssh);

                            }else if($row->hspk_uraian_ssh_hspk_sumber == "HSPK") {

                                $hspk_uraian_koefisien_hspk_4 = $hspk_uraian_koefisien;

                                $hspk_uraian = json_decode(get_hspk_uraian_by_kegiatan($row->hspk_uraian_ssh_hspk_kode));

                                foreach ($hspk_uraian as $row) { // fourth foreach

                                    $hspk_uraian_koefisien = $row->hspk_uraian_koefisien;

                                    if($row->hspk_uraian_ssh_hspk_sumber == "SSH") {

                                        $hspk_uraian_koefisien_ssh = $hspk_uraian_koefisien;

                                        $ssh = json_decode(get_ssh_detail_by_kode($row->hspk_uraian_ssh_hspk_kode));

                                        $ssh_total_4 += ($ssh->ssh_uraian_harga * $hspk_uraian_koefisien_ssh);

                                    }elseif($row->hspk_uraian_ssh_hspk_sumber == "HSPK") {

                                        // fifth handling

                                    } // end fourth if

                                } // end fourth foreach

                                $harga_analisa_satuan = ((($ssh_total_4) * 0.15) + ($ssh_total_4));

                                $harga_analisa_hspk = ($harga_analisa_satuan * $hspk_uraian_koefisien_hspk_3);

                                $ssh_total_3 += $harga_analisa_hspk;

                            } // end third if

                        } // end third foreach

                        $harga_analisa_satuan = ((($ssh_total_3) * 0.15) + ($ssh_total_3));

                        $harga_analisa_hspk = ($harga_analisa_satuan * $hspk_uraian_koefisien_hspk_3);

                        $ssh_total_2 += $harga_analisa_hspk;

                    }; // end second if

                } // end second foreach

                $harga_analisa_satuan = ((($ssh_total_2) * 0.15) + ($ssh_total_2));

                $harga_analisa_hspk = ($harga_analisa_satuan * $hspk_uraian_koefisien_hspk_2);

                $ssh_total += $harga_analisa_hspk;

            } // end first if

        } // end first foreach

        $harga_analisa_hspk = ((($ssh_total) * 0.15) + ($ssh_total));

        return $harga_analisa_hspk;

    } // end function

example execution that function:

$test = sum_hspk('01.04');
echo $test;

Body:
To make a recursive function, you need to think about what is the base case, and what you want to obtain (ssh_total) from the function. In this case, sum_hspk calculates ssh_total from "SSH" & "HSPK". "SSH" is your base case and you directly calculate the value. But for the "HSPK", it depends on "SSH" and "HSPK", therefore, you need to make a top-down approach until the base case "SSH" found. You need to call sum_hspk in "HSPK" conditions.

You should make this change to make recursive.

function get_ssh_total($row) {

    $ssh_total = 0;

    $hspk_uraian_koefisien = $row->hspk_uraian_koefisien;

    if ($row->hspk_uraian_ssh_hspk_sumber == "SSH") {

        $hspk_uraian_koefisien_ssh = $hspk_uraian_koefisien;

        $ssh = json_decode(get_ssh_detail_by_kode($row->hspk_uraian_ssh_hspk_kode));

        $ssh_total = ($ssh->ssh_uraian_harga * $hspk_uraian_koefisien_ssh);

    }
    else if ($row->hspk_uraian_ssh_hspk_sumber == "HSPK") {

        $hspk_uraian_koefisien_hspk_2 = $hspk_uraian_koefisien;

        $hspk_uraian = json_decode(get_hspk_uraian_by_kegiatan($row->hspk_uraian_ssh_hspk_kode));

        foreach($hspk_uraian as $row) {

            $ssh_total_2 += get_ssh_total($row);

        }

        $harga_analisa_satuan = ((($ssh_total_2) * 0.15) + ($ssh_total_2));

        $harga_analisa_hspk = ($harga_analisa_satuan * $hspk_uraian_koefisien_hspk_2);

        $ssh_total += $harga_analisa_hspk;

    }

    return $ssh_total;

}

function sum_hspk($hspk_uraian_ssh_hspk_kode) {

    $ssh_total = 0;

    $ssh_total_2 = 0;

    $ssh_total_3 = 0;

    $harga_analisa_hspk = 0;

    $harga_analisa_satuan = 0;

    $hspk_reference = json_decode(get_hspk_reference_uraian_by_hspk_uraian_hspk_kode($hspk_uraian_ssh_hspk_kode));

    $hspk_uraian = json_decode(get_hspk_uraian_by_kegiatan($hspk_reference->hspk_kegiatan_kode));

    foreach($hspk_uraian as $row) { // first foreach

        $ssh_total += get_ssh_total($row);

    } // end first foreach

    $harga_analisa_hspk = ((($ssh_total) * 0.15) + ($ssh_total));

    return $harga_analisa_hspk;

} // end function


来源: stackexchange

问:
Writing and Reading an ArrayList<model>
So I am pretty much new at this but I have built a library project that has an ArrayList BookList which in return has elements such as String Title, String Author, and int Quantity. I have an add method and a display method and  I want to create a method that I am able to save and load the BookList when I I give the appropriate input to do so. Moreover I want to do so, so when I load the BookList I can make changes to the elements in the ArrayList and it's not just reading from the file.

```<code>public class Library implements Serializable{...}
</code>```

Inside this class are my methods of saving and loading which are called in the main as well as the constructors for the ArrayList.

Save

```<code>   public void save(){
       try{
           FileOutputStream fileOut = new FileOutputStream("BookList.tmp");
           ObjectOutputStream objOut = new ObjectOutputStream(fileOut);
           objOut.writeObject(BookList);
           objOut.close();
       }catch(Exception ev){}
   }//end of save()
</code>```

Load

```<code>    public void load(){
        try{
            FileInputStream fileInput = new FileInputStream("BookList.tmp");
            ObjectInputStream objInput = new ObjectInputStream(fileInput);
            List<Book> BookList = (List<Book>) objInput.readObject();
            objInput.close();
        }
        catch (Exception ev){}
    }//end of load()
</code>```

Display

```<code>    public void displayBooks(){
        String t;
        String a;
        int q;
        String s;
        Book bo = new Book();
        for(int i = 0; i<BookList.size(); i++){
            bo = BookList.get(i);
            t = bo.gettitle();
            a = bo.getauthor();
            q = bo.getquantity();
            System.out.println(i + "." + t + " " + a + " " + q);
        }//end of loop
    }//end of displayBooks()
</code>```

But so far through the display method I have I am not able to see the BookList so I don't know if the save method works in the first place as well. So I want to know if the problem lies here or somewhere else.

答:
Most probable cause of your problem is that BookList in display() method and the one in load() method are different.

In display method, you are referring to BookList that is an instance variable but in load method, you have stored the result of objInput.readObject() method in a local variable with the same name BookList. I think you wanted to store the result in BookList that is an instance variable.

Try changing

```<code>List<Book> BookList = (List<Book>) objInput.readObject();
</code>```

to

```<code>BookList = (List<Book>) objInput.readObject();
</code>```

ContentLicense: CC BY-SA 3.0

Title: Writing and Reading an ArrayList<model>

Body:
So I am pretty much new at this but I have built a library project that has an ArrayList BookList which in return has elements such as String Title, String Author, and int Quantity. I have an add method and a display method and  I want to create a method that I am able to save and load the BookList when I I give the appropriate input to do so. Moreover I want to do so, so when I load the BookList I can make changes to the elements in the ArrayList and it's not just reading from the file.

public class Library implements Serializable{...}

Inside this class are my methods of saving and loading which are called in the main as well as the constructors for the ArrayList.

Save

   public void save(){
       try{
           FileOutputStream fileOut = new FileOutputStream("BookList.tmp");
           ObjectOutputStream objOut = new ObjectOutputStream(fileOut);
           objOut.writeObject(BookList);
           objOut.close();
       }catch(Exception ev){}
   }//end of save()

Load

    public void load(){
        try{
            FileInputStream fileInput = new FileInputStream("BookList.tmp");
            ObjectInputStream objInput = new ObjectInputStream(fileInput);
            List<Book> BookList = (List<Book>) objInput.readObject();
            objInput.close();
        }
        catch (Exception ev){}
    }//end of load()

Display

    public void displayBooks(){
        String t;
        String a;
        int q;
        String s;
        Book bo = new Book();
        for(int i = 0; i<BookList.size(); i++){
            bo = BookList.get(i);
            t = bo.gettitle();
            a = bo.getauthor();
            q = bo.getquantity();
            System.out.println(i + "." + t + " " + a + " " + q);
        }//end of loop
    }//end of displayBooks()

But so far through the display method I have I am not able to see the BookList so I don't know if the save method works in the first place as well. So I want to know if the problem lies here or somewhere else.

Body:
Most probable cause of your problem is that BookList in display() method and the one in load() method are different.

In display method, you are referring to BookList that is an instance variable but in load method, you have stored the result of objInput.readObject() method in a local variable with the same name BookList. I think you wanted to store the result in BookList that is an instance variable.

Try changing

List<Book> BookList = (List<Book>) objInput.readObject();

to

BookList = (List<Book>) objInput.readObject();


问:
Filtering a list in python with many key-value pairs
I have a list that looks like this:

```<code>commands = [
{'command': "start app", 'action': "monitor", 'max-threshold': True, 'zero-failcount': True, 'started': True, 'stopped': False, 'failed': False},
{'command': "read log", 'action': "monitor", 'max-threshold': False, 'zero-failcount': True, 'started': True, 'stopped': False, 'failed': False},
{'command': "kill app", 'action': "monitor", 'max-threshold': True, 'zero-failcount': True, 'started': True, 'stopped': False, 'failed': False}
]
</code>```

And I would like to filter so that only a few cases are seen in the new list. For example, only those with max-threshold with true, zero-failcount true, etc. How do I do this? I'm using Python 2.7.

答:
Use a list comprehension.

For example, something like:

```<code>[command for command in commands if command['max-threshold']]
</code>```

Body:
I have a list that looks like this:

commands = [
{'command': "start app", 'action': "monitor", 'max-threshold': True, 'zero-failcount': True, 'started': True, 'stopped': False, 'failed': False},
{'command': "read log", 'action': "monitor", 'max-threshold': False, 'zero-failcount': True, 'started': True, 'stopped': False, 'failed': False},
{'command': "kill app", 'action': "monitor", 'max-threshold': True, 'zero-failcount': True, 'started': True, 'stopped': False, 'failed': False}
]

And I would like to filter so that only a few cases are seen in the new list. For example, only those with max-threshold with true, zero-failcount true, etc. How do I do this? I'm using Python 2.7.

Body:
Use a list comprehension.

For example, something like:

[command for command in commands if command['max-threshold']]


问:
Django Creating a Custom User with the Django Rest Framework
I'm trying to create a custom user using the Django Rest Framework. I got it to the point to where I can create a regular user, but I'm unsure on how to extend it to the custom user model.

models.py:

```<code>from django.db import models
from django.contrib.postgres.fields import ArrayField
from django.contrib.auth.models import User

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    languages = ArrayField(models.CharField(max_length=30, blank=True))
</code>```

serializers.py:

```<code>from rest_framework import serializers
from django.contrib.auth.models import User

class UserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)

    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email', 'username', 'password')

    def create(self, validated_data, instance=None):
        user = super(UserSerializer, self).create(validated_data)
        user.set_password(validated_data['password'])
        user.save()
        return user
</code>```

views.py:

```<code>@api_view(['POST'])
@permission_classes((AllowAny,))
def create_user(request):
    serialized = UserSerializer(data=request.data)
    if serialized.is_valid():
        serialized.save()
        return Response(serialized.data, status=status.HTTP_201_CREATED)
    else:
        return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)
</code>```

How do I extend the languages field to the UserSerializer to where it can process it? Would it be better to create a signal for every time a user is created it then creates a userprofile automatically?

答:
You can do it two ways, either by creating a profile Serializer or without it.
With Serializer,

```<code>class UserProfileSerializer(serializers.ModelSerializer):
    languages = serializers.ListField(child=serializers.CharField(max_length=30, allow_blank=True))

    class Meta:
        model = UserProfile
        fields = ('languages',)

class UserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)
    userprofile = UserProfileSerializer(required=False)

    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email', 'username', 'password', 'userprofile')

    def create(self, validated_data, instance=None):
        profile_data = validated_data.pop('userprofile')
        user = User.objects.create(**validated_data)
        user.set_password(validated_data['password'])
        user.save()
        UserProfile.objects.update_or_create(user=user,**profile_data)
        return user
</code>```

without a profile serializer

```<code>class UserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)
    languages = serializers.ListField(child=serializers.CharField(max_length=30, allow_blank=True), source="userprofile.languages")

    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email', 'username', 'password', 'lanugages')

    def create(self, validated_data, instance=None):
        profile_data = validated_data.pop('userprofile')
        user = User.objects.create(**validated_data)
        user.set_password(validated_data['password'])
        user.save()
        UserProfile.objects.update_or_create(user=user,**profile_data)
        return user
</code>```

Body:
I'm trying to create a custom user using the Django Rest Framework. I got it to the point to where I can create a regular user, but I'm unsure on how to extend it to the custom user model.

models.py:

from django.db import models
from django.contrib.postgres.fields import ArrayField
from django.contrib.auth.models import User

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    languages = ArrayField(models.CharField(max_length=30, blank=True))

serializers.py:

from rest_framework import serializers
from django.contrib.auth.models import User

class UserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)

    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email', 'username', 'password')

    def create(self, validated_data, instance=None):
        user = super(UserSerializer, self).create(validated_data)
        user.set_password(validated_data['password'])
        user.save()
        return user

views.py:

@api_view(['POST'])
@permission_classes((AllowAny,))
def create_user(request):
    serialized = UserSerializer(data=request.data)
    if serialized.is_valid():
        serialized.save()
        return Response(serialized.data, status=status.HTTP_201_CREATED)
    else:
        return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)

How do I extend the languages field to the UserSerializer to where it can process it? Would it be better to create a signal for every time a user is created it then creates a userprofile automatically?

Body:
You can do it two ways, either by creating a profile Serializer or without it.
With Serializer,

class UserProfileSerializer(serializers.ModelSerializer):
    languages = serializers.ListField(child=serializers.CharField(max_length=30, allow_blank=True))

    class Meta:
        model = UserProfile
        fields = ('languages',)

class UserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)
    userprofile = UserProfileSerializer(required=False)

    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email', 'username', 'password', 'userprofile')

    def create(self, validated_data, instance=None):
        profile_data = validated_data.pop('userprofile')
        user = User.objects.create(**validated_data)
        user.set_password(validated_data['password'])
        user.save()
        UserProfile.objects.update_or_create(user=user,**profile_data)
        return user

without a profile serializer

class UserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)
    languages = serializers.ListField(child=serializers.CharField(max_length=30, allow_blank=True), source="userprofile.languages")

    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email', 'username', 'password', 'lanugages')

    def create(self, validated_data, instance=None):
        profile_data = validated_data.pop('userprofile')
        user = User.objects.create(**validated_data)
        user.set_password(validated_data['password'])
        user.save()
        UserProfile.objects.update_or_create(user=user,**profile_data)
        return user


问:
Opensource Nuget packages to open and read Excel files in ASP.NET MVC
Any Opensource Nuget packages available to open and read Excel files in ASP.NET MVC?</p>

答: you can try EPPlus or ClosedXML nuget packages. you can read/write/save</p>


问:
How to change the text from a textfield from a different class in WindowsForm
For a project I am trying to change the text of a RichTextBox using a method from a different class. However when trying to pass a string through, it doesn't change the text but when I write Console.Writeline, it does show up.

What I think the problem is, is that I have to refresh the WindowsForm before the text can change.

```<code>namespace RichTextBox
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
             addText.returnText();
         }

        public void addData(string s)
        {
            richTextBox1.AppendText(s);
            Console.WriteLine(s);
        }
    }
}
</code>```

And the other class:

```<code>namespace RichTextBox
{
    class addText
    {
        public static void returnText()
        {
            string s = "test test;";
            Form1 f = new Form1();
            f.addData(s);
        }
    }
}
</code>```

答:
your returnText method is creating a new Form1, it shouldn't.  There are a few options here, you could update the signature to expect a Form1 instance - returnText(Form1 f) and pass the current form instance to the method ( addText.returnText(this);

Or, and preferably, have the returnText method do exactly what it says - return the text, the calling code can update the rich text box.  It keeps the responsibilities separate and clearer.

```<code>public static string returnText()
{
 string s = "test test;";
 return s;
}
</code>```

calling code:

```<code>private void button1_Click(object sender, EventArgs e)
{
var s = addText.returnText();
addData(s);
}
</code>```

Body:
For a project I am trying to change the text of a RichTextBox using a method from a different class. However when trying to pass a string through, it doesn't change the text but when I write Console.Writeline, it does show up.

What I think the problem is, is that I have to refresh the WindowsForm before the text can change.

namespace RichTextBox
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
             addText.returnText();
         }

        public void addData(string s)
        {
            richTextBox1.AppendText(s);
            Console.WriteLine(s);
        }
    }
}

And the other class:

namespace RichTextBox
{
    class addText
    {
        public static void returnText()
        {
            string s = "test test;";
            Form1 f = new Form1();
            f.addData(s);
        }
    }
}

Body:
your returnText method is creating a new Form1, it shouldn't.  There are a few options here, you could update the signature to expect a Form1 instance - returnText(Form1 f) and pass the current form instance to the method ( addText.returnText(this);

Or, and preferably, have the returnText method do exactly what it says - return the text, the calling code can update the rich text box.  It keeps the responsibilities separate and clearer.

public static string returnText()
{
 string s = "test test;";
 return s;
}

calling code:

private void button1_Click(object sender, EventArgs e)
{
var s = addText.returnText();
addData(s);
}


问:
Find the Max and Min element out of all the nested arrays in javascript
I have a array like so:

```<code>var arr = [[12,45,75], [54,45,2],[23,54,75,2]];
</code>```

I want to find out the largest element and the smallest element out of all the elements in the nested array:

The min should be: 2

and

Max should be 75

I tried the functions below but they do not work:

```<code>    function Max(arrs)
    {
        if (!arrs || !arrs.length) return undefined;
        let max = Math.max.apply(window, arrs[0]), m,
            f = function(v){ return !isNaN(v); };
        for (let i = 1, l = arrs.length; i<l; i++) {
            if ((m = Math.max.apply(window, arrs[i].filter(f)))>max) max=m;
        }
        return max;
    }
    function Min(arrs)
    {
        if (!arrs || !arrs.length) return undefined;
        let min = Math.min.apply(window, arrs[0]), m,
            f = function(v){ return !isNaN(v); };
        for (let i = 1, l = arrs.length; i<l; i++) {
            if ((m = Math.min.apply(window, arrs[i].filter(f)))>min) min=m;
        }
        return min;
    }
</code>```

It gives out Max as 75 and min as 12.

Any guidance will be appreciated.

Also tried other answers in SO but none help.

The answer at Merge/flatten an array of arrays in JavaScript? resolves the problem of merging arrays.

Whereas my problem is to keep the array as is and perform operations.

答:
Solution without concatenation, which works for any level of nesting

let arr = [[12,45,75], [54,45,2],[23,54,75,2]];

function findMaxFromNestedArray(arr) {
  let max = Number.MIN_SAFE_INTEGER;

  for (let item of arr) {
    if(Array.isArray(item)) {
      let maxInChildArray = findMaxFromNestedArray(item);
      if (maxInChildArray > max) {
        max = maxInChildArray;
      }
    } else {
      if (item > max) {
        max = item;
      }
    }
  }

  return max;
}

console.log(findMaxFromNestedArray(arr))```

Body:
I have a array like so:

var arr = [[12,45,75], [54,45,2],[23,54,75,2]];

I want to find out the largest element and the smallest element out of all the elements in the nested array:

The min should be: 2

and

Max should be 75

I tried the functions below but they do not work:

    function Max(arrs)
    {
        if (!arrs || !arrs.length) return undefined;
        let max = Math.max.apply(window, arrs[0]), m,
            f = function(v){ return !isNaN(v); };
        for (let i = 1, l = arrs.length; i<l; i++) {
            if ((m = Math.max.apply(window, arrs[i].filter(f)))>max) max=m;
        }
        return max;
    }
    function Min(arrs)
    {
        if (!arrs || !arrs.length) return undefined;
        let min = Math.min.apply(window, arrs[0]), m,
            f = function(v){ return !isNaN(v); };
        for (let i = 1, l = arrs.length; i<l; i++) {
            if ((m = Math.min.apply(window, arrs[i].filter(f)))>min) min=m;
        }
        return min;
    }

It gives out Max as 75 and min as 12.

Any guidance will be appreciated.

Also tried other answers in SO but none help.

The answer at Merge/flatten an array of arrays in JavaScript? resolves the problem of merging arrays.

Whereas my problem is to keep the array as is and perform operations.


问:
how to set font-awesome check icon when click then check
i want to set font-awesome check icon that when ic click on it then its check when i click again its uncheck how this is possible .... i not use checkbox so plz tell me in this font-awesome check ....if its possible with jquery then tell me plzz how its done..
my code ....

<!DOCTYPE html>

 <title> </title>
 <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

    first

    second

    third

```

答:
Happy Coding :)

$('li').click(function() {
$(this).find('label i').toggleClass('hidden');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hidden{
display:none !important;
}</code>```

<!DOCTYPE html>

 <title> </title>
 <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

    first

    second

    third

```

Body:
Happy Coding :)

$('li').click(function() {
$(this).find('label i').toggleClass('hidden');
});

.hidden{
display:none !important;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
 <title> </title>
 <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
 <script type="text/javascript" src="js/jquery.js"></script>
</head>
<body>
<ul>
  <li>
   <label> first
      <i class="fa fa-check-square hidden" aria-hidden="true"></i>
   </label>
  </li>
  <li>
   <label> second
      <i class="fa fa-check-square hidden" aria-hidden="true"></i>
   </label>
  </li>
  <li>
   <label> third
      <i class="fa fa-check-square hidden" aria-hidden="true"></i>
   </label>
  </li>
</ul>
</body>
</html>


问:
Python string join performance
There are a lot of articles around the web concerning Python performance. The first thing you read is concatenating strings should not be done using '+'; avoid s1 + s2 + s3, and instead use str.join

I tried the following: concatenating two strings as part of a directory path: three approaches:

'+' which I should not do

str.join

os.path.join

Here is my code:

```<code>import os, time

s1 = '/part/one/of/dir'
s2 = 'part/two/of/dir'
N = 10000

t = time.clock()
for i in xrange(N):
    s = s1 + os.sep + s2
print time.clock() - t

t = time.clock()
for i in xrange(N):
    s = os.sep.join((s1, s2))
print time.clock() - t

t = time.clock()
for i in xrange(N):
    s = os.path.join(s1, s2)
print time.clock() - t
</code>```

Here the results (Python 2.5 on Windows XP):

0.0182201927899
0.0262544541275
0.120238186697
```

Shouldn't it be exactly the other way around?

答: String concatenation (+) has an optimized implementation on CPython. But this may not be the case on other architectures like Jython or IronPython. So when you want your code to perform well on these interpreters you should use the .join() method on strings. os.path.join() is specifically meant to join filesystem paths. It takes care of different path separators, too. This would be the right way to build a file name.

OwnerDisplayName: Danny

ContentLicense: CC BY-SA 4.0

Title: Python string join performance

Body:
There are a lot of articles around the web concerning Python performance. The first thing you read is concatenating strings should not be done using '+'; avoid s1 + s2 + s3, and instead use str.join

I tried the following: concatenating two strings as part of a directory path: three approaches:

'+' which I should not do

str.join

os.path.join

Here is my code:

import os, time

s1 = '/part/one/of/dir'
s2 = 'part/two/of/dir'
N = 10000

t = time.clock()
for i in xrange(N):
    s = s1 + os.sep + s2
print time.clock() - t

t = time.clock()
for i in xrange(N):
    s = os.sep.join((s1, s2))
print time.clock() - t

t = time.clock()
for i in xrange(N):
    s = os.path.join(s1, s2)
print time.clock() - t

Here the results (Python 2.5 on Windows XP):

0.0182201927899
0.0262544541275
0.120238186697

Shouldn't it be exactly the other way around?

LastEditorDisplayName: Danny

OwnerDisplayName: unbeknown


问:
SQL join and group problem
First to say I'm using mySQL and my only way of accessing database is over phpMyAdmin since this is for a website.

First I have a table of users like this (table1):

```<code>user_id | name
--------------
      1 | Mike
      2 | Johny
      3 | Bob
</code>```

and another table about their season results (table2):

```<code>user_id | season | result
-------------------------
      1 | 2009   |     10
      1 | 2010   |      8
      1 | 2011   |      5
      2 | 2009   |      7
      2 | 2010   |      3
      3 | 2009   |      1
</code>```

And now I want out the user's name and his last season's result, so something like this:

```<code>user_id | name | season | result
--------------------------------
      1 | Mike |   2011 |      5
      2 | Johny|   2010 |      3
      3 | Bob  |   2009 |      1
</code>```

The closest I have come to something like this was

```<code>SELECT * FROM table1 INNER JOIN table2 ON table1.user_id = table2.user_id GROUP BY id
</code>```

But I cannot provide that I want the newest season and it just uses a random one.
Anyone has any ideas how to do this?

best regards,
Rok

答:
Have you tried to order them by Season column?</p>

```<code>SELECT * FROM table1 INNER JOIN table2 ON table1.user_id = table2.user_id GROUP BY id ORDER BY season DESC</code>```

ContentLicense: CC BY-SA 2.5

Title: SQL join and group problem

Body:
First to say I'm using mySQL and my only way of accessing database is over phpMyAdmin since this is for a website.

First I have a table of users like this (table1):

user_id | name
--------------
      1 | Mike
      2 | Johny
      3 | Bob

and another table about their season results (table2):

user_id | season | result
-------------------------
      1 | 2009   |     10
      1 | 2010   |      8
      1 | 2011   |      5
      2 | 2009   |      7
      2 | 2010   |      3
      3 | 2009   |      1

And now I want out the user's name and his last season's result, so something like this:

user_id | name | season | result
--------------------------------
      1 | Mike |   2011 |      5
      2 | Johny|   2010 |      3
      3 | Bob  |   2009 |      1

The closest I have come to something like this was

SELECT * FROM table1 INNER JOIN table2 ON table1.user_id = table2.user_id GROUP BY id

But I cannot provide that I want the newest season and it just uses a random one.
Anyone has any ideas how to do this?

best regards,
Rok

Body:
Have you tried to order them by Season column?

SELECT * FROM table1 INNER JOIN table2 ON table1.user_id = table2.user_id GROUP BY id ORDER BY season DESC


问:
paintComponent code not working
I am new to Swing and trying to add a background of an image to my JFrame. However my paintComponent method is not working. Could you please give me some suggestions on how to fix my code so the image is painted in the background?

Code is below:

```<code>// all necessary imports have been added.
public class Menu extends JFrame  {
private Image backgroundImage;
private JFrame frame;

public static void main(String[] args) throws IOException {
    Menu window = new Menu();
    window.frame.setVisible(true);
}

public Menu() throws IOException {
    initialize();
}

public void initialize() throws IOException {

    frame = new JFrame();
    frame.setBounds(100, 100, 312, 294);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

}
public void paintComponent(Graphics g) throws IOException {
    backgroundImage = ImageIO.read(new File("P:\\Profiles\\workspace\\Games\\Images\\matrix.jpg"));
    g.drawImage(backgroundImage, 0, 0, null);

}
}
</code>```

答:
Overriding paintComponent of a JFrame is not useful, override the paintComponent of its content pane instead.

Extending JFrame is usually also not necessary.

Finally, it would better to use initialize to load the image (rather than loading it at each paint call) and do stuff on the content panel if you need.

Putting it all together, see this example :

```<code>public class Menu extends JPanel {

    private Image backgroundImage;

    public static void main(final String[] args) throws IOException {
        Menu menu = new Menu();
        JFrame frame = new JFrame();
        frame.setContentPane(menu);
        frame.setBounds(100, 100, 312, 294);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public Menu() throws IOException {
        initialize();
    }

    public void initialize() throws IOException {

        backgroundImage = ImageIO.read(new File("P:\\Profiles\\workspace\\Games\\Images\\matrix.jpg"));

    }

    @Override
    public void paintComponent(final Graphics g){

        super.paintComponent(g);
        g.drawImage(backgroundImage, 0, 0, this);

    }

}
</code>```

Title: paintComponent code not working

Body:
I am new to Swing and trying to add a background of an image to my JFrame. However my paintComponent method is not working. Could you please give me some suggestions on how to fix my code so the image is painted in the background?

Code is below:

// all necessary imports have been added.
public class Menu extends JFrame  {
private Image backgroundImage;
private JFrame frame;

public static void main(String[] args) throws IOException {
    Menu window = new Menu();
    window.frame.setVisible(true);
}

public Menu() throws IOException {
    initialize();
}

public void initialize() throws IOException {

    frame = new JFrame();
    frame.setBounds(100, 100, 312, 294);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

}
public void paintComponent(Graphics g) throws IOException {
    backgroundImage = ImageIO.read(new File("P:\\Profiles\\workspace\\Games\\Images\\matrix.jpg"));
    g.drawImage(backgroundImage, 0, 0, null);

}
}

Body:
Overriding paintComponent of a JFrame is not useful, override the paintComponent of its content pane instead.

Extending JFrame is usually also not necessary.

Finally, it would better to use initialize to load the image (rather than loading it at each paint call) and do stuff on the content panel if you need.

Putting it all together, see this example :

public class Menu extends JPanel {

    private Image backgroundImage;

    public static void main(final String[] args) throws IOException {
        Menu menu = new Menu();
        JFrame frame = new JFrame();
        frame.setContentPane(menu);
        frame.setBounds(100, 100, 312, 294);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public Menu() throws IOException {
        initialize();
    }

    public void initialize() throws IOException {

        backgroundImage = ImageIO.read(new File("P:\\Profiles\\workspace\\Games\\Images\\matrix.jpg"));

    }

    @Override
    public void paintComponent(final Graphics g){

        super.paintComponent(g);
        g.drawImage(backgroundImage, 0, 0, this);

    }

}


答:
Try debugging your code and you'll see that the text of the RichTextBox in the addText class is set. Only... it is another instance of Form1 and not your current shown form. Add following line in the returnText method to see this:

```<code>f.Show();
</code>```

Pass the form as a parameter to the class and then this will work. In the button click event, change the line to following:

```<code>addText.returnText(this);
</code>```

And the returnText method looks like this:

```<code>public static void returnText(Form1 form)
{
    string s = "test test;";
    form.addData(s);
}
</code>```

But better would be to return a value from the class and set that value in the richtextbox in the form class:

```<code>private void button1_Click(object sender, EventArgs e)
{
    richTextBox1.AppendText(addText.returnText());
    // OR
    addData(addText.returnText());
}

public static string returnText()
{
    string s = "test test;";
    return s;
}
</code>```

Title: How to change the text from a textfield from a different class in WindowsForm

Body:
Try debugging your code and you'll see that the text of the RichTextBox in the addText class is set. Only... it is another instance of Form1 and not your current shown form. Add following line in the returnText method to see this:

f.Show();

Pass the form as a parameter to the class and then this will work. In the button click event, change the line to following:

addText.returnText(this);

And the returnText method looks like this:

public static void returnText(Form1 form)
{
    string s = "test test;";
    form.addData(s);
}

But better would be to return a value from the class and set that value in the richtextbox in the form class:

private void button1_Click(object sender, EventArgs e)
{
    richTextBox1.AppendText(addText.returnText());
    // OR
    addData(addText.returnText());
}

public static string returnText()
{
    string s = "test test;";
    return s;
}


问:
OnBackpressed get empty view on tablayout
I am stuck in solving this problem. I have set tabs in fragment using TabLayout and ViewPager. The problem is when i move to next fragment and then i press back button i get empty tabs view.

Here I am attaching my code:

home.xml

```<code><?xml version="1.0" encoding="utf-8"?>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <android.support.design.widget.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:tabIndicatorColor="@android:color/white"
        app:tabIndicatorHeight="4dp" />

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="fill_parent" />

    </LinearLayout>`
</code>```

home.java(fragment)

```<code>@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.home, container, false);

    ((Drawer) getActivity()).setActionBarTitle("Home");

    Toast.makeText(getActivity(), "entry count" +    getActivity().getSupportFragmentManager().getBackStackEntryCount(), Toast.LENGTH_SHORT).show();

    tabLayout = (TabLayout) view.findViewById(R.id.tabLayout);

    tabLayout.addTab(tabLayout.newTab().setText("Products"));

    tabLayout.addTab(tabLayout.newTab().setText("Category"));

    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

    viewPager = (ViewPager) view.findViewById(R.id.pager);
    Pager adapter = new Pager(getActivity().getSupportFragmentManager(), tabLayout.getTabCount());
   tabLayout.getTabCount());

    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

    viewPager.setAdapter(adapter);

    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.setOnTabSelectedListener(this);
    return view;

}

@Override
public void onTabSelected(TabLayout.Tab tab) {
    viewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(TabLayout.Tab tab) {

}

@Override
public void onTabReselected(TabLayout.Tab tab) {

}
</code>```

pager.java (Adapter)

```<code>public class Pager extends FragmentStatePagerAdapter {

int tabCount;

public Pager(FragmentManager fm, int tabCount) {
    super(fm);
    this.tabCount = tabCount;
}

@Override
public Fragment getItem(int position) {
    switch (position) {
        case 0:
            Product tab1 = new Product();
            return tab1;
        case 1:
            Category tab2 = new Category();
            return tab2;
        default:
            return null;
    }
}

@Override
public int getCount() {
    return tabCount;
}
}
</code>```

MainActivity (where I set this tab fragment)

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_drawer);

    getSupportActionBar().setTitle("Home");
    fragment = new home();
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.replace(R.id.main, fragment);
    ft.commit();
</code>```

答:
I had faced same issue when replacing fragment and that replaced fragment have TabLayout (i.e. Inner Fragments)

After researching about this issue: i found solution

What i does:

replacing

```<code> ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity().getSupportFragmentManager());
</code>```

to

If your Parent Activity is extending AppCompatActivity , then use

```<code>ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());
</code>```

If your Parent Activity is extending Activity than use

```<code>ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity().getChildFragmentManager());
</code>```

Body:
I am stuck in solving this problem. I have set tabs in fragment using TabLayout and ViewPager. The problem is when i move to next fragment and then i press back button i get empty tabs view.

Here I am attaching my code:

home.xml

<?xml version="1.0" encoding="utf-8"?>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <android.support.design.widget.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:tabIndicatorColor="@android:color/white"
        app:tabIndicatorHeight="4dp" />

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="fill_parent" />

    </LinearLayout>`

home.java(fragment)

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.home, container, false);

    ((Drawer) getActivity()).setActionBarTitle("Home");

    Toast.makeText(getActivity(), "entry count" +    getActivity().getSupportFragmentManager().getBackStackEntryCount(), Toast.LENGTH_SHORT).show();

    tabLayout = (TabLayout) view.findViewById(R.id.tabLayout);

    tabLayout.addTab(tabLayout.newTab().setText("Products"));

    tabLayout.addTab(tabLayout.newTab().setText("Category"));

    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

    viewPager = (ViewPager) view.findViewById(R.id.pager);
    Pager adapter = new Pager(getActivity().getSupportFragmentManager(), tabLayout.getTabCount());
   tabLayout.getTabCount());

    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

    viewPager.setAdapter(adapter);

    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.setOnTabSelectedListener(this);
    return view;

}

@Override
public void onTabSelected(TabLayout.Tab tab) {
    viewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(TabLayout.Tab tab) {

}

@Override
public void onTabReselected(TabLayout.Tab tab) {

}

pager.java (Adapter)

public class Pager extends FragmentStatePagerAdapter {

int tabCount;

public Pager(FragmentManager fm, int tabCount) {
    super(fm);
    this.tabCount = tabCount;
}

@Override
public Fragment getItem(int position) {
    switch (position) {
        case 0:
            Product tab1 = new Product();
            return tab1;
        case 1:
            Category tab2 = new Category();
            return tab2;
        default:
            return null;
    }
}

@Override
public int getCount() {
    return tabCount;
}
}

MainActivity (where I set this tab fragment)

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_drawer);

    getSupportActionBar().setTitle("Home");
    fragment = new home();
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.replace(R.id.main, fragment);
    ft.commit();

Body:
I had faced same issue when replacing fragment and that replaced fragment have TabLayout (i.e. Inner Fragments)

After researching about this issue: i found solution

What i does:

replacing

 ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity().getSupportFragmentManager());

to

If your Parent Activity is extending AppCompatActivity , then use

ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());

If your Parent Activity is extending Activity than use

ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity().getChildFragmentManager());


问:
Show div using button and hide it if click outside the div
I tried to create a function to show and hide a div, to hide the div user can use close button or click outside the div, but the problem is the close function to hide the div if user click element outside the div run first before i the div is showed:

html:

$('#close-add').on('click', function() {
  $("#add-shipping-modal").hide();
});

$('#new-shipping').on('click', function() {
  $("#add-shipping-modal").show();
});

$('body').click(function(event) {
  setTimeout(
    if (!$(event.target).closest('#add-shipping-modal').length && !$(event.target).is('#add-shipping-modal')) {
      if ($("#add-shipping-modal").css('display') != 'none') {
        $("#add-shipping-modal").hide();
      }
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="new-shipping'">Open Div</button>
<div id="add-shipping-modal" style="display:none">
  <button id="close-add">Close Div</button>
  <p> Show Me </p>
</div></code>```

when i click the #new-shipping button, the hidden div won't show up, i guess it's because when i click the #new-shipping button, it shows the div first and then trigger the body click function

答:
You have added ' extra in your code after new-shipping

```<code><button id="new-shipping'">Open Div</button>
</code>```

should be

```<code> <button id="new-shipping">Open Div</button>
</code>```

https://jsfiddle.net/bntnfhLm/

Also please change the body click function by using preventdefault/stopPropagation

```<code>$("#add-shipping-modal").click(function(e){
    e.stopPropagation();
});

$(document).click(function(){
    $("#add-shipping-modal").hide();
});
</code>```

Body:
I tried to create a function to show and hide a div, to hide the div user can use close button or click outside the div, but the problem is the close function to hide the div if user click element outside the div run first before i the div is showed:

html:

$('#close-add').on('click', function() {
  $("#add-shipping-modal").hide();
});

$('#new-shipping').on('click', function() {
  $("#add-shipping-modal").show();
});

$('body').click(function(event) {
  setTimeout(
    if (!$(event.target).closest('#add-shipping-modal').length && !$(event.target).is('#add-shipping-modal')) {
      if ($("#add-shipping-modal").css('display') != 'none') {
        $("#add-shipping-modal").hide();
      }
    }
  });
});

<button id="new-shipping'">Open Div</button>

  <button id="close-add">Close Div</button>

 Show Me

when i click the #new-shipping button, the hidden div won't show up, i guess it's because when i click the #new-shipping button, it shows the div first and then trigger the body click function

Body:
You have added ' extra in your code after new-shipping

<button id="new-shipping'">Open Div</button>

should be

 <button id="new-shipping">Open Div</button>

https://jsfiddle.net/bntnfhLm/

Also please change the body click function by using preventdefault/stopPropagation

$("#add-shipping-modal").click(function(e){
    e.stopPropagation();
});

$(document).click(function(){
    $("#add-shipping-modal").hide();
});


问:
date time format null values return default time in PHP
i am currently working on codeigniter project.i have a database name is "student_detail" the table value have like this

```<code>  payment_date
1 NULL
2 NULL
3 2017-12-06 08:47:40

payment_date column is a DATETIME format
</code>```

. when i print this column it returns like this

```<code>payment_date
1 1970-01-01 00:00:00
2 1970-01-01 00:00:00
3 2017-12-06 08:47:40
</code>```

but i need to return as NULL not default time format.

答:
```<code>SELECT
id, IF(payment_date='1970-01-01 00:00:00', null, payment_date) as payment_date
FROM `student_detail`
</code>```

Body:
i am currently working on codeigniter project.i have a database name is "student_detail" the table value have like this

  payment_date
1 NULL
2 NULL
3 2017-12-06 08:47:40

payment_date column is a DATETIME format

. when i print this column it returns like this

payment_date
1 1970-01-01 00:00:00
2 1970-01-01 00:00:00
3 2017-12-06 08:47:40

but i need to return as NULL not default time format.


问:
S3.putObject - callback never gets called
I'm trying to upload an image to S3 but when I call s3.putObject(params, callback), my callback never gets called and no errors are logged.

Here's the relevant code:

```<code>var params = {
  Key: key,
  Body: imageData,
  ContentLength: imageData.byteCount,
  ContentType: contentType,
};
this.s3.putObject(params, function(err, data) {
  console.log('here');
  if (err) {
    callback(err);
    return;
  }
  callback(null, key);
});
</code>```

Where params is {
  Key: 'e2f99bf3a321282cc7dfaef69fe8ca62.jpg',
  Body: {imageData parsed from request using node-multiparty},
  ContentLength: 27802,
  ContentType: 'image/jpeg',
}

I have verified that this.s3 is valid and typeof this.s3.putObject is function as expected.

答:
I got exactly the same behavior with all the IAM rights, and lost a bit of time before I got it to work.

If your lambda function runs inside a VPC you have to create an endpoint for S3 as describe in this article from AWS blog.

If you want to see more in details where it hangs, you can use the following code. Instead of giving a callback a keep the reference on the request and basically observe its events (see the documentation of S3.putObject and AWS.Request).

```<code>var obj = s3.putObject(params);
obj.on('validate',             (...args)=>{args.unshift('validate');             console.log(...args);})
   .on('build',                (...args)=>{args.unshift('build');                console.log(...args);})
   .on('sign',                 (...args)=>{args.unshift('sign');                 console.log(...args);})
   .on('send',                 (...args)=>{args.unshift('send');                 console.log(...args);})
   .on('retry',                (...args)=>{args.unshift('retry');                console.log(...args);})
   .on('extractError',         (...args)=>{args.unshift('extractError');         console.log(...args);})
   .on('extractData',          (...args)=>{args.unshift('extractData');          console.log(...args);})
   .on('success',              (...args)=>{args.unshift('success');              console.log(...args);})
   .on('error',                (...args)=>{args.unshift('error');                console.log(...args);})
   .on('complete',             (...args)=>{args.unshift('complete');             console.log(...args);})
   .on('httpHeaders',          (...args)=>{args.unshift('httpHeaders');          console.log(...args);})
   .on('httpData',             (...args)=>{args.unshift('httpData');             console.log(...args);})
   .on('httpUploadProgress',   (...args)=>{args.unshift('httpUploadProgress');   console.log(...args);})
   .on('httpDownloadProgress', (...args)=>{args.unshift('httpDownloadProgress'); console.log(...args);})
   .on('httpError',            (...args)=>{args.unshift('httpError');            console.log(...args);})
   .on('httpDone',             (...args)=>{args.unshift('httpDone');             console.log(...args);})
   .send();
</code>```

By doing so I got to see the underlying HTTP request was trying to reach the public urls of the bucket, which is not possible from a VPC unless you have the endpoint :).

Here is also another post about accessing AWS ressources from a VPC also from AWS blog.

Body:
I'm trying to upload an image to S3 but when I call s3.putObject(params, callback), my callback never gets called and no errors are logged.

Here's the relevant code:

var params = {
  Key: key,
  Body: imageData,
  ContentLength: imageData.byteCount,
  ContentType: contentType,
};
this.s3.putObject(params, function(err, data) {
  console.log('here');
  if (err) {
    callback(err);
    return;
  }
  callback(null, key);
});

Where params is {
  Key: 'e2f99bf3a321282cc7dfaef69fe8ca62.jpg',
  Body: {imageData parsed from request using node-multiparty},
  ContentLength: 27802,
  ContentType: 'image/jpeg',
}

I have verified that this.s3 is valid and typeof this.s3.putObject is function as expected.

Body:
I got exactly the same behavior with all the IAM rights, and lost a bit of time before I got it to work.

If your lambda function runs inside a VPC you have to create an endpoint for S3 as describe in this article from AWS blog.

If you want to see more in details where it hangs, you can use the following code. Instead of giving a callback a keep the reference on the request and basically observe its events (see the documentation of S3.putObject and AWS.Request).

var obj = s3.putObject(params);
obj.on('validate',             (...args)=>{args.unshift('validate');             console.log(...args);})
   .on('build',                (...args)=>{args.unshift('build');                console.log(...args);})
   .on('sign',                 (...args)=>{args.unshift('sign');                 console.log(...args);})
   .on('send',                 (...args)=>{args.unshift('send');                 console.log(...args);})
   .on('retry',                (...args)=>{args.unshift('retry');                console.log(...args);})
   .on('extractError',         (...args)=>{args.unshift('extractError');         console.log(...args);})
   .on('extractData',          (...args)=>{args.unshift('extractData');          console.log(...args);})
   .on('success',              (...args)=>{args.unshift('success');              console.log(...args);})
   .on('error',                (...args)=>{args.unshift('error');                console.log(...args);})
   .on('complete',             (...args)=>{args.unshift('complete');             console.log(...args);})
   .on('httpHeaders',          (...args)=>{args.unshift('httpHeaders');          console.log(...args);})
   .on('httpData',             (...args)=>{args.unshift('httpData');             console.log(...args);})
   .on('httpUploadProgress',   (...args)=>{args.unshift('httpUploadProgress');   console.log(...args);})
   .on('httpDownloadProgress', (...args)=>{args.unshift('httpDownloadProgress'); console.log(...args);})
   .on('httpError',            (...args)=>{args.unshift('httpError');            console.log(...args);})
   .on('httpDone',             (...args)=>{args.unshift('httpDone');             console.log(...args);})
   .send();

By doing so I got to see the underlying HTTP request was trying to reach the public urls of the bucket, which is not possible from a VPC unless you have the endpoint :).

Here is also another post about accessing AWS ressources from a VPC also from AWS blog.


问:
Raspbian docker: Error response from daemon: cgroups: memory cgroup not supported on this system: unknown
I am new to docker, I plug my PI3 to test some stuff and I'm already facing an error, I can't figured that out myself.

So I freshly install raspbian and docker.

That's my install log

Then I try the classic hello-word test

and there is the log

答: Another solution is to add cgroup_enable=memory cgroup_memory=1 in /boot/cmdline.txt at the end of the line and reboot.


问:
User name in .bazelrc
I would like to add this to my .bazelrc, but the $(whoami) doesn't expand like if it was in a shell.

```<code>startup --output_user_root=/tmp/bazel/out/$(whoami)
</code>```

It produces the literal result:

```<code>/tmp/bazel/out/$(whoami)/faedb999bdce730c9c495251de1ca1a4/execroot/__main__/bazel-out/
</code>```

Is there any way to do what I want: adding a name/hash to the option in the .bashrc file?

Edit: what I really want is to set the outputRoot to /tmp/bazel/out without using an environment variable and to let bazel create it's user and workspace hash directories there.

答: You can run Bazel from a wrapper script. In fact, that's exactly what the bazel binary is (at least on Linux): it's a wrapper script that calls bazel-real. You can edit this wrapper script if you like, or rename it to bazel.sh and write your own wrapper.

Title: User name in .bazelrc

Body:
I would like to add this to my .bazelrc, but the $(whoami) doesn't expand like if it was in a shell.

startup --output_user_root=/tmp/bazel/out/$(whoami)

It produces the literal result:

/tmp/bazel/out/$(whoami)/faedb999bdce730c9c495251de1ca1a4/execroot/__main__/bazel-out/

Is there any way to do what I want: adding a name/hash to the option in the .bashrc file?

Edit: what I really want is to set the outputRoot to /tmp/bazel/out without using an environment variable and to let bazel create it's user and workspace hash directories there.


问:
C#: How to set default value if input is empty
If I have a method like this:

```<code>public void AddSomething(string ice = "10", string sweet = "20")
{
    Console.Write(ice);
    Console.Write(sweet);
}
</code>```

so if I input a string, it will write the string. If not, it will write the default string(10,20).

But I want something like this:

```<code>public void AddSomething(string ice = "10", string sweet = "20")
{
    if(ice = "")
        ice = default_vaule;    //which is 10
    if(sweet = "")
        sweet = default_vaule;  //which is 20
    Console.Write(ice);
    Console.Write(sweet);
}
</code>```

so if user input a empty string "", I can write the default value to user, so I can do not only this:

```<code>AddSomething("5");
</code>```

Also both of these:

```<code>AddSomething("5","");
AddSomething("","5");
</code>```

Anyone knows how to do that? THX!

答:
This question ( at least for me ) is unclear but from what you've posted I can suggest solution like this :

```<code>// default value for "ice"
const string default_ice = "10";
// default value for "sweet"
const string default_sweet = "20";

public void AddSomething(string ice = default_ice, string sweet = default_sweet)
{

    // check if "ice" value is set
    if(string.IsNullOrEmpty(ice))
        ice = default_ice;    // set "ice" value to the default one

    // check if "sweet" value is set
    if(string.IsNullOrEmpty(sweet))
        sweet = default_sweet;  // set "sweet" value to the default one

    Console.Write(ice);
    Console.Write(sweet);
}
</code>```

You can then also call it like such:

```<code>AddSomething(sweet: "1337");
// or
AddSomething("13", "37");
</code>```

or however you like.

Try this online

Body:
If I have a method like this:

public void AddSomething(string ice = "10", string sweet = "20")
{
    Console.Write(ice);
    Console.Write(sweet);
}

so if I input a string, it will write the string. If not, it will write the default string(10,20).

But I want something like this:

public void AddSomething(string ice = "10", string sweet = "20")
{
    if(ice = "")
        ice = default_vaule;    //which is 10
    if(sweet = "")
        sweet = default_vaule;  //which is 20
    Console.Write(ice);
    Console.Write(sweet);
}

so if user input a empty string "", I can write the default value to user, so I can do not only this:

AddSomething("5");

Also both of these:

AddSomething("5","");
AddSomething("","5");

Anyone knows how to do that? THX!

Body:
This question ( at least for me ) is unclear but from what you've posted I can suggest solution like this :

// default value for "ice"
const string default_ice = "10";
// default value for "sweet"
const string default_sweet = "20";

public void AddSomething(string ice = default_ice, string sweet = default_sweet)
{

    // check if "ice" value is set
    if(string.IsNullOrEmpty(ice))
        ice = default_ice;    // set "ice" value to the default one

    // check if "sweet" value is set
    if(string.IsNullOrEmpty(sweet))
        sweet = default_sweet;  // set "sweet" value to the default one

    Console.Write(ice);
    Console.Write(sweet);
}

You can then also call it like such:

AddSomething(sweet: "1337");
// or
AddSomething("13", "37");

or however you like.

Try this online


问:
How to use a fixed point sin function in Vivado HLS
I am calculating the intersection point of two lines given in the polar coordinate system:

typedef ap_fixed<16,3,AP_RND> t_lines_angle;
typedef ap_fixed<16,14,AP_RND> t_lines_rho;

bool get_intersection(
        hls::Polar_< t_lines_angle, t_lines_rho>* lineOne,
        hls::Polar_< t_lines_angle, t_lines_rho>* lineTwo,
        Point* point)
{
    float angleL1 = lineOne->angle.to_float();
    float angleL2 = lineTwo->angle.to_float();
    t_lines_angle rhoL1 = lineOne->rho.to_float();
    t_lines_angle rhoL2 = lineTwo->rho.to_float();
    t_lines_angle ct1=cosf(angleL1);
    t_lines_angle st1=sinf(angleL1);
    t_lines_angle ct2=cosf(angleL2);
    t_lines_angle st2=sinf(angleL2);
    t_lines_angle d=ct1*st2-st1*ct2;

    // we make sure that the lines intersect
    // which means that parallel lines are not possible
    point->X = (int)((st2*rhoL1-st1*rhoL2)/d);
    point->Y = (int)((-ct2*rhoL1+ct1*rhoL2)/d);

    return true;
}
```

After synthesis for our FPGA I saw that the 4 implementations of the float sine (and cos) take 4800 LUTs per implementation, which sums up to 19000 LUTs for these 4 functions. I want to reduce the LUT count by using a fixed point sine. I already found a implementation of CORDIC but I am not sure how to use it. The input of the function is an integer but i have a ap_fixed datatype. How can I map this ap_fixed to integer? and how can I map my 3.13 fixed point to the required 2.14 fixed point?

答:
You can use bit-slicing to get the fraction and the integer parts of the ap_fixed variable, and then manipulate them to get the new ap_fixed. Perhaps something like:

```<code>constexpr int max(int a, int b) { return a > b ? a : b; }

template <int W2, int I2, int W1, int I1>
ap_fixed<W2, I2> convert(ap_fixed<W1, I1> f)
{
    // Read fraction part as integer:
    ap_fixed<max(W2, W1) + 1, max(I2, I1) + 1> result = f(W1 - I1 - 1, 0);
    // Shift by the original number of bits in the fraction part
    result >>= W1 - I1;
    // Add the integer part
    result += f(W1 - 1, W1 - I1);
    return result;
}
</code>```

I haven't tested this code well, so take it with a grain of salt.

Body:
I am calculating the intersection point of two lines given in the polar coordinate system:

typedef ap_fixed<16,3,AP_RND> t_lines_angle;
typedef ap_fixed<16,14,AP_RND> t_lines_rho;

bool get_intersection(
        hls::Polar_< t_lines_angle, t_lines_rho>* lineOne,
        hls::Polar_< t_lines_angle, t_lines_rho>* lineTwo,
        Point* point)
{
    float angleL1 = lineOne->angle.to_float();
    float angleL2 = lineTwo->angle.to_float();
    t_lines_angle rhoL1 = lineOne->rho.to_float();
    t_lines_angle rhoL2 = lineTwo->rho.to_float();
    t_lines_angle ct1=cosf(angleL1);
    t_lines_angle st1=sinf(angleL1);
    t_lines_angle ct2=cosf(angleL2);
    t_lines_angle st2=sinf(angleL2);
    t_lines_angle d=ct1*st2-st1*ct2;

    // we make sure that the lines intersect
    // which means that parallel lines are not possible
    point->X = (int)((st2*rhoL1-st1*rhoL2)/d);
    point->Y = (int)((-ct2*rhoL1+ct1*rhoL2)/d);

    return true;
}

After synthesis for our FPGA I saw that the 4 implementations of the float sine (and cos) take 4800 LUTs per implementation, which sums up to 19000 LUTs for these 4 functions. I want to reduce the LUT count by using a fixed point sine. I already found a implementation of CORDIC but I am not sure how to use it. The input of the function is an integer but i have a ap_fixed datatype. How can I map this ap_fixed to integer? and how can I map my 3.13 fixed point to the required 2.14 fixed point?

Body:
You can use bit-slicing to get the fraction and the integer parts of the ap_fixed variable, and then manipulate them to get the new ap_fixed. Perhaps something like:

constexpr int max(int a, int b) { return a > b ? a : b; }

template <int W2, int I2, int W1, int I1>
ap_fixed<W2, I2> convert(ap_fixed<W1, I1> f)
{
    // Read fraction part as integer:
    ap_fixed<max(W2, W1) + 1, max(I2, I1) + 1> result = f(W1 - I1 - 1, 0);
    // Shift by the original number of bits in the fraction part
    result >>= W1 - I1;
    // Add the integer part
    result += f(W1 - 1, W1 - I1);
    return result;
}

I haven't tested this code well, so take it with a grain of salt.


问:
PHP redirect without header() or meta
I'm trying to design a page which does some database actions, then redirects to user back to the page they came from. The problem is that I use a require() function to get the connection to the database, so the headers are already sent. A meta tag is out of the question since I want it to look like all the processes are done from the page they came from. Any tips? Is there a way I can use the require() and the header() or do I have to drop one? Is there an alternative to header()?

答:
If you can't send the header() before some content gets sent, use output buffering by placing an ob_start(); at the beginning of your script before anything is sent. That way, any content will be stored in a buffer and won't be sent until the end of the script or when you manually send the buffer's contents.

On another note, simply requireing another file would not generate any headers/content unless that included script sends them. The most common "hidden" cause of this is unnoticed whitespace before or after the <?php ?> tags.

Title: PHP redirect without header() or meta


问:
C Language: I want to add all the positive integers when a negative number is inserted
I want to add all the positive integers when a negative number is entered.

Click for Example

```<code>int number;
int total;
int loopcount;
int a;
number = 0;
a = 0;
total = 0;

for(loopcount = 0; loopcount >=0; loopcount = loopcount + 1)
{
    printf("Enter Integer: ");
    scanf("%d", &number);
    a = number;

    if (a >= 0)
    {
        total = total + number;
    }
    else if(a < 0)
    {
        printf("Total positive int = %d\n", &total);
        break;
    }
}
</code>```

答:
There is a minor bug in your code here:

```<code>printf("Total positive int = %d\n", &total);
                                    ^
</code>```

When this is changed to:

```<code>printf("Total positive int = %d\n", total);
</code>```

A simpler version of the same would look like:

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

int main(void)
{
    int number = 0;
    int total = 0;

    while(1)
    {
        printf("Enter Integer: ");
        scanf("%d", &number);

        if (number >= 0)
        {
            total += number;
        }
        else if(number < 0)
        {
            total += number;
            printf("Total positive int = %d\n", total);
            break;
        }
        else
        {
            ;
        }
    }

    return 0;
}
</code>```

This code will do what it says, but it will also do different things if valid input is not inserted. Because, it doesn't take care of inputs that are not numbers.

Here is the one, that takes care of validating inputs and only allows numbers.

This version below has a lot to improve on, but I prefer it this way for letting learners understand the code and improve it further.

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

int main (void)
{
    char str[10] = { 0 }; //Assuming that the number can only be restricted to 9 digits. Change as required!
    char *ptr = NULL;
    double ret = 0.0;
    double total = 0.0;

    printf("Enter numbers: ");

    while(1)
    {
        str[0] = '\0';

        scanf("%s", str);
        ret = strtod(str, &ptr);
        if(ret == 0.0)
        {
           if(ptr != NULL)
           {
               printf("\nNot a number!");
               continue;
           }
           else
           {
               total += ret;
           }
        }
        else if(ret < 0.0)
        {
           total += ret;
           break;
        }
        else
        {
           total += ret;
        }
    }

    printf("\n%lf", total);

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

Body:
I want to add all the positive integers when a negative number is entered.

Click for Example

int number;
int total;
int loopcount;
int a;
number = 0;
a = 0;
total = 0;

for(loopcount = 0; loopcount >=0; loopcount = loopcount + 1)
{
    printf("Enter Integer: ");
    scanf("%d", &number);
    a = number;

    if (a >= 0)
    {
        total = total + number;
    }
    else if(a < 0)
    {
        printf("Total positive int = %d\n", &total);
        break;
    }
}

Body:
There is a minor bug in your code here:

printf("Total positive int = %d\n", &total);
                                    ^

When this is changed to:

printf("Total positive int = %d\n", total);

A simpler version of the same would look like:

#include<stdio.h>

int main(void)
{
    int number = 0;
    int total = 0;

    while(1)
    {
        printf("Enter Integer: ");
        scanf("%d", &number);

        if (number >= 0)
        {
            total += number;
        }
        else if(number < 0)
        {
            total += number;
            printf("Total positive int = %d\n", total);
            break;
        }
        else
        {
            ;
        }
    }

    return 0;
}

This code will do what it says, but it will also do different things if valid input is not inserted. Because, it doesn't take care of inputs that are not numbers.

Here is the one, that takes care of validating inputs and only allows numbers.

This version below has a lot to improve on, but I prefer it this way for letting learners understand the code and improve it further.

#include <stdio.h>
#include <stdlib.h>

int main (void)
{
    char str[10] = { 0 }; //Assuming that the number can only be restricted to 9 digits. Change as required!
    char *ptr = NULL;
    double ret = 0.0;
    double total = 0.0;

    printf("Enter numbers: ");

    while(1)
    {
        str[0] = '\0';

        scanf("%s", str);
        ret = strtod(str, &ptr);
        if(ret == 0.0)
        {
           if(ptr != NULL)
           {
               printf("\nNot a number!");
               continue;
           }
           else
           {
               total += ret;
           }
        }
        else if(ret < 0.0)
        {
           total += ret;
           break;
        }
        else
        {
           total += ret;
        }
    }

    printf("\n%lf", total);

    return(0);
}


问:
Use of pattern $match $in in aggregate function of Mongo PHP Library
I am using Mongo PHP Library in my code: https://github.com/mongodb/mongo-php-library/

I am trying to send following query to MongoDB using aggregate function in Mongo PHP Library:

Blockquote

```<code>db.customers.aggregate(
{$match: {Country: "India", Email: {$in: [/.*@gmail.com*/,/.*@hotmail.com*/] } } },
{$group : {_id : {Email: "Email"}, "count" : {$sum : 1} } },
{$sort : {"count" : -1} }
)
</code>```

This query works fine on MongoDB Server. But in PHP code it isn't working.

Blockquote

```<code>$query = array(
['$match' => ['Country' => "India",
              'Email' => ['$in' => ['/.*@gmail.com*/','/.*@hotmail.com*/']]
             ]
],
['$group' => ['_id' => ['Email' => '$Email']
              'count' => ['$sum' => 1]
             ]
],
['$sort' => ['count' => -1]]
);
$cursor = $this->customers->aggregate($query);
</code>```

$in array is not working with wildcard pattern as above. It doesn't show any error or result. But it works with exact email. How can i mention the pattern in $in array under $match

Please suggest how can i submit the wildcard pattern in Mongo PHP library.

答:
Try This </p>

```<code>$query = array(
array('$match' => array('Country' => "India",'Email' =>
    array('$in' => array('/.*@gmail.com*/','/.*@hotmail.com*/'))
)),

array('$group' =>  array('_id' =>  array('Email' => '$Email')
              'count' =>  array('$sum' => 1)
             )
),
 array('$sort' =>  array('count' => -1))
);
</code>```

Body:
I am using Mongo PHP Library in my code: https://github.com/mongodb/mongo-php-library/

I am trying to send following query to MongoDB using aggregate function in Mongo PHP Library:

Blockquote

db.customers.aggregate(
{$match: {Country: "India", Email: {$in: [/.*@gmail.com*/,/.*@hotmail.com*/] } } },
{$group : {_id : {Email: "Email"}, "count" : {$sum : 1} } },
{$sort : {"count" : -1} }
)

This query works fine on MongoDB Server. But in PHP code it isn't working.

Blockquote

$query = array(
['$match' => ['Country' => "India",
              'Email' => ['$in' => ['/.*@gmail.com*/','/.*@hotmail.com*/']]
             ]
],
['$group' => ['_id' => ['Email' => '$Email']
              'count' => ['$sum' => 1]
             ]
],
['$sort' => ['count' => -1]]
);
$cursor = $this->customers->aggregate($query);

$in array is not working with wildcard pattern as above. It doesn't show any error or result. But it works with exact email. How can i mention the pattern in $in array under $match

Please suggest how can i submit the wildcard pattern in Mongo PHP library.

Body:
Try This

$query = array(
array('$match' => array('Country' => "India",'Email' =>
    array('$in' => array('/.*@gmail.com*/','/.*@hotmail.com*/'))
)),

array('$group' =>  array('_id' =>  array('Email' => '$Email')
              'count' =>  array('$sum' => 1)
             )
),
 array('$sort' =>  array('count' => -1))
);


问:
How to update table without pivot
I need to  better way to update the table due to performance issue This is my current table structure Now based on the weekNum, Table 2 value need to updated. Currently using pivot to get update, any other alternate solution. Please help

Table1:

```<code>╔════════╦══════╦════════╦═══════╗
║ Row ID ║ Desc ║ WeekNum║  Amt  ║
╠════════╬══════╬════════╬═══════╣
║      1 ║ Total║     01 ║ 25.00 ║
║      2 ║ Total║     02 ║ 55.00 ║
║      3 ║ Total║     04 ║ 78.00 ║
║      4 ║ Total║     06 ║ 99.00 ║
║      5 ║ Total║     07 ║ 54.00 ║
║      6 ║ Total║     09 ║ 58.00 ║
╚════════╩══════╩════════╩═══════╝
</code>```

Table2:

```<code> ╔══╦═════╦══════╦══════╗═════╗═══════╗══════╗══════╗══════╗═════╗══════╗
 ║ID║ Desc║  01  ║  02  ║ 03  ║   04  ║  05  ║ 06   ║ 07   ║ 08  ║ 09   ║
 ╠══╬═════╬══════╬══════╣═════║═══════║══════║══════║══════║═════║═════ ║
 ║ 1║Total║25.00 ║55.00 ║NULL ║ 78.00 ║ NULL ║ 99.00║54.00 ║NULL ║58.00 ║
 ╚══╩═════╩══════╩══════╝═════╝═══════╝══════╝══════╝══════╝═════╝══════╝
</code>```

答:
If the PIVOT is slow, you can separate it to 9 different updates wrapped in transaction. Your base query will be:

```<code>UPDATE Table1
SET [01] = T2.[Amnt]
FROM Table1 T1
INNER JOIN Table2 T2
    ON T1.[Desc] = T2.[Desc]
WHERE T2.[Week] = '01';
</code>```

You will do this for each column. If your real example contains bigger number of distinct, weeks, you can use dynamic T-SQL statement to build the execution code. It will be shorter and looks better. Something like this:

```<code>DECLARE @DistitincWeeks TABLE
(
    [Week] VARCHAR(8)
);

INSERT INTO @DistitincWeeks ([Week])
SELECT DISTINCT [Week]
FROM Table1;

DECLARE @DynamictSQLStatement NVARCHAR(MAX)
       ,@CurrentWeek VARCHAR(8);

WHILE(EXISTS(SELECT 1 FROM @DistitincWeeks))
BEGIN;
    SELECT TOP (1) @CurrentWeek = [Week]
    FROM @DistitincWeeks;
    --

    SET @DynamictSQLStatement = @DynamictSQLStatement +
    '
    UPDATE Table1
    SET [' + @CurrentWeek + '] = T2.[Amnt]
    FROM Table1 T1
    INNER JOIN Table2 T2
        ON T1.[Desc] = T2.[Desc]
    WHERE T2.[Week] = ''' +  @CurrentWeek  +''';
    ';

    --
    DELETE FROM @DistitincWeeks
    WHERE [Week] @CurrentWeek
END;

EXECUTE sp_executesql @DynamictSQLStatement;
</code>```

Alternatively, you can create an after insert trigger on the Table1 which modifies the corresponding rows in Table2 when data is changed. You can use variant of the code above for the trigger body. Just be sure you are manipulating the rows in batches, not in loop or using cursor.

I don't like triggers and will advice if you have a routine, stored procedure or other application code, which is updating the Table1 data, just do update the data in the Table2, too. It's more clear for me, but you must be sure no other routine is modifying the data in Table1.

It will be better to constantly updating Table2 on small batches, when data in Table1 is modified against performing huge updates on every X hours or days.

If the following update is slow, too:

```<code>UPDATE Table1
SET [01] = T2.[Amnt]
FROM Table1 T1
INNER JOIN Table2 T2
    ON T1.[Desc] = T2.[Desc]
WHERE T2.[Week] = '01';
</code>```

You should check the table structure (column types) itself and the corresponding indexes.

Title: How to update table without pivot

Body:
I need to  better way to update the table due to performance issue This is my current table structure Now based on the weekNum, Table 2 value need to updated. Currently using pivot to get update, any other alternate solution. Please help

Table1:

╔════════╦══════╦════════╦═══════╗
║ Row ID ║ Desc ║ WeekNum║  Amt  ║
╠════════╬══════╬════════╬═══════╣
║      1 ║ Total║     01 ║ 25.00 ║
║      2 ║ Total║     02 ║ 55.00 ║
║      3 ║ Total║     04 ║ 78.00 ║
║      4 ║ Total║     06 ║ 99.00 ║
║      5 ║ Total║     07 ║ 54.00 ║
║      6 ║ Total║     09 ║ 58.00 ║
╚════════╩══════╩════════╩═══════╝

Table2:

 ╔══╦═════╦══════╦══════╗═════╗═══════╗══════╗══════╗══════╗═════╗══════╗
 ║ID║ Desc║  01  ║  02  ║ 03  ║   04  ║  05  ║ 06   ║ 07   ║ 08  ║ 09   ║
 ╠══╬═════╬══════╬══════╣═════║═══════║══════║══════║══════║═════║═════ ║
 ║ 1║Total║25.00 ║55.00 ║NULL ║ 78.00 ║ NULL ║ 99.00║54.00 ║NULL ║58.00 ║
 ╚══╩═════╩══════╩══════╝═════╝═══════╝══════╝══════╝══════╝═════╝══════╝

Body:
If the PIVOT is slow, you can separate it to 9 different updates wrapped in transaction. Your base query will be:

UPDATE Table1
SET [01] = T2.[Amnt]
FROM Table1 T1
INNER JOIN Table2 T2
    ON T1.[Desc] = T2.[Desc]
WHERE T2.[Week] = '01';

You will do this for each column. If your real example contains bigger number of distinct, weeks, you can use dynamic T-SQL statement to build the execution code. It will be shorter and looks better. Something like this:

DECLARE @DistitincWeeks TABLE
(
    [Week] VARCHAR(8)
);

INSERT INTO @DistitincWeeks ([Week])
SELECT DISTINCT [Week]
FROM Table1;

DECLARE @DynamictSQLStatement NVARCHAR(MAX)
       ,@CurrentWeek VARCHAR(8);

WHILE(EXISTS(SELECT 1 FROM @DistitincWeeks))
BEGIN;
    SELECT TOP (1) @CurrentWeek = [Week]
    FROM @DistitincWeeks;
    --

    SET @DynamictSQLStatement = @DynamictSQLStatement +
    '
    UPDATE Table1
    SET [' + @CurrentWeek + '] = T2.[Amnt]
    FROM Table1 T1
    INNER JOIN Table2 T2
        ON T1.[Desc] = T2.[Desc]
    WHERE T2.[Week] = ''' +  @CurrentWeek  +''';
    ';

    --
    DELETE FROM @DistitincWeeks
    WHERE [Week] @CurrentWeek
END;

EXECUTE sp_executesql @DynamictSQLStatement;

Alternatively, you can create an after insert trigger on the Table1 which modifies the corresponding rows in Table2 when data is changed. You can use variant of the code above for the trigger body. Just be sure you are manipulating the rows in batches, not in loop or using cursor.

I don't like triggers and will advice if you have a routine, stored procedure or other application code, which is updating the Table1 data, just do update the data in the Table2, too. It's more clear for me, but you must be sure no other routine is modifying the data in Table1.

It will be better to constantly updating Table2 on small batches, when data in Table1 is modified against performing huge updates on every X hours or days.

If the following update is slow, too:

UPDATE Table1
SET [01] = T2.[Amnt]
FROM Table1 T1
INNER JOIN Table2 T2
    ON T1.[Desc] = T2.[Desc]
WHERE T2.[Week] = '01';

You should check the table structure (column types) itself and the corresponding indexes.