问:
How to append an element in the end of list structure in java?
I'm trying to write a function to append a new element in the end of my list. But i dont know how my method always append new element in the first index of the list.

I have 2 class named Waypoint and TourElement. Waypoint contains method to handle points in linked list. TourElment contains waypoint and next.

Waypoint.java

```<code>public class Waypoint {
    int x  ;
    int y  ;
    public int getX()
    {
        return this.x;
    }
    public int getY()
    {
        return this.y;
    }
    public void setXY(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
}
</code>```

TourElement.java

```<code> public class TourElement {
     private Waypoint points;
     private TourElement next;
     public void setWaypoint( Waypoint points)
     {
         this.points = points;
     }
     public void setTourElement(TourElement next)
     {
         this.next = next;
     }
     Waypoint getWaypoint()
     {
         return this.points;
     }

     TourElement getNext()
     {
         return this.next;
     }

     //+ method below
}
</code>```

method add new TourElement in the list, Why is alway append TourElement in the first index of the list?

```<code>public TourElement append(Waypoint waypoint)
{
    TourElement newTourElement = new TourElement();
    TourElement current = this;
    while(current.next != null)
    {
        current = current.next;
    }
    newTourElement.setWaypoint(waypoint);
    current.next = newTourElement;
    return newTourElement;
}
</code>```

Here is my test case:
//create an element list:

```<code>private TourElement createElementList(int[][] waypoints){
        assert waypoints.length > 0;
        TourElement elem = new TourElement();
        int lastIndex = waypoints.length-1;
        Waypoint wp = createWaypoint(waypoints[lastIndex][0], waypoints[lastIndex][1]);
        elem.setWaypoint(wp);
        for (int i = lastIndex-1; i >= 0 ; i--) {
            wp = createWaypoint(waypoints[i][0], waypoints[i][1]);
            elem = elem.addStart(wp);
        }
        return elem;
    }
</code>```

//create an waypoint:

```<code>private Waypoint createWaypoint(int x, int y) {
        Waypoint wp = new Waypoint();
        wp.setXY(x, y);
        return wp;
    }
</code>```

//add Start

```<code>public   TourElement addStart(Waypoint wp) {
     TourElement newTourElement = new TourElement();
     newTourElement.setWaypoint(wp);
     newTourElement.setTourElement(this);
     return newTourElement;
    }

 public void testAppend() {
        TourElement elem = createElementList(new int[][] {{2, 2}});
        elem = elem.append(createWaypoint(3, 3));
        assertArrayEquals(new int[] {2, 2}, elem.getWaypoint().toArray());
        assertArrayEquals(new int[] {3, 3}, elem.getNext().getWaypoint().toArray());
        assertNull(elem.getNext().getNext());
    }

public void testAppend_AfterTwo() {
    TourElement elem = createElementList(new int[][] {{1, 1}, {2, 2}});
    elem = elem.append(createWaypoint(3, 3));
    assertArrayEquals(new int[] {1, 1}, elem.getWaypoint().toArray());
    assertArrayEquals(new int[] {2, 2}, elem.getNext().getWaypoint().toArray());
    assertArrayEquals(new int[] {3, 3}, elem.getNext().getNext().getWaypoint().toArray());
    assertNull(elem.getNext().getNext().getNext());
}
</code>```

I expect that the output will look like this:

Test case 1: {2,2} => {3,3}

Test case 2:  {1,1} => {2,2} =>{3,3}

But my actual output is:

Test case 1: {3, 3} => {2,2}

Test case 2:  {3,3} =>{1,1} =>{2,2}

答:
You're updating your "elem" in the line elem = elem.append(createWaypoint(3, 3));.

So I wonder, how your test cases return the complete list anyway? I'd expect the "actual output" would be "{3,3}" only.

To solve the issue, the test should NOT change the elem variable at all, after it's initialized in first place:

```<code> public void testAppend() {
        // add "final" to prevent accidentially changes of references
        final TourElement elem = createElementList(new int[][] {{2, 2}});

        // DO NOT CHANGE "elem"!
        // elem = elem.append(createWaypoint(3, 3));
        // instead keep the reference to the first elem:
        elem.append(createWaypoint(3, 3));

        assertArrayEquals(new int[] {2, 2}, elem.getWaypoint().toArray());
        assertArrayEquals(new int[] {3, 3}, elem.getNext().getWaypoint().toArray());
        assertNull(elem.getNext().getNext());
    }
</code>```

BTW: your code could be MUCH clearer, if you give the "Waypoint" a constructor "Waypoint(x, y)", make the x and y fields final, remove setXY() and add a toString().

```<code>public class Waypoint {
    final int x;
    final int y;
    public WayPoint(int x, int y) {
        this.x = x;
        this.y = y;
    }
    public int getX() { ... }
    public int getY() { ... }

    @Override
    public String toString() {
        return String.format("{%d,%d}", x, y);
    }
}
</code>```

Your TourElement could need a Collection<Waypoint> waypoints() method, which returns subsequent Waypoint objects (makes testing easier).

```<code>public Collection<Waypoint> waypoints() {
    Collection<Waypoint> res = new java.util.ArrayList<>();
    TourElement currTE = this;
    while (currTE.next()!=null) {
        res.add(currTE.getWaypoint());
        currTE = currTE.next();
    }
    return res;
}
</code>```

To then print the list of Waypoint, you simply do

```<code>    org.apache.commons.lang.StringUtils.join(elem.waypoints(), ", ");
</code>```

Body:
I'm trying to write a function to append a new element in the end of my list. But i dont know how my method always append new element in the first index of the list.

I have 2 class named Waypoint and TourElement. Waypoint contains method to handle points in linked list. TourElment contains waypoint and next.

Waypoint.java

public class Waypoint {
    int x  ;
    int y  ;
    public int getX()
    {
        return this.x;
    }
    public int getY()
    {
        return this.y;
    }
    public void setXY(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
}

TourElement.java

 public class TourElement {
     private Waypoint points;
     private TourElement next;
     public void setWaypoint( Waypoint points)
     {
         this.points = points;
     }
     public void setTourElement(TourElement next)
     {
         this.next = next;
     }
     Waypoint getWaypoint()
     {
         return this.points;
     }

     TourElement getNext()
     {
         return this.next;
     }

     //+ method below
}

method add new TourElement in the list, Why is alway append TourElement in the first index of the list?

public TourElement append(Waypoint waypoint)
{
    TourElement newTourElement = new TourElement();
    TourElement current = this;
    while(current.next != null)
    {
        current = current.next;
    }
    newTourElement.setWaypoint(waypoint);
    current.next = newTourElement;
    return newTourElement;
}

Here is my test case:
//create an element list:

private TourElement createElementList(int[][] waypoints){
        assert waypoints.length > 0;
        TourElement elem = new TourElement();
        int lastIndex = waypoints.length-1;
        Waypoint wp = createWaypoint(waypoints[lastIndex][0], waypoints[lastIndex][1]);
        elem.setWaypoint(wp);
        for (int i = lastIndex-1; i >= 0 ; i--) {
            wp = createWaypoint(waypoints[i][0], waypoints[i][1]);
            elem = elem.addStart(wp);
        }
        return elem;
    }

//create an waypoint:

private Waypoint createWaypoint(int x, int y) {
        Waypoint wp = new Waypoint();
        wp.setXY(x, y);
        return wp;
    }

//add Start

public   TourElement addStart(Waypoint wp) {
     TourElement newTourElement = new TourElement();
     newTourElement.setWaypoint(wp);
     newTourElement.setTourElement(this);
     return newTourElement;
    }

 public void testAppend() {
        TourElement elem = createElementList(new int[][] {{2, 2}});
        elem = elem.append(createWaypoint(3, 3));
        assertArrayEquals(new int[] {2, 2}, elem.getWaypoint().toArray());
        assertArrayEquals(new int[] {3, 3}, elem.getNext().getWaypoint().toArray());
        assertNull(elem.getNext().getNext());
    }

public void testAppend_AfterTwo() {
    TourElement elem = createElementList(new int[][] {{1, 1}, {2, 2}});
    elem = elem.append(createWaypoint(3, 3));
    assertArrayEquals(new int[] {1, 1}, elem.getWaypoint().toArray());
    assertArrayEquals(new int[] {2, 2}, elem.getNext().getWaypoint().toArray());
    assertArrayEquals(new int[] {3, 3}, elem.getNext().getNext().getWaypoint().toArray());
    assertNull(elem.getNext().getNext().getNext());
}

I expect that the output will look like this:

Test case 1: {2,2} => {3,3}

Test case 2:  {1,1} => {2,2} =>{3,3}

But my actual output is:

Test case 1: {3, 3} => {2,2}

Test case 2:  {3,3} =>{1,1} =>{2,2}

Body:
You're updating your "elem" in the line elem = elem.append(createWaypoint(3, 3));.

So I wonder, how your test cases return the complete list anyway? I'd expect the "actual output" would be "{3,3}" only.

To solve the issue, the test should NOT change the elem variable at all, after it's initialized in first place:

 public void testAppend() {
        // add "final" to prevent accidentially changes of references
        final TourElement elem = createElementList(new int[][] {{2, 2}});

        // DO NOT CHANGE "elem"!
        // elem = elem.append(createWaypoint(3, 3));
        // instead keep the reference to the first elem:
        elem.append(createWaypoint(3, 3));

        assertArrayEquals(new int[] {2, 2}, elem.getWaypoint().toArray());
        assertArrayEquals(new int[] {3, 3}, elem.getNext().getWaypoint().toArray());
        assertNull(elem.getNext().getNext());
    }

BTW: your code could be MUCH clearer, if you give the "Waypoint" a constructor "Waypoint(x, y)", make the x and y fields final, remove setXY() and add a toString().

public class Waypoint {
    final int x;
    final int y;
    public WayPoint(int x, int y) {
        this.x = x;
        this.y = y;
    }
    public int getX() { ... }
    public int getY() { ... }

    @Override
    public String toString() {
        return String.format("{%d,%d}", x, y);
    }
}

Your TourElement could need a Collection<Waypoint> waypoints() method, which returns subsequent Waypoint objects (makes testing easier).

public Collection<Waypoint> waypoints() {
    Collection<Waypoint> res = new java.util.ArrayList<>();
    TourElement currTE = this;
    while (currTE.next()!=null) {
        res.add(currTE.getWaypoint());
        currTE = currTE.next();
    }
    return res;
}

To then print the list of Waypoint, you simply do

