问:
mysql. Stored Procedure Error 1328
This is really baffling me. I am converting a simple procedure from informix into mysql. What it basically does is tell me what the next event is from an event table and a calendar table. In informix the procedure is simple.

```<code>FOREACH
SELECT  date,weekno,event
INTO    l_date,l_week,l_event
FROM    event,calendar
WHERE   dayno = dayno
AND     date = l_today
AND     start >= l_now
UNION
SELECT  date,weekno,event
FROM    event,calendar
WHERE   dayno = dayno
AND     date > l_today
UNION
SELECT  TODAY,9999,9999
FROM    event,calendar
WHERE   dayno   = dayno
AND     event = (SELECT MAX(event) FROM event)
ORDER BY 3

if l_event = 9999 then <error> end if;
EXIT FOREACH
END FOREACH
</code>```

So basically the query finds the next event and returns it. l_today and l_event are parameters that are passed. So on to the mysql version.

```<code>looper: BEGIN
    DECLARE curs1 CURSOR FOR
        SELECT CONCAT("SELECT date, weekno, event FROM event INNER JOIN calendar ON dayno = dayno",
                " WHERE date = '", lv_today ,"' AND start >= '", lv_time ,"'",
                " UNION SELECT date, weekno, event FROM event INNER JOIN calendar ON dayno = dayno WHERE date > '", lv_today ,"'",
                " UNION SELECT DATE(NOW()) AS date, 9999 AS weekno, 9999 AS event FROM event INNER JOIN calendar ON dayno = dayno",
                " WHERE (SELECT MAX(event) FROM event) ORDER BY event ");

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done := TRUE;

    OPEN curs1;
    loop1: LOOP
        FETCH curs1 INTO ldate, lweek, levent;
        SELECT ldate, lweek, levent;
        LEAVE looper;
    END LOOP loop1;
END;
</code>```

I haven't checked that the rest of the methodology works because I get this error:

Incorrect number of FETCH variables.

Does this mean that I have declare a different variable for each of the query returns? I am new to mysql. If this is the case what would be the best way to solve this conundrum? I have also changed to column and table names.

Many thanks

答:
https://dev.mysql.com/doc/refman/5.7/en/fetch.html The number of columns retrieved by the SELECT statement must match the number of output variables specified in the FETCH statement so yes but in fact you are only selecting 1 concatenated string - I think your first problem is with the select syntax which doesn't need the concat, the brackets or the quotes (unless you are trying to create a prepared statement for some reason - and even if you were I doubt if the code would be correct)

Simple Cursor

```<code>DROP PROCEDURE IF EXISTS EC;
DELIMITER $$

CREATE  PROCEDURE `EC`(
    IN `inemp_no` varchar(255)

)
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
LOOPER:begin
DECLARE done INT DEFAULT FALSE;
declare ename varchar(20);
declare esalary int default 0;
declare emp_cursor CURSOR FOR
 SELECT last_name,salary FROM employees where emp_no= inemp_no ;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

open emp_cursor;
read_loop: loop
        fetch emp_cursor into ename,esalary;
        if done then leave read_loop; end if;
        insert into debug_table (msg) values(concat('employee:',ename,' earns:',esalary));
end loop;
close emp_cursor;
end $$

DELIMITER ;

MariaDB [sandbox]> truncate table debug_table;
Query OK, 0 rows affected (0.22 sec)

MariaDB [sandbox]> call ec(2);
Query OK, 0 rows affected (0.03 sec)

MariaDB [sandbox]> select * from debug_table;
+----+--------------------------+------+
| id | msg                      | MSG2 |
+----+--------------------------+------+
|  1 | employee:BBB earns:39500 | NULL |
+----+--------------------------+------+
1 row in set (0.00 sec)
</code>```

Title: mysql. Stored Procedure Error 1328

Body:
This is really baffling me. I am converting a simple procedure from informix into mysql. What it basically does is tell me what the next event is from an event table and a calendar table. In informix the procedure is simple.

FOREACH
SELECT  date,weekno,event
INTO    l_date,l_week,l_event
FROM    event,calendar
WHERE   dayno = dayno
AND     date = l_today
AND     start >= l_now
UNION
SELECT  date,weekno,event
FROM    event,calendar
WHERE   dayno = dayno
AND     date > l_today
UNION
SELECT  TODAY,9999,9999
FROM    event,calendar
WHERE   dayno   = dayno
AND     event = (SELECT MAX(event) FROM event)
ORDER BY 3

if l_event = 9999 then <error> end if;
EXIT FOREACH
END FOREACH

So basically the query finds the next event and returns it. l_today and l_event are parameters that are passed. So on to the mysql version.

looper: BEGIN
    DECLARE curs1 CURSOR FOR
        SELECT CONCAT("SELECT date, weekno, event FROM event INNER JOIN calendar ON dayno = dayno",
                " WHERE date = '", lv_today ,"' AND start >= '", lv_time ,"'",
                " UNION SELECT date, weekno, event FROM event INNER JOIN calendar ON dayno = dayno WHERE date > '", lv_today ,"'",
                " UNION SELECT DATE(NOW()) AS date, 9999 AS weekno, 9999 AS event FROM event INNER JOIN calendar ON dayno = dayno",
                " WHERE (SELECT MAX(event) FROM event) ORDER BY event ");

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done := TRUE;

    OPEN curs1;
    loop1: LOOP
        FETCH curs1 INTO ldate, lweek, levent;
        SELECT ldate, lweek, levent;
        LEAVE looper;
    END LOOP loop1;
END;

I haven't checked that the rest of the methodology works because I get this error:

Incorrect number of FETCH variables.

Does this mean that I have declare a different variable for each of the query returns? I am new to mysql. If this is the case what would be the best way to solve this conundrum? I have also changed to column and table names.

Many thanks

Body:
https://dev.mysql.com/doc/refman/5.7/en/fetch.html The number of columns retrieved by the SELECT statement must match the number of output variables specified in the FETCH statement so yes but in fact you are only selecting 1 concatenated string - I think your first problem is with the select syntax which doesn't need the concat, the brackets or the quotes (unless you are trying to create a prepared statement for some reason - and even if you were I doubt if the code would be correct)

Simple Cursor

DROP PROCEDURE IF EXISTS EC;
DELIMITER $$

CREATE  PROCEDURE `EC`(
    IN `inemp_no` varchar(255)

)
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
LOOPER:begin
DECLARE done INT DEFAULT FALSE;
declare ename varchar(20);
declare esalary int default 0;
declare emp_cursor CURSOR FOR
 SELECT last_name,salary FROM employees where emp_no= inemp_no ;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

open emp_cursor;
read_loop: loop
        fetch emp_cursor into ename,esalary;
        if done then leave read_loop; end if;
        insert into debug_table (msg) values(concat('employee:',ename,' earns:',esalary));
end loop;
close emp_cursor;
end $$

DELIMITER ;

MariaDB [sandbox]> truncate table debug_table;
Query OK, 0 rows affected (0.22 sec)

MariaDB [sandbox]> call ec(2);
Query OK, 0 rows affected (0.03 sec)

MariaDB [sandbox]> select * from debug_table;
+----+--------------------------+------+
| id | msg                      | MSG2 |
+----+--------------------------+------+
|  1 | employee:BBB earns:39500 | NULL |
+----+--------------------------+------+
1 row in set (0.00 sec)


来源: stackexchange

问:
Parse 2D Array in Kotlin
I have created a 2D array named squareData as shown below:

```<code> private lateinit var squareData: Array<Array<String>>

 squareData = Array(3, {Array(3, {""})})
</code>```

Also, I initialized this array with some random values. Now I want to fetch this values one by one. How can I do it using for or forEachIndexed loop?

答:
You can use regular nested for loop.

```<code>for (arr in squareData) {
    for (s in arr) {
        println(s)
    }
}
</code>```

You can iterate using forEach:

```<code>squareData.forEach { it.forEach(::println) }
</code>```

or if you want index position as well, forEachIndexed:

