问:
Duplicates in an array invalid input
I tried making a simple code for checking in an array for duplicate numbers/numbers that are smaller than the size of the array and numbers that are bigger than the size of the array.
(for example for an array by the size of 7, the number in the array should be between 1-7 with no duplicates, if not the system will print invalid error)
when I enter an array by the size of 1 and enter the number 2 for example I get the following error message:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
      at sumn.main(sumn.java:24)

Here is the code itself, any thoughts on how to fix this?

```<code>public class sumn {
    public static boolean Duplicates(int arr[]) {
        int a, b;
        boolean flag = true;
        for (a=0;a<arr.length-1;a++) {
            for (b=a+1;b<arr.length;b++) {
                if (arr[b]==arr[a]) {
                    return false;
                }
            }
        }
        return flag;
    }

    public static void main(String[] args) {
        int N = MyConsole.readInt("Enter the size of the array:");
        int arr[] = new int [N];
        int i, j;
        boolean flag = true;
        for (i=0;i<arr.length;i++) {
            arr[i]= MyConsole.readInt("Enter a number between 1 to ");
        }
        for (j=0;j<arr.length;j++) {
            if (Duplicates(arr)==false || N<arr[i] || arr[i]<=0)
                flag = false;
            if (flag == false)  {
                System.out.println("Invalid input");
            }
        }
    }

}
</code>```

答:
I'm guessing line 24 is if (Duplicates(arr)==false || N<arr[i] || arr[i]<=0). The problem here is that after your first loop, i will have the value of arr.length. This will cause an ArrayIndexOutOfBoundsException everytime.

You can either replace i with j on that line, which seems to be what you intended to do. Or you can "clean up" a bit and scope i to only the loops by writing your loops like:

```<code>for(int i = 0; i < arr.length; i++) { ... }
</code>```

instead of

```<code>int i;
for(i = 0; i < arr.length; i++) { ... }
</code>```

Title: Duplicates in an array invalid input

Body:
I tried making a simple code for checking in an array for duplicate numbers/numbers that are smaller than the size of the array and numbers that are bigger than the size of the array.
(for example for an array by the size of 7, the number in the array should be between 1-7 with no duplicates, if not the system will print invalid error)
when I enter an array by the size of 1 and enter the number 2 for example I get the following error message:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
      at sumn.main(sumn.java:24)

Here is the code itself, any thoughts on how to fix this?

public class sumn {
    public static boolean Duplicates(int arr[]) {
        int a, b;
        boolean flag = true;
        for (a=0;a<arr.length-1;a++) {
            for (b=a+1;b<arr.length;b++) {
                if (arr[b]==arr[a]) {
                    return false;
                }
            }
        }
        return flag;
    }

    public static void main(String[] args) {
        int N = MyConsole.readInt("Enter the size of the array:");
        int arr[] = new int [N];
        int i, j;
        boolean flag = true;
        for (i=0;i<arr.length;i++) {
            arr[i]= MyConsole.readInt("Enter a number between 1 to ");
        }
        for (j=0;j<arr.length;j++) {
            if (Duplicates(arr)==false || N<arr[i] || arr[i]<=0)
                flag = false;
            if (flag == false)  {
                System.out.println("Invalid input");
            }
        }
    }

}

Body:
I'm guessing line 24 is if (Duplicates(arr)==false || N<arr[i] || arr[i]<=0). The problem here is that after your first loop, i will have the value of arr.length. This will cause an ArrayIndexOutOfBoundsException everytime.

You can either replace i with j on that line, which seems to be what you intended to do. Or you can "clean up" a bit and scope i to only the loops by writing your loops like:

for(int i = 0; i < arr.length; i++) { ... }

instead of

int i;
for(i = 0; i < arr.length; i++) { ... }


来源: stackexchange

问:
How set multi-line EditText with inputtype="number"?
I try set multi line for edittext if imputtype="number"
as:

```<code><EditText
            android:id="@+id/txtJianNo"
            android:layout_width="480px"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:background="@drawable/txtjianno"
            android:ems="10"
            android:gravity="top"
            android:inputType="number|textMultiLine"
            android:lines="2"
            android:singleLine="false"
            android:textColor="#5FB234"
            android:textSize="18dp" />
</code>```

But value of edittext doesn't new line if length of value > length of edittext.
How set multi-line EditText with inputtype="number"?

答: You can edittext.setSingleLine(false);

ContentLicense: CC BY-SA 3.0

Body:
I try set multi line for edittext if imputtype="number"
as:

<EditText
            android:id="@+id/txtJianNo"
            android:layout_width="480px"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:background="@drawable/txtjianno"
            android:ems="10"
            android:gravity="top"
            android:inputType="number|textMultiLine"
            android:lines="2"
            android:singleLine="false"
            android:textColor="#5FB234"
            android:textSize="18dp" />

But value of edittext doesn't new line if length of value > length of edittext.
How set multi-line EditText with inputtype="number"?

Body: You can edittext.setSingleLine(false);


问:
Django Timezone Awareness - Data to be stored in UTC

This is my first time developing a timezone aware web app.  I'm using Django 1.11.7.  I have looked through many posts regarding timezones and honestly, I'm starting to feel like I just don't understand the concept of timezones... 0_o

I'm making a booking app with start_time and end_time for each reservation.

I expect the user to be able to enter dates and times as he experiences them in his timezone.  On the other hand, I want these dates and times stored in a postgresql database in UTC format.

If I was choosing to reserve, for example, between 12am and 2am (today), the result in the database should show between 5pm and 7pm (today).

Right?

Django Internationalization settings:

```<code>LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_TZ = True
USE_L10N = True
USE_I18N = True
</code>```

During database creation:

```<code>start_time      TIMESTAMP WITH TIME ZONE NOT NULL,
end_time        TIMESTAMP WITH TIME ZONE NOT NULL
</code>```

Using Django's built in admin page feature, I enter the following information:

But when I look up the results in the database, here's what I get:

```<code>2017-12-05 19:00:00-05 | 2017-12-05 20:59:59-05
</code>```

The stored result changed in the opposite direction of what I was expecting.  I was expecting:

```<code>2017-12-06 05:00:00+05 | 2017-12-06 07:00:00+05
</code>```

If my expectations are wrong and everything is working fine, I would be grateful if you could explain to me how I should interpret the timezone when I read it.

Otherwise, if my expectations where right, I would appreciate any advice.

Thank you.

答:
The basic issue here is that you've misunderstood what the admin is doing for you ("I expect the user to be able to enter dates and times as he experiences them in his timezone"). In fact, the admin interprets all datetimes in the server time zone (UTC in your case).

Note: You are 5 hours behind server time

actually means:

Warning: The values you enter here will be interpreted in the server timezone, which is 5 hours ahead of you.

(I agree with you that this wording is ambiguous. You might want to file a ticket about improving it.)

For background on this issue, see this ticket. The root of the problem is that there's no way to get the user's timezone in the browser. What you can do is compare the current time in the browser to the current time on the server and post the warning above if they are different.

If you want to interpret datetimes in the user's timezone, there's no alternative but to ask the user to indicate their timezone explicitly, record it somewhere, and then activate() it to make it the current timezone. This is the technique described in the documentation. I believe that there are third-party packages that provide timezone selection widgets based on the list of timezones in pytz.

You're also misreading the time display. I think what you were expecting is 2017-12-06 05:00:00+00. Instead the result is 2017-12-06 00:00:00+00 in UTC or, equivalently, 2017-12-05 19:00:00-05 in Ottawa time, which is what you reported.

Body:
This is my first time developing a timezone aware web app.  I'm using Django 1.11.7.  I have looked through many posts regarding timezones and honestly, I'm starting to feel like I just don't understand the concept of timezones... 0_o

I'm making a booking app with start_time and end_time for each reservation.

I expect the user to be able to enter dates and times as he experiences them in his timezone.  On the other hand, I want these dates and times stored in a postgresql database in UTC format.

If I was choosing to reserve, for example, between 12am and 2am (today), the result in the database should show between 5pm and 7pm (today).

Right?

Django Internationalization settings:

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_TZ = True
USE_L10N = True
USE_I18N = True

During database creation:

start_time      TIMESTAMP WITH TIME ZONE NOT NULL,
end_time        TIMESTAMP WITH TIME ZONE NOT NULL

Using Django's built in admin page feature, I enter the following information:

But when I look up the results in the database, here's what I get:

2017-12-05 19:00:00-05 | 2017-12-05 20:59:59-05

The stored result changed in the opposite direction of what I was expecting.  I was expecting:

2017-12-06 05:00:00+05 | 2017-12-06 07:00:00+05

If my expectations are wrong and everything is working fine, I would be grateful if you could explain to me how I should interpret the timezone when I read it.

Otherwise, if my expectations where right, I would appreciate any advice.

Thank you.


问:
I Need to flatten an array
How could I flatten my array of object :