    org.apache.commons.lang.StringUtils.join(elem.waypoints(), ", ");


来源: stackexchange

问:
Finding missing numbers in a preset range
I am having a problem finding missing values within a preset range.  For example I have:

Column A: 3, 5, 7, 9, 10, 11
I want either VBA or a formula in excel to return
Column B: 1, 2, 4, 6, 8, 12, 13 --> 30

The final number in Column B will vary.  I want it to change based on user discretion.  For my problem I am working with days of the month.  So January, February, and March have different total days.  I've seen a lot of examples, but all are based on a array in the spreedsheet.  What if I want to change the array to 1-30, 1-31, or 1-28 (depending on which month I am looking at)?

答:
This is similar to the formula quoted by OP in the comment above but generalised for user-defined number of numbers:

```<code>=IFERROR(SMALL(IF(ISERROR(MATCH(ROW(A$1:INDEX(A:A,C$2)),D$2:INDEX(D:D,COUNT(D:D)+ROW(D$1)),0)),
ROW(A$1:INDEX(A:A,C$2))),ROW()-ROW(A$1)),"")
</code>```

Must be entered as an array formula using CtrlShiftEnter

EDIT

You can change the formula so that you can set both the start and end points:

```<code>=IFERROR(SMALL(IF(ISERROR(MATCH(ROW(INDEX(A:A,C$2):INDEX(A:A,C$3)),D$2:INDEX(D:D,COUNT(D:D)+ROW(D$1)),0)),
ROW(INDEX(A:A,C$2):INDEX(A:A,C$3))),ROW()-ROW(A$1)),"")
</code>```

This works with dates if column B is formatted appropriately:

ContentLicense: CC BY-SA 4.0

Body:
This is similar to the formula quoted by OP in the comment above but generalised for user-defined number of numbers:

=IFERROR(SMALL(IF(ISERROR(MATCH(ROW(A$1:INDEX(A:A,C$2)),D$2:INDEX(D:D,COUNT(D:D)+ROW(D$1)),0)),
ROW(A$1:INDEX(A:A,C$2))),ROW()-ROW(A$1)),"")

Must be entered as an array formula using CtrlShiftEnter

EDIT

You can change the formula so that you can set both the start and end points:

=IFERROR(SMALL(IF(ISERROR(MATCH(ROW(INDEX(A:A,C$2):INDEX(A:A,C$3)),D$2:INDEX(D:D,COUNT(D:D)+ROW(D$1)),0)),
ROW(INDEX(A:A,C$2):INDEX(A:A,C$3))),ROW()-ROW(A$1)),"")

This works with dates if column B is formatted appropriately:


问:
Download multiple files with multiple threads
I am trying to download few files using 3 threads. my requirement is i want to achieve file download on 3 threads so that all files download 3 times in 3 different folders so that the files dont overwrite. I am using __counter to append 1,2,3 to the folders. Problem is if i give Thread count as 1 or 2 or 3 , it is behaving same in all the scenarios i.e. it always create two folders Folder1 and Folder2 and in all in folder1 it download all the files and in folder2 only last file gets downloaded with size as 0 KB.

Number of threads = 1

Attaching what i have tried so far-

答:
Please try without counter function and with prefix, and two threads. I am guessing it based on the below information.

https://jmeter.apache.org/usermanual/component_reference.html#Save_Responses_to_a_file

Please note that Filename Prefix must not contain Thread related data,
  so don't use any Variable (${varName}) or functions like
  ${__threadNum} in this field

Or try to keep some delay/pacing between two threads.

Hope this helps.

Update:-
Just give the folder path and file name without extension. It will save the with extension. I tried with image and it is save as Myfile1.jpeg


问:
Why does Xlim and Ylim not work as expected
Why does the xlim and ylim not work as expected? It should show y-lim from 1-4 and xlim from 1-3. This is not the case. Any idea why?

答:
I would recommend using NumPy's loadtxt to read the data into two separate arrays as shown in the following complete answer. Also, you should try to set the limits after plotting.

```<code>import numpy as np
import matplotlib.pyplot as plt

x, y = np.loadtxt('....\test.txt', unpack=True)
plt.plot(x, y)
plt.ylim(1, 4)
plt.xlim(1, 3)
plt.show()
</code>```

Body:
I would recommend using NumPy's loadtxt to read the data into two separate arrays as shown in the following complete answer. Also, you should try to set the limits after plotting.

import numpy as np
import matplotlib.pyplot as plt

x, y = np.loadtxt('....\test.txt', unpack=True)
plt.plot(x, y)
plt.ylim(1, 4)
plt.xlim(1, 3)
plt.show()


问:
AzureSpatialAnchors basic demo not saving
I just checked out the spatial anchors demo from GitHub, changed the keys and deployed it to my Samsung S8 successfully.

But when I try to save an anchor I get an IllegalStateException:

```<code>05-18 12:17:32.667 5536-6285/com.microsoft.sampleandroid E/CBindingAutoGen: exception causing failure: std::exception
05-18 12:17:32.670 5536-6286/com.microsoft.sampleandroid W/System.err: java.util.concurrent.ExecutionException: java.lang.IllegalStateException: std::exception.Request CV: . Response CV: .
05-18 12:17:32.674 5536-6286/com.microsoft.sampleandroid W/System.err:     at java.util.concurrent.FutureTask.report(FutureTask.java:123)
05-18 12:17:32.675 5536-6286/com.microsoft.sampleandroid W/System.err:     at java.util.concurrent.FutureTask.get(FutureTask.java:193)
05-18 12:17:32.677 5536-6286/com.microsoft.sampleandroid W/System.err:     at com.microsoft.sampleandroid.AzureSpatialAnchorsManager.lambda$toEmptyCompletableFuture$2(AzureSpatialAnchorsManager.java:147)
05-18 12:17:32.680 5536-6286/com.microsoft.sampleandroid W/System.err:     at com.microsoft.sampleandroid.-$$Lambda$AzureSpatialAnchorsManager$8SSZbzB3fyFTuS1Rv6e_KEvy8B8.run(Unknown Source:2)
05-18 12:17:32.682 5536-6286/com.microsoft.sampleandroid W/System.err:     at java.util.concurrent.CompletableFuture$AsyncRun.run(CompletableFuture.java:1661)
05-18 12:17:32.684 5536-6286/com.microsoft.sampleandroid W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
05-18 12:17:32.686 5536-6286/com.microsoft.sampleandroid W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
05-18 12:17:32.687 5536-6286/com.microsoft.sampleandroid W/System.err:     at java.lang.Thread.run(Thread.java:764)
05-18 12:17:32.690 5536-6286/com.microsoft.sampleandroid W/System.err: Caused by: java.lang.IllegalStateException: std::exception.Request CV: . Response CV: .
05-18 12:17:32.692 5536-6286/com.microsoft.sampleandroid W/System.err:     at com.microsoft.azure.spatialanchors.NativeLibraryHelpers.checkStatus(NativeLibraryHelpers.java:65)
05-18 12:17:32.693 5536-6286/com.microsoft.sampleandroid W/System.err:     at com.microsoft.azure.spatialanchors.CloudSpatialAnchorSession$3.call(CloudSpatialAnchorSession.java:393)
05-18 12:17:32.695 5536-6286/com.microsoft.sampleandroid W/System.err:     at com.microsoft.azure.spatialanchors.CloudSpatialAnchorSession$3.call(CloudSpatialAnchorSession.java:390)
05-18 12:17:32.696 5536-6286/com.microsoft.sampleandroid W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:266)
05-18 12:17:32.697 5536-6286/com.microsoft.sampleandroid W/System.err:  ... 3 more
05-18 12:17:32.700 5536-6286/com.microsoft.sampleandroid W/System.err: java.util.concurrent.CompletionException: java.lang.RuntimeException: java.util.concurrent.ExecutionException: java.lang.IllegalStateException: std::exception.Request CV: . Response CV: .
05-18 12:17:32.701 5536-6286/com.microsoft.sampleandroid W/System.err:     at java.util.concurrent.CompletableFuture.encodeThrowable(CompletableFuture.java:276)
05-18 12:17:32.701 5536-6286/com.microsoft.sampleandroid W/System.err:     at java.util.concurrent.CompletableFuture.completeThrowable(CompletableFuture.java:282)
05-18 12:17:32.702 5536-6286/com.microsoft.sampleandroid W/System.err:     at java.util.concurrent.CompletableFuture$AsyncRun.run(CompletableFuture.java:1664)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
05-18 12:17:32.703 5536-6286/com.microsoft.sampleandroid W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
05-18 12:17:32.703 5536-6286/com.microsoft.sampleandroid W/System.err:     at java.lang.Thread.run(Thread.java:764)
05-18 12:17:32.704 5536-6286/com.microsoft.sampleandroid W/System.err: Caused by: java.lang.RuntimeException: java.util.concurrent.ExecutionException: java.lang.IllegalStateException: std::exception.Request CV: . Response CV: .
05-18 12:17:32.705 5536-6286/com.microsoft.sampleandroid W/System.err:     at com.microsoft.sampleandroid.AzureSpatialAnchorsManager.lambda$toEmptyCompletableFuture$2(AzureSpatialAnchorsManager.java:150)
05-18 12:17:32.705 5536-6286/com.microsoft.sampleandroid W/System.err:     at com.microsoft.sampleandroid.-$$Lambda$AzureSpatialAnchorsManager$8SSZbzB3fyFTuS1Rv6e_KEvy8B8.run(Unknown Source:2)
05-18 12:17:32.706 5536-6286/com.microsoft.sampleandroid W/System.err:     at java.util.concurrent.CompletableFuture$AsyncRun.run(CompletableFuture.java:1661)
        ... 3 more
05-18 12:17:32.707 5536-6286/com.microsoft.sampleandroid W/System.err: Caused by: java.util.concurrent.ExecutionException: java.lang.IllegalStateException: std::exception.Request CV: . Response CV: .
        at java.util.concurrent.FutureTask.report(FutureTask.java:123)
05-18 12:17:32.708 5536-6286/com.microsoft.sampleandroid W/System.err:     at java.util.concurrent.FutureTask.get(FutureTask.java:193)
        at com.microsoft.sampleandroid.AzureSpatialAnchorsManager.lambda$toEmptyCompletableFuture$2(AzureSpatialAnchorsManager.java:147)
05-18 12:17:32.709 5536-6286/com.microsoft.sampleandroid W/System.err:  ... 5 more
05-18 12:17:32.710 5536-6286/com.microsoft.sampleandroid W/System.err: Caused by: java.lang.IllegalStateException: std::exception.Request CV: . Response CV: .
05-18 12:17:32.711 5536-6286/com.microsoft.sampleandroid W/System.err:     at com.microsoft.azure.spatialanchors.NativeLibraryHelpers.checkStatus(NativeLibraryHelpers.java:65)
        at com.microsoft.azure.spatialanchors.CloudSpatialAnchorSession$3.call(CloudSpatialAnchorSession.java:393)
05-18 12:17:32.713 5536-6286/com.microsoft.sampleandroid W/System.err:     at com.microsoft.azure.spatialanchors.CloudSpatialAnchorSession$3.call(CloudSpatialAnchorSession.java:390)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        ... 3 more

</code>```

I just used the normal code and did nothing else

答: Check the credentials… Error occurs if trying to access with wrong credentials.</p>

Body:
I just checked out the spatial anchors demo from GitHub, changed the keys and deployed it to my Samsung S8 successfully.

But when I try to save an anchor I get an IllegalStateException:

05-18 12:17:32.667 5536-6285/com.microsoft.sampleandroid E/CBindingAutoGen: exception causing failure: std::exception
05-18 12:17:32.670 5536-6286/com.microsoft.sampleandroid W/System.err: java.util.concurrent.ExecutionException: java.lang.IllegalStateException: std::exception.Request CV: . Response CV: .
05-18 12:17:32.674 5536-6286/com.microsoft.sampleandroid W/System.err:     at java.util.concurrent.FutureTask.report(FutureTask.java:123)
05-18 12:17:32.675 5536-6286/com.microsoft.sampleandroid W/System.err:     at java.util.concurrent.FutureTask.get(FutureTask.java:193)
05-18 12:17:32.677 5536-6286/com.microsoft.sampleandroid W/System.err:     at com.microsoft.sampleandroid.AzureSpatialAnchorsManager.lambda$toEmptyCompletableFuture$2(AzureSpatialAnchorsManager.java:147)
05-18 12:17:32.680 5536-6286/com.microsoft.sampleandroid W/System.err:     at com.microsoft.sampleandroid.-$$Lambda$AzureSpatialAnchorsManager$8SSZbzB3fyFTuS1Rv6e_KEvy8B8.run(Unknown Source:2)
05-18 12:17:32.682 5536-6286/com.microsoft.sampleandroid W/System.err:     at java.util.concurrent.CompletableFuture$AsyncRun.run(CompletableFuture.java:1661)
05-18 12:17:32.684 5536-6286/com.microsoft.sampleandroid W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
05-18 12:17:32.686 5536-6286/com.microsoft.sampleandroid W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
05-18 12:17:32.687 5536-6286/com.microsoft.sampleandroid W/System.err:     at java.lang.Thread.run(Thread.java:764)
05-18 12:17:32.690 5536-6286/com.microsoft.sampleandroid W/System.err: Caused by: java.lang.IllegalStateException: std::exception.Request CV: . Response CV: .
05-18 12:17:32.692 5536-6286/com.microsoft.sampleandroid W/System.err:     at com.microsoft.azure.spatialanchors.NativeLibraryHelpers.checkStatus(NativeLibraryHelpers.java:65)
05-18 12:17:32.693 5536-6286/com.microsoft.sampleandroid W/System.err:     at com.microsoft.azure.spatialanchors.CloudSpatialAnchorSession$3.call(CloudSpatialAnchorSession.java:393)
05-18 12:17:32.695 5536-6286/com.microsoft.sampleandroid W/System.err:     at com.microsoft.azure.spatialanchors.CloudSpatialAnchorSession$3.call(CloudSpatialAnchorSession.java:390)
05-18 12:17:32.696 5536-6286/com.microsoft.sampleandroid W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:266)
05-18 12:17:32.697 5536-6286/com.microsoft.sampleandroid W/System.err:  ... 3 more
05-18 12:17:32.700 5536-6286/com.microsoft.sampleandroid W/System.err: java.util.concurrent.CompletionException: java.lang.RuntimeException: java.util.concurrent.ExecutionException: java.lang.IllegalStateException: std::exception.Request CV: . Response CV: .
05-18 12:17:32.701 5536-6286/com.microsoft.sampleandroid W/System.err:     at java.util.concurrent.CompletableFuture.encodeThrowable(CompletableFuture.java:276)
05-18 12:17:32.701 5536-6286/com.microsoft.sampleandroid W/System.err:     at java.util.concurrent.CompletableFuture.completeThrowable(CompletableFuture.java:282)
05-18 12:17:32.702 5536-6286/com.microsoft.sampleandroid W/System.err:     at java.util.concurrent.CompletableFuture$AsyncRun.run(CompletableFuture.java:1664)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
05-18 12:17:32.703 5536-6286/com.microsoft.sampleandroid W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
05-18 12:17:32.703 5536-6286/com.microsoft.sampleandroid W/System.err:     at java.lang.Thread.run(Thread.java:764)
05-18 12:17:32.704 5536-6286/com.microsoft.sampleandroid W/System.err: Caused by: java.lang.RuntimeException: java.util.concurrent.ExecutionException: java.lang.IllegalStateException: std::exception.Request CV: . Response CV: .
05-18 12:17:32.705 5536-6286/com.microsoft.sampleandroid W/System.err:     at com.microsoft.sampleandroid.AzureSpatialAnchorsManager.lambda$toEmptyCompletableFuture$2(AzureSpatialAnchorsManager.java:150)
05-18 12:17:32.705 5536-6286/com.microsoft.sampleandroid W/System.err:     at com.microsoft.sampleandroid.-$$Lambda$AzureSpatialAnchorsManager$8SSZbzB3fyFTuS1Rv6e_KEvy8B8.run(Unknown Source:2)
05-18 12:17:32.706 5536-6286/com.microsoft.sampleandroid W/System.err:     at java.util.concurrent.CompletableFuture$AsyncRun.run(CompletableFuture.java:1661)
        ... 3 more