```<code>squareData.forEachIndexed { i,it -> println(i); it.forEach(::println) }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Parse 2D Array in Kotlin

Body:
I have created a 2D array named squareData as shown below:

 private lateinit var squareData: Array<Array<String>>

 squareData = Array(3, {Array(3, {""})})

Also, I initialized this array with some random values. Now I want to fetch this values one by one. How can I do it using for or forEachIndexed loop?

Body:
You can use regular nested for loop.

for (arr in squareData) {
    for (s in arr) {
        println(s)
    }
}

You can iterate using forEach:

squareData.forEach { it.forEach(::println) }

or if you want index position as well, forEachIndexed:

squareData.forEachIndexed { i,it -> println(i); it.forEach(::println) }


问:
Centos6.9 install python3.5 display error permission denied after make

CentOS release 6.9 (Final) : Linux version 2.6.32-696.10.2.el6.i686 (mockbuild@c1bl.rdu2.centos.org) (gcc version 4.4.7 20120313 (Red Hat 4.4.7-18) (GCC) ) #1 SMP Tue Sep 12 13:54:13 UTC 2017

Install command :

wget https://www.python.org/ftp/python/3.5.4/Python-3.5.4.tgz
tar -zxvf Python-3.5.4.tgz
cd Python-3.5.4
mkdir /usr/local/python3.5
./configure --prefix=/usr/local/python3.5

Error step :

make

gcc -pthread -c -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes    -Werror=declaration-after-statement   -I. -I./Include    -DPy_BUILD_CORE \
      -DGITVERSION="\"LC_ALL=C \"" \
      -DGITTAG="\"LC_ALL=C \"" \
      -DGITBRANCH="\"LC_ALL=C \"" \
      -o Modules/getbuildinfo.o ./Modules/getbuildinfo.c
/bin/sh: /usr/bin/gcc: Permission denied
make: *** [Modules/getbuildinfo.o] Error 126

the power of /bin/sh and /usr/bin/gcc

[root@iZ2814clj1uZ Python-3.5.4]# ll /bin/sh
lrwxrwxrwx 1 root root 4 May 11  2017 /bin/sh -> bash
[root@iZ2814clj1uZ Python-3.5.4]# ll /bin/bash
-rwxr-xr-x 1 root root 872372 Mar 23  2017 /bin/bash
[root@iZ2814clj1uZ Python-3.5.4]# ll /usr/bin/gcc
-rwxr-xr-x 2 root root 234948 Mar 22  2017 /usr/bin/gcc

I haved tried chmod 777 /bin/sh , /bin/bash , /usr/bin/gcc  and reboot the system, but it doesn't work. Has anyone else had this problem with this ?
Thanks for any help/suggestions.

update 2017-11-13: selinux audit log

type=USER_AUTH msg=audit(1510502012.108:840): user pid=4273 uid=0 auid=4294967295 ses=4294967295 msg='op=PAM:authentication acct="root" exe="/usr/sbin/sshd" hostname=[ip address1] addr=[ip address1] terminal=ssh res=success'
type=USER_ACCT msg=audit(1510502012.108:841): user pid=4273 uid=0 auid=4294967295 ses=4294967295 msg='op=PAM:accounting acct="root" exe="/usr/sbin/sshd" hostname=[ip address1] addr=[ip address1] terminal=ssh res=success'
type=CRYPTO_KEY_USER msg=audit(1510502012.108:842): user pid=4273 uid=0 auid=4294967295 ses=4294967295 msg='op=destroy kind=session fp=? direction=both spid=4274 suid=74 rport=31432 laddr=[ip address] lport=5676  exe="/usr/sbin/sshd" hostname=? addr=[ip address1] terminal=? res=success'
type=USER_AUTH msg=audit(1510502012.108:843): user pid=4273 uid=0 auid=4294967295 ses=4294967295 msg='op=success acct="root" exe="/usr/sbin/sshd" hostname=? addr=[ip address1] terminal=ssh res=success'
type=CRED_ACQ msg=audit(1510502012.109:844): user pid=4273 uid=0 auid=4294967295 ses=4294967295 msg='op=PAM:setcred acct="root" exe="/usr/sbin/sshd" hostname=[ip address1] addr=[ip address1] terminal=ssh res=success'
type=LOGIN msg=audit(1510502012.109:845): pid=4273 uid=0 old auid=4294967295 new auid=0 old ses=4294967295 new ses=106
type=USER_START msg=audit(1510502012.111:846): user pid=4273 uid=0 auid=0 ses=106 msg='op=PAM:session_open acct="root" exe="/usr/sbin/sshd" hostname=[ip address1] addr=[ip address1] terminal=ssh res=success'
type=USER_LOGIN msg=audit(1510502012.189:847): user pid=4273 uid=0 auid=0 ses=106 msg='op=login id=0 exe="/usr/sbin/sshd" hostname=[ip address1] addr=[ip address1] terminal=ssh res=success

答: Today,I found the answer. I haved install a security software, which prohibited create and excute binary file in the system directory. So I uninstalled it and my system back to normal.</p>


问:
Open multiple links in Excel with VBA
I have the following code that should open multiple links in excel all at once

```<code>Sub OpenLink()
    Dim xHyperlink As Hyperlink
    Dim WorkRng As Range
    On Error Resume Next
    xTitleId = "Select Area"
    Set WorkRng = Application.Selection
    Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)
    For Each xHyperlink In WorkRng.Hyperlinks
        xHyperlink.Follow
    Next