var mylist = [{
    THEMEID: 1,
    TITLE: "myTheme1",
    PARENTID: 0,
    children: [{
        ITEMID: 1,
        NAME: "myItem1",
        THEMEID: 1,
        PARENTID: 1,
        TITLE: "myItem1"
      },
      {
        THEMEID: 3,
        TITLE: "mySubTheme1",
        PARENTID: 1,
        children: [{
          ITEMID: 3,
          NAME: "myItem3",
          THEMEID: 3,
          PARENTID: 2,
          TITLE: "myItem3"
        }]
      }
    ]
  },
  {
    THEMEID: 2,
    TITLE: "myTheme2",
    PARENTID: 0,
    children: [{
      ITEMID: 4,
      NAME: "myItem4",
      THEMEID: 2,
      PARENTID: 1,
      TITLE: "myItem4"
    }]
  },
  {
    THEMEID: 6,
    TITLE: "myTheme3",
    PARENTID: 0,
    children: [{
      THEMEID: 5,
      TITLE: "mySubTheme3",
      PARENTID: 1,
      children: [{
        THEMEID: 4,
        TITLE: "mySubSubTheme3",
        PARENTID: 2,
        children: [{
          ITEMID: 2,
          NAME: "myItem2",
          THEMEID: 4,
          PARENTID: 3,
          TITLE: "myItem2"
        }]
      }]
    }]
  }
];

   console.log(mylist)```
</div>
</div>
</p>

<p>In a array where are indexes of children are to record in the children array of the parent array
How could I flatten my myList array to obtain a array as this, by having that the indexes of children to record in the children array of the parent:
Example :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var myFLaten = [
{THEMEID: 1, TITLE: "myTheme1", PARENTID: 0, children:[1,2]},
{ITEMID: 1, NAME: "myItem1", THEMEID: 1, PARENTID: 1, TITLE: "myItem1"},
{THEMEID: 3, TITLE: "mySubTheme1", PARENTID: 1, children:[3]},
{ITEMID: 3, NAME: "myItem3", THEMEID: 3, PARENTID: 2, TITLE: "myItem3"}]

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

答:
You could store the last children reference in a closure and iterate the given array. On inserting a new object in the flat array, another insert is made with the index of the inserted objects.

var tree = [{ THEMEID: 1, TITLE: "myTheme1", PARENTID: 0, children: [{ ITEMID: 1, NAME: "myItem1", THEMEID: 1, PARENTID: 1, TITLE: "myItem1" }, { THEMEID: 3, TITLE: "mySubTheme1", PARENTID: 1, children: [{ ITEMID: 3, NAME: "myItem3", THEMEID: 3, PARENTID: 2, TITLE: "myItem3" }] }] }, { THEMEID: 2, TITLE: "myTheme2", PARENTID: 0, children: [{ ITEMID: 4, NAME: "myItem4", THEMEID: 2, PARENTID: 1, TITLE: "myItem4" }] }, { THEMEID: 6, TITLE: "myTheme3", PARENTID: 0, children: [{ THEMEID: 5, TITLE: "mySubTheme3", PARENTID: 1, children: [{ THEMEID: 4, TITLE: "mySubSubTheme3", PARENTID: 2, children: [{ ITEMID: 2, NAME: "myItem2", THEMEID: 4, PARENTID: 3, TITLE: "myItem2" }] }] }] }],
    flat = tree.reduce(function fn(parent, children) {
        return function (r, o) {
            var temp = { THEMEID: o.THEMEID, TITLE: o.TITLE, PARENTID: o.PARENTID, parentIndex: parent },
                index = r.push(temp) - 1;
            if ('ITEMID' in o) {
                temp.ITEMID = o.ITEMID;
            }
            children.push(index);
            if (o.children) {
                o.children.reduce(fn(index, temp.children = []), r);
            }
            return r;
        };
    }(undefined, []), []);

console.log(flat);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: I Need to flatten an array

Body:
How could I flatten my array of object :

var mylist = [{
    THEMEID: 1,
    TITLE: "myTheme1",
    PARENTID: 0,
    children: [{
        ITEMID: 1,
        NAME: "myItem1",
        THEMEID: 1,
        PARENTID: 1,
        TITLE: "myItem1"
      },
      {
        THEMEID: 3,
        TITLE: "mySubTheme1",
        PARENTID: 1,
        children: [{
          ITEMID: 3,
          NAME: "myItem3",
          THEMEID: 3,
          PARENTID: 2,
          TITLE: "myItem3"
        }]
      }
    ]
  },
  {
    THEMEID: 2,
    TITLE: "myTheme2",
    PARENTID: 0,
    children: [{
      ITEMID: 4,
      NAME: "myItem4",
      THEMEID: 2,
      PARENTID: 1,
      TITLE: "myItem4"
    }]
  },
  {
    THEMEID: 6,
    TITLE: "myTheme3",
    PARENTID: 0,
    children: [{
      THEMEID: 5,
      TITLE: "mySubTheme3",
      PARENTID: 1,
      children: [{
        THEMEID: 4,
        TITLE: "mySubSubTheme3",
        PARENTID: 2,
        children: [{
          ITEMID: 2,
          NAME: "myItem2",
          THEMEID: 4,
          PARENTID: 3,
          TITLE: "myItem2"
        }]
      }]
    }]
  }
];

   console.log(mylist)

In a array where are indexes of children are to record in the children array of the parent array
How could I flatten my myList array to obtain a array as this, by having that the indexes of children to record in the children array of the parent:
Example :

var myFLaten = [
{THEMEID: 1, TITLE: "myTheme1", PARENTID: 0, children:[1,2]},
{ITEMID: 1, NAME: "myItem1", THEMEID: 1, PARENTID: 1, TITLE: "myItem1"},
{THEMEID: 3, TITLE: "mySubTheme1", PARENTID: 1, children:[3]},
{ITEMID: 3, NAME: "myItem3", THEMEID: 3, PARENTID: 2, TITLE: "myItem3"}]

console.log(myFLaten)

Body:
You could store the last children reference in a closure and iterate the given array. On inserting a new object in the flat array, another insert is made with the index of the inserted objects.

var tree = [{ THEMEID: 1, TITLE: "myTheme1", PARENTID: 0, children: [{ ITEMID: 1, NAME: "myItem1", THEMEID: 1, PARENTID: 1, TITLE: "myItem1" }, { THEMEID: 3, TITLE: "mySubTheme1", PARENTID: 1, children: [{ ITEMID: 3, NAME: "myItem3", THEMEID: 3, PARENTID: 2, TITLE: "myItem3" }] }] }, { THEMEID: 2, TITLE: "myTheme2", PARENTID: 0, children: [{ ITEMID: 4, NAME: "myItem4", THEMEID: 2, PARENTID: 1, TITLE: "myItem4" }] }, { THEMEID: 6, TITLE: "myTheme3", PARENTID: 0, children: [{ THEMEID: 5, TITLE: "mySubTheme3", PARENTID: 1, children: [{ THEMEID: 4, TITLE: "mySubSubTheme3", PARENTID: 2, children: [{ ITEMID: 2, NAME: "myItem2", THEMEID: 4, PARENTID: 3, TITLE: "myItem2" }] }] }] }],
    flat = tree.reduce(function fn(parent, children) {
        return function (r, o) {
            var temp = { THEMEID: o.THEMEID, TITLE: o.TITLE, PARENTID: o.PARENTID, parentIndex: parent },
                index = r.push(temp) - 1;
            if ('ITEMID' in o) {
                temp.ITEMID = o.ITEMID;
            }
            children.push(index);
            if (o.children) {
                o.children.reduce(fn(index, temp.children = []), r);
            }
            return r;
        };
    }(undefined, []), []);

console.log(flat);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
shell if-else issue with can't jump to else block
```<code>#!/bin/bash
read -p "Enter your MO or attribute name: " name
grep -q $name *.txt      #judge the input whether exists or not. if it exists , $? will equal 0, if not , $? will equal 1.
echo $?
if [ $? -eq 0 ];then
  echo "Send to file 2"
  echo $name >> 2.txt
else
  echo "Send to file 1"
  echo $name >> 1.txt
fi
</code>```

Below is the program progress

```<code>Enter your MO or attribute name: sssqq
1                 #means no file contains "sssqqq"
Send to file 2

Enter your MO or attribute name: chenghuang
0                  #means some file contains "chenghuang"
Send to file 2
</code>```

As you see, whether the input exists in the file or not , they all will be send to 2.txt. But my purpose is that if the input exists in the file , the input will be sent to file 2, if not, it will be sent to file 1.
what's wrong with if-else?

答:
Save result to variable and manipulate with it:

```<code>res=$?
echo $res
if [ $res -eq 0 ];then
  echo "Send to file 2"
  echo $name >> 2.txt
else
  echo "Send to file 1"
  echo $name >> 1.txt
fi
</code>```

The problem is that echo $? which you have called is replaced the previous result $? with its own new result.

Body:
#!/bin/bash
read -p "Enter your MO or attribute name: " name
grep -q $name *.txt      #judge the input whether exists or not. if it exists , $? will equal 0, if not , $? will equal 1.
echo $?
if [ $? -eq 0 ];then
  echo "Send to file 2"
  echo $name >> 2.txt
else
  echo "Send to file 1"
  echo $name >> 1.txt
fi

Below is the program progress

Enter your MO or attribute name: sssqq
1                 #means no file contains "sssqqq"
Send to file 2

Enter your MO or attribute name: chenghuang
0                  #means some file contains "chenghuang"
Send to file 2

As you see, whether the input exists in the file or not , they all will be send to 2.txt. But my purpose is that if the input exists in the file , the input will be sent to file 2, if not, it will be sent to file 1.
what's wrong with if-else?

Body:
Save result to variable and manipulate with it:

res=$?
echo $res
if [ $res -eq 0 ];then
  echo "Send to file 2"
  echo $name >> 2.txt
else
  echo "Send to file 1"
  echo $name >> 1.txt
fi

The problem is that echo $? which you have called is replaced the previous result $? with its own new result.


问:
How to avoid bootstrap table borders
So I want to avoid the borders in my tbody.
Currently my code is:

```<code><body>
<div class="container">
    <div class="row">
        <div class="col-md-6">
            <table class="table">
                <thead>
                    <tr>
                        <th>TIME</th>
                        <th>LOCATION</th>
                        <th>MESSAGE</th>
                    </tr>
                </thead>
                <tbody>
                    <c:forEach items="${dbitems}" var="item" begin = "0" end = "5">
                        <tr>
                            <td>${item.time}</td>
                            <td>${item.location}</td>
                            <td>${item.message}</td>
                        </tr>
                    </c:forEach>
                </tbody>
            </table>
        </div>
        <div class="col-md-6">
            <table class="table">
                <thead>
                    <tr>
                        <th>TIME</th>
                        <th>LOCATION</th>
                        <th>MESSAGE</th>
                    </tr>
                </thead>
                <tbody>
                    <c:forEach items="${dbitems}" var="item" begin = "6" end = "11">
                        <tr>
                            <td>${item.time}</td>
                            <td>${item.location}</td>
                            <td>${item.message}</td>
                        </tr>
                    </c:forEach>
                </tbody>
            </table>
        </div>
    </div>
</div>
</code>```

My output currently looks like this:

After some research I found out that using tableclass table-borderless might be a solution so I tried it.
But what I get in the output doesn't fit my expectations:

I put both table classes to table-borderless

I want to achieve the same with as in the first picture but without the row border lines.

Thanks in advance.

答:
Use this css,it will solved your issue

.table.table-bl thead>tr>th, .table.table-bl tbody>tr>th, .table.table-bl tfoot>tr>th, .table.table-bl thead>tr>td, .table.table-bl tbody>tr>td, .table.table-bl tfoot>tr>td {
    border-top: none;
}
.table.table-bl thead>tr>th {
    border-bottom: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="container">
    <div class="row">
        <div class="col-md-6">
            <table class="table table-bl">
                <thead>
                    <tr>
                        <th>TIME</th>
                        <th>LOCATION</th>
                        <th>MESSAGE</th>
                    </tr>
                </thead>
                <tbody>
                    <c:forEach items="${dbitems}" var="item" begin = "0" end = "5">
                        <tr>
                            <td>${item.time}</td>
                            <td>${item.location}</td>
                            <td>${item.message}</td>
                        </tr>
                        <tr>
                            <td>${item.time}</td>
                            <td>${item.location}</td>
                            <td>${item.message}</td>
                        </tr>
                        <tr>
                            <td>${item.time}</td>
                            <td>${item.location}</td>
                            <td>${item.message}</td>
                        </tr>
                    </c:forEach>
                </tbody>
            </table>
        </div>
        <div class="col-md-6">
            <table class="table table-bl">
                <thead>
                    <tr>
                        <th>TIME</th>
                        <th>LOCATION</th>
                        <th>MESSAGE</th>
                    </tr>
                </thead>
                <tbody>
                    <c:forEach items="${dbitems}" var="item" begin = "6" end = "11">
                        <tr>
                            <td>${item.time}</td>
                            <td>${item.location}</td>
                            <td>${item.message}</td>
                        </tr>
                    </c:forEach>
                </tbody>
            </table>
        </div>
    </div>
</div></code>```

Title: How to avoid bootstrap table borders