05-18 12:17:32.707 5536-6286/com.microsoft.sampleandroid W/System.err: Caused by: java.util.concurrent.ExecutionException: java.lang.IllegalStateException: std::exception.Request CV: . Response CV: .
        at java.util.concurrent.FutureTask.report(FutureTask.java:123)
05-18 12:17:32.708 5536-6286/com.microsoft.sampleandroid W/System.err:     at java.util.concurrent.FutureTask.get(FutureTask.java:193)
        at com.microsoft.sampleandroid.AzureSpatialAnchorsManager.lambda$toEmptyCompletableFuture$2(AzureSpatialAnchorsManager.java:147)
05-18 12:17:32.709 5536-6286/com.microsoft.sampleandroid W/System.err:  ... 5 more
05-18 12:17:32.710 5536-6286/com.microsoft.sampleandroid W/System.err: Caused by: java.lang.IllegalStateException: std::exception.Request CV: . Response CV: .
05-18 12:17:32.711 5536-6286/com.microsoft.sampleandroid W/System.err:     at com.microsoft.azure.spatialanchors.NativeLibraryHelpers.checkStatus(NativeLibraryHelpers.java:65)
        at com.microsoft.azure.spatialanchors.CloudSpatialAnchorSession$3.call(CloudSpatialAnchorSession.java:393)
05-18 12:17:32.713 5536-6286/com.microsoft.sampleandroid W/System.err:     at com.microsoft.azure.spatialanchors.CloudSpatialAnchorSession$3.call(CloudSpatialAnchorSession.java:390)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        ... 3 more

I just used the normal code and did nothing else


问:
jQuery and AJAX Loading
I am making a page that when you click on a "story" it loads the text and the media for that story, I have a seperate PHP script for the story text and the media (video or image) loading. both scripts work and actually it all works.

My problem is that when you click the story it is supposed to load the text, and then slide the media down when it's loaded However, it slides down even when the text is still loading.

newspaper.nmyster.co.uk/ is the site in question. click on the vimeo story on the left and see what I mean.

The code for the AJAX that loads the story and media is:

```<code>$.ajax({
  url: './scripts/storyLoader.php?storyid='+storyId,
  success: function(result){
    $('#storycontainer').hide();
    $('#loading').remove();
    $('#storycontainer').hide(0).html(result).fadeIn(1000);
    }
});
$.ajax({
  url: './scripts/mediaLoader.php?storyid='+storyId,
  success: function(result){
    $('.martefact').hide();
    $('#loading').remove();
    $('.martefact').html(result).slideDown(1000);
    }
});
</code>```

Basically, I only want the media div to slide down once the video or image has finished loading.

Thanks

答:
Your request is asynchronous. It means that the script won't wait for data to load before executing the aesthetics bit.
You need to add async: false to your $.ajax call (look up other options over at jQuery documentation). That way, browser will wait for data to arrive first before executing the rest of JS.</p>

ContentLicense: CC BY-SA 3.0

Title: jQuery and AJAX Loading

Body:
I am making a page that when you click on a "story" it loads the text and the media for that story, I have a seperate PHP script for the story text and the media (video or image) loading. both scripts work and actually it all works.

My problem is that when you click the story it is supposed to load the text, and then slide the media down when it's loaded However, it slides down even when the text is still loading.

newspaper.nmyster.co.uk/ is the site in question. click on the vimeo story on the left and see what I mean.

The code for the AJAX that loads the story and media is:

$.ajax({
  url: './scripts/storyLoader.php?storyid='+storyId,
  success: function(result){
    $('#storycontainer').hide();
    $('#loading').remove();
    $('#storycontainer').hide(0).html(result).fadeIn(1000);
    }
});
$.ajax({
  url: './scripts/mediaLoader.php?storyid='+storyId,
  success: function(result){
    $('.martefact').hide();
    $('#loading').remove();
    $('.martefact').html(result).slideDown(1000);
    }
});

Basically, I only want the media div to slide down once the video or image has finished loading.

Thanks


问:
How to get a view from within Espresso to pass into an IdlingResource?
I essentially have a custom IdlingResource that takes a View a constructor argument. I can't find anywhere that really talks about how to implement it.

I'm trying to use this answer: https://stackoverflow.com/a/32763454/1193321

As you can see, it takes a ViewPager, but when I'm registering the IdlingResource in my test class, I'm not sure how I can get my view.

I've tried findViewById() and I've tried getting the currently running activity and then calling findViewById() on that, with no luck.

Anyone know what to do in this scenario?

答:
If you are using ActivityScenarioRule from androidx.test.ext.junit.rules (since ActivityTestRule "will be deprecated and eventually removed from library in the future"), you can get your Activity instance and call findViewById method:

```<code>import androidx.test.ext.junit.rules.activityScenarioRule
import androidx.test.ext.junit.runners.AndroidJUnit4

@RunWith(AndroidJUnit4::class) {

    @get: Rule
    var testRule = activityScenarioRule<MainActivity>()

    @Test
    fun mainTestCase() {
        testRule.scenario.onActivity { activity ->
            val view = activity.findViewById<YourView>(R.id.view)
        }
    }
}

</code>```

Body:
If you are using ActivityScenarioRule from androidx.test.ext.junit.rules (since ActivityTestRule "will be deprecated and eventually removed from library in the future"), you can get your Activity instance and call findViewById method:

import androidx.test.ext.junit.rules.activityScenarioRule
import androidx.test.ext.junit.runners.AndroidJUnit4

@RunWith(AndroidJUnit4::class) {

    @get: Rule
    var testRule = activityScenarioRule<MainActivity>()

    @Test
    fun mainTestCase() {
        testRule.scenario.onActivity { activity ->
            val view = activity.findViewById<YourView>(R.id.view)
        }
    }
}


问:
Web application hangs while calling Graph API
We have developed an asp.net web application in which we perform authentication using Azure B2C and also calling Azure Graph API to fetch additional custom attributes. I am able to successfully authenticate using OpenIDConnectMiddleware. But when I try to get the user information using Azure Graph API it hangs.

AuthenticationResult result = await authContext.AcquireTokenAsync(this.aadGraphResourceId, credential);

答:
should be like this right </p>

```<code>AuthenticationResult result = await authContext.AcquireTokenAsync(this.aadGraphResourceId, credential).ConfigureAwait(false);
</code>```

Body:
should be like this right

AuthenticationResult result = await authContext.AcquireTokenAsync(this.aadGraphResourceId, credential).ConfigureAwait(false);


答:
So here is an example:

Formula in B2:

```<code>=IFERROR(INDEX(ROW($A$1:$A$30),MATCH(0,IFERROR(MATCH(ROW($A$1:$A$30),$A$2:$A$7,0),COUNTIF($B$1:$B1,ROW($A$1:$A$30))),0)),"")
</code>```

Confirmed through CtrlShiftEnter

You can change this part ROW($A$1:$A$30) to your liking to include a larger range of numbers (or smaller) depending on the month.

Title: Finding missing numbers in a preset range

Body:
I am having a problem finding missing values within a preset range.  For example I have:

Column A: 3, 5, 7, 9, 10, 11
I want either VBA or a formula in excel to return
Column B: 1, 2, 4, 6, 8, 12, 13 --> 30

The final number in Column B will vary.  I want it to change based on user discretion.  For my problem I am working with days of the month.  So January, February, and March have different total days.  I've seen a lot of examples, but all are based on a array in the spreedsheet.  What if I want to change the array to 1-30, 1-31, or 1-28 (depending on which month I am looking at)?

Body:
So here is an example:

Formula in B2:

=IFERROR(INDEX(ROW($A$1:$A$30),MATCH(0,IFERROR(MATCH(ROW($A$1:$A$30),$A$2:$A$7,0),COUNTIF($B$1:$B1,ROW($A$1:$A$30))),0)),"")

Confirmed through CtrlShiftEnter