End Sub
</code>```

Which, however, it is not working and I cannot understand why.

My links are of the form =HYPERLINK("http://example.com"; "Wording") and they work standalone.

答:
I believe this is not work as you are using the  hyperlink function (instead of right click > hyperlink..)

You can prove that this is the issue by right click assigning a hyperlink to a cell and testing your code there.

Are you getting the link address from another cell? if so you could go straight there and open the link using ActiveWorkbook.FollowHyperlink or you could use a technique like this reading the hyperlink value from a formula:

https://stackoverflow.com/a/42564907/359135

Some working (hopefully) code that extracts the url from the formula and opens it:

```<code>Sub OpenLinks()
    Dim xHyperlink As Hyperlink
    Dim WorkRng As Range
    On Error Resume Next
    xTitleId = "Select Area"
    Set WorkRng = Application.Selection
    Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)
    For Each c In WorkRng.Cells
      Dim sFormula As String
      Dim l As String
      sFormula = c.Formula
      l = Mid(sFormula, WorksheetFunction.Search("""", sFormula) + 1, WorksheetFunction.Search(",", sFormula) - WorksheetFunction.Search("""", sFormula) - 2)
      ActiveWorkbook.FollowHyperlink l
    Next
End Sub
</code>```

I had to tweak the code from that example to not include the quotation marks when extracting the url from the formula text.

Title: Open multiple links in Excel with VBA

Body:
I have the following code that should open multiple links in excel all at once

Sub OpenLink()
    Dim xHyperlink As Hyperlink
    Dim WorkRng As Range
    On Error Resume Next
    xTitleId = "Select Area"
    Set WorkRng = Application.Selection
    Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)
    For Each xHyperlink In WorkRng.Hyperlinks
        xHyperlink.Follow
    Next
End Sub

Which, however, it is not working and I cannot understand why.

My links are of the form =HYPERLINK("http://example.com"; "Wording") and they work standalone.

Body:
I believe this is not work as you are using the  hyperlink function (instead of right click > hyperlink..)

You can prove that this is the issue by right click assigning a hyperlink to a cell and testing your code there.

Are you getting the link address from another cell? if so you could go straight there and open the link using ActiveWorkbook.FollowHyperlink or you could use a technique like this reading the hyperlink value from a formula:

https://stackoverflow.com/a/42564907/359135

Some working (hopefully) code that extracts the url from the formula and opens it:

Sub OpenLinks()
    Dim xHyperlink As Hyperlink
    Dim WorkRng As Range
    On Error Resume Next
    xTitleId = "Select Area"
    Set WorkRng = Application.Selection
    Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)
    For Each c In WorkRng.Cells
      Dim sFormula As String
      Dim l As String
      sFormula = c.Formula
      l = Mid(sFormula, WorksheetFunction.Search("""", sFormula) + 1, WorksheetFunction.Search(",", sFormula) - WorksheetFunction.Search("""", sFormula) - 2)
      ActiveWorkbook.FollowHyperlink l
    Next
End Sub

I had to tweak the code from that example to not include the quotation marks when extracting the url from the formula text.


问:
Nested Serializers with multiple tables not working
I have the below tables in models.py.

```<code>class ProductLine(models.Model):
    availability = models.CharField(max_length=20, blank=True, null=True)
    series = models.CharField(max_length=20, blank=True, null=True)
    model = models.CharField(max_length=20, blank=True, null=True)

    class Meta:
        db_table = "product_line"

class DriveType(models.Model):
    drive_name = models.CharField(max_length=20, blank=True, null=True)
    product_line = models.ForeignKey(ProductLine, related_name="drive_type")

class Requirements(models.Model):
    performance_unit = models.CharField(max_length=100, blank=True, null=True)
    drive_type = models.OneToOneField(DriveType,on_delete=models.CASCADE,primary_key=True)

    class Meta:
        db_table = "requirements"

class WorkloadType(models.Model):
    workload_type_options = models.CharField(max_length=50, blank=True, null=True)
    drive_type = models.OneToOneField(DriveType,on_delete=models.CASCADE,primary_key=True)

    class Meta:
        db_table = "workload_type"
</code>```

I have below serializers:

```<code>class WorkloadTypeSerializer(serializers.ModelSerializer):
    class Meta:
        model = WorkloadType
        fields = "__all__"

class RequirementsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Requirements
        fields = "__all__"

class DriveTypeSerializer(serializers.ModelSerializer):
    requirements = RequirementsSerializer(many = False, read_only = True)
    workload_type = WorkloadTypeSerializer(many=False,read_only=True)

    class Meta:
        model = DriveType
        fields = (
        "drive_name", "available_drive_type", "capacity", "raid_type", "raid_size", "workload", "workload_percentage",
        "raid_groups", "compression", "compression_value","requirements","workload_type")

class ProductLineSerializer(serializers.ModelSerializer):
    drive_type = DriveTypeSerializer(many=True, read_only=True)

    class Meta:
        model = ProductLine
        fields = ('availability','series','model','drive_type')
</code>```

In my views  I have this:

```<code>class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
    def get_queryset(self):
        return ProductLine.objects.filter(id=self.kwargs.get("pk"))
    serializer_class = ProductLineSerializer
</code>```

I am getting output as below :

```<code>{
    "availability": "Current",
    "series": "3000",
    "model": "2000",
    "drive_type": [
        {
            "drive_name": "drive1",
            "requirements": {
                "drive_type": 2,
                "performance_unit": "by_iops",
            }
        }
    ]
}
</code>```

Why I am not able to see WorkLoadType tables data in json where as I am able to see Requirements data . I don't even see the field in json. Nested serializers only support a single relation tables

答:
Answering my own question. Have to use related_name in the models for reverse relationship.</p>

```<code>class Requirements(models.Model):
    performance_unit = models.CharField(max_length=100, blank=True, null=True)
    drive_type = models.OneToOneField(DriveType,on_delete=models.CASCADE,primary_key=True,related_name=requirements)

    class Meta:
        db_table = "requirements"

class WorkloadType(models.Model):
    workload_type_options = models.CharField(max_length=50, blank=True, null=True)
    drive_type = models.OneToOneField(DriveType,on_delete=models.CASCADE,primary_key=True,related_name=workload_type)
</code>```

Body:
I have the below tables in models.py.

class ProductLine(models.Model):
    availability = models.CharField(max_length=20, blank=True, null=True)
    series = models.CharField(max_length=20, blank=True, null=True)
    model = models.CharField(max_length=20, blank=True, null=True)

    class Meta:
        db_table = "product_line"

class DriveType(models.Model):
    drive_name = models.CharField(max_length=20, blank=True, null=True)
    product_line = models.ForeignKey(ProductLine, related_name="drive_type")

class Requirements(models.Model):
    performance_unit = models.CharField(max_length=100, blank=True, null=True)
    drive_type = models.OneToOneField(DriveType,on_delete=models.CASCADE,primary_key=True)

    class Meta:
        db_table = "requirements"

class WorkloadType(models.Model):
    workload_type_options = models.CharField(max_length=50, blank=True, null=True)
    drive_type = models.OneToOneField(DriveType,on_delete=models.CASCADE,primary_key=True)

    class Meta:
        db_table = "workload_type"

I have below serializers:

class WorkloadTypeSerializer(serializers.ModelSerializer):
    class Meta:
        model = WorkloadType
        fields = "__all__"

class RequirementsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Requirements
        fields = "__all__"

class DriveTypeSerializer(serializers.ModelSerializer):
    requirements = RequirementsSerializer(many = False, read_only = True)
    workload_type = WorkloadTypeSerializer(many=False,read_only=True)

    class Meta:
        model = DriveType
        fields = (
        "drive_name", "available_drive_type", "capacity", "raid_type", "raid_size", "workload", "workload_percentage",
        "raid_groups", "compression", "compression_value","requirements","workload_type")

class ProductLineSerializer(serializers.ModelSerializer):
    drive_type = DriveTypeSerializer(many=True, read_only=True)

    class Meta:
        model = ProductLine
        fields = ('availability','series','model','drive_type')

In my views  I have this:

class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
    def get_queryset(self):
        return ProductLine.objects.filter(id=self.kwargs.get("pk"))
    serializer_class = ProductLineSerializer

I am getting output as below :

{
    "availability": "Current",
    "series": "3000",
    "model": "2000",
    "drive_type": [
        {
            "drive_name": "drive1",
            "requirements": {
                "drive_type": 2,
                "performance_unit": "by_iops",
            }
        }
    ]
}

Why I am not able to see WorkLoadType tables data in json where as I am able to see Requirements data . I don't even see the field in json. Nested serializers only support a single relation tables

Body:
Answering my own question. Have to use related_name in the models for reverse relationship.

class Requirements(models.Model):
    performance_unit = models.CharField(max_length=100, blank=True, null=True)
    drive_type = models.OneToOneField(DriveType,on_delete=models.CASCADE,primary_key=True,related_name=requirements)

    class Meta:
        db_table = "requirements"

class WorkloadType(models.Model):
    workload_type_options = models.CharField(max_length=50, blank=True, null=True)
    drive_type = models.OneToOneField(DriveType,on_delete=models.CASCADE,primary_key=True,related_name=workload_type)


问:
Expandable Listview error inflating class TextView
I am using material design tablayout in my main activity where i have scrollable tabs and in my very first fragment i am using expandable listview.

Here is my fragment code

```<code>public class House_Hold_List_Fragment extends Fragment {
    ExpandableListAdapter listAdapter;
    ExpandableListView expListView;
    List<HouseHoldList_Model> listDataHeader;
    HashMap<HouseHoldList_Model, List<String>> listDataChild;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.house_hold_list_fragment, container, false);
        setHasOptionsMenu(true);
        expListView = (ExpandableListView) view.findViewById(R.id.lvExp);
        listDataHeader = new ArrayList<HouseHoldList_Model>();
        listDataChild = new HashMap<HouseHoldList_Model, List<String>>();
        loadModel();
        // preparing list data
        prepareListData();

        listAdapter = new ExpandableListAdapter(getActivity(), listDataHeader, listDataChild);

        // setting list adapter
        expListView.setAdapter(listAdapter);
        return view;
    }

    public void prepareListData(){
        List<String> top250 = new ArrayList<String>();
        top250.add("The Shawshank Redemption");
        top250.add("The Godfather");
        top250.add("The Godfather: Part II");
        top250.add("Pulp Fiction");
        top250.add("The Good, the Bad and the Ugly");
        top250.add("The Dark Knight");
        top250.add("12 Angry Men");

        List<String> nowShowing = new ArrayList<String>();
        nowShowing.add("The Conjuring");
        nowShowing.add("Despicable Me 2");
        nowShowing.add("Turbo");
        nowShowing.add("Grown Ups 2");
        nowShowing.add("Red 2");
        nowShowing.add("The Wolverine");

        List<String> comingSoon = new ArrayList<String>();
        comingSoon.add("2 Guns");
        comingSoon.add("The Smurfs 2");
        comingSoon.add("The Spectacular Now");
        comingSoon.add("The Canyons");
        comingSoon.add("Europa Report");

        listDataChild.put((HouseHoldList_Model)listDataHeader.get(0), top250); // Header, Child data
        listDataChild.put(listDataHeader.get(1), nowShowing);
        listDataChild.put(listDataHeader.get(2), comingSoon);

    }

    public void loadModel(){
        listDataHeader.add(new HouseHoldList_Model("A"));
        listDataHeader.add(new HouseHoldList_Model("B"));
        listDataHeader.add(new HouseHoldList_Model("C"));
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // TODO Auto-generated method stub
        //super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.menu, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.search:
                //do something
                Log.e("search clicked","sd");
                return true;

            case R.id.action_settings:
                //do something
                Log.e("search clicked","sd");
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
</code>```

and here is my model class code where i am just adding name

```<code>public class HouseHoldList_Model {
    String name;

    public HouseHoldList_Model(){
    }

    public HouseHoldList_Model(String name){
        this.name=name;
    }
}
</code>```

and here is my ExpandableListAdapter class code

```<code>public class ExpandableListAdapter extends BaseExpandableListAdapter {

    private Context _context;
    private List<HouseHoldList_Model> _listDataHeader; // header titles
    // child data in format of header title, child title
    private HashMap<HouseHoldList_Model
            , List<String>> _listDataChild;

    public ExpandableListAdapter(Context context, List<HouseHoldList_Model> listDataHeader,
                                 HashMap<HouseHoldList_Model, List<String>> listChildData) {
        this._context = context;
        this._listDataHeader = listDataHeader;
        this._listDataChild = listChildData;
    }

    @Override
    public Object getChild(int groupPosition, int childPosititon) {
        return this._listDataChild.get(this._listDataHeader.get(groupPosition))
                .get(childPosititon);
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public View getChildView(int groupPosition, final int childPosition,
                             boolean isLastChild, View convertView, ViewGroup parent) {

        final String childText = (String) getChild(groupPosition, childPosition);

        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) this._context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.house_holld_list_item, null);
        }

        TextView txtListChild = (TextView) convertView
                .findViewById(R.id.house_hold_list_item);

        txtListChild.setText(childText);
        return convertView;
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return this._listDataChild.get(this._listDataHeader.get(groupPosition))
                .size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return this._listDataHeader.get(groupPosition);
    }

    @Override
    public int getGroupCount() {
        return this._listDataHeader.size();
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded,
                             View convertView, ViewGroup parent) {
        HouseHoldList_Model model = (HouseHoldList_Model) getGroup(groupPosition);
        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) this._context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.house_hold_list_row, null);
        }
        TextView lblListHeader = (TextView) convertView
                .findViewById(R.id.house_hold_name);
        lblListHeader.setText(model.name);

        return convertView;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }
}
</code>```

my house_hold_list_row is a custom layout for row where i have different fields like name,address etc but at the time i am just displaying only name.
here my logcat.

```<code>11-13 18:03:05.565 6756-6756/com.zaigham.lhw_diary E/AndroidRuntime: FATAL EXCEPTION: main
                                                                     Process: com.zaigham.lhw_diary, PID: 6756
                                                                     android.view.InflateException: Binary XML file line #0: Error inflating class TextView
                                                                         at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:714)
                                                                         at android.view.LayoutInflater.rInflate(LayoutInflater.java:756)
                                                                         at android.view.LayoutInflater.rInflate(LayoutInflater.java:759)
                                                                         at android.view.LayoutInflater.rInflate(LayoutInflater.java:759)
                                                                         at android.view.LayoutInflater.rInflate(LayoutInflater.java:759)
                                                                         at android.view.LayoutInflater.rInflate(LayoutInflater.java:759)
                                                                         at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
                                                                         at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
                                                                         at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
                                                                         at com.zaigham.lhw_diary.HouseHoldList.ExpandableListAdapter.getGroupView(ExpandableListAdapter.java:86)
</code>```

Here is my house_hold_list_row

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/gray">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"
        android:layout_centerInParent="true"
        android:layout_marginRight="5dp"
        android:layout_marginLeft="5dp"
        android:orientation="vertical">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:weightSum="3">
            <TextView
                android:id="@+id/house_hold_number"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:text="1"
                android:layout_gravity="center_vertical"
                android:layout_marginLeft="5dp"
                android:padding="8dp"
                android:gravity="center"
                android:layout_marginTop="10dp"
                android:layout_marginBottom="10dp"
                android:textColor="@color/white"
                android:background="@drawable/hh_count_round"
                android:layout_weight=".5"/>
            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:layout_weight="2.2"
                android:orientation="vertical">
                <TextView
                    android:id="@+id/house_hold_name"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textStyle="bold"
                    android:textSize="18dp"
                    android:textColor="@color/blacktext"
                    android:text="Muhammad Ramza"/>
                <TextView
                    android:id="@+id/house_hold_address"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Main double road g-11"
                    android:textColor="@color/blacktext"/>
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">
                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Family Members"
                        android:textColor="@color/blacktext" />
                    <TextView
                        android:id="@+id/house_hold_fm_number"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="10"
                        android:layout_marginLeft="10dp"
                        android:background="@drawable/hh_fm_count_round"
                        android:textColor="@color/white"/>
                </LinearLayout>
            </LinearLayout>
            <ImageView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:src="@drawable/down"
                android:layout_marginRight="5dp"
                android:layout_gravity="center"
                android:layout_weight=".3"/>

        </LinearLayout>

    </LinearLayout>

</RelativeLayout>
</code>```