Body:
So I want to avoid the borders in my tbody.
Currently my code is:

                        TIME
                        LOCATION
                        MESSAGE

                    <c:forEach items="${dbitems}" var="item" begin = "0" end = "5">

                            ${item.time}
                            ${item.location}
                            ${item.message}

                    </c:forEach>

                        TIME
                        LOCATION
                        MESSAGE

                    <c:forEach items="${dbitems}" var="item" begin = "6" end = "11">

                            ${item.time}
                            ${item.location}
                            ${item.message}

                    </c:forEach>

My output currently looks like this:

After some research I found out that using tableclass table-borderless might be a solution so I tried it.
But what I get in the output doesn't fit my expectations:

I put both table classes to table-borderless

I want to achieve the same with as in the first picture but without the row border lines.

Thanks in advance.

Body:
Use this css,it will solved your issue

.table.table-bl thead>tr>th, .table.table-bl tbody>tr>th, .table.table-bl tfoot>tr>th, .table.table-bl thead>tr>td, .table.table-bl tbody>tr>td, .table.table-bl tfoot>tr>td {
    border-top: none;
}
.table.table-bl thead>tr>th {
    border-bottom: none;
}

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="container">
    <div class="row">
        <div class="col-md-6">
            <table class="table table-bl">
                <thead>
                    <tr>
                        <th>TIME</th>
                        <th>LOCATION</th>
                        <th>MESSAGE</th>
                    </tr>
                </thead>
                <tbody>
                    <c:forEach items="${dbitems}" var="item" begin = "0" end = "5">
                        <tr>
                            <td>${item.time}</td>
                            <td>${item.location}</td>
                            <td>${item.message}</td>
                        </tr>
                        <tr>
                            <td>${item.time}</td>
                            <td>${item.location}</td>
                            <td>${item.message}</td>
                        </tr>
                        <tr>
                            <td>${item.time}</td>
                            <td>${item.location}</td>
                            <td>${item.message}</td>
                        </tr>
                    </c:forEach>
                </tbody>
            </table>
        </div>
        <div class="col-md-6">
            <table class="table table-bl">
                <thead>
                    <tr>
                        <th>TIME</th>
                        <th>LOCATION</th>
                        <th>MESSAGE</th>
                    </tr>
                </thead>
                <tbody>
                    <c:forEach items="${dbitems}" var="item" begin = "6" end = "11">
                        <tr>
                            <td>${item.time}</td>
                            <td>${item.location}</td>
                            <td>${item.message}</td>
                        </tr>
                    </c:forEach>
                </tbody>
            </table>
        </div>
    </div>
</div>


答: Your issue is the use of $?. $? always holds the return value of the last command. After you run echo $?, the $? in your if statement holds the return value of echo.

Title: shell if-else issue with can't jump to else block


问:
Chrome DevTools search all javascript files in website
I'm working on a new client's website that loads Javascript from a CDN so the Javascript is not embedded or inline with the webpage source. I would like to pause everytime getCurrentPosition() is executed in order to determine which external JS file it is contained in.

I realize I could use other tools to do a string search through the contents of the JS files but I would rather keep to Chrome's debugging tools.

Should I be trying to create a watch expression or is there another way to pin down when and where a certain JS function is fired?

答:
Open Google Dev tools(F12)

Press Ctrl + p

In the opened box search for all files(JS, CSS, ...).

In the box you have 5 options:

At the first select a file for using options 2-5

Type 'filename' and select it.

Type ':linenumber' to go to specific line number(':10' go to line 10).

Type '@symbol' to go to specific symbol('@TestSymbol' go to TestSymbol symbol).

In this option, if you write @JSFunctionName or @CSSClassName then the cursor
will navigate to the JSFunctionName or the CSSClassName.

Type '!snippet' to go to specific snippet('!snippetTest' go to snippetTest snippet).

Type '>googleCommand' to go to specific command('>Clear console' clear the console).

ContentLicense: CC BY-SA 4.0


问:
Information about remote IP addresses
I want to track all IP addresses with which my computer is communicating. I am using C# and Visual Studio. There is one listBox in which I will put all remote IP address. I am new to network programming so I need some direction about that kind of problem.

My question is how to do this? How to get information about remote IP addresses which which my computer make connections?

答:
On Windows, there's an IP helper library, iphlpapi, which can discover information about open connections on your machine. In particular, you want to look at the GetTcpTable and GetUdpTable functions.

The problem is this is a C API. To use these from C# requires you to use the P/Invoke API. It's a trivial task, but can take some time to do. Each of the C structs used need rewriting in C#, making use of the System.Runtime.InteropServices namespace to marshal them. Much of this can be automated, or done by decorating struct fields with the correct attributes, but there may be cases where you need to marshal a structure manually.

The C functions you import need marking with [DllImport("iphlpapi.dll")] with any other relevant attributes depending on the function you're importing. You can read more about PInvoke at msdn, and perhaps find some already written imports at the pinvoke wiki. In addition, there is a tool which can attempt to automate much of it for you, the Pinvoke interop assitant

ContentLicense: CC BY-SA 2.5

Title: Information about remote IP addresses


问:
Random shuffling of an array
I need to randomly shuffle the following Array:

```<code>int[] solutionArray = {1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1};
</code>```

Is there any function to do that?

答:
A simple solution for Groovy:

```<code>solutionArray.sort{ new Random().nextInt() }
</code>```

This will sort all elements of the array list randomly which archives the desired result of shuffling all elements.

Title: Random shuffling of an array

Body:
I need to randomly shuffle the following Array:

int[] solutionArray = {1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1};

Is there any function to do that?

Body:
A simple solution for Groovy:

solutionArray.sort{ new Random().nextInt() }

This will sort all elements of the array list randomly which archives the desired result of shuffling all elements.


问:
How do I create a C++ callback invoked from JavaScript using JavaScriptCore on iOS?
I'm using JavaScript core to facilitate communication between C++ and JavaScript for an iOS project I'm working on.  The following works to invoke a javascript function from C++:

```<code>#include <JavaScriptCore/JavaScriptCore.h>

void myCPPFunction()
{
    JSGlobalContextRef globalContext =
    JSGlobalContextCreateInGroup(JSContextGroupCreate(), nullptr);
    auto funcOutput = JSEvaluateScript(globalContext,
        JSStringCreateWithUTF8CString(("function test() {
            return 'hi'; } test();", nullptr, nullptr, 1, nullptr);

    // funcOutput now contains a JSValue containing the
    // return value of the function ('hi').

}
</code>```

Now, I want to invoke a C++ function from the JavaScript.  For example, if I have a C++ function defined as follows:

```<code>double myCPPCallback(unsigned long x)
{
    // do stuff
}
</code>```

How do I invoke this C++ code from the JavaScript I'm currently running with JSEvaluateScript?

答:
It is easiest to do with JSObjectMakeFunctionWithCallback to what you can provide JSObjectCallAsFunctionCallback declared by you that then calls your C++ functions. Then you can call the callback in JavaScript code by name that you gave to it in JSObjectMakeFunctionWithCallback.

Also note that you should not perhaps use the very thing like ...

```<code>JSGlobalContextRef globalContext =
                   JSGlobalContextCreateInGroup(JSContextGroupCreate(), nullptr);
</code>```

... because that way you leak the group (result of JSContextGroupCreate()). I try to fabricate example OSX code (no time to test it):

```<code>#include <iostream>
#include <JavaScriptCore/JavaScriptCore.h>

JSValueRef HelloCallback( JSContextRef ctx
                        , JSObjectRef function
                        , JSObjectRef thisObject
                        , size_t argumentCount
                        , const JSValueRef arguments[]
                        , JSValueRef* exception)
{
    // here do the C++ stuff
    std::cout << "Hello World" << std::endl;
    return JSValueMakeUndefined(ctx);
}

int main(int argc, const char * argv[])
{
    // bad raw opaque pointers TODO: manage with smart pointers
    JSContextGroupRef group = JSContextGroupCreate();
    JSGlobalContextRef globalContext = JSGlobalContextCreateInGroup(group, nullptr);
    JSObjectRef globalObject = JSContextGetGlobalObject(globalContext);
    JSStringRef helloFunctionName = JSStringCreateWithUTF8CString("hello");

    // make function object
    JSObjectRef functionObject = JSObjectMakeFunctionWithCallback( globalContext
                                                         , helloFunctionName
                                                         , &HelloCallback);
    // set it as proprty of global object
    JSObjectSetProperty( globalContext
                       , globalObject
                       , helloFunctionName
                       , functionObject
                       , kJSPropertyAttributeNone
                       , nullptr );

    // make javascript
    JSStringRef statement = JSStringCreateWithUTF8CString("hello()");
    // evaluate it
    JSEvaluateScript( globalContext
                    , statement
                    , nullptr
                    , nullptr
                    , 1
                    , nullptr );

    // manual raw pointer management ... hopefully did not forget any
    JSGlobalContextRelease(globalContext);
    JSContextGroupRelease(group);
    JSStringRelease(helloFunctionName);
    JSStringRelease(statement);

    return 0;
}
</code>```

Body:
I'm using JavaScript core to facilitate communication between C++ and JavaScript for an iOS project I'm working on.  The following works to invoke a javascript function from C++:

#include <JavaScriptCore/JavaScriptCore.h>