You can change this part ROW($A$1:$A$30) to your liking to include a larger range of numbers (or smaller) depending on the month.


问:
Anonymize html with regex
I'm trying to anonymize a HTML string with regex, for an SQL query.

https://regex101.com/r/QWt1E1/1

```<code>(?<!\<)[^<>\s](?!\>)
</code>```

```<code><p><em>Hi [User</em></p>
<p><em>Tack för visat intresse.</em></p>
<p><em>Good luck!</em><em> </em></p>
<p><em>Sincerely</em></p>
</code>```

```<code><p><em>nn nnnnn</nm></p>
<p><em>nnnn nnnnnnnn nnnnn nnnnnnnnn</nm></p>
<p><em>nnnn nnnnn</nm><em>nnnnnn</nm></p>
<p><em>nnnnnnnnn</nm></p>
</code>```

The plan was to replace every character that is not within <>, with an n.
It almost works, but in my example it replaces the e in . Not sure why and how to fix that.

How can I adjust the regex to not replace the e in the example?

答:
Negative lookahead for [^<>]*> instead of just >, to ensure that the current position is not followed by a > before any other angle brackets (because that would indicate you're currently inside a tag).

This also means that you can drop the lookbehind:

```<code>[^<>\s](?![^<>]*>)
          ^^^^^^
</code>```

https://regex101.com/r/QWt1E1/3

Still, it would be better to parse the HTML using an HTML parser, if at all possible

Title: Anonymize html with regex

Body:
I'm trying to anonymize a HTML string with regex, for an SQL query.

https://regex101.com/r/QWt1E1/1

(?<!\<)[^<>\s](?!\>)

Hi [User

Tack för visat intresse.

Good luck!

Sincerely

nn nnnnn</nm>

nnnn nnnnnnnn nnnnn nnnnnnnnn</nm>

nnnn nnnnn</nm>nnnnnn</nm>

nnnnnnnnn</nm>

The plan was to replace every character that is not within <>, with an n.
It almost works, but in my example it replaces the e in . Not sure why and how to fix that.

How can I adjust the regex to not replace the e in the example?

Body:
Negative lookahead for [^<>]*> instead of just >, to ensure that the current position is not followed by a > before any other angle brackets (because that would indicate you're currently inside a tag).

This also means that you can drop the lookbehind:

[^<>\s](?![^<>]*>)
          ^^^^^^

https://regex101.com/r/QWt1E1/3

Still, it would be better to parse the HTML using an HTML parser, if at all possible


问:
Unknown Property – yii\base\UnknownPropertyException for behavior method
I have set some properties in behavior() method and I'm getting this error

```<code>public function behaviors()
{
    return [
        'access'=>[
            'class'=> AccessControl::className(),
            'only'=>['create','update'],
            'rules'=>[
                'allow'=>true,
                'roles'=>['@'],
            ],

        ],
        'verbs' => [
            'class' => VerbFilter::className(),
            'actions' => [
                'delete' => ['POST'],
            ],
        ],
    ];
}
</code>```

please someone see it to solve

答:
Just change as per below code</p>

```<code>'access'=>[
            'class'=> AccessControl::className(),
            'rules'=>[
                'actions'=>['create','update'],
                'allow'=>true,
                'roles'=>['@'],
            ],

</code>```

Body:
I have set some properties in behavior() method and I'm getting this error

public function behaviors()
{
    return [
        'access'=>[
            'class'=> AccessControl::className(),
            'only'=>['create','update'],
            'rules'=>[
                'allow'=>true,
                'roles'=>['@'],
            ],

        ],
        'verbs' => [
            'class' => VerbFilter::className(),
            'actions' => [
                'delete' => ['POST'],
            ],
        ],
    ];
}

please someone see it to solve

Body:
Just change as per below code

'access'=>[
            'class'=> AccessControl::className(),
            'rules'=>[
                'actions'=>['create','update'],
                'allow'=>true,
                'roles'=>['@'],
            ],


问:
Create Release on GitLab with PowerShell
I try to create a powershell script which can help us to create a release on our private gitlab server.

I found this tutorial
How to create releases in GitLab?

I'm not able to figure out how I can replace the curl command with the powershell invoke-webrequest command.

I already tried multiple concepts for this. In our case we have some code files and create the package in the same repository. The package is included in the gitignore file. (That's fine for us)

Now I tried to do this

$body = @{'form'='file=@/our awesome app.app'}
Invoke-RestMethod -Headers @{ 'PRIVATE-TOKEN'='<mytoeken>' } -Uri https://scm.domain.net/api/v4/projects/19/uploads -Body $Body
```

Result:

Invoke-RestMethod : {"error":"file is invalid"}

Does anyone have a script for creating a gitlab release page with download and changelog with powershell.

I also tried release it but I'm not able to configure it for gitlab.
https://www.npmjs.com/package/release-it#gitlab-releases

答:
Below is a collection of some PowerShell snippets I have written or used for this purpose. Maybe this can help some people. Can you not create the $Body in the script also - it looks like it fails create the content from the file?

```<code># Provides code snippets for Windows Powershell to use Gitlabs API to do various tasks
# for example [ Issue management, Release creation etc.]

# https://docs.gitlab.com/ee/api/

# Variables
# modify with you own content
$glUrl = "http://<your-gitlab-url>"
$p =  "3"                                   # Project ID
$tag = "1.3"                                # Modify this to create/delete release ...
$token = "<EDIT_ME>"                        # Your access token (http://<your-gitlab-url>/profile/personal_access_tokens)
$projectsUrl = "$glUrl/api/v4/projects"     # i.e. http://<your-gitlab-url>/api/v4/projects
$pUrl = "$projectsUrl/$p"                   # i.e. http://<your-gitlab-url>/api/v4/projects/3
$releaseUrl = "$pUrl/releases"              # i.e. http://<your-gitlab-url>/api/v4/projects/3/releases
$artifactsUrl = "$pUrl/jobs/artifacts/$tag/download?job=build-standard" # i.e. Build artifacts created for $tag and the relevant job ("build-standard"; can be modified)

# Project List
$r = Invoke-RestMethod -Headers @{ 'PRIVATE-TOKEN'="$token" } -Uri $projectsUrl
$r | Sort-Object -Property id | Format-Table -Property id, name

# Issues List
$r = Invoke-RestMethod -Headers @{ 'PRIVATE-TOKEN'="$token" } -Uri $pUrl/issues
$r | Sort-Object -Property id | Format-Table -Property id, state, title

# New Issue
Invoke-RestMethod -Method Post -Headers @{ 'PRIVATE-TOKEN'="$token" } -Uri "$pUrl/issues?title=Hello from PS&labels=test"

# Comment on the Issue
Invoke-RestMethod -Method Post -Headers @{ 'PRIVATE-TOKEN'="$token" } -Uri "$pUrl/issues/3/notes?body=Hello PowerShell"

function Register-NewIssue {
    param(
        [string]$title,
        [string]$desc = '',
        [string]$uri = '$projectUrl/issues'
    )

    $title = [System.Web.HttpUtility]::UrlEncode($title)
    $desc = [System.Web.HttpUtility]::UrlEncode($desc)
    $u = "$uri`?title=$title&description=$desc"
    $r = Invoke-RestMethod -Method Post -Headers @{ 'PRIVATE-TOKEN'= "$token" } -Uri $u
    $r | Format-List -Property iid, state, title, description
}
# Get list of  Releases
Invoke-RestMethod -Method Get -Headers @{ 'PRIVATE-TOKEN'="$token" } -Uri $releaseUrl

# Create a Release
$JSON = @"
{
  "name": "New release",
  "tag_name": $tag,
  "ref": "master",
  "description": "FromPS",
  "assets":{
      "links":[
         {
            "name":"Executables",
            "url":"$artifactsUrl"
         }
      ]
   }
}
"@

Invoke-RestMethod -Method Post -Headers @{ 'PRIVATE-TOKEN'="$token"; 'Content-Type'='application/json' } -Body $JSON -Uri "$releaseUrl"
Read-Host -Prompt "Press Enter to continue"

# Adds only a link to this Release manually
$JSONLINK = @'
{"name":"awesome-exec",
 "url":"$artifactsUrl"
}
'@
Invoke-RestMethod -Method Post -Headers @{ 'PRIVATE-TOKEN'= "$token"; 'Content-Type'='application/json' } -Body $JSONLINK -Uri "$releaseUrl/$tag/assets/links"

# Delete a Release
Invoke-RestMethod -Method Delete -Headers @{ 'PRIVATE-TOKEN'= "$token" } -Uri "$releaseUrl/$tag"
</code>```

Body:
I try to create a powershell script which can help us to create a release on our private gitlab server.

I found this tutorial
How to create releases in GitLab?

I'm not able to figure out how I can replace the curl command with the powershell invoke-webrequest command.

I already tried multiple concepts for this. In our case we have some code files and create the package in the same repository. The package is included in the gitignore file. (That's fine for us)

Now I tried to do this

$body = @{'form'='file=@/our awesome app.app'}
Invoke-RestMethod -Headers @{ 'PRIVATE-TOKEN'='<mytoeken>' } -Uri https://scm.domain.net/api/v4/projects/19/uploads -Body $Body

Result:

Invoke-RestMethod : {"error":"file is invalid"}

Does anyone have a script for creating a gitlab release page with download and changelog with powershell.

I also tried release it but I'm not able to configure it for gitlab.
https://www.npmjs.com/package/release-it#gitlab-releases

Body:
Below is a collection of some PowerShell snippets I have written or used for this purpose. Maybe this can help some people. Can you not create the $Body in the script also - it looks like it fails create the content from the file?

# Provides code snippets for Windows Powershell to use Gitlabs API to do various tasks
# for example [ Issue management, Release creation etc.]

# https://docs.gitlab.com/ee/api/

# Variables
# modify with you own content
$glUrl = "http://<your-gitlab-url>"
$p =  "3"                                   # Project ID
$tag = "1.3"                                # Modify this to create/delete release ...
$token = "<EDIT_ME>"                        # Your access token (http://<your-gitlab-url>/profile/personal_access_tokens)
$projectsUrl = "$glUrl/api/v4/projects"     # i.e. http://<your-gitlab-url>/api/v4/projects
$pUrl = "$projectsUrl/$p"                   # i.e. http://<your-gitlab-url>/api/v4/projects/3
$releaseUrl = "$pUrl/releases"              # i.e. http://<your-gitlab-url>/api/v4/projects/3/releases
$artifactsUrl = "$pUrl/jobs/artifacts/$tag/download?job=build-standard" # i.e. Build artifacts created for $tag and the relevant job ("build-standard"; can be modified)

# Project List
$r = Invoke-RestMethod -Headers @{ 'PRIVATE-TOKEN'="$token" } -Uri $projectsUrl
$r | Sort-Object -Property id | Format-Table -Property id, name

# Issues List
$r = Invoke-RestMethod -Headers @{ 'PRIVATE-TOKEN'="$token" } -Uri $pUrl/issues
$r | Sort-Object -Property id | Format-Table -Property id, state, title

# New Issue
Invoke-RestMethod -Method Post -Headers @{ 'PRIVATE-TOKEN'="$token" } -Uri "$pUrl/issues?title=Hello from PS&labels=test"

# Comment on the Issue
Invoke-RestMethod -Method Post -Headers @{ 'PRIVATE-TOKEN'="$token" } -Uri "$pUrl/issues/3/notes?body=Hello PowerShell"

function Register-NewIssue {
    param(
        [string]$title,
        [string]$desc = '',
        [string]$uri = '$projectUrl/issues'
    )

    $title = [System.Web.HttpUtility]::UrlEncode($title)
    $desc = [System.Web.HttpUtility]::UrlEncode($desc)
    $u = "$uri`?title=$title&description=$desc"
    $r = Invoke-RestMethod -Method Post -Headers @{ 'PRIVATE-TOKEN'= "$token" } -Uri $u
    $r | Format-List -Property iid, state, title, description
}
# Get list of  Releases
Invoke-RestMethod -Method Get -Headers @{ 'PRIVATE-TOKEN'="$token" } -Uri $releaseUrl

# Create a Release
$JSON = @"
{
  "name": "New release",
  "tag_name": $tag,
  "ref": "master",
  "description": "FromPS",
  "assets":{
      "links":[
         {
            "name":"Executables",
            "url":"$artifactsUrl"
         }
      ]
   }
}
"@

Invoke-RestMethod -Method Post -Headers @{ 'PRIVATE-TOKEN'="$token"; 'Content-Type'='application/json' } -Body $JSON -Uri "$releaseUrl"
Read-Host -Prompt "Press Enter to continue"

# Adds only a link to this Release manually
$JSONLINK = @'
{"name":"awesome-exec",
 "url":"$artifactsUrl"
}
'@
Invoke-RestMethod -Method Post -Headers @{ 'PRIVATE-TOKEN'= "$token"; 'Content-Type'='application/json' } -Body $JSONLINK -Uri "$releaseUrl/$tag/assets/links"

# Delete a Release
Invoke-RestMethod -Method Delete -Headers @{ 'PRIVATE-TOKEN'= "$token" } -Uri "$releaseUrl/$tag"


问:
Get content inside script as text
I would like to print the content of a script tag is that possible with jquery?

index.html

```<code><script type="text/javascript">

    function sendRequest(uri, handler)
    {

    }
</script>
</code>```

Code

```<code>alert($("script")[0].???);
</code>```

result

```<code>function sendRequest(uri, handler)
{

}
</code>```

答:
You may use document.getElementsByTagName("script") to get an HTMLCollection with all scripts, then iterate it to obtain the text of each script. Obviously you can get text only for local javascript. For external script (src=) you must use an ajax call to get the text.
Using jQuery something like this:</p>

```<code>var scripts=document.getElementsByTagName("script");
for(var i=0; i<scripts.length; i++){
    script_text=scripts[i].text;
    if(script_text.trim()!==""){ // local script text
        // so something with script_text ...
    }
    else{ // external script get with src=...
        $.when($.get(scripts[i].src))
            .done(function(script_text) {
              // so something with script_text ...
            });
    }
}
</code>```

Title: Get content inside script as text

Body:
I would like to print the content of a script tag is that possible with jquery?

index.html

Code

alert($("script")[0].???);

result

function sendRequest(uri, handler)
{

}

Body:
You may use document.getElementsByTagName("script") to get an HTMLCollection with all scripts, then iterate it to obtain the text of each script. Obviously you can get text only for local javascript. For external script (src=) you must use an ajax call to get the text.
Using jQuery something like this:

var scripts=document.getElementsByTagName("script");
for(var i=0; i<scripts.length; i++){
    script_text=scripts[i].text;
    if(script_text.trim()!==""){ // local script text
        // so something with script_text ...
    }
    else{ // external script get with src=...
        $.when($.get(scripts[i].src))
            .done(function(script_text) {
              // so something with script_text ...
            });
    }
}


问:
Why is fprintf causing memory leak and behaving unpredictably when width argument is missing
The following simple program is behaving unpredictably. Sometimes it prints "0.00000", sometimes it prints more "0" than I can count. Some times it uses up all memory on the system, before the system either kills some process, or it fails with bad_alloc.

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

int main() {
  fprintf(stdout, "%.*f", 0.0);
}
</code>```

I'm aware that this is incorrect usage of fprintf. There should be another argument specifying the width of the formatting. It's just surprising that the behavior is so unpredictable. Sometimes it seems to use a default width, while sometimes it fails very badly. Could this not be made to always fail or always use some default behaviour?

I came over similar usage in some code at work, and spent a lot of time figuring out what was happening. It only seemed to happen with debug builds, but would not happen while debugging with gdb. Another curiosity is that running it through valgrind would consistently bring about the printing of many "0"s case, which otherwise happens quite seldom, but the memory usage issue would never occur then either.

I am running Red Hat Enterprise Linux 7, and compiled with gcc 4.8.5.

答:
Formally this is undefined behavior.

As for what you're observing in practice:

My guess is that fprintf ends up using an uninitialized integer as the number of decimal places to output. That's because it'll try to read a number from a location where the caller didn't write any particular value, so you'll just get whatever bits happen to be stored there. If that happens to be a huge number, fprintf will try to allocate a lot of memory to store the result string internally. That would explain the "running out of memory" part.

If the uninitialized value isn't quite that big, the allocation will succeed and you'll end up with a lot of zeroes.

And finally, if the random integer value happens to be just 5, you'll get 0.00000.

Valgrind probably consistently initializes the memory your program sees, so the behavior becomes deterministic.

Could this not be made to always fail

I'm pretty sure it won't even compile if you use gcc -pedantic -Wall -Wextra -Werror.

Body:
The following simple program is behaving unpredictably. Sometimes it prints "0.00000", sometimes it prints more "0" than I can count. Some times it uses up all memory on the system, before the system either kills some process, or it fails with bad_alloc.

#include "stdio.h"

int main() {
  fprintf(stdout, "%.*f", 0.0);
}

I'm aware that this is incorrect usage of fprintf. There should be another argument specifying the width of the formatting. It's just surprising that the behavior is so unpredictable. Sometimes it seems to use a default width, while sometimes it fails very badly. Could this not be made to always fail or always use some default behaviour?

I came over similar usage in some code at work, and spent a lot of time figuring out what was happening. It only seemed to happen with debug builds, but would not happen while debugging with gdb. Another curiosity is that running it through valgrind would consistently bring about the printing of many "0"s case, which otherwise happens quite seldom, but the memory usage issue would never occur then either.

I am running Red Hat Enterprise Linux 7, and compiled with gcc 4.8.5.


问:
Azure Storage Deleted blob still available
I have a link something like below to download my pdf from the Azure Storage

https://mycompany.blob.core.windows.net/invoice/someuniqueid.pdf

which works as intended.

My problem is when I try to delete the blob from the storage, (which will make the file unavailable if I call the link again) it still downloads the pdf.

I understand this is because of cache or something.  But how or when does the cache clears?

答:
I understand this is because of cache or something. But how or when
  does the cache clears?

Your understanding is correct. Most likely the content was cached by the browser.

The duration for which a browser caches a blob can be controlled by Cache-Control property of the blob. By setting Cache-Control property appropriately (e.g. no-cache), you can instruct a browser to cache the content accordingly.


问:
arm-gcc mktime binary size
I need to perform simple arithmetic on struct tm from time.h. I need to add or subtract seconds or minutes, and be able to normalize the structure. Normally, I'd use mktime(3) which performs this normalization as a side effect:

struct tm t = {.tm_hour=0, .tm_min=59, .tm_sec=40};
t.tm_sec += 30;
mktime(&t);
// t.tm_hour is now  1
// t.tm_min  is now  0
// t.tm_sec  is now 10
```

I'm doing this on an STM32 with 32 kB of flash, and binary gets very big. mktime(3) and the other stuff it pulls in take up 16 kB of flash--half the available space.

Is there a function in newlib that is specifically responsible for struct tm normalization? I realize that linking to a private function like that would make the code less portable.

答:
There is a validate_structure() function in newlib/libc/time/mktime.c which does a part of the job, normalizes month, day-of-month, hour, min, sec, but leaves day-of-week and day-of-year alone.

It's declared static, so you can't simply call it, but you can copy the function from the sources. (There might be licensing issues though). Or you can just reimplement it, it's quite straightforward.

The tm_wday and tm_yday is calculated later in mktime(), so you'd need the whole mess including the timezone stuff in order to have these two normalized.

The bulk of that 16kB code is related to a call to siscanf(), a variant of sscanf() without floating point support, which is (I believe) used to parse timezone and DST information in environment variables.

You can cut lots of unnecessary code by using --specs=nano.specs when linking, which would switch to simplified printf/scanf code, saving about 10kB of code in your case.

Title: arm-gcc mktime binary size

Body:
I need to perform simple arithmetic on struct tm from time.h. I need to add or subtract seconds or minutes, and be able to normalize the structure. Normally, I'd use mktime(3) which performs this normalization as a side effect:

struct tm t = {.tm_hour=0, .tm_min=59, .tm_sec=40};
t.tm_sec += 30;
mktime(&t);
// t.tm_hour is now  1
// t.tm_min  is now  0
// t.tm_sec  is now 10

I'm doing this on an STM32 with 32 kB of flash, and binary gets very big. mktime(3) and the other stuff it pulls in take up 16 kB of flash--half the available space.

Is there a function in newlib that is specifically responsible for struct tm normalization? I realize that linking to a private function like that would make the code less portable.


问:
Django shell: Model-to-string with unicode fails / fails not
can someone give me a hint why the umlaut in the model instance's name is turned to garbage once but printed correctly when the unicode() is 'print()'ed?

```<code>class Geo(Position):
    name = models.CharField(max_length = 161)

    def __unicode__(self):
        return u'%s' % self.name
</code>```

In shell:

```<code>In [10]: Geo.objects.get(pk=1)
Out[10]: <Geo: Eichst├ñtt>
In [11]: print Geo.objects.get(pk=1).__unicode__()
Eichstätt
</code>```

答:
Geo.repr() is invoked, when you print, but not unicode
EDIT: http://docs.python.org/library/functions.html#repr
Also i am not sure why parser got out underlines in the method names

Body:
can someone give me a hint why the umlaut in the model instance's name is turned to garbage once but printed correctly when the unicode() is 'print()'ed?

class Geo(Position):
    name = models.CharField(max_length = 161)

    def __unicode__(self):
        return u'%s' % self.name

In shell:

In [10]: Geo.objects.get(pk=1)
Out[10]: <Geo: Eichst├ñtt>
In [11]: print Geo.objects.get(pk=1).__unicode__()
Eichstätt


问:
How to use @Inject or @EJB in a CXF interceptor context?
Is there a way to use @Inject or @EJB in a CXF interceptor? I know I can still do a JNDI lookup but I'd rather avoid it.

I find it weird that JAX-WS handlers are managed but CXF interceptors are not. Is it possible to make them managed? I'm using annotations to add my interceptors to the endpoint (@org.apache.cxf.interceptor.InInterceptors and @org.apache.cxf.interceptor.InInterceptors), could it be handled with a configuration file?

Configuration:

Java 6

JBoss EAP 6.1 (AS 7.2)

CXF 2.6.6

答:
I have injected with the help of CDI 1.1 as below.

beans.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
      http://java.sun.com/xml/ns/javaee
      http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>
</code>```

cxf-servlet.xml

```<code><beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cxf="http://cxf.apache.org/core"
    xsi:schemaLocation="
http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="callerInfoInterceptor" class="my.CallerInfoInterceptor" />

    <cxf:bus>
        <cxf:inInterceptors>
            <ref bean="callerInfoInterceptor" />
        </cxf:inInterceptors>
        <cxf:properties>
            ......
            .....
        </cxf:properties>
    </cxf:bus>

</beans>
</code>```

CallerInfoInterceptor.java (CXF Interceptor)

```<code>public class CallerInfoInterceptor extends AbstractPhaseInterceptor<Message>  {

    @Inject CallerInfoBean callerInfo; // bean

    public CallerInfoInterceptor() {
        super(Phase.RECEIVE);
    }

    @Override
    public void handleMessage(Message message){
     ...........

     if (callerInfo == null) {
            callerInfo =
          javax.enterprise.inject.spi.CDI.current().select(CallerInfoBean.class).get();
        }
    }
</code>```

Body:
I have injected with the help of CDI 1.1 as below.

beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
      http://java.sun.com/xml/ns/javaee
      http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>

cxf-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cxf="http://cxf.apache.org/core"
    xsi:schemaLocation="
http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="callerInfoInterceptor" class="my.CallerInfoInterceptor" />

    <cxf:bus>
        <cxf:inInterceptors>
            <ref bean="callerInfoInterceptor" />
        </cxf:inInterceptors>
        <cxf:properties>
            ......
            .....
        </cxf:properties>
    </cxf:bus>

</beans>

CallerInfoInterceptor.java (CXF Interceptor)

public class CallerInfoInterceptor extends AbstractPhaseInterceptor<Message>  {

    @Inject CallerInfoBean callerInfo; // bean

    public CallerInfoInterceptor() {
        super(Phase.RECEIVE);
    }

    @Override
    public void handleMessage(Message message){
     ...........

     if (callerInfo == null) {
            callerInfo =
          javax.enterprise.inject.spi.CDI.current().select(CallerInfoBean.class).get();
        }
    }


问:
jarsigner: unable to open jar file: app-release-unsigned.apk
I am currently working on cordova project and I tried to generate key with the set of lines

```<code>keytool -genkey -v -keystore <myappname.keystore> -alias <myappname> -keyalg RSA -keysize 2048 -validity 10000
</code>```

I also generated a keystore after that I used the below line

```<code>jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore <myappname.keystore> app-release-unsigned.apk <myappname>
</code>```

but I get this issue

jarsigner: unable to open jar file: app-release-unsigned.apk

Can anyone help me with the solution. Thanks in advance.

答:
In the application root:

```<code>cd platforms/android
./gradlew assembleRelease
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore <myappname.keystore> app/build/outputs/apk/release/app-release-unsigned.apk <myappname>
</code>```

I've suppossed you are really using Cordova not Ionic.

Body:
I am currently working on cordova project and I tried to generate key with the set of lines

keytool -genkey -v -keystore <myappname.keystore> -alias <myappname> -keyalg RSA -keysize 2048 -validity 10000

I also generated a keystore after that I used the below line

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore <myappname.keystore> app-release-unsigned.apk <myappname>

but I get this issue

jarsigner: unable to open jar file: app-release-unsigned.apk

Can anyone help me with the solution. Thanks in advance.

Body:
In the application root:

cd platforms/android
./gradlew assembleRelease
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore <myappname.keystore> app/build/outputs/apk/release/app-release-unsigned.apk <myappname>

I've suppossed you are really using Cordova not Ionic.


问:
How can i have more than one buttons on action with search view?
Actually i want to make an action bar in which in should have dropdown menu , serach option,menu option and one other icon when i add drop down menu , the search bar is not on full action bar.when i click search icon the search view should be on full action bar but it only on half remaining is covered by dropdown menu

this is java code

```<code>@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.mainpage, menu);
        getMenuInflater().inflate(R.menu.android_action_bar_spinner_menu, menu);

        MenuItem item = menu.findItem(R.id.spinner);
        Spinner spinner = (Spinner) MenuItemCompat.getActionView(item);

        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.dropdown, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_search, menu);

        MenuItem search_item = menu.findItem(R.id.mi_search);

        SearchView searchView = (SearchView) search_item.getActionView();
        searchView.setFocusable(false);
        searchView.setQueryHint("Search");
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String s) {

                //clear the previous data in search arraylist if exist
                Toast.makeText(MainpageActivity.this, s, Toast.LENGTH_SHORT).show();
                     return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                Toast.makeText(MainpageActivity.this, s, Toast.LENGTH_SHORT).show();
                return false;
            }
        });

        return true;

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_alldocs) {
            // Handle the camera action
        } else if (id == R.id.nav_shared) {

        } else if (id == R.id.nav_tags) {

        } else if (id == R.id.notifications) {

        } else if (id == R.id.nav_settings) {

        }

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