答:
IMO your textview cannot reference to convertView so take it in your if() condition try below code </p>

```<code>    if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) this._context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.house_hold_list_row, null)
          TextView lblListHeader = (TextView) convertView
                .findViewById(R.id.house_hold_name);
        lblListHeader.setText(model.name);
        }
</code>```

Body:
I am using material design tablayout in my main activity where i have scrollable tabs and in my very first fragment i am using expandable listview.

Here is my fragment code

public class House_Hold_List_Fragment extends Fragment {
    ExpandableListAdapter listAdapter;
    ExpandableListView expListView;
    List<HouseHoldList_Model> listDataHeader;
    HashMap<HouseHoldList_Model, List<String>> listDataChild;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.house_hold_list_fragment, container, false);
        setHasOptionsMenu(true);
        expListView = (ExpandableListView) view.findViewById(R.id.lvExp);
        listDataHeader = new ArrayList<HouseHoldList_Model>();
        listDataChild = new HashMap<HouseHoldList_Model, List<String>>();
        loadModel();
        // preparing list data
        prepareListData();

        listAdapter = new ExpandableListAdapter(getActivity(), listDataHeader, listDataChild);

        // setting list adapter
        expListView.setAdapter(listAdapter);
        return view;
    }

    public void prepareListData(){
        List<String> top250 = new ArrayList<String>();
        top250.add("The Shawshank Redemption");
        top250.add("The Godfather");
        top250.add("The Godfather: Part II");
        top250.add("Pulp Fiction");
        top250.add("The Good, the Bad and the Ugly");
        top250.add("The Dark Knight");
        top250.add("12 Angry Men");

        List<String> nowShowing = new ArrayList<String>();
        nowShowing.add("The Conjuring");
        nowShowing.add("Despicable Me 2");
        nowShowing.add("Turbo");
        nowShowing.add("Grown Ups 2");
        nowShowing.add("Red 2");
        nowShowing.add("The Wolverine");

        List<String> comingSoon = new ArrayList<String>();
        comingSoon.add("2 Guns");
        comingSoon.add("The Smurfs 2");
        comingSoon.add("The Spectacular Now");
        comingSoon.add("The Canyons");
        comingSoon.add("Europa Report");

        listDataChild.put((HouseHoldList_Model)listDataHeader.get(0), top250); // Header, Child data
        listDataChild.put(listDataHeader.get(1), nowShowing);
        listDataChild.put(listDataHeader.get(2), comingSoon);

    }

    public void loadModel(){
        listDataHeader.add(new HouseHoldList_Model("A"));
        listDataHeader.add(new HouseHoldList_Model("B"));
        listDataHeader.add(new HouseHoldList_Model("C"));
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // TODO Auto-generated method stub
        //super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.menu, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.search:
                //do something
                Log.e("search clicked","sd");
                return true;

            case R.id.action_settings:
                //do something
                Log.e("search clicked","sd");
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

and here is my model class code where i am just adding name

public class HouseHoldList_Model {
    String name;

    public HouseHoldList_Model(){
    }

    public HouseHoldList_Model(String name){
        this.name=name;
    }
}

and here is my ExpandableListAdapter class code

public class ExpandableListAdapter extends BaseExpandableListAdapter {

    private Context _context;
    private List<HouseHoldList_Model> _listDataHeader; // header titles
    // child data in format of header title, child title
    private HashMap<HouseHoldList_Model
            , List<String>> _listDataChild;

    public ExpandableListAdapter(Context context, List<HouseHoldList_Model> listDataHeader,
                                 HashMap<HouseHoldList_Model, List<String>> listChildData) {
        this._context = context;
        this._listDataHeader = listDataHeader;
        this._listDataChild = listChildData;
    }

    @Override
    public Object getChild(int groupPosition, int childPosititon) {
        return this._listDataChild.get(this._listDataHeader.get(groupPosition))
                .get(childPosititon);
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public View getChildView(int groupPosition, final int childPosition,
                             boolean isLastChild, View convertView, ViewGroup parent) {

        final String childText = (String) getChild(groupPosition, childPosition);

        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) this._context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.house_holld_list_item, null);
        }

        TextView txtListChild = (TextView) convertView
                .findViewById(R.id.house_hold_list_item);

        txtListChild.setText(childText);
        return convertView;
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return this._listDataChild.get(this._listDataHeader.get(groupPosition))
                .size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return this._listDataHeader.get(groupPosition);
    }

    @Override
    public int getGroupCount() {
        return this._listDataHeader.size();
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded,
                             View convertView, ViewGroup parent) {
        HouseHoldList_Model model = (HouseHoldList_Model) getGroup(groupPosition);
        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) this._context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.house_hold_list_row, null);
        }
        TextView lblListHeader = (TextView) convertView
                .findViewById(R.id.house_hold_name);
        lblListHeader.setText(model.name);

        return convertView;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }
}

my house_hold_list_row is a custom layout for row where i have different fields like name,address etc but at the time i am just displaying only name.
here my logcat.

11-13 18:03:05.565 6756-6756/com.zaigham.lhw_diary E/AndroidRuntime: FATAL EXCEPTION: main
                                                                     Process: com.zaigham.lhw_diary, PID: 6756
                                                                     android.view.InflateException: Binary XML file line #0: Error inflating class TextView
                                                                         at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:714)
                                                                         at android.view.LayoutInflater.rInflate(LayoutInflater.java:756)
                                                                         at android.view.LayoutInflater.rInflate(LayoutInflater.java:759)
                                                                         at android.view.LayoutInflater.rInflate(LayoutInflater.java:759)
                                                                         at android.view.LayoutInflater.rInflate(LayoutInflater.java:759)
                                                                         at android.view.LayoutInflater.rInflate(LayoutInflater.java:759)
                                                                         at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
                                                                         at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
                                                                         at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
                                                                         at com.zaigham.lhw_diary.HouseHoldList.ExpandableListAdapter.getGroupView(ExpandableListAdapter.java:86)

Here is my house_hold_list_row

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/gray">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"
        android:layout_centerInParent="true"
        android:layout_marginRight="5dp"
        android:layout_marginLeft="5dp"
        android:orientation="vertical">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:weightSum="3">
            <TextView
                android:id="@+id/house_hold_number"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:text="1"
                android:layout_gravity="center_vertical"
                android:layout_marginLeft="5dp"
                android:padding="8dp"
                android:gravity="center"
                android:layout_marginTop="10dp"
                android:layout_marginBottom="10dp"
                android:textColor="@color/white"
                android:background="@drawable/hh_count_round"
                android:layout_weight=".5"/>
            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:layout_weight="2.2"
                android:orientation="vertical">
                <TextView
                    android:id="@+id/house_hold_name"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textStyle="bold"
                    android:textSize="18dp"
                    android:textColor="@color/blacktext"
                    android:text="Muhammad Ramza"/>
                <TextView
                    android:id="@+id/house_hold_address"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Main double road g-11"
                    android:textColor="@color/blacktext"/>
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">
                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Family Members"
                        android:textColor="@color/blacktext" />
                    <TextView
                        android:id="@+id/house_hold_fm_number"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="10"
                        android:layout_marginLeft="10dp"
                        android:background="@drawable/hh_fm_count_round"
                        android:textColor="@color/white"/>
                </LinearLayout>
            </LinearLayout>
            <ImageView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:src="@drawable/down"
                android:layout_marginRight="5dp"
                android:layout_gravity="center"
                android:layout_weight=".3"/>

        </LinearLayout>

    </LinearLayout>

</RelativeLayout>

Body:
IMO your textview cannot reference to convertView so take it in your if() condition try below code

    if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) this._context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.house_hold_list_row, null)
          TextView lblListHeader = (TextView) convertView
                .findViewById(R.id.house_hold_name);
        lblListHeader.setText(model.name);
        }


问:
Modifying font size for pie chart lables
I am using a simple script for a pie chart, but I am unable to change the font size of the pie labels. Is there an easy way to change it?

Below is my plotting code:

```<code>h = pie ([0.1,0.1,0.1,0.1,0.1], {"unlikely","possible","likely","very likely","certain"});
y = 0;
n = 1;

colormap([1 1 n;    %// unlikely
          1 1 y;    %// possible
          1 1 y;    %// likely
          1 1 y;    %// very unlikely
          1 1 n;])  %// certainly
ax = gca();
set(ax,'fontsize', 18);
view([270, -90])
</code>```

答:
The variable h contains an array of five Patch objects intertwined with 5 Text objects. Use the following command to set all font sizes for the text objects.

```<code>set(h(2:2:end),'FontSize',16);
</code>```

Body:
I am using a simple script for a pie chart, but I am unable to change the font size of the pie labels. Is there an easy way to change it?

Below is my plotting code:

h = pie ([0.1,0.1,0.1,0.1,0.1], {"unlikely","possible","likely","very likely","certain"});
y = 0;
n = 1;

colormap([1 1 n;    %// unlikely
          1 1 y;    %// possible
          1 1 y;    %// likely
          1 1 y;    %// very unlikely
          1 1 n;])  %// certainly
ax = gca();
set(ax,'fontsize', 18);
view([270, -90])

Body:
The variable h contains an array of five Patch objects intertwined with 5 Text objects. Use the following command to set all font sizes for the text objects.

set(h(2:2:end),'FontSize',16);


问:
Azure function goes idle when running in Consumption Plan with ServiceBus Queue trigger
I have also asked this question in the MSDN Azure forums, but have not received any guidance as to why my function goes idle.

I have an Azure function running on a Consumption plan that goes idle (i.e. does not respond to new messages on the ServiceBus trigger queue) despite following the instructions outlined in this GitHub issue:

The configuration for the function is the following json:

```<code>{
  "ConnectionStrings": {
    "MyConnectionString": "Server=tcp:project.database.windows.net,1433;Database=myDB;User ID=user@project;Password=password;Encrypt=True;Connection Timeout=30;"
  },
  "Values": {
    "serviceBusConnection": "Endpoint=sb://project.servicebus.windows.net/;SharedAccessKeyName=SharedAccessKeyName;SharedAccessKey=KEY_HERE",
  }
}
</code>```

And the function signature is:

```<code>public static void ProcessQueue([ServiceBusTrigger("queueName", AccessRights.Listen, Connection = "serviceBusConnection")] ...)
</code>```

Based on the discussion in the GitHub issue, I believed that having either a serviceBusConnection entry OR an AzureWebJobServiceBus entry should be enough to ensure that the central listener triggers the function when a new message is added to the ServiceBusQueue, but that is proving to not be the case.

Can anyone clarify the difference between how those two settings are used, or notice anything else with the settings I provided that might be causing the function to not properly be triggered after a period of inactivity?

答:
I suggest there are several possible causes for this behavior. I have several Azure subs and only one of them had issues with Storage/Service Bus-based triggers only popping up when app is not idle. So far I have observed that actions listed below will prevent triggers from working correctly:

Creating any Storage-based trigger, deleting (for any reason) the triggering object and re-creating it.

Corrupting azure function input parameters by deleting/altering associated objects without recompiling a function

Restarting functions app when one of the functions fails to compile/bind to trigger OR input parameter and hangs may cause same problems.
It has also been observed that using legacy Connection Strings setting for trigger binding will not work.

Clean deploy of an affected function app will most likely solve the problem if it was caused by any of the actions described above.

EDIT:
It looks like this is also caused by setting Authorization/Authentication on the functions app, but I have not yet figured out if it happens in general or when Auth has specific configuration. Tested on affected Azure sub by disabling auth at all - function going idle after 30-40 mins, queue trigger still initiates an execution, though with a delay as expected. I have found an old bug related to this, but it says issue resolved.

Body:
I have also asked this question in the MSDN Azure forums, but have not received any guidance as to why my function goes idle.

I have an Azure function running on a Consumption plan that goes idle (i.e. does not respond to new messages on the ServiceBus trigger queue) despite following the instructions outlined in this GitHub issue:

The configuration for the function is the following json:

{
  "ConnectionStrings": {
    "MyConnectionString": "Server=tcp:project.database.windows.net,1433;Database=myDB;User ID=user@project;Password=password;Encrypt=True;Connection Timeout=30;"
  },
  "Values": {
    "serviceBusConnection": "Endpoint=sb://project.servicebus.windows.net/;SharedAccessKeyName=SharedAccessKeyName;SharedAccessKey=KEY_HERE",
  }
}

And the function signature is:

public static void ProcessQueue([ServiceBusTrigger("queueName", AccessRights.Listen, Connection = "serviceBusConnection")] ...)

Based on the discussion in the GitHub issue, I believed that having either a serviceBusConnection entry OR an AzureWebJobServiceBus entry should be enough to ensure that the central listener triggers the function when a new message is added to the ServiceBusQueue, but that is proving to not be the case.

Can anyone clarify the difference between how those two settings are used, or notice anything else with the settings I provided that might be causing the function to not properly be triggered after a period of inactivity?


问:
What's the meaning of a ! before a command in the shell?
What is the purpose of a shell command (part of a shell script) starting with an exclamation mark?

Concrete example:

In foo.sh:

```<code>#!/usr/bin/env bash
set -e
! docker stop foo
! docker rm -f foo
# ... other stuff
</code>```

I know that without the space the exclamation mark is used for history replacements and ! <expression> according to the man page can be used to evaluate "True if expr is false". But in the example context that does not make sense to me.

答:
TL;DR: This is just by-passing the set -e flag in the specific line where you are using it.

Adding add to hek2mgl's correct and useful answer.

You have:

```<code>set -e
! command
</code>```

Bash Reference Manual → Pipelines describes:

Each command in a pipeline is executed in its own subshell. The exit status of a pipeline is the exit status of the last command in the pipeline (...). If the reserved word ‘!’ precedes the pipeline, the exit status is the logical negation of the exit status as described above. The shell waits for all commands in the pipeline to terminate before returning a value.

This means that ! preceding a command is negating the exit status of it:

```<code>$ echo 23
23
$ echo $?
0
                # But
$ ! echo 23
23
$ echo $?
1
</code>```

Or:

```<code>$ echo 23 && echo "true" || echo "fail"
23
true
$ ! echo 23 && echo "true" || echo "fail"
23
fail
</code>```

The exit status is useful in many ways. In your script, used together with set -e makes the script exit whenever a command returns a non-zero status.

Thus, when you have:

```<code>set -e
command1
command2
</code>```

If command1 returns a non-zero status, the script will finish and won't proceed to command2.

However, there is also an interesting point to mention, described in 4.3.1 The Set Builtin:

-e

Exit immediately if a pipeline (see Pipelines), which may consist of a single simple command (see Simple Commands), a list (see Lists), or a compound command (see Compound Commands) returns a non-zero status. The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test in an if statement, part of any command executed in a && or || list except the command following the final && or ||, any command in a pipeline but the last, or if the command’s return status is being inverted with !. If a compound command other than a subshell returns a non-zero status because a command failed while -e was being ignored, the shell does not exit. A trap on ERR, if set, is executed before the shell exits.

Taking all of these into consideration, when you have:

```<code>set -e
! command1
command2
</code>```

What you are doing is to by-pass the set -e flag in the command1. Why?

if command1 runs properly, it will return a zero status. ! will negate it, but set -e won't trigger an exit by the because it comes from a return status inverted with !, as described above.

if command1 fails, it will return a non-zero status. ! will negate it, so the line will end up returning a zero status and the script will continue normally.

ContentLicense: CC BY-SA 4.0

Body:
What is the purpose of a shell command (part of a shell script) starting with an exclamation mark?

Concrete example:

In foo.sh:

#!/usr/bin/env bash
set -e
! docker stop foo
! docker rm -f foo
# ... other stuff

I know that without the space the exclamation mark is used for history replacements and ! <expression> according to the man page can be used to evaluate "True if expr is false". But in the example context that does not make sense to me.

Body:
TL;DR: This is just by-passing the set -e flag in the specific line where you are using it.

Adding add to hek2mgl's correct and useful answer.

You have:

set -e
! command

Bash Reference Manual → Pipelines describes:

Each command in a pipeline is executed in its own subshell. The exit status of a pipeline is the exit status of the last command in the pipeline (...). If the reserved word ‘!’ precedes the pipeline, the exit status is the logical negation of the exit status as described above. The shell waits for all commands in the pipeline to terminate before returning a value.

This means that ! preceding a command is negating the exit status of it:

$ echo 23
23
$ echo $?
0
                # But
$ ! echo 23
23
$ echo $?
1

Or:

$ echo 23 && echo "true" || echo "fail"
23
true
$ ! echo 23 && echo "true" || echo "fail"
23
fail

The exit status is useful in many ways. In your script, used together with set -e makes the script exit whenever a command returns a non-zero status.

Thus, when you have:

set -e
command1
command2

If command1 returns a non-zero status, the script will finish and won't proceed to command2.

However, there is also an interesting point to mention, described in 4.3.1 The Set Builtin:

-e

Exit immediately if a pipeline (see Pipelines), which may consist of a single simple command (see Simple Commands), a list (see Lists), or a compound command (see Compound Commands) returns a non-zero status. The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test in an if statement, part of any command executed in a && or || list except the command following the final && or ||, any command in a pipeline but the last, or if the command’s return status is being inverted with !. If a compound command other than a subshell returns a non-zero status because a command failed while -e was being ignored, the shell does not exit. A trap on ERR, if set, is executed before the shell exits.

Taking all of these into consideration, when you have:

set -e
! command1
command2

What you are doing is to by-pass the set -e flag in the command1. Why?

if command1 runs properly, it will return a zero status. ! will negate it, but set -e won't trigger an exit by the because it comes from a return status inverted with !, as described above.

if command1 fails, it will return a non-zero status. ! will negate it, so the line will end up returning a zero status and the script will continue normally.


问:
Define which fields are shown in a Django forms.ModelForm list
I want to restrict which fields are shown in the list view of a Django forms.ModelForm

I can restrict which fields are shown in the update and create forms but can't work out how to do this for the list view of the form.

My model looks like this:

```<code>class Teacher(models.Model):

    name = models.CharField(max_length=255)
    email = models.CharField(max_length=30)
    slug = extension_fields.AutoSlugField(populate_from='name', blank=True)
</code>```

My view code looks like this:

```<code>class TeacherListView(GroupRequiredMixin, ListView):
   model = Teacher
   group_required = [u"school_admin"]
   login_url = "/login/"
</code>```

My form code looks like this:

```<code>class TeacherForm(forms.ModelForm):
    class Meta:
        model = Teacher
        fields = ['name', 'email' ]
</code>```

I am trying to hide the slug field from the list view.

答:
You can try this </p>

```<code>class TeacherForm(forms.ModelForm):

    class Meta:
      model = Teacher
      exclude = ['slug']
</code>```

Body:
I want to restrict which fields are shown in the list view of a Django forms.ModelForm

I can restrict which fields are shown in the update and create forms but can't work out how to do this for the list view of the form.

My model looks like this:

class Teacher(models.Model):

    name = models.CharField(max_length=255)
    email = models.CharField(max_length=30)
    slug = extension_fields.AutoSlugField(populate_from='name', blank=True)

My view code looks like this:

class TeacherListView(GroupRequiredMixin, ListView):
   model = Teacher
   group_required = [u"school_admin"]
   login_url = "/login/"

My form code looks like this:

class TeacherForm(forms.ModelForm):
    class Meta:
        model = Teacher
        fields = ['name', 'email' ]

I am trying to hide the slug field from the list view.

Body:
You can try this

class TeacherForm(forms.ModelForm):

    class Meta:
      model = Teacher
      exclude = ['slug']