void myCPPFunction()
{
    JSGlobalContextRef globalContext =
    JSGlobalContextCreateInGroup(JSContextGroupCreate(), nullptr);
    auto funcOutput = JSEvaluateScript(globalContext,
        JSStringCreateWithUTF8CString(("function test() {
            return 'hi'; } test();", nullptr, nullptr, 1, nullptr);

    // funcOutput now contains a JSValue containing the
    // return value of the function ('hi').

}

Now, I want to invoke a C++ function from the JavaScript.  For example, if I have a C++ function defined as follows:

double myCPPCallback(unsigned long x)
{
    // do stuff
}

How do I invoke this C++ code from the JavaScript I'm currently running with JSEvaluateScript?

Body:
It is easiest to do with JSObjectMakeFunctionWithCallback to what you can provide JSObjectCallAsFunctionCallback declared by you that then calls your C++ functions. Then you can call the callback in JavaScript code by name that you gave to it in JSObjectMakeFunctionWithCallback.

Also note that you should not perhaps use the very thing like ...

JSGlobalContextRef globalContext =
                   JSGlobalContextCreateInGroup(JSContextGroupCreate(), nullptr);

... because that way you leak the group (result of JSContextGroupCreate()). I try to fabricate example OSX code (no time to test it):

#include <iostream>
#include <JavaScriptCore/JavaScriptCore.h>

JSValueRef HelloCallback( JSContextRef ctx
                        , JSObjectRef function
                        , JSObjectRef thisObject
                        , size_t argumentCount
                        , const JSValueRef arguments[]
                        , JSValueRef* exception)
{
    // here do the C++ stuff
    std::cout << "Hello World" << std::endl;
    return JSValueMakeUndefined(ctx);
}

int main(int argc, const char * argv[])
{
    // bad raw opaque pointers TODO: manage with smart pointers
    JSContextGroupRef group = JSContextGroupCreate();
    JSGlobalContextRef globalContext = JSGlobalContextCreateInGroup(group, nullptr);
    JSObjectRef globalObject = JSContextGetGlobalObject(globalContext);
    JSStringRef helloFunctionName = JSStringCreateWithUTF8CString("hello");

    // make function object
    JSObjectRef functionObject = JSObjectMakeFunctionWithCallback( globalContext
                                                         , helloFunctionName
                                                         , &HelloCallback);
    // set it as proprty of global object
    JSObjectSetProperty( globalContext
                       , globalObject
                       , helloFunctionName
                       , functionObject
                       , kJSPropertyAttributeNone
                       , nullptr );

    // make javascript
    JSStringRef statement = JSStringCreateWithUTF8CString("hello()");
    // evaluate it
    JSEvaluateScript( globalContext
                    , statement
                    , nullptr
                    , nullptr
                    , 1
                    , nullptr );

    // manual raw pointer management ... hopefully did not forget any
    JSGlobalContextRelease(globalContext);
    JSContextGroupRelease(group);
    JSStringRelease(helloFunctionName);
    JSStringRelease(statement);

    return 0;
}


问:
Angular 4 add click event on button dynamically
Here is the code of button displayed from loop.

```<code>for( let k=0; k<this.newTmpArr.length; k++ ){
    myTable += "<tr>";
    for( let key2 in this.newTmpArr[k] ){
        if(this.newTmpArr[k][key2] == 'button' ){
          myTable += `<td><button (click)="test()">Click</button></td>`;
          break;
        }
        if(this.newTmpArr[k][key2] == 'link' ){
          myTable += `<td><a href="#" (click)="test()">Click</a></td>`;
          break;
        } else {
          myTable += "<td>" + this.newTmpArr[k][key2] + "</td>";
        }

    }
    myTable += "</tr>";
}

test(){
  alert("Working!");
}
</code>```

Here is the screenshot of the page look like after dynamic data rendered.

答:
here is the code work for me. it may helpful for you guys too.</p>

```<code><tr *ngFor="let item of newTmpArr">
       <td *ngFor="let i of item">
          <span *ngIf="i.value; then dynamicVal; else elseblock"></span>
          <ng-template #dynamicVal>
          <span *ngIf="i.type == 'button'">
          <button (click)="clickMe(item)">Click</button>
          </span>
          <span *ngIf="i.type == 'link'">
             <a [href]="i.link">{{i.value}}</a>
          </span>
          </ng-template>
          <ng-template #elseblock>{{i}}</ng-template>
       </td>
</tr>
</code>```

Body:
Here is the code of button displayed from loop.

for( let k=0; k<this.newTmpArr.length; k++ ){
    myTable += "
";
    for( let key2 in this.newTmpArr[k] ){
        if(this.newTmpArr[k][key2] == 'button' ){
          myTable += `<td><button (click)="test()">Click</button></td>`;
          break;
        }
        if(this.newTmpArr[k][key2] == 'link' ){
          myTable += `<td><a href="#" (click)="test()">Click</a></td>`;
          break;
        } else {
          myTable += "" + this.newTmpArr[k][key2] + "	";
        }

    }
    myTable += "
";
}

test(){
  alert("Working!");
}

Here is the screenshot of the page look like after dynamic data rendered.

Body:
here is the code work for me. it may helpful for you guys too.

<tr *ngFor="let item of newTmpArr">
       <td *ngFor="let i of item">
          <span *ngIf="i.value; then dynamicVal; else elseblock"></span>
          <ng-template #dynamicVal>
          <span *ngIf="i.type == 'button'">
          <button (click)="clickMe(item)">Click</button>
          </span>
          <span *ngIf="i.type == 'link'">
             <a [href]="i.link">{{i.value}}</a>
          </span>
          </ng-template>
          <ng-template #elseblock>{{i}}</ng-template>
       </td>
</tr>


问:
How to get categories of custom post type in WP-JSON v2 API?
I am trying to get categories of custom post type but unable to find any solution. The WP REST API documentation returns only the categories of blog post.

Custom posts API: https://themographics.com/wordpress/service-providers/wp-json/wp/v2/sp_categories

Categories API: https://themographics.com/wordpress/service-providers/wp-json/wp/v2/categories [returns default categories of blog post type]

Is there any way like
https://themographics.com/wordpress/service-providers/wp-json/wp/v2/sp_categories/categories

答:
You can do it this way:</p>

```<code>add_action('init', 'json_handler');
function json_handler(){
    $categories = get_terms( 'my_cat', 'orderby=count&hide_empty=0' );
    if( ! is_wp_error( $categories ) ) {
        // encode the $categories array as json
        print_r( json_encode( $categories ) );
    }
}
</code>```

Body:
You can do it this way:

add_action('init', 'json_handler');
function json_handler(){
    $categories = get_terms( 'my_cat', 'orderby=count&hide_empty=0' );
    if( ! is_wp_error( $categories ) ) {
        // encode the $categories array as json
        print_r( json_encode( $categories ) );
    }
}


问:
fatal error LNK1112: module machine type 'X86' conflicts with target machine type 'AMD64'
I am using VS 2003 .Net on 32 bit XP OS. I have also installed "Microsoft Platform SDK" on my machine. Can I build vc++ application (binaries) targeted for 64 bit OS?

I am using following project options :

```<code>    Name="VCLinkerTool"
    AdditionalOptions="/machine:AMD64 bufferoverflowU.lib"
    OutputFile="\bin\Release\MM64.dll"
    LinkIncremental="1"
    SuppressStartupBanner="TRUE"
    AdditionalLibraryDirectories=""C:\Program Files\Microsoft Platform SDK\Lib\AMD64""
    GenerateDebugInformation="TRUE"
    ProgramDatabaseFile="\bin\Release\MM64.pdb"
    GenerateMapFile="TRUE"
    MapFileName="\bin\Release\MM64.map"
    MapExports="TRUE"
    MapLines="TRUE"
    OptimizeReferences="2"
    EnableCOMDATFolding="2"
    ImportLibrary=".\Release/MM64.lib"
    TargetMachine="0"/>
</code>```

I am getting following error:

```<code>fatal error LNK1112: module machine type 'X86' conflicts with target machine type 'AMD64'
</code>```

Do I need to build project on 64 bit OS or I need to change project settings to resolve this error.
Please help me to resolve this issue.

答:
I faced above error when I tried to build my custom library for ARM64 in Visual Studio 2017. And my target machine was already ARM64 as expected.

Apparently, problem was in ARM64 compiler which was not installed(though I could run build in ARM64). I installed it by running Visual Studio Installer Individual Components -> Visual C++ compiler and libraries for ARM64

Next I got error MSB8022: Compiling Desktop applications for the ARM platform is not supported.

It was resolved by adding

```<code><PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'" Label="Configuration">
  ...
  <PlatformToolset>v141</PlatformToolset>
  <WindowsSDKDesktopARM64Support>true</WindowsSDKDesktopARM64Support>
</PropertyGroup>
</code>```

into my project file.
After all of above I could succefully build my project in ARM64.

Hope it will be useful.

Body:
I am using VS 2003 .Net on 32 bit XP OS. I have also installed "Microsoft Platform SDK" on my machine. Can I build vc++ application (binaries) targeted for 64 bit OS?

I am using following project options :

    Name="VCLinkerTool"
    AdditionalOptions="/machine:AMD64 bufferoverflowU.lib"
    OutputFile="\bin\Release\MM64.dll"
    LinkIncremental="1"
    SuppressStartupBanner="TRUE"
    AdditionalLibraryDirectories=""C:\Program Files\Microsoft Platform SDK\Lib\AMD64""
    GenerateDebugInformation="TRUE"
    ProgramDatabaseFile="\bin\Release\MM64.pdb"
    GenerateMapFile="TRUE"
    MapFileName="\bin\Release\MM64.map"
    MapExports="TRUE"
    MapLines="TRUE"
    OptimizeReferences="2"
    EnableCOMDATFolding="2"
    ImportLibrary=".\Release/MM64.lib"
    TargetMachine="0"/>

I am getting following error:

fatal error LNK1112: module machine type 'X86' conflicts with target machine type 'AMD64'

Do I need to build project on 64 bit OS or I need to change project settings to resolve this error.
Please help me to resolve this issue.

Body:
I faced above error when I tried to build my custom library for ARM64 in Visual Studio 2017. And my target machine was already ARM64 as expected.

Apparently, problem was in ARM64 compiler which was not installed(though I could run build in ARM64). I installed it by running Visual Studio Installer Individual Components -> Visual C++ compiler and libraries for ARM64

Next I got error MSB8022: Compiling Desktop applications for the ARM platform is not supported.

It was resolved by adding

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'" Label="Configuration">
  ...
  <PlatformToolset>v141</PlatformToolset>
  <WindowsSDKDesktopARM64Support>true</WindowsSDKDesktopARM64Support>
</PropertyGroup>

into my project file.
After all of above I could succefully build my project in ARM64.

Hope it will be useful.


问:
I need someone who explain me these lines of code
I need someone who explain me this code, line by line. I specially don't understand this line:

```<code>operator std::map<T, U>()
</code>```

Thank you very much.

```<code>template <typename T, typename U>
class create_map
{
    std::map<T, U> m_map;
public:
    create_map(const T& key, const U& val)
    {
        m_map[key] = val;
    }
    create_map<T, U>& operator()(const T& key, const U& val)
    {
        m_map[key] = val;
        return *this;
    }
    operator std::map<T, U>()
    {
        return m_map;
    }
};
</code>```

答:
There's not much to understand about it. operator std::map<T, U>() overrides the class' conversion operator (which takes no parameters) to provide an object instance of type std::map<T, U>. std::map is a STL standard class for associative key->value storage. In your case it maps from keys of type T to values of type U. T and U have been undefined so far (you wrote template class, but where are the template parameters?)

The conversion operator allows to use the class instance in place of the type the operator provides conversion for, like this.

```<code>class foo {
    operator char const *() {
        return "foo instance as char const *";
    }
};

// ...

void bar(foo &f)
{
    // here the class instance is used as if it were a char const *
    cout << f << endl;
}
</code>```

Body:
I need someone who explain me this code, line by line. I specially don't understand this line:

operator std::map<T, U>()

Thank you very much.

template <typename T, typename U>
class create_map
{
    std::map<T, U> m_map;
public:
    create_map(const T& key, const U& val)
    {
        m_map[key] = val;
    }
    create_map<T, U>& operator()(const T& key, const U& val)
    {
        m_map[key] = val;
        return *this;
    }
    operator std::map<T, U>()
    {
        return m_map;
    }
};

Body:
There's not much to understand about it. operator std::map<T, U>() overrides the class' conversion operator (which takes no parameters) to provide an object instance of type std::map<T, U>. std::map is a STL standard class for associative key->value storage. In your case it maps from keys of type T to values of type U. T and U have been undefined so far (you wrote template class, but where are the template parameters?)

The conversion operator allows to use the class instance in place of the type the operator provides conversion for, like this.

class foo {
    operator char const *() {
        return "foo instance as char const *";
    }
};

// ...

void bar(foo &f)
{
    // here the class instance is used as if it were a char const *
    cout << f << endl;
}


答:
in  tag try this css

```<code> <style>
    body, div, table, tr, th {
    border-style: none !important;}
 </style>
</code>```

Title: How to avoid bootstrap table borders

Body:
in <head> tag try this css

 <style>
    body, div, table, tr, th {
    border-style: none !important;}
 </style>


问:
One user with two format in send email action in sharepoint designer 2013
I have a problem in sharepoint designer 2013, when I want to use the “send email” action, in select user window. I have two entries for one user! One in this format: “DomainName\Username”, and one of in this format: “i: 0#.w|DomainName\username”.

Only when I select the second format, send email works correctly! Why does this happen?

答:
When you have a pure SharePoint login functionality, your environment uses "Domain/ User name" format to login in to your system.

When you integrate any third party login i.e configure FBA, SharePoint changes the format of AD users to "i: 0#.w|DomainName\username". Even if you remove your FBA, your login users has same identity further.

"i: 0 #." is used to identify the type of claim you have set up in your environment. You can get more information here.


问:
Why does Rust not recognize that I re-assign to the moved variable inside a closure?
I am having trouble understanding why a particular pattern is not compiling.

Rust recognizes when I move a variable and then reassign to it outside of a closure and I think properly allows the code to compile, but when I try to do the same in a closure that will be run more than once it will not.

```<code>fn main() {
    let mut v = vec![1, 2, 3, 4];
    v.into_iter().fold(0, |a, b| a + b);
    v = vec![1, 2, 3, 4];
    vec![1, 2, 3].into_iter().for_each(|x| {
        v.into_iter().fold(x, |a, b| a + b);
        v = vec![1, 2, 3, 4];
    });
}
</code>```

error[E0507]: cannot move out of captured outer variable in an `FnMut` closure
 --> src/main.rs:6:9
  |
2 |     let mut v = vec![1, 2, 3, 4];
  |         ----- captured outer variable
...
6 |         v.into_iter().fold(x, |a, b| a + b);
  |         ^ cannot move out of captured outer variable in an `FnMut` closure
```

It seems to me that the reassignment to v should satisfy the borrow checker that no variable will be accessed after being moved. Am I missing something?

答:
As @Shepmaster mentioned, the fix is to use std::mem::replace.

So, what is the difference between:

```<code>    v.into_iter().fold(x, |a, b| a + b);
    v = vec![1, 2, 3, 4];
</code>```

and:

```<code>    let v_old = std::mem::replace(&mut v, vec![1, 2, 3, 4]);
    v_old.into_iter().fold(x, |a, b| a + b);
</code>```

?

In two words: exception safety.

If, for some reason, the expression v.into_iter().fold(...) would panic, it would leave v moved out and the next statement would never be executed.

This is perfectly acceptable in a FnOnce, as you will never call the closure another time, but not acceptable in a FnMut or Fn as on the next call... what would you do with v?

On the other hand, using std::mem::replace, you swap first and then execute the potentially panicking operation. If the operation does panic, then all that is left "moved out" is a temporary variable which disappears at the end of the stack frame anyway. No issue.

Body:
I am having trouble understanding why a particular pattern is not compiling.

Rust recognizes when I move a variable and then reassign to it outside of a closure and I think properly allows the code to compile, but when I try to do the same in a closure that will be run more than once it will not.

fn main() {
    let mut v = vec![1, 2, 3, 4];
    v.into_iter().fold(0, |a, b| a + b);
    v = vec![1, 2, 3, 4];
    vec![1, 2, 3].into_iter().for_each(|x| {
        v.into_iter().fold(x, |a, b| a + b);
        v = vec![1, 2, 3, 4];
    });
}

error[E0507]: cannot move out of captured outer variable in an `FnMut` closure
 --> src/main.rs:6:9
  |
2 |     let mut v = vec![1, 2, 3, 4];
  |         ----- captured outer variable
...
6 |         v.into_iter().fold(x, |a, b| a + b);
  |         ^ cannot move out of captured outer variable in an `FnMut` closure

It seems to me that the reassignment to v should satisfy the borrow checker that no variable will be accessed after being moved. Am I missing something?

Body:
As @Shepmaster mentioned, the fix is to use std::mem::replace.

So, what is the difference between:

    v.into_iter().fold(x, |a, b| a + b);
    v = vec![1, 2, 3, 4];

and:

    let v_old = std::mem::replace(&mut v, vec![1, 2, 3, 4]);
    v_old.into_iter().fold(x, |a, b| a + b);

?

In two words: exception safety.

If, for some reason, the expression v.into_iter().fold(...) would panic, it would leave v moved out and the next statement would never be executed.

This is perfectly acceptable in a FnOnce, as you will never call the closure another time, but not acceptable in a FnMut or Fn as on the next call... what would you do with v?

On the other hand, using std::mem::replace, you swap first and then execute the potentially panicking operation. If the operation does panic, then all that is left "moved out" is a temporary variable which disappears at the end of the stack frame anyway. No issue.


问:
NSNotification concept - what piece of code goes where?
Part of me thinks I understand the NSNotification concept. It's a centralized broadcast system with string based notifications. Post on one side, observe on one or multiple other sides and act accordingly. Another part of me though, the part that has to write the code, gets confused every time I need a notification. What piece of code goes into which header/implementation, what files actually do the observing and how do I keep it from becoming a mess? Time to straighten it out, will you help me verify these assumptions? I'm fairly confident up to number 4, but number 5 hits the confusion jackpot.

NSNotifications are created with help from the [NSNotification defaultCenter], one does not alloc/init a NSNotification. Correct?

The object performing the postNofification feat always passes self into the posting code: [[NSNotificationCenter defaultCenter] postNotificationName:@"note name" object:self]. Correct?

Event bubbling exists in other languages, but not in Objective-C with NSNotification. You don't pass along notifications, you make the notification name specific enough for the global broadcast. Correct?

If you still want to pass along a notification posted by object A, you observe it in B, handle it and post a new, more specific notification for object C to observe. Eg. @"MenuItemTapped" from A to B, and @"NavigateTo" from B to C. Correct?

The name of a notification is a NSString. Because both the poster and the observer want to avoid typos, we store the NSString constant in a [extern const|define|class method|none of the above]. Could you help me pick one?

One attempt was to create something like a NotificationNames.h file, which would contain all the extern NSString *const NOTE_NAME declarations. Yet that undermines the portability of a notification.

Another attempt was to subclass NSNotification (with an XCode template to keep the creation fast), but because this concept is taken from subclassing the Event-class in AS3, it seemed very un-objective-c-ish. There's also the weirdness that you can't call [super init] on a NSNotification, so things started to get out of hand.

My troubles with this one arise from the cumbersome #import statements. How to minimize typo's, yet keep the constants/defines portable?

答:
You've mostly got it. Your numbers 1-3 are generally correct.

You shouldn't ever need to alloc your own NSNotification object.

You generally pass "self" as the "object" of the notification as you say, but you could also pass something else in if you are notifying "on behalf of" something else, conceptually. But that would be less common case.

Notifications aren't the same as "events" in the UI. Cocoa does have events; they are mouse/keyboard/touch events, and they do "bubble" up the "responder chain" through the UI objects. Notifications are a totally independent mechanism that is not tied to UI, and it is used for generally global broadcast among otherwise decoupled/independent objects. It's more akin to having multiple delegates for an object.

Yes, you should define the name of the notification somewhere that everyone who uses it can see. In Cocoa itself, this is usually a public header with a declaration like extern NSString *const UIKeyboardDidShowNotification. In some private implementation file is the definition.

A special note regarding your #4 above. Think of notifications as notifications, not as instructions. They usually capture state changes or broadly interesting events. "MenuItemTapped" is a reasonable thing to notify about, but "NavigateTo" usually isn't, because the implication is that you're telling some specific object to navigate somewhere. If that's the case, that object should probably be a delegate (or should be a property) of the thing that wants the navigation, and you should cause it to happen directly. This isn't a requirement, of course, and you can use the mechanism for whatever you want. But the Cocoa design patterns generally don't use notifications for "telling objects what to do", only for "telling whoever cares what will/did happen". Make sense?

Finally, specifically re: your examples in #4-- those sound like genuine UI events, and seem like the whole thing could be handled via delegation, unless there's some reason why those objects need to be so decoupled.


问:
How to sum count variable in PHP
i want to sum for some data which come from function foreach in PHP, but i found error while run it, here my simple code :

```<code>        <?php
            $no=1;
            foreach($data_tersimpan->result_array() as $dp)
            {
            ?>
            <?php
            $total = 0;
            $total += count($dp['id_plan']);
            echo $total;
        ?>
         <?php
                $no++;
            }
         ?>
</code>```

from my code above, i print $total, then data shown like this :

```<code>1   1   1   1   1
</code>```

I want to get summary 5 if i print $total
is there any suggestion to make summary in php scrypt(not in sql query)?

THanks

答:
you have misplaced {}& opening tag for PHP within in your PHP code .which causes error.have you enabled ERROR_display in your PHP ini file?

```<code>  <?php
            $no=1;
            $total = 0;
            foreach($data_tersimpan->result_array() as $dp)
            {
            $total += count($dp['id_plan']);
             }
            echo $total;
        ?>
</code>```

Title: How to sum count variable in PHP

Body:
i want to sum for some data which come from function foreach in PHP, but i found error while run it, here my simple code :

        <?php
            $no=1;
            foreach($data_tersimpan->result_array() as $dp)
            {
            ?>
            <?php
            $total = 0;
            $total += count($dp['id_plan']);
            echo $total;
        ?>
         <?php
                $no++;
            }
         ?>

from my code above, i print $total, then data shown like this :

1   1   1   1   1

I want to get summary 5 if i print $total
is there any suggestion to make summary in php scrypt(not in sql query)?

THanks

Body:
you have misplaced {}& opening tag for PHP within in your PHP code .which causes error.have you enabled ERROR_display in your PHP ini file?

  <?php
            $no=1;
            $total = 0;
            foreach($data_tersimpan->result_array() as $dp)
            {
            $total += count($dp['id_plan']);
             }
            echo $total;
        ?>


问:
Linux kernel detecting the pre-boot environment for watchdog
So I'm developing for an embedded Linux system and we had some trouble with an external watchdog chip which needed to be fed very early in the boot process.

More specifically, from what we could work out it would this external watchdog would cause a reset while the kernel was decompressing its image in the pre-boot environment. Not enough down time before it starts needing to be fed, which should probably have been sorted in hardware as it is external, but an internal software solution is wanted.

The solution from one of our developers was to put in some extra code into...

int zlib_inflate(z_streamp strm, int flush) in the lib/zlib_inflate/inflate.c kernel code

This new code periodically toggles the watchdog pin during the decompression.

Now besides the fact that I feel like this is a little bit of a dirty hack. It does work, and it has raised an interesting point in my mind. Because this lib is used after boot as well. So is there a nice way for a bit of code detecting whether you're in the pre-boot environment? So it could only preform this toggling pre-boot and not when the lib is used later.

As an aside, I'm also interested in any ideas to avoid the hack in the first place.

答: Another idea can be disabling watchdog from bootloader and enabling it from user space once system has booted completely.</p>


答:
That's because you are resetting your total for every iteration of the loop.</p>

```<code><?php
    $total = 0;
    $no=1;
    foreach($data_tersimpan->result_array() as $dp) {
        $total += count($dp['id_plan']);
        $no++;
    }
    echo $total;
?>
</code>```

Title: How to sum count variable in PHP

Body:
That's because you are resetting your total for every iteration of the loop.

<?php
    $total = 0;
    $no=1;
    foreach($data_tersimpan->result_array() as $dp) {
        $total += count($dp['id_plan']);
        $no++;
    }
    echo $total;
?>


问:
Inno Setup - npm program added to PATH by subinstaller is not recognized in a batch file executed from installer
I have created a Windows installer using Inno Setup for an app I have made. As part of the installer I have included the installation of some third party applications followed by a batch file, to execute a number of npm command operable program or batch file.

Everything installs okay but when the batch file runs I get the message

'npm' is not recognized as an internal or external command

The commands don't run and so the app won't open.  However, if I leave everything as it is and just rerun the batch file again after the installation, the commands execute and the app works fine.  How can I get the batch file to run properly as part of the installation?

Inno Setup Run Section

[Run]
Filename: "{tmp}\Git-2.15.0-64-bit.exe";  Flags: waituntilterminated
Filename: "{tmp}\rubyinstaller-2.3.3-x64.exe";  Flags: waituntilterminated
Filename: "{tmp}\visualcppbuildtools_full.exe";  Flags: waituntilterminated
Filename: "msiexec.exe"; Parameters: "/i ""{tmp}\mongodb-win32-x86_64-2008plus-ssl-3.4.10-signed.msi"; WorkingDir: {tmp}; Flags: waituntilterminated
Filename: "msiexec.exe"; Parameters: "/i ""{tmp}\node-v6.11.0-x64.msi"; WorkingDir: {tmp}; Flags: waituntilterminated
Filename: "{tmp}\setup.bat";
Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; Flags: shellexec postinstall skipifsilent
```

<p><strong>Batch File</strong></p>

<pre class="lang-none prettyprint-override"><code>cd C:/Users/%USERNAME%/Documents/myApp/api/
call npm install -g bower
call npm install -g grunt
call npm install -g grunt-cli
call npm config set msvs_version 2015 -global
call npm install bcrypt -save
call npm install
cd ../admin/
call npm install -g bower
call npm install -g grunt
call npm install -g grunt-cli
echo 1 | call gem install compass
call bower install
call npm install
</code>```

答:
If the batch file works after your installer completes, one of the subinstallers probably adds npm to the PATH environment variable. But changes to environment does not apply automatically to existing processes (that includes Inno Setup installer itself) and their child processes (that includes your batch file executed from Inno Setup installer), only to new processes.

You would have to explicitly reload the environment before running the batch file.

[Run]
Filename: "{tmp}\setup.bat"; BeforeInstall: RefreshEnvironment
```

Where the RefreshEnvironment implementation is shown in:

Environment variable not recognized [not available] for [Run] programs in Inno Setup

Or you can of course use an absolute path in the batch file. But for that you would have to generate the batch file on the fly based on installation location.

Or run the batch file from the npm directory. Use WorkingDir parameter for that.

Body:
I have created a Windows installer using Inno Setup for an app I have made. As part of the installer I have included the installation of some third party applications followed by a batch file, to execute a number of npm command operable program or batch file.

Everything installs okay but when the batch file runs I get the message

'npm' is not recognized as an internal or external command

The commands don't run and so the app won't open.  However, if I leave everything as it is and just rerun the batch file again after the installation, the commands execute and the app works fine.  How can I get the batch file to run properly as part of the installation?

Inno Setup Run Section

[Run]
Filename: "{tmp}\Git-2.15.0-64-bit.exe";  Flags: waituntilterminated
Filename: "{tmp}\rubyinstaller-2.3.3-x64.exe";  Flags: waituntilterminated
Filename: "{tmp}\visualcppbuildtools_full.exe";  Flags: waituntilterminated
Filename: "msiexec.exe"; Parameters: "/i ""{tmp}\mongodb-win32-x86_64-2008plus-ssl-3.4.10-signed.msi"; WorkingDir: {tmp}; Flags: waituntilterminated
Filename: "msiexec.exe"; Parameters: "/i ""{tmp}\node-v6.11.0-x64.msi"; WorkingDir: {tmp}; Flags: waituntilterminated
Filename: "{tmp}\setup.bat";
Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; Flags: shellexec postinstall skipifsilent

Batch File

cd C:/Users/%USERNAME%/Documents/myApp/api/
call npm install -g bower
call npm install -g grunt
call npm install -g grunt-cli
call npm config set msvs_version 2015 -global
call npm install bcrypt -save
call npm install
cd ../admin/
call npm install -g bower
call npm install -g grunt
call npm install -g grunt-cli
echo 1 | call gem install compass
call bower install
call npm install

Body:
If the batch file works after your installer completes, one of the subinstallers probably adds npm to the PATH environment variable. But changes to environment does not apply automatically to existing processes (that includes Inno Setup installer itself) and their child processes (that includes your batch file executed from Inno Setup installer), only to new processes.

You would have to explicitly reload the environment before running the batch file.

[Run]
Filename: "{tmp}\setup.bat"; BeforeInstall: RefreshEnvironment

Where the RefreshEnvironment implementation is shown in:

Environment variable not recognized [not available] for [Run] programs in Inno Setup

Or you can of course use an absolute path in the batch file. But for that you would have to generate the batch file on the fly based on installation location.

Or run the batch file from the npm directory. Use WorkingDir parameter for that.


问:
Search by string date mysql
I need to run query that return a rows by range of dates.
the dates are saved in a string format like "22/11/2017"
i try to used in str_to_date but its not work so good.
my query :

```<code>SELECT Activities.Date AS 'dates'  FROM Attendance
                           INNER JOIN Activities ON Activities.ID=Attendance.ActivitiesID
                           INNER JOIN Groups ON Activities.GroupID=Groups.ID
                           INNER JOIN Projects ON Projects.ID=Groups.ProjectID
                           WHERE Attendance.Attendance <>'' AND Projects.ID=16 AND  (str_to_date(Activities.Date,'%d/%m/%Y')>="01/11/2017" AND str_to_date(Activities.Date,'%d/%m/%Y')<='30/11/2017') GROUP BY Activities.Date
                            ORDER BY Groups.Name
</code>```

The result :

```<code>'24/09/2017','24/10/2017','24/11/2017','24/12/2017','25/09/2017','25/10/2017,..
</code>```

答:
```<code> Select STR_TO_DATE(string_date_col, '%d/%m/%y') FROM table_name...
</code>```

In your case, you are converting it into date but you are again comparing it with string, you need to convert all the strings to date format so that it can have a valid comparison so it should be

```<code>(str_to_date(Activities.Date,'%d/%m/%Y')>=str_to_date("01/11/2017",'%d/%m/%Y')
</code>```

instead of

```<code>(str_to_date(Activities.Date,'%d/%m/%Y')>="01/11/2017"
</code>```

Title: Search by string date mysql

Body:
I need to run query that return a rows by range of dates.
the dates are saved in a string format like "22/11/2017"
i try to used in str_to_date but its not work so good.
my query :

SELECT Activities.Date AS 'dates'  FROM Attendance
                           INNER JOIN Activities ON Activities.ID=Attendance.ActivitiesID
                           INNER JOIN Groups ON Activities.GroupID=Groups.ID
                           INNER JOIN Projects ON Projects.ID=Groups.ProjectID
                           WHERE Attendance.Attendance <>'' AND Projects.ID=16 AND  (str_to_date(Activities.Date,'%d/%m/%Y')>="01/11/2017" AND str_to_date(Activities.Date,'%d/%m/%Y')<='30/11/2017') GROUP BY Activities.Date
                            ORDER BY Groups.Name

The result :

'24/09/2017','24/10/2017','24/11/2017','24/12/2017','25/09/2017','25/10/2017,..

Body:
 Select STR_TO_DATE(string_date_col, '%d/%m/%y') FROM table_name...

In your case, you are converting it into date but you are again comparing it with string, you need to convert all the strings to date format so that it can have a valid comparison so it should be

(str_to_date(Activities.Date,'%d/%m/%Y')>=str_to_date("01/11/2017",'%d/%m/%Y')

instead of

(str_to_date(Activities.Date,'%d/%m/%Y')>="01/11/2017"


问:
How to login SSH on Azure Databricks cluster
I used the following ubuntu command to access SSH login as,

ssh user@hostname_or_IP

Can able to see Master node hostname

but not able to get the username from Azure Databricks cluster

Refer this doc,
https://docs.azuredatabricks.net/user-guide/clusters/spark-config.html#spark-config

答:
Unfortunately, we cannot SSH to the Cluster for now.

I did a test in my lab:

There was a SSH section in the Cluster configuration. But now, we cannot see it here.

Also, I found the VMs behind the Databricks in a resource group, I try to change the SSH configuration from portal but failed. Then I found the Databricks resource group has been locked to Read-Only. You cannot delete it from portal neither.

I tried to found the cause why cannot SSH the Cluster behind the Databricks, I saw the NSG rule of the VMs which belongs to that Databricks :

It means that Azure Databricks only allow only one source to SSH the VM, and the source is Databricks control plane . We can also understand this in the picture of Architecture of Azure Databricks:

Azure Databricks is a very new feature in Azure. I believe it will be better in future.You can post your idea in Azure Feedback Forum or in this blog's comment. Azure Team will review it .

Hope this helps!


问:
How to perform double sort inside an array?
I don't know the exact term exists for this type of sorting. Here is the problem -
I have a class foo

```<code>class foo:
    def __init__(self,a1,a2):
        self.attrb1 = a1
        self.attrb2 = a2

    def sort(self):
        return self.attrb1
</code>```

An array "bar" contain objects of type foo. I want to sort the array in descending order according to the two attributes. First by attrb1

```<code>bar.sort(key=foo.sort,reverse=True)
</code>```

Then I want to sort the sorted elements within themselves according to attrb2. So for two elements foo1 and foo2 in the array we have -

```<code>foo1 > foo2
if foo1.attrb1 > foo2.attrb1
elif foo1.attrb1 == foo2.attrb1
foo1.attrb2 > foo2.attrb2
</code>```

How can I do this?

答:
You can also do it without lambda (which I personally don't like):

```<code>import operator
bar.sort(key=operator.attrgetter("attrb1","attrb2"))
</code>```

operator.attrgetter works like this:

```<code>a = foo(3,4)
b = operator.attrgetter("attrb1","attrb2")(a)
print(b) #  You get (3,4)
</code>```

Body:
I don't know the exact term exists for this type of sorting. Here is the problem -
I have a class foo

class foo:
    def __init__(self,a1,a2):
        self.attrb1 = a1
        self.attrb2 = a2

    def sort(self):
        return self.attrb1

An array "bar" contain objects of type foo. I want to sort the array in descending order according to the two attributes. First by attrb1

bar.sort(key=foo.sort,reverse=True)

Then I want to sort the sorted elements within themselves according to attrb2. So for two elements foo1 and foo2 in the array we have -

foo1 > foo2
if foo1.attrb1 > foo2.attrb1
elif foo1.attrb1 == foo2.attrb1
foo1.attrb2 > foo2.attrb2

How can I do this?

Body:
You can also do it without lambda (which I personally don't like):

import operator
bar.sort(key=operator.attrgetter("attrb1","attrb2"))

operator.attrgetter works like this:

a = foo(3,4)
b = operator.attrgetter("attrb1","attrb2")(a)
print(b) #  You get (3,4)


问:
Need help for java to randomly decide between male or female
I am new to coding, and I am currently modding a code. Here is pat of the original.

```<code> if ((world[row][col] == ORGANISM) && (check == 2))
            worldCopy[row][col] = ORGANISM;
</code>```

The original code would basically spawn a offspring (a.k.a a *) in a certain location on a grid. However, now I am modding for the offspring to be randomly male or female. How should I write a new piece of subcode so that it would randomly pick for ORGANISM to be male or female? I don't need specifics, just want some help because I am stuck.

答:
Look into the Random class. It provides random generation of ints, and in your case, booleans. I don't know what data type organism is, but something like this should help:

```<code>if(new Random().nextBoolean()) {
    //Male
} else {
    //Female
}
</code>```

Inside those statements, set the type of organism (I'm guessing that's an enum variable)

Body:
I am new to coding, and I am currently modding a code. Here is pat of the original.

 if ((world[row][col] == ORGANISM) && (check == 2))
            worldCopy[row][col] = ORGANISM;

The original code would basically spawn a offspring (a.k.a a *) in a certain location on a grid. However, now I am modding for the offspring to be randomly male or female. How should I write a new piece of subcode so that it would randomly pick for ORGANISM to be male or female? I don't need specifics, just want some help because I am stuck.

Body:
Look into the Random class. It provides random generation of ints, and in your case, booleans. I don't know what data type organism is, but something like this should help:

if(new Random().nextBoolean()) {
    //Male
} else {
    //Female
}

Inside those statements, set the type of organism (I'm guessing that's an enum variable)


问:
Mongoose cursor with async operations
I am new to mongo and now drowned in whole lot of documentation.All I want is to use mongoose cursor to work async with my data operation inside cursor.It should wait to play next iteration until operation is complete.
I read in a that we can do so by

QueryCursor#eachAsync(fn, [options], [options.parallel], [callback])

If fn returns a promise, will wait for the promise to resolve

Since i am new to mongo I don't know how to create a promise and resolve it later.

```<code>var cursor = Users.find({ "is_verified" : false }).cursor();
cursor.eachAsync(function (doc) {
    //create promise here
    async.series({
       one: function(callback){
          callback(null,1);
       },
       two: function(callback){
          callback(null,2);
       },
       three: function(callback){
          callback(null,3);
       },
       four: function(callback){
          //resolve promise here
          if() callback(null,4)
       },
   },function(err,result){})

}).then(()=>console.log('FINISHED'));
</code>```

答:
I would call your function in an array like this:
[This is semi pseudo-code]</p>

```<code>for(parameter in parameters) {
  users.find({"parameter":parameter}, function( err, data) {
    if (err) return handleError(err);
    functionToFeedTemplate(data);
    functionToSendMail(data);
  }
}
</code>```

Title: Mongoose cursor with async operations

Body:
I am new to mongo and now drowned in whole lot of documentation.All I want is to use mongoose cursor to work async with my data operation inside cursor.It should wait to play next iteration until operation is complete.
I read in a that we can do so by

QueryCursor#eachAsync(fn, [options], [options.parallel], [callback])

If fn returns a promise, will wait for the promise to resolve

Since i am new to mongo I don't know how to create a promise and resolve it later.

var cursor = Users.find({ "is_verified" : false }).cursor();
cursor.eachAsync(function (doc) {
    //create promise here
    async.series({
       one: function(callback){
          callback(null,1);
       },
       two: function(callback){
          callback(null,2);
       },
       three: function(callback){
          callback(null,3);
       },
       four: function(callback){
          //resolve promise here
          if() callback(null,4)
       },
   },function(err,result){})

}).then(()=>console.log('FINISHED'));

Body:
I would call your function in an array like this:
[This is semi pseudo-code]

for(parameter in parameters) {
  users.find({"parameter":parameter}, function( err, data) {
    if (err) return handleError(err);
    functionToFeedTemplate(data);
    functionToSendMail(data);
  }
}


问:
Fetch json response inside array of array
My Json response is as follows.I want to get the individual array item from the response like static website,dynamic website.Can you help me please?</p>

```<code>{
  "data": [
    [
      "Static Website"
    ],
    [
      "Dynamic Website"
    ],
    [
      "E-Commerce Website"
    ],
    [
      "ERP"
    ],
    [
      "IOS Application"
    ],
    [
      "Social Networking"
    ],
    [
      "Web Application"
    ],
    [
      "Graphic Design"
    ]
  ],
  "status": 200
}
</code>```

答:
Try this One.</p>

```<code>public void parseJsonResponse(JSONObject jsonObject) {
    try {
        JSONArray jsonArray = jsonObject.getJSONArray("data");
        String status = jsonObject.getString("status");
        Log.d("StatusCode", "Status" + status);

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONArray jsonarrayInner = (JSONArray) jsonArray.get(i);
            Log.d("", "JsonArray Value" + jsonarrayInner);

            for (int j = 0; j < jsonarrayInner.length(); j++) {
                String s1 = jsonarrayInner.getString(j);

            }
        }
    } catch (JSONException e) {
        e.printStackTrace();

    }
}
</code>```

Body:
My Json response is as follows.I want to get the individual array item from the response like static website,dynamic website.Can you help me please?

{
  "data": [
    [
      "Static Website"
    ],
    [
      "Dynamic Website"
    ],
    [
      "E-Commerce Website"
    ],
    [
      "ERP"
    ],
    [
      "IOS Application"
    ],
    [
      "Social Networking"
    ],
    [
      "Web Application"
    ],
    [
      "Graphic Design"
    ]
  ],
  "status": 200
}

Body:
Try this One.

public void parseJsonResponse(JSONObject jsonObject) {
    try {
        JSONArray jsonArray = jsonObject.getJSONArray("data");
        String status = jsonObject.getString("status");
        Log.d("StatusCode", "Status" + status);

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONArray jsonarrayInner = (JSONArray) jsonArray.get(i);
            Log.d("", "JsonArray Value" + jsonarrayInner);

            for (int j = 0; j < jsonarrayInner.length(); j++) {
                String s1 = jsonarrayInner.getString(j);

            }
        }
    } catch (JSONException e) {
        e.printStackTrace();

    }
}


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

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

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

. when i print this column it returns like this

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

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

答:
Without a PHP code we cannot help.

MySQL works as expected: http://sqlfiddle.com/#!9/7e591f/1

EDITED:
Your framework most probably converts undefined datetime NULL to valid date time value 1970-01-01 00:00:00 which is the very beginning of PHP time - it equals to 0 (zero) second.

Some more info you can find on Codeigniter help: https://www.codeigniter.com/user_guide/helpers/date_helper.html

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

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

payment_date column is a DATETIME format

. when i print this column it returns like this

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

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


问:
Laravel - Query builder with pivot table, return where all in
I have tables customers, products and customer_products.
In customer_products there are id, customer_id and product_id columns.
In search form I have 'products' input field, and can add multiple products for searching.
So, in that case $request->products is array, and I want to pass that array in query builder to return all customers who bought at least all products from $request->products array.
If each customers had only one products I would then use whereIn method, but when customers has multiple products ordered I dont have idea how to solve that.
I tried with foreach but I did not get the result which want.

答:
I finally found solution. If someone has same problem this is solution which gives me correct results, whereHas method is what I need for:</p>

```<code>$customesrs = Customers::with('products');
if($request->has('products'))
{
  foreach($request->products as $product)
  {
   $customers->whereHas('products', function($query) use ($product) {
     $query->where('product_id', $product);
   });
  }
}
$customers->get();
</code>```

Body:
I finally found solution. If someone has same problem this is solution which gives me correct results, whereHas method is what I need for:

$customesrs = Customers::with('products');
if($request->has('products'))
{
  foreach($request->products as $product)
  {
   $customers->whereHas('products', function($query) use ($product) {
     $query->where('product_id', $product);
   });
  }
}
$customers->get();


问:
How to stop a transparent-fill circle getting mouse events inside it?
I want a Circle to respond to mouse events only when the mouse is on it's 'stroke' , i mean boundary. Of course, the circle has a transparent fill and a colorful stroke. Extending JavaFX Path looks painful to me, is there any way to do that with this Circle class?

答: Your solution does not work anymore in Java 9 but in your case you could just set the fill of the circle to null. This should have the same effect.</p>


问:
WPF icon specifications to support Windows 7 and being backward compatible
I had the problem to get a FileFormatException as soon as I started a WPF application under Windows XP. As I figured out, it was caused by having image sizes bigger than 64x64 pixels in my application icon.

If a Vista icon, that contains
  png-image, is used as Window.Icon the
  application fails to launch with an
  FileFormatException.

Make sure the icon has max size 64x64
  pixels.  It can still be 32 bit (using
  alpha channel).

Is this really the only workaround to not have image sizes bigger than 64x64 pixels in my icon? Isn't there a way to support Windows 7 icons at its highest resolution (256x256 pixels) and being backward compatible to Windows XP at the same time?

I'm aware of the icon specifications for the different single Windows OSs, but is there also a specification of how to support Windows 7 and being backward compatible?

Thanks in advance!

答: Set a png-image as the windows icon (XAML or code) and set in the project-settings the real icon-file with the high resolution-content for the executable file (project-icon). Windows XP will accept your Window-instances and window 7 has it's highres-icons.</p>


问:
auto Function with if Statement won't return a value
I made a template and an auto function that compare 2 values and return the smallest one.
This is my code:

```<code>#include <iostream>
using namespace std;

// Template with a value returning function: PrintSmaller
template <typename T, typename U>
auto PrintSmaller(T NumOne, U NumTwo) {
    if (NumOne > NumTwo) {
        return NumTwo;
    }
    else {
        return NumOne;
    }
}

int main() {

    int iA = 345;
    float fB = 23.4243;

    cout << PrintSmaller(iA, fB) << endl;
    cout << PrintSmaller(fB, iA) << endl;

    return 0;
}
</code>```

But it won't compile, I get this error on VS 2015:
Error  C3487   'int': all return expressions must deduce to the same type: previously it was 'float'

However, if I delete the if statement and write the function PrintSmaller like this it works with no problems :

```<code>auto PrintSmaller(T NumOne, U NumTwo) {
return (NumOne < NumTwo ? NumOne : NumTwo);
}
</code>```

What is the difference ? and why the first code won't compile ?
Thank you.

答:
Until yesterday (2017-12-06) this was not compiling under MSVC. But after VS 15.5 update it does.

```<code>    auto msvc_does_compile = [](auto _string)
     {
      using string_type = decltype(_string);
      return std::vector<string_type>{};
     };
   /*
    OK since VS 2017 15.5 update
   auto vec1 = msvc_does_compile( std::string{} );
   */
</code>```

Adding explicit return type will choke MSVC , but not gcc/clang as usual:

```<code>auto msvc_does_not_compile = [](auto _string)
    // explicit return type makes msvc not to compile
    -> std::vector< decltype(_string) >
  {
    using string_type = decltype(_string);
    return std::vector<string_type>{};
  };
</code>```

And something of the same but simpler will be stopped even at the IDE stage:

```<code>    auto msvc_ide_does_not_allow = []( bool wide )
    {
       if (wide)
        return std::vector<std::string>();

        return std::vector<std::wstring>();
    };
</code>```

Yes, again that troublesome pair gcc/clang has no problems with the above. Try which ever online ide you prefer to convince yourself...

Body:
I made a template and an auto function that compare 2 values and return the smallest one.
This is my code:

#include <iostream>
using namespace std;

// Template with a value returning function: PrintSmaller
template <typename T, typename U>
auto PrintSmaller(T NumOne, U NumTwo) {
    if (NumOne > NumTwo) {
        return NumTwo;
    }
    else {
        return NumOne;
    }
}

int main() {

    int iA = 345;
    float fB = 23.4243;

    cout << PrintSmaller(iA, fB) << endl;
    cout << PrintSmaller(fB, iA) << endl;

    return 0;
}

But it won't compile, I get this error on VS 2015:
Error  C3487   'int': all return expressions must deduce to the same type: previously it was 'float'

However, if I delete the if statement and write the function PrintSmaller like this it works with no problems :

auto PrintSmaller(T NumOne, U NumTwo) {
return (NumOne < NumTwo ? NumOne : NumTwo);
}

What is the difference ? and why the first code won't compile ?
Thank you.

Body:
Until yesterday (2017-12-06) this was not compiling under MSVC. But after VS 15.5 update it does.

    auto msvc_does_compile = [](auto _string)
     {
      using string_type = decltype(_string);
      return std::vector<string_type>{};
     };
   /*
    OK since VS 2017 15.5 update
   auto vec1 = msvc_does_compile( std::string{} );
   */

Adding explicit return type will choke MSVC , but not gcc/clang as usual:

auto msvc_does_not_compile = [](auto _string)
    // explicit return type makes msvc not to compile
    -> std::vector< decltype(_string) >
  {
    using string_type = decltype(_string);
    return std::vector<string_type>{};
  };

And something of the same but simpler will be stopped even at the IDE stage:

    auto msvc_ide_does_not_allow = []( bool wide )
    {
       if (wide)
        return std::vector<std::string>();

        return std::vector<std::wstring>();
    };

Yes, again that troublesome pair gcc/clang has no problems with the above. Try which ever online ide you prefer to convince yourself...


问:
css active class not working for Tabs
Could you help me with this please ?

css active class not working for Tabs

Demo: http://dev.ktimes.co/was20378/tab/index-nw2.html

CSS

```<code>.filter-button
{
        padding: 6px 20px;
    font-size: 18px;
    border: 1px solid #fd0009;
    border-radius: 20px;
    text-align: center;
    color: #fd0009;
    margin-bottom: 30px;

}
.filter-button:hover, .filter-button.active
{
    font-size: 18px;
    border: 1px solid #fd0009;
   border-radius: 20px;
    text-align: center;
    color: #ffffff;
    background-color: #fd0009;

}
.btn-default.filter-button.active {
    background-color: #fd0009 !important;
    color: #FFF !important;
}
</code>```

答:
Try like this :</p>

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

        $(".filter-button").click(function () {
            var value = $(this).attr('data-filter');

            if (value == "all") {
                $('.filter').show('1000');
            }
            else {

                $(".filter").not('.' + value).hide('3000');
                $('.filter').filter('.' + value).show('3000');

                }

               $(".filter-button").removeClass("active");

               $(this).addClass("active");
        });
    });
</code>```

Title: css active class not working for Tabs

Body:
Could you help me with this please ?

css active class not working for Tabs

Demo: http://dev.ktimes.co/was20378/tab/index-nw2.html

CSS

.filter-button
{
        padding: 6px 20px;
    font-size: 18px;
    border: 1px solid #fd0009;
    border-radius: 20px;
    text-align: center;
    color: #fd0009;
    margin-bottom: 30px;

}
.filter-button:hover, .filter-button.active
{
    font-size: 18px;
    border: 1px solid #fd0009;
   border-radius: 20px;
    text-align: center;
    color: #ffffff;
    background-color: #fd0009;

}
.btn-default.filter-button.active {
    background-color: #fd0009 !important;
    color: #FFF !important;
}

Body:
Try like this :

        $(document).ready(function () {

        $(".filter-button").click(function () {
            var value = $(this).attr('data-filter');

            if (value == "all") {
                $('.filter').show('1000');
            }
            else {

                $(".filter").not('.' + value).hide('3000');
                $('.filter').filter('.' + value).show('3000');

                }

               $(".filter-button").removeClass("active");

               $(this).addClass("active");
        });
    });


问:
PySpark groupByKey returning pyspark.resultiterable.ResultIterable
I am trying to figure out why my groupByKey is returning the following:

```<code>[(0, <pyspark.resultiterable.ResultIterable object at 0x7fc659e0a210>), (1, <pyspark.resultiterable.ResultIterable object at 0x7fc659e0a4d0>), (2, <pyspark.resultiterable.ResultIterable object at 0x7fc659e0a390>), (3, <pyspark.resultiterable.ResultIterable object at 0x7fc659e0a290>), (4, <pyspark.resultiterable.ResultIterable object at 0x7fc659e0a450>), (5, <pyspark.resultiterable.ResultIterable object at 0x7fc659e0a350>), (6, <pyspark.resultiterable.ResultIterable object at 0x7fc659e0a1d0>), (7, <pyspark.resultiterable.ResultIterable object at 0x7fc659e0a490>), (8, <pyspark.resultiterable.ResultIterable object at 0x7fc659e0a050>), (9, <pyspark.resultiterable.ResultIterable object at 0x7fc659e0a650>)]
</code>```

I have flatMapped values that look like this:

```<code>[(0, u'D'), (0, u'D'), (0, u'D'), (0, u'D'), (0, u'D'), (0, u'D'), (0, u'D'), (0, u'D'), (0, u'D'), (0, u'D')]
</code>```

I'm doing just a simple:

```<code>groupRDD = columnRDD.groupByKey()
</code>```

答:
Example:

```<code>r1 = sc.parallelize([('a',1),('b',2)])
r2 = sc.parallelize([('b',1),('d',2)])
r1.cogroup(r2).mapValues(lambda x:tuple(reduce(add,__builtin__.map(list,x))))
</code>```

Result:

```<code>[('d', (2,)), ('b', (2, 1)), ('a', (1,))]
</code>```

Body:
I am trying to figure out why my groupByKey is returning the following:

[(0, <pyspark.resultiterable.ResultIterable object at 0x7fc659e0a210>), (1, <pyspark.resultiterable.ResultIterable object at 0x7fc659e0a4d0>), (2, <pyspark.resultiterable.ResultIterable object at 0x7fc659e0a390>), (3, <pyspark.resultiterable.ResultIterable object at 0x7fc659e0a290>), (4, <pyspark.resultiterable.ResultIterable object at 0x7fc659e0a450>), (5, <pyspark.resultiterable.ResultIterable object at 0x7fc659e0a350>), (6, <pyspark.resultiterable.ResultIterable object at 0x7fc659e0a1d0>), (7, <pyspark.resultiterable.ResultIterable object at 0x7fc659e0a490>), (8, <pyspark.resultiterable.ResultIterable object at 0x7fc659e0a050>), (9, <pyspark.resultiterable.ResultIterable object at 0x7fc659e0a650>)]

I have flatMapped values that look like this:

[(0, u'D'), (0, u'D'), (0, u'D'), (0, u'D'), (0, u'D'), (0, u'D'), (0, u'D'), (0, u'D'), (0, u'D'), (0, u'D')]

I'm doing just a simple:

groupRDD = columnRDD.groupByKey()

Body:
Example:

r1 = sc.parallelize([('a',1),('b',2)])
r2 = sc.parallelize([('b',1),('d',2)])
r1.cogroup(r2).mapValues(lambda x:tuple(reduce(add,__builtin__.map(list,x))))

Result:

[('d', (2,)), ('b', (2, 1)), ('a', (1,))]


问:
One central XML Schema for multiple XML files?
Currently, we have several configuration XML files in use, which all handle a separate portion of our configuration. One for test sequence, one for timeout, etc. These separate XML files are all defined/validated against a single XML Schema document, which holds all the definitions used in the separate XML files. Is this good practice? Or should each type of XML file have its own, separate XML Schema?</p>

答: There are arguments both ways - it's a judgement call. If there are common parts to the different files then a common schema certainly has benefits. If there aren't, and if the domains are so separate that there aren't likely to be, then I would go for separate schemas. But there's no easy answer. When you're defining a set of 400 application-to-application message formats for an integration backbone in a large investment bank, as one of my clients was, the disadvantages of both approaches become starkly clear.</p>


问:
Selecting git executable in Jenkins Multi-configuration project depending on axis
I've got a Multi-configuration job in Jenkins.

Currently it has 2 axes, one for build type with values "Debug" and "Release" another one with 2 values too, setting some preprocessor macros.

I'd like to add one more axis with build platform: Windows or Linux.

My project is stored in git, and the "Source code management" part of the Jenkins job configuration contains configured "Git executable", chosen from the drop-down list.

As I understand, this list is formed from global Jenkins settings. My Jenkins has 2 git executables configured, one for linux slaves, and one for windows slaves.

However, this multiconfig job uses only one executable, "Default", configured for Linux slaves.

This makes me keeping 2 Jenkins jobs, one for windows, and one for linux.
Some inconvenience of this setup is that build results appear in different locations.

Is there any way to choose this parameter depending on axis value?

答:
One can override default git location in the settings of the node.

Manage Jenkins -> Manage Nodes -> select windows node -> Configure -> Node properties in the lower part of the page.

Then check "Tool locations" checkbox and add path for default Git.
Not sure, if spaces in paths are properly supported, didn't check.

Next tricky thing will be development of universal scripts, that run both in Linux Bash and in Windows CMD.  Less tricky alternative is rewriting all my build scripts to some cross-platform language.


问:
Is there an equivalent method to C's scanf in Java?
Java has the notion of format strings, bearing a strong resemblance to format strings in other languages. It is used in JDK methods like String#format() for output conversion.

I was wondering if there's an input conversion method akin to C's scanf in Java?

答:
THERE'S an even simpler answer</p>

```<code>import java.io.BufferedReader;
import java.util.Scanner;

public class Main {

    public static void main(String[] args)
    {
        String myBeautifulScanf = new Scanner(System.in).nextLine();
        System.out.println( myBeautifulScanf );

    }
}
</code>```

Body:
THERE'S an even simpler answer

import java.io.BufferedReader;
import java.util.Scanner;

public class Main {

    public static void main(String[] args)
    {
        String myBeautifulScanf = new Scanner(System.in).nextLine();
        System.out.println( myBeautifulScanf );

    }
}