</code>```

this is xml of search view menu

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="codes4.com.simplelistview.MainActivity">

    <item

        android:id="@+id/mi_search"
        android:title="search something"
        app:showAsAction="always"

        app:actionViewClass="android.support.v7.widget.SearchView"
        />

</menu>
</code>```

this is xml of dropdown menu

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/spinner"
        android:title="ActionBar Spinner"
        app:actionViewClass="android.widget.Spinner"
        android:background="#ff00"
        app:showAsAction="always"
        />
</menu>
</code>```

答:
```<code>import numpy as np
import cv2

cap = cv2.VideoCapture(0)

while(True):
     # Capture frame-by-frame
     ret, frame = cap.read()

# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

# Display the resulting frame
cv2.imshow('frame',gray)
#this line save your image into Dir
cv2.imwrite("you dir path eg. C:\", img)
if cv2.waitKey(1) & 0xFF == ord('q'):
    break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
</code>```

Body:
Actually i want to make an action bar in which in should have dropdown menu , serach option,menu option and one other icon when i add drop down menu , the search bar is not on full action bar.when i click search icon the search view should be on full action bar but it only on half remaining is covered by dropdown menu

this is java code

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.mainpage, menu);
        getMenuInflater().inflate(R.menu.android_action_bar_spinner_menu, menu);

        MenuItem item = menu.findItem(R.id.spinner);
        Spinner spinner = (Spinner) MenuItemCompat.getActionView(item);

        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.dropdown, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_search, menu);

        MenuItem search_item = menu.findItem(R.id.mi_search);

        SearchView searchView = (SearchView) search_item.getActionView();
        searchView.setFocusable(false);
        searchView.setQueryHint("Search");
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String s) {

                //clear the previous data in search arraylist if exist
                Toast.makeText(MainpageActivity.this, s, Toast.LENGTH_SHORT).show();
                     return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                Toast.makeText(MainpageActivity.this, s, Toast.LENGTH_SHORT).show();
                return false;
            }
        });

        return true;

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_alldocs) {
            // Handle the camera action
        } else if (id == R.id.nav_shared) {

        } else if (id == R.id.nav_tags) {

        } else if (id == R.id.notifications) {

        } else if (id == R.id.nav_settings) {

        }

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

this is xml of search view menu

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="codes4.com.simplelistview.MainActivity">

    <item

        android:id="@+id/mi_search"
        android:title="search something"
        app:showAsAction="always"

        app:actionViewClass="android.support.v7.widget.SearchView"
        />

</menu>

this is xml of dropdown menu

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/spinner"
        android:title="ActionBar Spinner"
        app:actionViewClass="android.widget.Spinner"
        android:background="#ff00"
        app:showAsAction="always"
        />
</menu>


问:
Add a new property to an object property
I need to write new properties for the comment property without erasing it.
This is my object now:

```<code>product:
{
  name: 'name',
  briefPDescription: 'text',
  details:
   {
     about: 'text',
     description: 'text',
     comment:
     {
         "text": 'text'
     },
     subDescription: 'text'
}
</code>```

What you need to write:

```<code>author:
{
    name: 'name',
    position: 'text',
    photo: '../avatar.png'
}
</code>```

How should it be:

```<code>product:
{
  name: 'name',
  briefPDescription: 'text',
  details:
  {
     about: 'text',
     description: 'text',
     comment:
     {
         text: ''text',
         name: 'name',
         position: 'text',
         photo: '../avatar.png'
     },
     subDescription: 'text'
}
</code>```

I did this:

```<code>product.comment = author;
</code>```

But it deleted the text property.
How can I write new properties to the comment property without erasing it?

答:
Try this:

```<code>product.details.comment = {...product.details.comment, ...author};
</code>```

For more info about the Spread operator see the documentation.

Body:
I need to write new properties for the comment property without erasing it.
This is my object now:

product:
{
  name: 'name',
  briefPDescription: 'text',
  details:
   {
     about: 'text',
     description: 'text',
     comment:
     {
         "text": 'text'
     },
     subDescription: 'text'
}

What you need to write:

author:
{
    name: 'name',
    position: 'text',
    photo: '../avatar.png'
}

How should it be:

product:
{
  name: 'name',
  briefPDescription: 'text',
  details:
  {
     about: 'text',
     description: 'text',
     comment:
     {
         text: ''text',
         name: 'name',
         position: 'text',
         photo: '../avatar.png'
     },
     subDescription: 'text'
}

I did this:

product.comment = author;

But it deleted the text property.
How can I write new properties to the comment property without erasing it?

Body:
Try this:

product.details.comment = {...product.details.comment, ...author};

For more info about the Spread operator see the documentation.


问:
codeigniter data retrieve issue?
I want to retrieve data from a table1 and I have to retrieve data from another table table2 with foreign key of table1 and display in views. How is it possible?

My controller is:

```<code>$data['products'] = $this->MProducts->getProducts($customer_id);
        foreach($data['products'] as $product){
            $cat_id = $product['category_id'];
            $data['category_name'] = $this->MCats->getCategoryById($cat_id);
        }
</code>```

My view is:

```<code>foreach ($products as $list){
        echo "<tr valign='top'>\n";
        echo "<td align='center'>".$list['name']."</td>\n";

        echo "<td align='center'>".$category_name."</td>\n";
        echo "<td align='center'>";
        echo $list['status'];
        echo "</td>\n";

        echo "<td align='center'>".$list['marked_price']."</td>\n";
        echo "<td align='center'>".$list['discount_percent']."</td>\n";
        echo "<td align='center'>";
        echo anchor('products/partner/edit/'.$list['id'],'edit');
        echo " | ";
        echo anchor('products/partner/delete/'.$list['id'],'delete');
        echo "</td>\n";
        echo "</tr>\n";
</code>```

In $category_name it gives the last value of category in all rows.

答:
You should read about joins here.

But you would do something like:

```<code>$this->db->select('products.*, category.category_name');
$this->db->join('products', 'category.category_id = products.category_id');
$this->db->where('products.customer_id', $customer_id); // i guessed this part
$this->db->get('products');
</code>```

// EDIT: also you have an mistake in your loop. It should look like this:

```<code>foreach($data['products'] as $key=>$product){
    $cat_id = $product['category_id'];
    $data['products'][$key]['category_name'] = $this->MCats->getCategoryById($cat_id);
}
</code>```

then to should each products' category in your view use this:

```<code>echo "<td align='center'>".$list['category_name']."</td>\n";
</code>```

Title: codeigniter data retrieve issue?

Body:
I want to retrieve data from a table1 and I have to retrieve data from another table table2 with foreign key of table1 and display in views. How is it possible?

My controller is:

$data['products'] = $this->MProducts->getProducts($customer_id);
        foreach($data['products'] as $product){
            $cat_id = $product['category_id'];
            $data['category_name'] = $this->MCats->getCategoryById($cat_id);
        }

My view is:

foreach ($products as $list){
        echo "
\n";
        echo "".$list['name']."	\n";

        echo "".$category_name."	\n";
        echo "";
        echo $list['status'];
        echo "	\n";

        echo "".$list['marked_price']."	\n";
        echo "".$list['discount_percent']."	\n";
        echo "";
        echo anchor('products/partner/edit/'.$list['id'],'edit');
        echo " | ";
        echo anchor('products/partner/delete/'.$list['id'],'delete');
        echo "	\n";
        echo "
\n";

In $category_name it gives the last value of category in all rows.

Body:
You should read about joins here.

But you would do something like:

$this->db->select('products.*, category.category_name');
$this->db->join('products', 'category.category_id = products.category_id');
$this->db->where('products.customer_id', $customer_id); // i guessed this part
$this->db->get('products');

// EDIT: also you have an mistake in your loop. It should look like this:

foreach($data['products'] as $key=>$product){
    $cat_id = $product['category_id'];
    $data['products'][$key]['category_name'] = $this->MCats->getCategoryById($cat_id);
}

then to should each products' category in your view use this:

echo "<td align='center'>".$list['category_name']."</td>\n";


问:
Compare multiple Lists only one time each in python
I have trouble with some code. I want my code to compare 2 Lists contained in a List of multiple Lists but only one time each.

resultList = [
    ['Student1', ['Sport', 'History']],
    ['Student2', ['Math', 'Spanish']],
    ['Student3', ['French', 'History']],
    ['Student4', ['English', 'Sport']],
]

for list1 in resultList:
    for list2 in resultList:
        i = 0
        for subject in list1[1]:
            if subject in list2[1]:
                if list2[1].index(subject) >= list1[1].index(subject):
                    i+=1
                else:
                    i+=2
        print(list1[0] + ' - ' + list2[0] + ' : ' + str(i))
```

<p>This prints :</p>

```Student1 - Student1 : 2
Student1 - Student2 : 0
Student1 - Student3 : 1
Student1 - Student4 : 1
Student2 - Student1 : 0
Student2 - Student2 : 2
Student2 - Student3 : 0
Student2 - Student4 : 0
Student3 - Student1 : 1
Student3 - Student2 : 0
Student3 - Student3 : 2
Student3 - Student4 : 0
Student4 - Student1 : 2
Student4 - Student2 : 0
Student4 - Student3 : 0
Student4 - Student4 : 2
```

<p>And i would like this result :</p>

```Student1 - Student1 : 2
Student1 - Student2 : 0
Student1 - Student3 : 1
Student1 - Student4 : 1
Student2 - Student2 : 2
Student2 - Student3 : 0
Student2 - Student4 : 0
Student3 - Student3 : 2
Student3 - Student4 : 0
Student4 - Student4 : 2
```

Thanks you for your help !

答:
version with two modified lines and two new ones, compared to the original:</p>

```<code>resultList = [
['Student1', ['Sport', 'History']],
['Student2', ['Math', 'Spanish']],
['Student3', ['French', 'History']],
['Student4', ['English', 'Sport']],
]

for index1 in range(0,len(resultList)):
    for index2 in range(index1, len(resultList)):
        i = 0
        list1 = resultList[index1]
        list2 = resultList[index2]
        for subject in list1[1]:
            if subject in list2[1]:
                if list2[1].index(subject) >= list1[1].index(subject):
                    i+=1
                else:
                    i+=2
        print(list1[0] + ' - ' + list2[0] + ' : ' + str(i))
</code>```

Body:
I have trouble with some code. I want my code to compare 2 Lists contained in a List of multiple Lists but only one time each.

resultList = [
    ['Student1', ['Sport', 'History']],
    ['Student2', ['Math', 'Spanish']],
    ['Student3', ['French', 'History']],
    ['Student4', ['English', 'Sport']],
]

for list1 in resultList:
    for list2 in resultList:
        i = 0
        for subject in list1[1]:
            if subject in list2[1]:
                if list2[1].index(subject) >= list1[1].index(subject):
                    i+=1
                else:
                    i+=2
        print(list1[0] + ' - ' + list2[0] + ' : ' + str(i))

This prints :

Student1 - Student1 : 2
Student1 - Student2 : 0
Student1 - Student3 : 1
Student1 - Student4 : 1
Student2 - Student1 : 0
Student2 - Student2 : 2
Student2 - Student3 : 0
Student2 - Student4 : 0
Student3 - Student1 : 1
Student3 - Student2 : 0
Student3 - Student3 : 2
Student3 - Student4 : 0
Student4 - Student1 : 2
Student4 - Student2 : 0
Student4 - Student3 : 0
Student4 - Student4 : 2

And i would like this result :

Student1 - Student1 : 2
Student1 - Student2 : 0
Student1 - Student3 : 1
Student1 - Student4 : 1
Student2 - Student2 : 2
Student2 - Student3 : 0
Student2 - Student4 : 0
Student3 - Student3 : 2
Student3 - Student4 : 0
Student4 - Student4 : 2

Thanks you for your help !

Body:
version with two modified lines and two new ones, compared to the original:

resultList = [
['Student1', ['Sport', 'History']],
['Student2', ['Math', 'Spanish']],
['Student3', ['French', 'History']],
['Student4', ['English', 'Sport']],
]

for index1 in range(0,len(resultList)):
    for index2 in range(index1, len(resultList)):
        i = 0
        list1 = resultList[index1]
        list2 = resultList[index2]
        for subject in list1[1]:
            if subject in list2[1]:
                if list2[1].index(subject) >= list1[1].index(subject):
                    i+=1
                else:
                    i+=2
        print(list1[0] + ' - ' + list2[0] + ' : ' + str(i))


问:
Kubernetes Container Command
I'm working with Neo4j in Kubernetes.
For a showcase, I want to fill the Neo4j in the Pods with initial data which i can do with a cypher-file, I'm having in the /bin folder using the cypher-shell.
So basically I start the container and run cat bin/initialData.cypher | bin/cypher-shell.
I've validated that this works by running it in the kubectl exec -it <pod> /bin/bash bash.
However, no matter how I try to map to the spec.container.command, it fails.
Currently my best guess is

```<code>spec:
  containers:
    command:
        - /bin/bash
        - -c
        - |
          cd bin
          ls
          cat initialData.cypher | cypher-shell
</code>```

which does not work. It displays the ls correctly but throws a connection refused afterwards, where I have no idea where its coming from.

edit: Updated

答:
You did valid spec, but with a wrong syntax.

Try like this

```<code>spec:
  containers:
    command: ["/bin/bash"]
    args: ["-c","cat import/initialData.cypher | bin/cypher-shell"]
</code>```

Update:
In your neo4j.conf you have to uncomment the lines related to using the neo4j-shell

```<code># Enable a remote shell server which Neo4j Shell clients can log in to.
dbms.shell.enabled=true
# The network interface IP the shell will listen on (use 0.0.0.0 for all interfaces).
dbms.shell.host=127.0.0.1
# The port the shell will listen on, default is 1337.
dbms.shell.port=1337
</code>```

Title: Kubernetes Container Command

Body:
I'm working with Neo4j in Kubernetes.
For a showcase, I want to fill the Neo4j in the Pods with initial data which i can do with a cypher-file, I'm having in the /bin folder using the cypher-shell.
So basically I start the container and run cat bin/initialData.cypher | bin/cypher-shell.
I've validated that this works by running it in the kubectl exec -it <pod> /bin/bash bash.
However, no matter how I try to map to the spec.container.command, it fails.
Currently my best guess is

spec:
  containers:
    command:
        - /bin/bash
        - -c
        - |
          cd bin
          ls
          cat initialData.cypher | cypher-shell

which does not work. It displays the ls correctly but throws a connection refused afterwards, where I have no idea where its coming from.

edit: Updated

Body:
You did valid spec, but with a wrong syntax.

Try like this

spec:
  containers:
    command: ["/bin/bash"]
    args: ["-c","cat import/initialData.cypher | bin/cypher-shell"]

Update:
In your neo4j.conf you have to uncomment the lines related to using the neo4j-shell

# Enable a remote shell server which Neo4j Shell clients can log in to.
dbms.shell.enabled=true
# The network interface IP the shell will listen on (use 0.0.0.0 for all interfaces).
dbms.shell.host=127.0.0.1
# The port the shell will listen on, default is 1337.
dbms.shell.port=1337


问:
TS2538 Type 'undefined' cannot be used as an index type. when check assigned to variable
I get TS error:

TypeScript error: Type 'undefined' cannot be used as an index type.  TS2538

For this simple function (getting object from array based on provided index):

const myArr: Array<object> = [{name: 'John'}, {name: 'Tom'}]

function getData(index?: number) {
    const isIndex : boolean = typeof index !== 'undefined';

    return isIndex ? myArr[index] : {};
}
```

<p>What's more mysterious for me is that when I change it to:</p>

```function getData(index?: number) {
    return typeof index !== 'undefined' ? myArr[index] : {};
}
```

Everything works like a charm - why?

答:
Type guards don't work with intermediate variables. You have to directly test the variable:

```<code>function getData(index?: number) {
  return index !== undefined ? myArr[index] : {};
}
</code>```

Or:

```<code>function getData(index?: number) {
  if (index === undefined)
    return {};
  return myArr[index]
}
</code>```

See also: documentation from the handbook on type guards.

Notice: typeof index !== 'undefined' is not required nowadays: ES2015/2016 way of 'typeof varName === 'undefined`?

Body:
I get TS error:

TypeScript error: Type 'undefined' cannot be used as an index type.  TS2538

For this simple function (getting object from array based on provided index):

const myArr: Array<object> = [{name: 'John'}, {name: 'Tom'}]

function getData(index?: number) {
    const isIndex : boolean = typeof index !== 'undefined';

    return isIndex ? myArr[index] : {};
}

What's more mysterious for me is that when I change it to:

function getData(index?: number) {
    return typeof index !== 'undefined' ? myArr[index] : {};
}

Everything works like a charm - why?

Body:
Type guards don't work with intermediate variables. You have to directly test the variable:

function getData(index?: number) {
  return index !== undefined ? myArr[index] : {};
}

Or:

function getData(index?: number) {
  if (index === undefined)
    return {};
  return myArr[index]
}

See also: documentation from the handbook on type guards.

Notice: typeof index !== 'undefined' is not required nowadays: ES2015/2016 way of 'typeof varName === 'undefined`?


问:
Swift.Streaming audio from url with error code -999 "cancelled"
This is my code :

```<code>var playering = AVPlayer()

private func streamAudio(url: String) {
    guard let url = URL(string: url) else {return}
    let playerItems = AVPlayerItem(url: url)
    ReportVC.playering = AVPlayer(playerItem: playerItems)
    ReportVC.playering.play()
}
</code>```

and i call streamAudio in viewDidLoad() method like this :

```<code>self.streamAudio(url: "https://stage.careandcarers.com/file/get/0b710400-4454-4a46-9ed5-8a542f046ed8.m4a")
</code>```

but i get this error in console :

2019-05-29 12:19:32.940076+0430 CC[13305:463451] Task <314067AD-725A-4C8E-820A-18D0A9351624>.<1> load failed with error Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo={NSErrorFailingURLStringKey=https://stage.careandcarers.com/file/get/0b710400-4454-4a46-9ed5-8a542f046ed8.m4a, NSErrorFailingURLKey=https://stage.careandcarers.com/file/get/0b710400-4454-4a46-9ed5-8a542f046ed8.m4a, _NSURLErrorRelatedURLSessionTaskErrorKey=(
      "LocalDataTask <314067AD-725A-4C8E-820A-18D0A9351624>.<1>"
  ), _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <314067AD-725A-4C8E-820A-18D0A9351624>.<1>, NSLocalizedDescription=cancelled} [-999]
  2019-05-29 12:19:32.943557+0430 CC[13305:460502] Task <314067AD-725A-4C8E-820A-18D0A9351624>.<1> finished with error - code: -999
  2019-05-29 12:19:32.943604+0430 CC[13305:461457] TIC Read Status [5:0x0]: 1:57

what is the problem?

答:
try it:

```<code>func streamPlay(streamUrl : string){
let playerItem = AVPlayerItem( url:NSURL( string: streamUrl )! as URL )
        player = AVPlayer(playerItem:playerItem)
        player!.rate = 1.0;
        //isplay is a bool variable that indicate your stream playing is in process or not(default value = false)
        if isPlay{

            player!.pause()
            //playDemo is button that you use to stream play
            playDemo!.setImage(UIImage(named: "playBtn"), for: UIControl.State.normal)
            playDemo!.setTitle("Pause", for: UIControl.State.normal)
            isPlay = false

        }else{

            player!.play()
            playDemo!.setImage(UIImage(named: "media_pause"), for: UIControl.State.normal)
            playDemo!.setTitle("play", for: UIControl.State.normal)
            isPlay = true
        }
}
</code>```

in your viewDidLoad:

```<code> let url = "https://stage.careandcarers.com/file/get/0b710400-4454-4a46-9ed5-8a542f046ed8.m4a"
 streamPlay(streamUrl : url)
</code>```

Body:
This is my code :

var playering = AVPlayer()

private func streamAudio(url: String) {
    guard let url = URL(string: url) else {return}
    let playerItems = AVPlayerItem(url: url)
    ReportVC.playering = AVPlayer(playerItem: playerItems)
    ReportVC.playering.play()
}

and i call streamAudio in viewDidLoad() method like this :

self.streamAudio(url: "https://stage.careandcarers.com/file/get/0b710400-4454-4a46-9ed5-8a542f046ed8.m4a")

but i get this error in console :

2019-05-29 12:19:32.940076+0430 CC[13305:463451] Task <314067AD-725A-4C8E-820A-18D0A9351624>.<1> load failed with error Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo={NSErrorFailingURLStringKey=https://stage.careandcarers.com/file/get/0b710400-4454-4a46-9ed5-8a542f046ed8.m4a, NSErrorFailingURLKey=https://stage.careandcarers.com/file/get/0b710400-4454-4a46-9ed5-8a542f046ed8.m4a, _NSURLErrorRelatedURLSessionTaskErrorKey=(
      "LocalDataTask <314067AD-725A-4C8E-820A-18D0A9351624>.<1>"
  ), _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <314067AD-725A-4C8E-820A-18D0A9351624>.<1>, NSLocalizedDescription=cancelled} [-999]
  2019-05-29 12:19:32.943557+0430 CC[13305:460502] Task <314067AD-725A-4C8E-820A-18D0A9351624>.<1> finished with error - code: -999
  2019-05-29 12:19:32.943604+0430 CC[13305:461457] TIC Read Status [5:0x0]: 1:57

what is the problem?

Body:
try it:

func streamPlay(streamUrl : string){
let playerItem = AVPlayerItem( url:NSURL( string: streamUrl )! as URL )
        player = AVPlayer(playerItem:playerItem)
        player!.rate = 1.0;
        //isplay is a bool variable that indicate your stream playing is in process or not(default value = false)
        if isPlay{

            player!.pause()
            //playDemo is button that you use to stream play
            playDemo!.setImage(UIImage(named: "playBtn"), for: UIControl.State.normal)
            playDemo!.setTitle("Pause", for: UIControl.State.normal)
            isPlay = false

        }else{

            player!.play()
            playDemo!.setImage(UIImage(named: "media_pause"), for: UIControl.State.normal)
            playDemo!.setTitle("play", for: UIControl.State.normal)
            isPlay = true
        }
}

in your viewDidLoad:

 let url = "https://stage.careandcarers.com/file/get/0b710400-4454-4a46-9ed5-8a542f046ed8.m4a"
 streamPlay(streamUrl : url)


问:
Is there a way to get the timestamp of each call from a callstack?
I'd like to use the callstack of a function call when an exception is thrown to get an accurate timelime.
I know that from a callstack I can get for each call its name and its caller name + line + file. But is it possible to know the timestamp for each called function ?

    function callA() {
        callB();
    }

    function callB() {
        callC();
    }

    function callC() {
        throw new Error('Boom');
    }
```

<p>What chrome console prints is:</p>

```Uncaught Error: Boom
    at callC (<anonymous>:13:8)
    at callB (<anonymous>:8:2)
    at callA (<anonymous>:3:2)
    at <anonymous>:1:1
```

<p>What I'd like to work with in my js code would be something like :</p>

```Uncaught Error: Boom
    at callC (<anonymous>:13:8) timestamp : 1559117311448
    at callB (<anonymous>:8:2) timestamp : 1559117311449
    at callA (<anonymous>:3:2) timestamp : 1559117311449
    at <anonymous>:1:1
```

答:
Math.floor(Date.now() / 1000) for seconds from Jan 1, 1970. Or a precise time duration type (start to end) performance.now()

function callA() {
  console.log(performance.now());
  callB();
  console.log(performance.now());
}

function callB() {
  let t0 = performance.now();
  callC();
  let t1 = performance.now();
  console.log(`Start: ${t0} End: ${t1}`);
}

function callC() {
  throw new Error('Boom');
  console.log(Math.floor(Date.now() / 1000))
}```

Body:
I'd like to use the callstack of a function call when an exception is thrown to get an accurate timelime.
I know that from a callstack I can get for each call its name and its caller name + line + file. But is it possible to know the timestamp for each called function ?

    function callA() {
        callB();
    }

    function callB() {
        callC();
    }

    function callC() {
        throw new Error('Boom');
    }

What chrome console prints is:

Uncaught Error: Boom
    at callC (<anonymous>:13:8)
    at callB (<anonymous>:8:2)
    at callA (<anonymous>:3:2)
    at <anonymous>:1:1

What I'd like to work with in my js code would be something like :

Uncaught Error: Boom
    at callC (<anonymous>:13:8) timestamp : 1559117311448
    at callB (<anonymous>:8:2) timestamp : 1559117311449
    at callA (<anonymous>:3:2) timestamp : 1559117311449
    at <anonymous>:1:1


问:
devise rails - customizing error handling and views
Using rails 3 , devise 1.2
What should a customized sign up view look like? The default is this:

```<code>%h2 Sign Up
= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f|
</code>```

= devise_error_messages!

can i replace resource with something like User model?
And how are errors handled? I read that devise.error_messages should not be used as its just a stub. Very new to rails and devise, so all suggestions/simple solutions welcome.

答:
The devise_error_message is just an helper to check all #errors in your resource. So you just need define you own view of managing your errors. By exemple the simplest is :</p>

```<code>- unless @user.errors.empty?
  %ul
    - @user.errors.each do |error|
      %li= error.full_message
</code>```

Body:
Using rails 3 , devise 1.2
What should a customized sign up view look like? The default is this:

%h2 Sign Up
= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f|

= devise_error_messages!

can i replace resource with something like User model?
And how are errors handled? I read that devise.error_messages should not be used as its just a stub. Very new to rails and devise, so all suggestions/simple solutions welcome.

Body:
The devise_error_message is just an helper to check all #errors in your resource. So you just need define you own view of managing your errors. By exemple the simplest is :

- unless @user.errors.empty?
  %ul
    - @user.errors.each do |error|
      %li= error.full_message


答:
You can use the spread operator syntax, to a) keep all the value that were already inside product.details.comment, and b) to add the values of author:

var product = {
  name: 'name',
  briefPDescription: 'text',
  details: {
    about: 'text',
    description: 'text',
    comment: {
      "text": 'text'
    },
    subDescription: 'text'
  }
}

var author = {
  name: 'name',
  position: 'text',
  photo: '../avatar.png'
}

product.details.comment = { ...product.details.comment, ...author}

console.log(product)```

Title: Add a new property to an object property


问:
Socket.io - Is there a way to save socketid to prevent a new one being generated
After a connection to the socket.io server a socket.id is given for the connection. When the socket connection has not been used after some time a new socket id is generated.

I have read a lot of tutorials that do a "hello world" connection that just gets you connected, but, there is not much literature on messaging peer-to-peer/group. The docs give a 3 line paragraph on rooms/namespaces and every question related to this is just given a link to the same 3 line paragraph.

I understand that you can create and object/array of chats(in this example). For this example, let's say it is an object. That Object looks something like this:

```<code>const connections = {
  "randomSocketID1": {
    recipient: "Mom",
    messages: [Array of Objects]
    //more information
    }
}
</code>```

I then send a message to randomSocketID1 --> 'Hello'. Then next day I want to send another message to "Mom". Is that socketID going to be the same OR AT LEAST will "randomSocketID1" be updated under the hood, to its updated ID(which sounds improbable)? Is the regeneration of the socketID a product of garbage collection or a socket/engine/websocket protocol?

thanks for any clarification

答:
So I was still unable to find an actual answer to this and by the 0 responses i see that no one knows. So what I have done in order to make sure that user and socket id are maintained is whenever a user enters the component that connects to the socketio server an automatic 'update-user' is emitted and the back end then just finds the user and assigns it the value.

So I have something like this:

chat.component.ts:

```<code>ngOnInit(){
  this.socket.emit('update-user', 'Ctfrancia');
}
</code>```

then in the back end:

```<code>const users = {};

io.on('connection', socket => {
  socket.on('update-user', user => {
    if (user in users) users[user] = socket.id;
    else users[user] = socket.id
  });
});
</code>```

Body:
After a connection to the socket.io server a socket.id is given for the connection. When the socket connection has not been used after some time a new socket id is generated.

I have read a lot of tutorials that do a "hello world" connection that just gets you connected, but, there is not much literature on messaging peer-to-peer/group. The docs give a 3 line paragraph on rooms/namespaces and every question related to this is just given a link to the same 3 line paragraph.

I understand that you can create and object/array of chats(in this example). For this example, let's say it is an object. That Object looks something like this:

const connections = {
  "randomSocketID1": {
    recipient: "Mom",
    messages: [Array of Objects]
    //more information
    }
}

I then send a message to randomSocketID1 --> 'Hello'. Then next day I want to send another message to "Mom". Is that socketID going to be the same OR AT LEAST will "randomSocketID1" be updated under the hood, to its updated ID(which sounds improbable)? Is the regeneration of the socketID a product of garbage collection or a socket/engine/websocket protocol?

thanks for any clarification

Body:
So I was still unable to find an actual answer to this and by the 0 responses i see that no one knows. So what I have done in order to make sure that user and socket id are maintained is whenever a user enters the component that connects to the socketio server an automatic 'update-user' is emitted and the back end then just finds the user and assigns it the value.

So I have something like this:

chat.component.ts:

ngOnInit(){
  this.socket.emit('update-user', 'Ctfrancia');
}

then in the back end:

const users = {};

io.on('connection', socket => {
  socket.on('update-user', user => {
    if (user in users) users[user] = socket.id;
    else users[user] = socket.id
  });
});


问:
How to replace all dots in a string using JavaScript
I want to replace all the occurrences of a dot(.) in a JavaScript string

For example, I have:

```<code>var mystring = 'okay.this.is.a.string';
</code>```

I want to get: okay this is a string.

So far I tried:

```<code>mystring.replace(/./g,' ')
</code>```

but this ends up with all the string replaced to spaces.

答:
```<code>mystring.replace(new RegExp('.', "g"), ' ');
</code>```

Body:
I want to replace all the occurrences of a dot(.) in a JavaScript string

For example, I have:

var mystring = 'okay.this.is.a.string';

I want to get: okay this is a string.

So far I tried:

mystring.replace(/./g,' ')

but this ends up with all the string replaced to spaces.