问:
Using RequestOptions in AppGlideModule with Glide 4
I used the `Glide library with AppGlideModule, version of library 4.1.1. Here is my glide module class:

```<code>@GlideModule
public class GlideUtil extends AppGlideModule {

    private final int IMAGE_CACHE_SIZE = 20 * 1024 * 1024; // 20 MB
    private final String IMAGE_FOLDER = "/User/Images";

    @Override
    public void applyOptions(Context context, GlideBuilder builder) {
        RequestOptions requestOptions = new RequestOptions();
        requestOptions.format(DecodeFormat.PREFER_ARGB_8888);
        requestOptions.diskCacheStrategy(DiskCacheStrategy.ALL);
        builder.setDefaultRequestOptions(requestOptions);
        InternalCacheDiskCacheFactory factory = new InternalCacheDiskCacheFactory(context, IMAGE_FOLDER, IMAGE_CACHE_SIZE);
        builder.setDiskCache(factory);

    }

    @Override
    public boolean isManifestParsingEnabled() {
        return false;
    }
</code>```

This code worked successfully. But when i updated version of glide library to 4.3.1

```<code>compile 'com.github.bumptech.glide:glide:4.3.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.3.1'
</code>```

in GlideUtil class i saw messages: "The result of format is not used", "The result of diskCacheStrategyis not used":

So, how to resolve this? And do the methods diskCacheStrategy and format work on Glide 4.3.1 ?

答:
The problem is, that you are not using the builder object, that is returned by format(), thus your actions become pointless, that's why lint warns you. You can see that method annotated with @CheckResult, that's how lint understands, that you are on a wrong way, because you are "not checking the result" returned by that method.

Instead perform following:

```
<code>
    RequestOptions requestOptions = new RequestOptions();
    requestOptions = requestOptions.format(DecodeFormat.PREFER_ARGB_8888);
    requestOptions = requestOptions.diskCacheStrategy(DiskCacheStrategy.ALL);
</code>
```

Now the warning would be gone.

Or you may perform following directly:

```
<code>
    builder.setDefaultRequestOptions(new RequestOptions()
                                        .format(DecodeFormat.PREFER_ARGB_8888)
                                        .diskCacheStrategy(DiskCacheStrategy.ALL));
</code>
```

Body:
I used the `Glide library with AppGlideModule, version of library 4.1.1. Here is my glide module class:

@GlideModule
public class GlideUtil extends AppGlideModule {

    private final int IMAGE_CACHE_SIZE = 20 * 1024 * 1024; // 20 MB
    private final String IMAGE_FOLDER = "/User/Images";

    @Override
    public void applyOptions(Context context, GlideBuilder builder) {
        RequestOptions requestOptions = new RequestOptions();
        requestOptions.format(DecodeFormat.PREFER_ARGB_8888);
        requestOptions.diskCacheStrategy(DiskCacheStrategy.ALL);
        builder.setDefaultRequestOptions(requestOptions);
        InternalCacheDiskCacheFactory factory = new InternalCacheDiskCacheFactory(context, IMAGE_FOLDER, IMAGE_CACHE_SIZE);
        builder.setDiskCache(factory);

    }

    @Override
    public boolean isManifestParsingEnabled() {
        return false;
    }

This code worked successfully. But when i updated version of glide library to 4.3.1

compile 'com.github.bumptech.glide:glide:4.3.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.3.1'

in GlideUtil class i saw messages: "The result of format is not used", "The result of diskCacheStrategyis not used":

So, how to resolve this? And do the methods diskCacheStrategy and format work on Glide 4.3.1 ?

Body:
The problem is, that you are not using the builder object, that is returned by format(), thus your actions become pointless, that's why lint warns you. You can see that method annotated with @CheckResult, that's how lint understands, that you are on a wrong way, because you are "not checking the result" returned by that method.

Instead perform following:

    RequestOptions requestOptions = new RequestOptions();
    requestOptions = requestOptions.format(DecodeFormat.PREFER_ARGB_8888);
    requestOptions = requestOptions.diskCacheStrategy(DiskCacheStrategy.ALL);

Now the warning would be gone.

Or you may perform following directly:

    builder.setDefaultRequestOptions(new RequestOptions()
                                        .format(DecodeFormat.PREFER_ARGB_8888)
                                        .diskCacheStrategy(DiskCacheStrategy.ALL));


问:
Error:(24, 0) Could not find method annotationProcessor() for arguments [com.google.dagger:dagger-compiler:2.10]
I try to build a module:api on Android Studio 3, gradle 4.1, Android Studio plugin 3.0.0, using Dagger 2

So my build.gradle is:

```<code>apply plugin: 'java-library'

repositories {
    jcenter()
    google()
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation project(':api_shared')

    // Guava
    implementation group: 'com.google.guava', name: 'guava', version: '23.0'

    // Dagger 2
    compile 'com.google.dagger:dagger:2.10'
    annotationProcessor 'com.google.dagger:dagger-compiler:2.10'
}

sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
</code>```

And I get the following error.

```<code>Error:(24, 0) Could not find method annotationProcessor() for arguments [com.google.dagger:dagger-compiler:2.10] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.
<a href="openFile:D:\Users\me\Workspace\Sample3\api\build.gradle">Open File</a>
</code>```

I saw similar errors for guys using old plugin version but here, I don't understand why I get this error.
Any idea?

答:
You need the Android Gradle plugin (version 2.2 or newer) to use the annotationProcessor DSL.

You are using apply plugin: 'java-library' not the Android Plugin.

Body:
I try to build a module:api on Android Studio 3, gradle 4.1, Android Studio plugin 3.0.0, using Dagger 2

So my build.gradle is:

apply plugin: 'java-library'

repositories {
    jcenter()
    google()
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation project(':api_shared')

    // Guava
    implementation group: 'com.google.guava', name: 'guava', version: '23.0'

    // Dagger 2
    compile 'com.google.dagger:dagger:2.10'
    annotationProcessor 'com.google.dagger:dagger-compiler:2.10'
}

sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8

And I get the following error.

Error:(24, 0) Could not find method annotationProcessor() for arguments [com.google.dagger:dagger-compiler:2.10] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.
Open File

I saw similar errors for guys using old plugin version but here, I don't understand why I get this error.
Any idea?


问:
Will the ternary operator be executed on every digest?
If I use the ternary operator in my Angular.js view will it be executed on every digest(like functions) or only if the variables necessary for the decision are changed?

Example:

```<code><div>{{ui.isTrue ? "foo" : "bar"}}</div>
</code>```

or:

```<code><div ng-bind="ui.isTrue ? 'foo' : 'bar'"></div>
</code>```

Would it be executed on every digest or only when is ui.IsTrue changed?

答:
Here is example what you are looking, and yes  it will be executed on every digest

var app = angular.module('myApp', []);
app.controller('MyController', ['$scope', MyController]);
function MyController($scope) {
 $scope.isTrue = true;
    setInterval(function() {
      $scope.isTrue = !$scope.isTrue;
      $scope.$digest();
  }, 1000);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.14/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<div ng-app="myApp" ng-controller='MyController'>
    <div>{{isTrue ? "foo" : "bar"}}</div>
</div></code>```

Read about Digest

Body:
If I use the ternary operator in my Angular.js view will it be executed on every digest(like functions) or only if the variables necessary for the decision are changed?

Example:

{{ui.isTrue ? "foo" : "bar"}}

or:

Would it be executed on every digest or only when is ui.IsTrue changed?

Body:
Here is example what you are looking, and yes  it will be executed on every digest

var app = angular.module('myApp', []);
app.controller('MyController', ['$scope', MyController]);
function MyController($scope) {
 $scope.isTrue = true;
    setInterval(function() {
      $scope.isTrue = !$scope.isTrue;
      $scope.$digest();
  }, 1000);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.14/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<div ng-app="myApp" ng-controller='MyController'>
    <div>{{isTrue ? "foo" : "bar"}}</div>
</div>

Read about Digest


问:
Running SQL query after AJAX completes
I currently have 2 html dropdowns. Once I select from one, it filters the data in my HTML table and displays data based on the selection. I can also make changes to each row and, by clicking a save button, run an update query that updates the table. After, running that update, I want it to re-run the same query that was used to filter the results based on the dropdown selection so you can see the most up-to-date results of what you selected after clicking save and running the update statement. Right now, you can see that I have window.location.href = window.location.href; under the success callback in my AJAX function, but that reloads the entire page and runs the default query that displays on page load, so that doesn't work for me.

All of my queries that filter the table results after a dropdown selection are in my dropdown-display.php page that is called once I select something.

HTML Dropdowns:

```<code><form name="testForm" action="">
    <select id="collector">
        <option value="" selected="selected" disabled="disabled">Collector Name</option>
        <?php foreach($collect->fetchAll() as $name) { ?>
            <option class="choice" value="<?php echo htmlspecialchars($name['Collector Name']);?>"><?php echo $name['Collector Name'];?></option>
        <?php } ?>
    </select>

    <select id="date">
        <option value="" selected="selected" disabled="disabled">Bill Date</option>
        <?php foreach($bill_date->fetchAll() as $date) { ?>
            <option class="choice" value="<?php echo $date['Date'];?>"><?php echo $date['Date'];?></option>
        <?php } ?>
    </select>
</form>
</code>```

JavaScript (index.js):

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

    $('.save').click(function (event) {

        var $row = $(this).parents('tr');
            var acct = $row.find('td[name="account"]').text();
            var date = $row.find('td[name="date"]').text();
            var checked = $row.find('input[name="selected"]').is(':checked');
            var currency = $row.find('input[name="currency"]').val();
            var datepicker = $row.find('input[name="datepicker"]').val();
            var notes = $row.find('textarea[name="notes"]').val();
            var paid = $row.find('input[name="paid"]').is(':checked');

    var request = $.ajax({

          type: "POST",
          url: "update.php",
          data: { acct: acct, date: date, checked: checked, currency: currency, datepicker: datepicker, notes: notes, paid: paid },
          success: function(data){
              alert('Row successfully saved');
              //window.location.href = window.location.href;
              }
            });

        });

    });
</code>```

And this is my javascript that is run in my head tag in my main index.php page:

```<code>function showUser(collector,date) {
  $('#billing_table').hide();
  if (collector == "") {
      document.getElementById("txtHint").innerHTML = "";
      return;
  } else {
      if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("txtHint").innerHTML = this.responseText;

            var newTableObject = document.getElementById('billing_table');
            sorttable.makeSortable(newTableObject);

        }
    }

    $.ajax(
      "dropdown-display.php"
      ,{
        data:{
          q:collector,
          data:date||undefined
        }
      }
    ).then(
      function(responseText){
        $("#txtHint").html(responseText);
        sorttable.makeSortable($('#billing_table')[0]);
      }
      ,function(error){
        console.warn("something went wrong:",error);
        debugger;
      }
    )

  }
}

$(document).ready(function(){

    $("#collector, #date").change(function(e){
    showUser(
      $("#collector").val()
      ,$("#date").val()
    );
  });

    $("#collector").change(function(e){
        $.post('index-ajax.php',{filter:'Name',by:$(this).val()},function(data){
            $("#date .choice").hide();
            $.each(data, function(key,row) {
                $("#date option").filter(function(i){
                    return $(this).attr("value").indexOf( row.item ) != -1;
                }).show();
            });
        },"JSON");
    });

});
</code>```

答:
You can bind the event after successful response of ajax like that:</p>

```<code>$(document).ready(function () {
   $('.save').click(function (event) {
      var $row = $(this).parents('tr');
      var acct = $row.find('td[name="account"]').text();
      var date = $row.find('td[name="date"]').text();
      var checked = $row.find('input[name="selected"]').is(':checked');
      var currency = $row.find('input[name="currency"]').val();
      var datepicker = $row.find('input[name="datepicker"]').val();
      var notes = $row.find('textarea[name="notes"]').val();
      var paid = $row.find('input[name="paid"]').is(':checked');

            var request = $.ajax({
        type: "POST",
        url: "update.php",
        data: { acct: acct, date: date, checked: checked, currency: currency, datepicker: datepicker, notes: notes, paid: paid },
        success: function(data){
          alert('Row successfully saved');
          $('#chdir select').bind('change', getDirs); // this is use for example like change of select
        }
      });
   });
});

function getDirs(){
  //any functionality you want
}
</code>```

Title: Running SQL query after AJAX completes

Body:
I currently have 2 html dropdowns. Once I select from one, it filters the data in my HTML table and displays data based on the selection. I can also make changes to each row and, by clicking a save button, run an update query that updates the table. After, running that update, I want it to re-run the same query that was used to filter the results based on the dropdown selection so you can see the most up-to-date results of what you selected after clicking save and running the update statement. Right now, you can see that I have window.location.href = window.location.href; under the success callback in my AJAX function, but that reloads the entire page and runs the default query that displays on page load, so that doesn't work for me.

All of my queries that filter the table results after a dropdown selection are in my dropdown-display.php page that is called once I select something.

HTML Dropdowns:

<form name="testForm" action="">
    <select id="collector">
        <option value="" selected="selected" disabled="disabled">Collector Name</option>
        <?php foreach($collect->fetchAll() as $name) { ?>
            <option class="choice" value="<?php echo htmlspecialchars($name['Collector Name']);?>"><?php echo $name['Collector Name'];?></option>
        <?php } ?>
    </select>

    <select id="date">
        <option value="" selected="selected" disabled="disabled">Bill Date</option>
        <?php foreach($bill_date->fetchAll() as $date) { ?>
            <option class="choice" value="<?php echo $date['Date'];?>"><?php echo $date['Date'];?></option>
        <?php } ?>
    </select>
</form>

JavaScript (index.js):

$(document).ready(function () {

    $('.save').click(function (event) {

        var $row = $(this).parents('tr');
            var acct = $row.find('td[name="account"]').text();
            var date = $row.find('td[name="date"]').text();
            var checked = $row.find('input[name="selected"]').is(':checked');
            var currency = $row.find('input[name="currency"]').val();
            var datepicker = $row.find('input[name="datepicker"]').val();
            var notes = $row.find('textarea[name="notes"]').val();
            var paid = $row.find('input[name="paid"]').is(':checked');

    var request = $.ajax({

          type: "POST",
          url: "update.php",
          data: { acct: acct, date: date, checked: checked, currency: currency, datepicker: datepicker, notes: notes, paid: paid },
          success: function(data){
              alert('Row successfully saved');
              //window.location.href = window.location.href;
              }
            });

        });

    });

And this is my javascript that is run in my head tag in my main index.php page:

function showUser(collector,date) {
  $('#billing_table').hide();
  if (collector == "") {
      document.getElementById("txtHint").innerHTML = "";
      return;
  } else {
      if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("txtHint").innerHTML = this.responseText;

            var newTableObject = document.getElementById('billing_table');
            sorttable.makeSortable(newTableObject);

        }
    }

    $.ajax(
      "dropdown-display.php"
      ,{
        data:{
          q:collector,
          data:date||undefined
        }
      }
    ).then(
      function(responseText){
        $("#txtHint").html(responseText);
        sorttable.makeSortable($('#billing_table')[0]);
      }
      ,function(error){
        console.warn("something went wrong:",error);
        debugger;
      }
    )

  }
}

$(document).ready(function(){

    $("#collector, #date").change(function(e){
    showUser(
      $("#collector").val()
      ,$("#date").val()
    );
  });

    $("#collector").change(function(e){
        $.post('index-ajax.php',{filter:'Name',by:$(this).val()},function(data){
            $("#date .choice").hide();
            $.each(data, function(key,row) {
                $("#date option").filter(function(i){
                    return $(this).attr("value").indexOf( row.item ) != -1;
                }).show();
            });
        },"JSON");
    });

});

Body:
You can bind the event after successful response of ajax like that:

$(document).ready(function () {
   $('.save').click(function (event) {
      var $row = $(this).parents('tr');
      var acct = $row.find('td[name="account"]').text();
      var date = $row.find('td[name="date"]').text();
      var checked = $row.find('input[name="selected"]').is(':checked');
      var currency = $row.find('input[name="currency"]').val();
      var datepicker = $row.find('input[name="datepicker"]').val();
      var notes = $row.find('textarea[name="notes"]').val();
      var paid = $row.find('input[name="paid"]').is(':checked');

            var request = $.ajax({
        type: "POST",
        url: "update.php",
        data: { acct: acct, date: date, checked: checked, currency: currency, datepicker: datepicker, notes: notes, paid: paid },
        success: function(data){
          alert('Row successfully saved');
          $('#chdir select').bind('change', getDirs); // this is use for example like change of select
        }
      });
   });
});

function getDirs(){
  //any functionality you want
}


问:
Java Socket Programming
I am building a simple client/server application using java sockets and experimenting with the ObjectOutputStream etc.

I have been following the tutorial at this url http://java.sun.com/developer/technicalArticles/ALT/sockets starting half way down when it talks about transporting objects over sockets.

See my code for the client http://pastebin.com/m37e4c577 However this doesn't seem to work and i cannot figure out what's not working. The code commented out at the bottom is directly copied out of the tutorial - and this works when i just use that instead of creating the client object.

Can anyone see anything i am doing wrong?

答:
The problem is the order you are creating the streams:

In the server from the article (which I assume is what you are using), when a new connection is opened, the server opens first an input stream, and then an output stream:

```<code>public Connect(Socket clientSocket) {
 client = clientSocket;
 try {
  ois = new ObjectInputStream(client.getInputStream());
  oos = new ObjectOutputStream(client.getOutputStream());
 } catch(Exception e1) {
     // ...
 }
 this.start();
}
</code>```

The commented example code uses the reverse order, first establishing the output stream, then the input stream:

```<code>// open a socket connection
socket = new Socket("localhost", 2000);
// open I/O streams for objects
oos = new ObjectOutputStream(socket.getOutputStream());
ois = new ObjectInputStream(socket.getInputStream());
</code>```

But your code does it the other way around:

```<code>server = new Socket(host, port);
in = new ObjectInputStream(server.getInputStream());
out = new ObjectOutputStream(server.getOutputStream());
</code>```

Establishing an output stream/input stream pair will stall until they have exchanged their handshaking information, so you must match the order of creation. You can do this just by swapping lines 34 and 35 in your example code.

OwnerDisplayName: Malachi

Title: Java Socket Programming

Body:
The problem is the order you are creating the streams:

In the server from the article (which I assume is what you are using), when a new connection is opened, the server opens first an input stream, and then an output stream:

public Connect(Socket clientSocket) {
 client = clientSocket;
 try {
  ois = new ObjectInputStream(client.getInputStream());
  oos = new ObjectOutputStream(client.getOutputStream());
 } catch(Exception e1) {
     // ...
 }
 this.start();
}

The commented example code uses the reverse order, first establishing the output stream, then the input stream:

// open a socket connection
socket = new Socket("localhost", 2000);
// open I/O streams for objects
oos = new ObjectOutputStream(socket.getOutputStream());
ois = new ObjectInputStream(socket.getInputStream());

But your code does it the other way around:

server = new Socket(host, port);
in = new ObjectInputStream(server.getInputStream());
out = new ObjectOutputStream(server.getOutputStream());

Establishing an output stream/input stream pair will stall until they have exchanged their handshaking information, so you must match the order of creation. You can do this just by swapping lines 34 and 35 in your example code.

OwnerDisplayName: Mike Houston

ContentLicense: CC BY-SA 2.5


问:
PL SQL How to put many wrappers in one package
reference: How to make a wrapper to return something other than ref cursor

I've got many wrapped functions that are similar to the one below, only they return different columns of course. How can i put them all in one package. because what the examples below does is replace my wrapper package everytime.

I want to know how to remove the global declarations on top so that i can add many in the same package each with different return columns

```<code>create or replace package WrapperSample is

  type TResultRow is record(
     if_type         codes.cd%type
    ,number_infected Integer);

  type TResultRowList is table of TResultRow;

  function GetADedIcWarningsProv
  (
    p_hos_id in work_entity_data.hos_id%type
   ,p_date   in date
  ) return TResultRowList
    pipelined;

end WrapperSample;
/

create or replace package body WrapperSample is

  function GetADedIcWarningsProv
  (
    p_hos_id in work_entity_data.hos_id%type
   ,p_date   in date
  ) return TResultRowList
    pipelined is
    v_refcur   eOdatatypes_package.eOrefcur;
    currentRow TResultRow;
  begin
    v_refcur := YourSchema.getADedIcWarningsProv(p_hos_id, p_date);

    loop
      fetch v_refcur
        INTO currentRow;
      exit when v_refcur%NotFound;
      pipe row(currentRow);
    end loop;

    close v_refcur;

    return;
  end;

end WrapperSample;
/
</code>```

答:
you would use one record definition and one table definition per different column set.</p>

```<code>create or replace package WrapperSample is

  type R_WarningsProv is record(/*...*/);

  type T_WarningsProv is table of R_WarningsProv ;

  function GetADedIcWarningsProv(/*...*/) return T_WarningsProv pipelined;

  type R_OtherFunction is record(/*...*/);

  type T_OtherFunction is table of R_OtherFunction ;

  function OtherFunction(/*...*/) return T_OtherFunction pipelined;

  /* Multiple functions can use the same types as long as
     they share the same column definition */

  function SomeOtherFunction(/*...*/) return T_OtherFunction pipelined;

end WrapperSample;
</code>```

Body:
reference: How to make a wrapper to return something other than ref cursor

I've got many wrapped functions that are similar to the one below, only they return different columns of course. How can i put them all in one package. because what the examples below does is replace my wrapper package everytime.

I want to know how to remove the global declarations on top so that i can add many in the same package each with different return columns

create or replace package WrapperSample is

  type TResultRow is record(
     if_type         codes.cd%type
    ,number_infected Integer);

  type TResultRowList is table of TResultRow;

  function GetADedIcWarningsProv
  (
    p_hos_id in work_entity_data.hos_id%type
   ,p_date   in date
  ) return TResultRowList
    pipelined;

end WrapperSample;
/

create or replace package body WrapperSample is

  function GetADedIcWarningsProv
  (
    p_hos_id in work_entity_data.hos_id%type
   ,p_date   in date
  ) return TResultRowList
    pipelined is
    v_refcur   eOdatatypes_package.eOrefcur;
    currentRow TResultRow;
  begin
    v_refcur := YourSchema.getADedIcWarningsProv(p_hos_id, p_date);

    loop
      fetch v_refcur
        INTO currentRow;
      exit when v_refcur%NotFound;
      pipe row(currentRow);
    end loop;

    close v_refcur;

    return;
  end;

end WrapperSample;
/

Body:
you would use one record definition and one table definition per different column set.

create or replace package WrapperSample is

  type R_WarningsProv is record(/*...*/);

  type T_WarningsProv is table of R_WarningsProv ;

  function GetADedIcWarningsProv(/*...*/) return T_WarningsProv pipelined;

  type R_OtherFunction is record(/*...*/);

  type T_OtherFunction is table of R_OtherFunction ;

  function OtherFunction(/*...*/) return T_OtherFunction pipelined;

  /* Multiple functions can use the same types as long as
     they share the same column definition */

  function SomeOtherFunction(/*...*/) return T_OtherFunction pipelined;

end WrapperSample;


问:
ObjectBox Source entity has no ID (should have been put before)
I got an exception while trying to insert new object.

Logcat:

```<code>java.lang.IllegalStateException: Source entity has no ID (should have been put before)
at io.objectbox.relation.ToMany.internalCheckApplyToDbRequired(ToMany.java:599)
</code>```

Insert function:

```<code>public static void setSyncData(long contactId, SyncerData syncData) {
    final Box<SyncerData> box = getObjectBoxStore().boxFor(SyncerData.class);
    SyncerData syncerData = box.query().equal(SyncerData_.id, contactId).build().findFirst();
    if (syncerData == null) {
        syncerData = new SyncerData();
        syncerData.setPhoneOrIdKey(ContactData.generateId(Phone.EMPTY, contactId));
    }
    syncerData.setSyncerDetailsToMany(syncData.getSyncerDetailsToMany());
    box.put(syncerData);
}
</code>```

What that's mean, that I can't put new object ToMany list before I added to object?

答:
I think it's related to https://github.com/objectbox/objectbox-java/issues/104.

In essence setting a relation to a new plain List is somewhat problematic because ObjectBox lacks the change tracking, which is available in the ToManyclass. We'll look how to sync that in a future release.

Please try something like the following:

```<code>toMany.clear();
toMany.addAll(newList);
</code>```

Body:
I got an exception while trying to insert new object.

Logcat:

java.lang.IllegalStateException: Source entity has no ID (should have been put before)
at io.objectbox.relation.ToMany.internalCheckApplyToDbRequired(ToMany.java:599)

Insert function:

public static void setSyncData(long contactId, SyncerData syncData) {
    final Box<SyncerData> box = getObjectBoxStore().boxFor(SyncerData.class);
    SyncerData syncerData = box.query().equal(SyncerData_.id, contactId).build().findFirst();
    if (syncerData == null) {
        syncerData = new SyncerData();
        syncerData.setPhoneOrIdKey(ContactData.generateId(Phone.EMPTY, contactId));
    }
    syncerData.setSyncerDetailsToMany(syncData.getSyncerDetailsToMany());
    box.put(syncerData);
}

What that's mean, that I can't put new object ToMany list before I added to object?

Body:
I think it's related to https://github.com/objectbox/objectbox-java/issues/104.

In essence setting a relation to a new plain List is somewhat problematic because ObjectBox lacks the change tracking, which is available in the ToManyclass. We'll look how to sync that in a future release.

Please try something like the following:

toMany.clear();
toMany.addAll(newList);


问:
Is there any performance benefit to using .net 4's no-PIA feature?
I understand that there's a deployment benefit to no-PIA, but is there a performance benefit to having the types embedded in the assembly?</p>

答:
It's my understanding this is a deployment feature.  You shouldn't see much of a performance difference.

There may be a slight improvement over the time it takes to load the PIA.


问:
How to batch execute with JOOQ
I'm calling existing MySql stored procedures using JOOQ. My code is in Java. Everything is ok but i'm a bit confused when it comes to batch inserts. For example, i have simple like this:

```<code>private void executeBatch(DSLContext context, LinkedList<AbstractRoutine<Void>> procedures) {
        BatchBindStep step = null;
        for (AbstractRoutine<Void> procedure : procedures) {
            step = context.batch (context.select(procedure.asField()));
        }

        step.execute();
    }
</code>```

Each and every procedure from supplied LinkedList is an update or insert procedure with it's own arguments set and is actually ready for execution. I'm just trying to bind them together for batch processing.

When i try execute code above, i'm getting error:

```<code>Caused by: java.sql.BatchUpdateException: Can not issue SELECT via executeUpdate().
</code>```

What am i doing wrong? What should i fix? I was trying to search for an answer online but seems like using JOOQ both batch stored procedure calls isn't so popular. I have to do it in order to keep compatibility with rest of my pre-JOOQ application....

答: As discussed with Lukas Eder in said Google group, this feature (batch calling stored procedures) will be added to JOOQ 3.11.</p>

Title: How to batch execute with JOOQ

Body:
I'm calling existing MySql stored procedures using JOOQ. My code is in Java. Everything is ok but i'm a bit confused when it comes to batch inserts. For example, i have simple like this:

private void executeBatch(DSLContext context, LinkedList<AbstractRoutine<Void>> procedures) {
        BatchBindStep step = null;
        for (AbstractRoutine<Void> procedure : procedures) {
            step = context.batch (context.select(procedure.asField()));
        }

        step.execute();
    }

Each and every procedure from supplied LinkedList is an update or insert procedure with it's own arguments set and is actually ready for execution. I'm just trying to bind them together for batch processing.

When i try execute code above, i'm getting error:

Caused by: java.sql.BatchUpdateException: Can not issue SELECT via executeUpdate().

What am i doing wrong? What should i fix? I was trying to search for an answer online but seems like using JOOQ both batch stored procedure calls isn't so popular. I have to do it in order to keep compatibility with rest of my pre-JOOQ application....


问:
extending React.Component vs Component
I just got in a project on React Native, where I constantly see classes extending both React.Component and Component itself.

Examples:

class SomeView extends React.Component

or

class OtherView extends Component

in both of them we are importing React, {Component} from React

Is there any actual difference, if so, which one? Didn't found any info on the web. Cheers!

答:
Well you can do whatever you want really.

Doing import { Component } from 'react' is effectively the same thing as React.Component.

The import { Component } from 'react' syntax is called a Named Import

The import statement is used to import bindings which are exported by another module.

```<code>import defaultExport from "module-name";
import * as name from "module-name";
import { export } from "module-name";
import { export as alias } from "module-name";
import { export1 , export2 } from "module-name";
import { export1 , export2 as alias2 , [...] } from "module-name";
import defaultExport, { export [ , [...] ] } from "module-name";
import defaultExport, * as name from "module-name";
import "module-name";
</code>```

Title: extending React.Component vs Component

Body:
Well you can do whatever you want really.

Doing import { Component } from 'react' is effectively the same thing as React.Component.

The import { Component } from 'react' syntax is called a Named Import

The import statement is used to import bindings which are exported by another module.

import defaultExport from "module-name";
import * as name from "module-name";
import { export } from "module-name";
import { export as alias } from "module-name";
import { export1 , export2 } from "module-name";
import { export1 , export2 as alias2 , [...] } from "module-name";
import defaultExport, { export [ , [...] ] } from "module-name";
import defaultExport, * as name from "module-name";
import "module-name";