问:
Filling 2d Array from lists
I have a file which contains the following data :

```<code>4
5
0 2

0 1 0.6
0 2 0.2
0 3 0.5
1 3 0.8
2 3 0.3
</code>```

the first line is the nodes number, the second line is edges number and the 3rd line contains the nodes with special constraints.

However, I used this code to read it from the file into two lists,values and nodes, where values list contain the edges ( for example: 0 1 0.6), while the nodes list contain the values of the 3 lines ( 4 , 5, {0,2} ) respectively.

I need to construct two arrays one is an equivalent to adjacency matrix which is like this

```<code>int graph[][] = {
            {0, 6, 2, 5},
            {6, 0, 0, 8},
            {2, 0, 0, 3},
            {5, 8, 3, 0}
        };
</code>```

and the other array is the special nodes id, i.e.,

```<code>int  special [] ={0,2};
</code>```

I can read the values from a file and separate them into two lists nodes and values in the following shape:
nodes list contains : 4 ,5 ,0 ,2
values list contains : 0,1,0.6,0,2,0.2,0,3,0.5,1,3,0.8,2,3,0.3

I declared a two dimensional array  called graph2 in order to hold the values that came from the lists. But the problem is I cannot find the relationship to populate data from values list to fit in the graph2 2d array. It must to be like the graph array but its initialization would be dynamic from that file.

So, basically what I need is to create two arrays: one is like the graph array( 2d array) and the other one is like special array( 1d ). Based on the file I must do that. Thanks in advance

My code:

```<code>List<Double> values = new ArrayList<>();
        List<Integer> nodes = new ArrayList<>();
        int c = 0;
        File file = new File("text.txt");
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String text = null;

            while ((text = reader.readLine()) != null) {
                if (c <= 2) {

                    String[] str = text.split(" ");
                    for (int i = 0; i < str.length; i++) {
                        if (str[i].trim().length() > 0) {
                            nodes.add(Integer.parseInt(str[i]));
                        }
                    }
                    c++;
                } else {

                    String[] str = text.split(" ");
                    for (int i = 0; i < str.length; i++) {
                        if (str[i].trim().length() > 0) {
                            values.add(Double.parseDouble(str[i]));
                        }
                    }
                }

            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                System.out.print(e);
            }
        }
        double graph2 [] []  =new double [nodes.get(0)][nodes.get(0)];
</code>```

答:
The following code will create the 2D array from your file (not the adjacency map that you can then easily create yourself)

nodes will only contain the special nodes and graph2 will contains the edges descriptors.

(NB: I did not test it so tell me if something goes wrong)

```<code>List<Double> values = new ArrayList<>();
List<Integer> nodes = new ArrayList<>();
int c = 0;
File file = new File("text.txt");
BufferedReader reader = null;

double[][] graph2 = null;

try {
    reader = new BufferedReader(new FileReader(file));
    String text = null;
    while ((text = reader.readLine()) != null) {
        // The first line gives the number of nodes (You will use to create the int[][] graph = new int[nOfNodes][nOfNodes];)
        if (c == 0) {
            numberOfNodes = Integer.parseInt(text.trim());
        }
        // The second one gives the number of edges
        else if (c == 1) {
            nOfEdges = Integer.parseInt(text.trim());
            graph2 = new double[nOfEdges][3];
        }
        // And third the list of special nodes
        // `nodes` will now contains only your special constrained one
        else if (c == 2) {
            String[] str = text.split(" ");
            for (int i = 0; i < str.length; i++) {
                if (str[i].trim().length() > 0) {
                    nodes.add(Integer.parseInt(str[i]));
                }
            }
        } else { // Then you have your edges descriptors
            String[] str = text.split(" ");
            for (int i = 0; i < str.length; i++) {
                if (str[i].trim().length() > 0) {
                     graph2[c-4][i] = Double.parseDouble(str[i]);
                }
            }
        }
        c++;
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        if (reader != null) {
            reader.close();
        }
    } catch (IOException e) {
        System.out.print(e);
    }
}
</code>```

Then to create your graph you can initialize it to zeros and then loop over graph2 to populate it.

Title: Filling 2d Array from lists

Body:
I have a file which contains the following data :

4
5
0 2

0 1 0.6
0 2 0.2
0 3 0.5
1 3 0.8
2 3 0.3

the first line is the nodes number, the second line is edges number and the 3rd line contains the nodes with special constraints.

However, I used this code to read it from the file into two lists,values and nodes, where values list contain the edges ( for example: 0 1 0.6), while the nodes list contain the values of the 3 lines ( 4 , 5, {0,2} ) respectively.

I need to construct two arrays one is an equivalent to adjacency matrix which is like this

int graph[][] = {
            {0, 6, 2, 5},
            {6, 0, 0, 8},
            {2, 0, 0, 3},
            {5, 8, 3, 0}
        };

and the other array is the special nodes id, i.e.,

int  special [] ={0,2};

I can read the values from a file and separate them into two lists nodes and values in the following shape:
nodes list contains : 4 ,5 ,0 ,2
values list contains : 0,1,0.6,0,2,0.2,0,3,0.5,1,3,0.8,2,3,0.3

I declared a two dimensional array  called graph2 in order to hold the values that came from the lists. But the problem is I cannot find the relationship to populate data from values list to fit in the graph2 2d array. It must to be like the graph array but its initialization would be dynamic from that file.

So, basically what I need is to create two arrays: one is like the graph array( 2d array) and the other one is like special array( 1d ). Based on the file I must do that. Thanks in advance

My code:

List<Double> values = new ArrayList<>();
        List<Integer> nodes = new ArrayList<>();
        int c = 0;
        File file = new File("text.txt");
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String text = null;

            while ((text = reader.readLine()) != null) {
                if (c <= 2) {

                    String[] str = text.split(" ");
                    for (int i = 0; i < str.length; i++) {
                        if (str[i].trim().length() > 0) {
                            nodes.add(Integer.parseInt(str[i]));
                        }
                    }
                    c++;
                } else {

                    String[] str = text.split(" ");
                    for (int i = 0; i < str.length; i++) {
                        if (str[i].trim().length() > 0) {
                            values.add(Double.parseDouble(str[i]));
                        }
                    }
                }

            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                System.out.print(e);
            }
        }
        double graph2 [] []  =new double [nodes.get(0)][nodes.get(0)];

Body:
The following code will create the 2D array from your file (not the adjacency map that you can then easily create yourself)

nodes will only contain the special nodes and graph2 will contains the edges descriptors.

(NB: I did not test it so tell me if something goes wrong)

List<Double> values = new ArrayList<>();
List<Integer> nodes = new ArrayList<>();
int c = 0;
File file = new File("text.txt");
BufferedReader reader = null;

double[][] graph2 = null;

try {
    reader = new BufferedReader(new FileReader(file));
    String text = null;
    while ((text = reader.readLine()) != null) {
        // The first line gives the number of nodes (You will use to create the int[][] graph = new int[nOfNodes][nOfNodes];)
        if (c == 0) {
            numberOfNodes = Integer.parseInt(text.trim());
        }
        // The second one gives the number of edges
        else if (c == 1) {
            nOfEdges = Integer.parseInt(text.trim());
            graph2 = new double[nOfEdges][3];
        }
        // And third the list of special nodes
        // `nodes` will now contains only your special constrained one
        else if (c == 2) {
            String[] str = text.split(" ");
            for (int i = 0; i < str.length; i++) {
                if (str[i].trim().length() > 0) {
                    nodes.add(Integer.parseInt(str[i]));
                }
            }
        } else { // Then you have your edges descriptors
            String[] str = text.split(" ");
            for (int i = 0; i < str.length; i++) {
                if (str[i].trim().length() > 0) {
                     graph2[c-4][i] = Double.parseDouble(str[i]);
                }
            }
        }
        c++;
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        if (reader != null) {
            reader.close();
        }
    } catch (IOException e) {
        System.out.print(e);
    }
}

Then to create your graph you can initialize it to zeros and then loop over graph2 to populate it.


来源: stackexchange

问:
DIV height like having some text inside
On one of my web pages I have a DIV element, containing string of text inside, which is of, say, 1.1em size. For example:

```<code><div id="displaydiv">
    <b>Hello World</b>
</div>
</code>```

Another page has the same DIV element, but with no text inside it at all. And that's why this DIV has the visual height of less value than the one on the first page.

```<code><div id="displaydiv">

</div>
</code>```

What is the recommended way of keeping the DIV element on the second page of the same height as on the first one?

答:
Try putting an   inside.

If the page is dynamically generated and your template language supports conditionals, make sure only to show the   when there's no content.

Otherwise, if you can't show it only when empty, to avoid messing up your text alignment (thanks to @bensiu for pointing this out), stick the   at the end of the string (or beginning if the text is right-aligned). If it's center-aligned, you can put an   on both ends.

ContentLicense: CC BY-SA 2.5

Title: DIV height like having some text inside

Body:
On one of my web pages I have a DIV element, containing string of text inside, which is of, say, 1.1em size. For example:

    Hello World

Another page has the same DIV element, but with no text inside it at all. And that's why this DIV has the visual height of less value than the one on the first page.

What is the recommended way of keeping the DIV element on the second page of the same height as on the first one?

Body:
Try putting an &nbsp; inside.

If the page is dynamically generated and your template language supports conditionals, make sure only to show the &nbsp; when there's no content.

Otherwise, if you can't show it only when empty, to avoid messing up your text alignment (thanks to @bensiu for pointing this out), stick the &nbsp; at the end of the string (or beginning if the text is right-aligned). If it's center-aligned, you can put an &nbsp; on both ends.


问:
Determining Multiple of the Closest Pairs in Plane
When determining the closest pair of vertices in a plane with the sweep algorithm outlined below, is it possible to determine multiple pairs without additional runs?

Sort points according to their x-coordinates.

Split the set of points into two equal-sized subsets by a vertical line x=xmid.
Solve the problem recursively in the left and right subsets. This yields the left-side and right-side minimum distances dLmin and dRmin, respectively.

Find the minimal distance dLRmin among the set of pairs of points in which one point lies on the left of the dividing vertical and the other point lies to the right.

The final answer is the minimum among dLmin, dRmin, and dLRmin.

答:
You need to store the equal Closest Pairs in a separate list.

Whenever you compare two distances, you must compare the shortest to that in the separate list.

If shorter, empty the list.

If equal, append to the list (possibly both pairs).

Using a constant-time store, this will not degrade the algorithm complexity.

ContentLicense: CC BY-SA 3.0


问:
How to tell what triggered jQuery focus()?
I have an input field and a button. It is necessary that when the button is clicked the input field gets focus.

I need the behaviour to be slightly different depending on whether the input field was focused manually by the user or if it was focused due the button being clicked.

It seems this would be relatively simple, but I couldn't come up with a solution so far. Any ideas very welcome.

```<code>$("button").click(function() {
    target_input = $("input");
    target_input.focus();
});

$("input").focus(function() {
    // if focus done manually by user
    //    do something
    // if focus done via button
    //    do something else
});
</code>```

答:
Here is a solution that uses no extra variables, instead it checks the event.

```<code>$("button").click(function() {
    target_input = $("input");
    target_input.focus();
});

$("input").focus(function(e) {
    // if focus done manually by user
    //    do something
    // if focus done via button
    //    do something else

   if(e.originalEvent.relatedTarget){
      // only from button events
   }

   // here is from all events
});
</code>```

this e.originalEvent.relatedTarget will return null if we didn't use the button to originate the focus.
remember to add e to the function.

Body:
I have an input field and a button. It is necessary that when the button is clicked the input field gets focus.

I need the behaviour to be slightly different depending on whether the input field was focused manually by the user or if it was focused due the button being clicked.

It seems this would be relatively simple, but I couldn't come up with a solution so far. Any ideas very welcome.

$("button").click(function() {
    target_input = $("input");
    target_input.focus();
});

$("input").focus(function() {
    // if focus done manually by user
    //    do something
    // if focus done via button
    //    do something else
});

Body:
Here is a solution that uses no extra variables, instead it checks the event.

$("button").click(function() {
    target_input = $("input");
    target_input.focus();
});

$("input").focus(function(e) {
    // if focus done manually by user
    //    do something
    // if focus done via button
    //    do something else

   if(e.originalEvent.relatedTarget){
      // only from button events
   }

   // here is from all events
});

this e.originalEvent.relatedTarget will return null if we didn't use the button to originate the focus.
remember to add e to the function.


问:
Docker port 80:80 127.0.0.1
Im having a huge issue and I can't get round it

Basically i went through the Laravel installation and installed homestead 7 and im using virtual box... vagrant

Now before this I'm using docker to run other application through it... which worked and it looks like something i've done is using the same port so I now cant use docker on that port

Cannot start service website: driver failed programming external connectivity on endpoint distinctly_website_1 (edc81f653cb3ac8c2af9b7ce070d0a0ccbb3ec255af452338ff4677ce99b156a): Error starting userland proxy: Bind for 0.0.0.0:80: unexpected error (Failure EADDRINUSE)
  ERROR: Encountered errors while bringing up the project.

I just need some help with removing this conflict with the port so I can run my docker applications. I dont care about anything than docker

答:
Just an update found a solution

```<code>sudo apachectl stop
</code>```

this stopped the service that was conflicting and i can now use my docker image

Title: Docker port 80:80 127.0.0.1

Body:
Just an update found a solution

sudo apachectl stop

this stopped the service that was conflicting and i can now use my docker image


问:
Type conversion error from LabeledPoint in pyspark.mllib, for using linear regression model in pyspark.ml
I have the following code for linear regression using pyspark.ml package. However I get this error message for the last line, when the model is being fit:

IllegalArgumentException: u'requirement failed: Column features must
  be of type org.apache.spark.ml.linalg.VectorUDT@3bfc3ba7 but was
  actually org.apache.spark.mllib.linalg.VectorUDT@f71b0bce.

Does anyone has an idea what is missing?
Is there any replacement in pyspark.ml for LabeledPoint in pyspark.mllib?

```<code>from pyspark import SparkContext
from pyspark.ml.regression import LinearRegression
from pyspark.mllib.regression import LabeledPoint
import numpy as np
from pandas import *

data = sc.textFile("/FileStore/tables/w7baik1x1487076820914/randomTableSmall.csv")

def parsePoint(line):
    values = [float(x) for x in line.split(',')]
    return LabeledPoint(values[1], [values[0]])

points_df = data.map(parsePoint).toDF()

lr = LinearRegression()

model = lr.fit(points_df, {lr.regParam:0.0})
</code>```

答:
Spark newer versions don't accept spark.mllib.linalg.VectorUDT (you do not need to get it from mllib.linalg).

try to replace

from pyspark.mllib.regression import LabeledPoint

by:

from pyspark.ml.linalg import Vectors

Body:
I have the following code for linear regression using pyspark.ml package. However I get this error message for the last line, when the model is being fit:

IllegalArgumentException: u'requirement failed: Column features must
  be of type org.apache.spark.ml.linalg.VectorUDT@3bfc3ba7 but was
  actually org.apache.spark.mllib.linalg.VectorUDT@f71b0bce.

Does anyone has an idea what is missing?
Is there any replacement in pyspark.ml for LabeledPoint in pyspark.mllib?

from pyspark import SparkContext
from pyspark.ml.regression import LinearRegression
from pyspark.mllib.regression import LabeledPoint
import numpy as np
from pandas import *

data = sc.textFile("/FileStore/tables/w7baik1x1487076820914/randomTableSmall.csv")

def parsePoint(line):
    values = [float(x) for x in line.split(',')]
    return LabeledPoint(values[1], [values[0]])

points_df = data.map(parsePoint).toDF()

lr = LinearRegression()

model = lr.fit(points_df, {lr.regParam:0.0})


问:
OpenMP parallelizing matrix multiplication by a triple for loop (performance issue)
I'm writing a program for matrix multiplication with OpenMP, that, for cache convenience, implements the multiplication A x B(transpose) rows X rows instead of the classic A x B rows x columns, for better cache efficiency. Doing this I faced an interesting fact that for me is illogic: if in this code i parallelize the extern loop the program is slower than if I put the OpenMP directives in the most inner loop, in my computer the times are 10.9 vs 8.1 seconds.

//A and B are double* allocated with malloc, Nu is the lenght of the matrixes
//which are square

//#pragma omp parallel for
for (i=0; i<Nu; i++){
  for (j=0; j<Nu; j++){
    *(C+(i*Nu+j)) = 0.;
#pragma omp parallel for
    for(k=0;k<Nu ;k++){
      *(C+(i*Nu+j))+=*(A+(i*Nu+k)) * *(B+(j*Nu+k));//C(i,j)=sum(over k) A(i,k)*B(k,j)
    }
  }
}
```

答:
You could probably have some dependencies in the data when you parallelize the outer loop and compiler is not able to figure it out and adds additional locks.

Most probably it decides that different outer loop iterations could write into the same (C+(i*Nu+j)) and it adds access locks to protect it.

Compiler could probably figure out that there are no dependencies if you'll parallelize the 2nd loop. But figuring out that there are no dependencies parallelizing the outer loop is not so trivial for a compiler.

UPDATE

Some performance measurements.

Hi again. It looks like 1000 double * and + is not enough to cover the cost of threads synchronization.

I've done few small tests and simple vector scalar multiplication is not effective with openmp unless the number of elements is less than ~10'000. Basically, larger your array is, more performance will you get from using openmp.

So parallelizing the most inner loop you'll have to separate task between different threads and gather data back 1'000'000 times.

PS. Try Intel ICC, it is kinda free to use for students and open source projects. I remember being using openmp for smaller that 10'000 elements arrays.

UPDATE 2: Reduction example

    double sum = 0.0;
    int k=0;
    double *al = A+i*Nu;
    double *bl = A+j*Nu;
    #pragma omp parallel for shared(al, bl) reduction(+:sum)
    for(k=0;k<Nu ;k++){
        sum +=al[k] * bl[k]; //C(i,j)=sum(over k) A(i,k)*B(k,j)
    }
    C[i*Nu+j] = sum;
```


问:
iText7 multiple signature
I want to do multiple signatures in a pdf document with iText7 , but the problem is when I have once sign , it works . If I sign twice , the first signature is invalid . It looks like this :

unsigned PDF

signed PDF

and here is my code:

```<code>@Test
public void testMutiSign() {

    iTextSignerUtil1.SignMultPDF(getBytes(unsignedPath), destPath1);

    iTextSignerUtil2.SignMultPDF(getBytes(destPath1), destPath2);

}

 IExternalSignatureContainer externalP7DetachSignatureContainer = new IExternalSignatureContainer() {
    @Override
    public byte[] sign(InputStream data) throws GeneralSecurityException {

        //byte[] hashData = HashUtil.hash(data , "SHA256");

        byte signData = null;
        signData = signUtil.signP7DetachData(data);

        return signData;

    }

    @Override
    public void modifySigningDictionary(PdfDictionary signDic) {
        signDic.put(PdfName.Filter, PdfName.Adobe_PPKLite);
        signDic.put(PdfName.SubFilter, PdfName.Adbe_pkcs7_detached);
    }
};

public void SignMultPDF(byte[] pdfFile , String destPath , String name , String fname , String value){

    boolean success = false;

    int estimatedSize = 300000;

    while (!success) {
        try {

            PdfReader pdfReader = new PdfReader(new ByteArrayInputStream(pdfFile));
            PdfSigner pdfSigner = new PdfSigner(pdfReader, new FileOutputStream(destPath), true);

          pdfSigner.signExternalContainer(externalP7DetachSignatureContainer, estimatedSize);

            success = true;

        } catch (IOException e) {
            e.printStackTrace();
            estimatedSize += 1000;
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
    }
}
</code>```

Above is all my sample code .

And one more question , did I miss to create signature field ?

答:
The cause of this issue is a quirk of the original file: It has an empty indirect dictionary which it uses both as Info dictionary and as Outlines dictionaries.

Whenever manipulating a PDF iText updates its Info dictionary, in particular the ModDate is likely to change each time.

Thus, during each signing pass the Info dictionary is changed, and as the dictionary object is shared, so is the Outlines dictionary. But changing the Outlines of an already signed PDF is not allowed. Thus, the Info (and Outlines) changes during the creation of the second signature are not allowed and invalidate the first signature.

This file is nearly the same as the original file, the only difference is that it uses different empty dictionaries for Info and Outlines (as there was a currently unused empty indirect dictionary in the file, I merely needed to change the reference of Info or Outlines to this unused object). When signing this file twice, Adobe does not complain anymore.

Is this a bug in iText or in the PDF? I think iText should use a new indirect object number when changing the Info dictionary because such duplicate uses of dictionaries is not generally forbidden in PDFs. But a PDF making use of such
duplicate indirect object uses is really asking for trouble. So I think this question brings both an iText issue and an issue in the PDF into the light.

Title: iText7 multiple signature

Body:
I want to do multiple signatures in a pdf document with iText7 , but the problem is when I have once sign , it works . If I sign twice , the first signature is invalid . It looks like this :

unsigned PDF

signed PDF

and here is my code:

@Test
public void testMutiSign() {

    iTextSignerUtil1.SignMultPDF(getBytes(unsignedPath), destPath1);

    iTextSignerUtil2.SignMultPDF(getBytes(destPath1), destPath2);

}

 IExternalSignatureContainer externalP7DetachSignatureContainer = new IExternalSignatureContainer() {
    @Override
    public byte[] sign(InputStream data) throws GeneralSecurityException {

        //byte[] hashData = HashUtil.hash(data , "SHA256");

        byte signData = null;
        signData = signUtil.signP7DetachData(data);

        return signData;

    }

    @Override
    public void modifySigningDictionary(PdfDictionary signDic) {
        signDic.put(PdfName.Filter, PdfName.Adobe_PPKLite);
        signDic.put(PdfName.SubFilter, PdfName.Adbe_pkcs7_detached);
    }
};

public void SignMultPDF(byte[] pdfFile , String destPath , String name , String fname , String value){

    boolean success = false;

    int estimatedSize = 300000;

    while (!success) {
        try {

            PdfReader pdfReader = new PdfReader(new ByteArrayInputStream(pdfFile));
            PdfSigner pdfSigner = new PdfSigner(pdfReader, new FileOutputStream(destPath), true);

          pdfSigner.signExternalContainer(externalP7DetachSignatureContainer, estimatedSize);

            success = true;

        } catch (IOException e) {
            e.printStackTrace();
            estimatedSize += 1000;
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
    }
}

Above is all my sample code .

And one more question , did I miss to create signature field ?


Title: Calculating the time between start/end time intervals in SQL Server 2008

Body:
A user visit tracking data set records the first and last action time of every visit:

idvisit user_id     visit_date  visit_first_action_time visit_last_action_time
5732    abdifa01    2017-11-13  2017-11-13 07:23:41     2017-11-13 12:54:10
5140    abdifa01    2017-11-09  2017-11-09 07:14:22     2017-11-09 18:13:04
4906    abdifa01    2017-11-08  2017-11-08 07:58:05     2017-11-08 19:52:09
4663    abdifa01    2017-11-07  2017-11-07 10:11:52     2017-11-07 12:09:01
4741    abdifa01    2017-11-07  2017-11-07 12:54:17     2017-11-07 20:11:51
5760    abirio00    2017-11-13  2017-11-13 08:14:17     2017-11-13 12:59:31
5681    abirio00    2017-11-12  2017-11-12 10:31:00     2017-11-12 16:12:01
5620    abirio00    2017-11-11  2017-11-11 09:27:21     2017-11-11 12:45:07
5643    abirio00    2017-11-11  2017-11-11 14:06:32     2017-11-11 17:01:38
5553    abirio00    2017-11-10  2017-11-10 15:21:07     2017-11-10 16:07:02
5554    abirio00    2017-11-10  2017-11-10 15:21:07     2017-11-10 15:21:07
5436    abirio00    2017-11-10  2017-11-10 08:24:53     2017-11-10 14:41:17
5183    abirio00    2017-11-09  2017-11-09 08:08:23     2017-11-09 08:08:23
5204    abirio00    2017-11-09  2017-11-09 08:42:23     2017-11-09 09:19:50
5236    abirio00    2017-11-09  2017-11-09 09:51:40     2017-11-09 10:20:54
5252    abirio00    2017-11-09  2017-11-09 10:57:29     2017-11-09 15:48:59

How would you produce a similar dataset using SQL query which displays the idle time between above records for the same user_id on the same visit_date ?

user_id     visit_date  start_idle_time        finish_idle_time
abdifa01    2017-11-07  2017-11-07 12:09:01    2017-11-07 12:54:17
abirio00    2017-11-11  2017-11-11 12:45:07    2017-11-11 14:06:32
abirio00    2017-11-10  2017-11-11 14:41:17    2017-11-11 15:21:07
abirio00    2017-11-09  2017-11-09 08:08:23    2017-11-09 08:42:23
abirio00    2017-11-09  2017-11-09 09:19:50    2017-11-09 09:51:40
abirio00    2017-11-09  2017-11-09 10:20:54    2017-11-09 10:57:29

Body:
For SQL Server 2012 an later, use LEAD(). For SQL 2008 you can use ROW_NUMBER() and a self join that uses the generated row number offset by 1 to align the "next values" to the current row. Both techniques are shown below for comparison. A common table expression (CTE) is used to facilitate the self join.

SQL Fiddle

MS SQL Server 2014 Schema Setup:

CREATE TABLE Table1
    ([idvisit] int, [user_id] varchar(8), [visit_date] date, [visit_first_action_time] datetime, [visit_last_action_time] datetime)
;

INSERT INTO Table1
    ([idvisit], [user_id], [visit_date], [visit_first_action_time], [visit_last_action_time])
VALUES
    (5732, 'abdifa01', '2017-11-13 00:00:00', '2017-11-13 07:23:41', '2017-11-13 12:54:10'),
    (5140, 'abdifa01', '2017-11-09 00:00:00', '2017-11-09 07:14:22', '2017-11-09 18:13:04'),
    (4906, 'abdifa01', '2017-11-08 00:00:00', '2017-11-08 07:58:05', '2017-11-08 19:52:09'),
    (4663, 'abdifa01', '2017-11-07 00:00:00', '2017-11-07 10:11:52', '2017-11-07 12:09:01'),
    (4741, 'abdifa01', '2017-11-07 00:00:00', '2017-11-07 12:54:17', '2017-11-07 20:11:51'),
    (5760, 'abirio00', '2017-11-13 00:00:00', '2017-11-13 08:14:17', '2017-11-13 12:59:31'),
    (5681, 'abirio00', '2017-11-12 00:00:00', '2017-11-12 10:31:00', '2017-11-12 16:12:01'),
    (5620, 'abirio00', '2017-11-11 00:00:00', '2017-11-11 09:27:21', '2017-11-11 12:45:07'),
    (5643, 'abirio00', '2017-11-11 00:00:00', '2017-11-11 14:06:32', '2017-11-11 17:01:38'),
    (5553, 'abirio00', '2017-11-10 00:00:00', '2017-11-10 15:21:07', '2017-11-10 16:07:02'),
    (5554, 'abirio00', '2017-11-10 00:00:00', '2017-11-10 15:21:07', '2017-11-10 15:21:07'),
    (5436, 'abirio00', '2017-11-10 00:00:00', '2017-11-10 08:24:53', '2017-11-10 14:41:17'),
    (5183, 'abirio00', '2017-11-09 00:00:00', '2017-11-09 08:08:23', '2017-11-09 08:08:23'),
    (5204, 'abirio00', '2017-11-09 00:00:00', '2017-11-09 08:42:23', '2017-11-09 09:19:50'),
    (5236, 'abirio00', '2017-11-09 00:00:00', '2017-11-09 09:51:40', '2017-11-09 10:20:54'),
    (5252, 'abirio00', '2017-11-09 00:00:00', '2017-11-09 10:57:29', '2017-11-09 15:48:59')
;

Query using LEAD():

select
        idvisit
      , user_id
      , visit_date
      , visit_first_action_time
      , visit_last_action_time
      , lead (visit_first_action_time) over (partition by user_id, visit_date
                                             order by visit_first_action_time ASC, visit_last_action_time ASC) as start_idle_time
      , datediff(ss,visit_last_action_time
                 , lead (visit_first_action_time) over (partition by user_id, visit_date
                                                        order by visit_first_action_time ASC, visit_last_action_time ASC)
                ) as secs_between
from Table1
order by user_id, visit_date, visit_first_action_time, visit_last_action_time
;

Results:

| idvisit |  user_id | visit_date | visit_first_action_time | visit_last_action_time |      start_idle_time | secs_between |
|---------|----------|------------|-------------------------|------------------------|----------------------|--------------|
|    4663 | abdifa01 | 2017-11-07 |    2017-11-07T10:11:52Z |   2017-11-07T12:09:01Z | 2017-11-07T12:54:17Z |         2716 |
|    4741 | abdifa01 | 2017-11-07 |    2017-11-07T12:54:17Z |   2017-11-07T20:11:51Z |               (null) |       (null) |
|    4906 | abdifa01 | 2017-11-08 |    2017-11-08T07:58:05Z |   2017-11-08T19:52:09Z |               (null) |       (null) |
|    5140 | abdifa01 | 2017-11-09 |    2017-11-09T07:14:22Z |   2017-11-09T18:13:04Z |               (null) |       (null) |
|    5732 | abdifa01 | 2017-11-13 |    2017-11-13T07:23:41Z |   2017-11-13T12:54:10Z |               (null) |       (null) |
|    5183 | abirio00 | 2017-11-09 |    2017-11-09T08:08:23Z |   2017-11-09T08:08:23Z | 2017-11-09T08:42:23Z |         2040 |
|    5204 | abirio00 | 2017-11-09 |    2017-11-09T08:42:23Z |   2017-11-09T09:19:50Z | 2017-11-09T09:51:40Z |         1910 |
|    5236 | abirio00 | 2017-11-09 |    2017-11-09T09:51:40Z |   2017-11-09T10:20:54Z | 2017-11-09T10:57:29Z |         2195 |
|    5252 | abirio00 | 2017-11-09 |    2017-11-09T10:57:29Z |   2017-11-09T15:48:59Z |               (null) |       (null) |
|    5436 | abirio00 | 2017-11-10 |    2017-11-10T08:24:53Z |   2017-11-10T14:41:17Z | 2017-11-10T15:21:07Z |         2390 |
|    5554 | abirio00 | 2017-11-10 |    2017-11-10T15:21:07Z |   2017-11-10T15:21:07Z | 2017-11-10T15:21:07Z |            0 |
|    5553 | abirio00 | 2017-11-10 |    2017-11-10T15:21:07Z |   2017-11-10T16:07:02Z |               (null) |       (null) |
|    5620 | abirio00 | 2017-11-11 |    2017-11-11T09:27:21Z |   2017-11-11T12:45:07Z | 2017-11-11T14:06:32Z |         4885 |
|    5643 | abirio00 | 2017-11-11 |    2017-11-11T14:06:32Z |   2017-11-11T17:01:38Z |               (null) |       (null) |
|    5681 | abirio00 | 2017-11-12 |    2017-11-12T10:31:00Z |   2017-11-12T16:12:01Z |               (null) |       (null) |
|    5760 | abirio00 | 2017-11-13 |    2017-11-13T08:14:17Z |   2017-11-13T12:59:31Z |               (null) |       (null) |

Query using ROW_NUMBER() and CTE:

with myCTE as (
      select
             table1.*
           , row_number()  over (partition by user_id, visit_date
                    order by visit_first_action_time ASC, visit_last_action_time ASC) as rn
      from table1
      )
select
        t1.idvisit
      , t1.user_id
      , t1.visit_date
      , t1.visit_first_action_time
      , t1.visit_last_action_time
      , t2.visit_first_action_time as start_idle_time
      , datediff(ss,t1.visit_last_action_time, t2.visit_first_action_time)  as secs_between
from myCTE t1
left join myCTE t2 on t1.user_id = t2.user_id and t1.visit_date = t2.visit_date
                  and t1.rn = t2.rn-1
order by t1.user_id, t1.visit_date, t1.visit_first_action_time, t1.visit_last_action_time
;

Results:

| idvisit |  user_id | visit_date | visit_first_action_time | visit_last_action_time |      start_idle_time | secs_between |
|---------|----------|------------|-------------------------|------------------------|----------------------|--------------|
|    4663 | abdifa01 | 2017-11-07 |    2017-11-07T10:11:52Z |   2017-11-07T12:09:01Z | 2017-11-07T12:54:17Z |         2716 |
|    4741 | abdifa01 | 2017-11-07 |    2017-11-07T12:54:17Z |   2017-11-07T20:11:51Z |               (null) |       (null) |
|    4906 | abdifa01 | 2017-11-08 |    2017-11-08T07:58:05Z |   2017-11-08T19:52:09Z |               (null) |       (null) |
|    5140 | abdifa01 | 2017-11-09 |    2017-11-09T07:14:22Z |   2017-11-09T18:13:04Z |               (null) |       (null) |
|    5732 | abdifa01 | 2017-11-13 |    2017-11-13T07:23:41Z |   2017-11-13T12:54:10Z |               (null) |       (null) |
|    5183 | abirio00 | 2017-11-09 |    2017-11-09T08:08:23Z |   2017-11-09T08:08:23Z | 2017-11-09T08:42:23Z |         2040 |
|    5204 | abirio00 | 2017-11-09 |    2017-11-09T08:42:23Z |   2017-11-09T09:19:50Z | 2017-11-09T09:51:40Z |         1910 |
|    5236 | abirio00 | 2017-11-09 |    2017-11-09T09:51:40Z |   2017-11-09T10:20:54Z | 2017-11-09T10:57:29Z |         2195 |
|    5252 | abirio00 | 2017-11-09 |    2017-11-09T10:57:29Z |   2017-11-09T15:48:59Z |               (null) |       (null) |
|    5436 | abirio00 | 2017-11-10 |    2017-11-10T08:24:53Z |   2017-11-10T14:41:17Z | 2017-11-10T15:21:07Z |         2390 |
|    5554 | abirio00 | 2017-11-10 |    2017-11-10T15:21:07Z |   2017-11-10T15:21:07Z | 2017-11-10T15:21:07Z |            0 |
|    5553 | abirio00 | 2017-11-10 |    2017-11-10T15:21:07Z |   2017-11-10T16:07:02Z |               (null) |       (null) |
|    5620 | abirio00 | 2017-11-11 |    2017-11-11T09:27:21Z |   2017-11-11T12:45:07Z | 2017-11-11T14:06:32Z |         4885 |
|    5643 | abirio00 | 2017-11-11 |    2017-11-11T14:06:32Z |   2017-11-11T17:01:38Z |               (null) |       (null) |
|    5681 | abirio00 | 2017-11-12 |    2017-11-12T10:31:00Z |   2017-11-12T16:12:01Z |               (null) |       (null) |
|    5760 | abirio00 | 2017-11-13 |    2017-11-13T08:14:17Z |   2017-11-13T12:59:31Z |               (null) |       (null) |


问:
I need to print divs and appending array contents inside of them in Javascript. How do i do that?
I have a div like this

```<code>    <div id="news" class="col-sm-6 col-md-4 col-lg-4 pb-70">
  <div class="post-prev-img">
      <a href="blog-single-sidebar-right.html"><img src="images/blog/post-prev-1.jpg" alt="img"></a>
    </div>

    <div class="post-prev-title">
      <h3><a href="blog-single-sidebar-right.html">TIME FOR MINIMALISM</a></h3>
    </div>

    <div class="post-prev-info">
      JULE 10<span class="slash-divider">/</span><a href="http://themeforest.net/user/abcgomel/portfolio?ref=abcgomel">JOHN DOE</a>
    </div>

    <div class="post-prev-text">
      Lorem ipsum dolor sit amet, consectetur adipisicing elit. Recusandae, nostrum, cumque culpa provident aliquam commodi assumenda laudantium magnam illo nostrum.
    </div>

    <div class="post-prev-more-cont clearfix">
      <div class="post-prev-more left">
        <a href="blog-single-sidebar-right.html" class="blog-more">READ MORE</a>
      </div>
      <div class="right" >
        <a href="blog-single-sidebar-right.html#comments" class="post-prev-count"><span aria-hidden="true" class="icon_comment_alt"></span><span class="icon-count">21</span></a>
        <a href="http://themeforest.net/user/abcgomel/portfolio?ref=abcgomel" class="post-prev-count"><span aria-hidden="true" class="icon_heart_alt"></span><span class="icon-count">53</span></a>
        <a href="#" class="post-prev-count dropdown-toggle" data-toggle="dropdown" aria-expanded="false" >
          <span aria-hidden="true" class="social_share"></span>
        </a>
        <ul class="social-menu dropdown-menu dropdown-menu-right" role="menu">
          <li><a href="#"><span aria-hidden="true" class="social_facebook"></span></a>
          </li>
          <li><a href="#"><span aria-hidden="true" class="social_twitter"></span></a></li>
          <li><a href="#"><span aria-hidden="true" class="social_dribbble"></span></a></li>
        </ul>
      </div>
    </div>
</div>
</code>```

I need this to be my "skeleton" for my other divs.
Now i want to make a for and append the content of my array inside of it and print every div inside an HTML page. How do i do that?

Thanks

答:
Try jQuery templates. You write your HTML code inside script tags and in your JS code you can call them and use them as you wish:

```<code><script id="bookTemplate" type="text/x-jQuery-tmpl">
<div>
<img src="BookPictures/${picture}" alt="" />
<h2>${title}</h2>
price: ${formatPrice(price)}
</div>
</script>
</code>```

Usage:

$("#bookTemplate").tmpl(books).appendTo("#bookContainer");

Body:
I have a div like this

TIME FOR MINIMALISM

      JULE 10/JOHN DOE

      Lorem ipsum dolor sit amet, consectetur adipisicing elit. Recusandae, nostrum, cumque culpa provident aliquam commodi assumenda laudantium magnam illo nostrum.

        READ MORE

        21
        53

I need this to be my "skeleton" for my other divs.
Now i want to make a for and append the content of my array inside of it and print every div inside an HTML page. How do i do that?

Thanks

Body:
Try jQuery templates. You write your HTML code inside script tags and in your JS code you can call them and use them as you wish:

<script id="bookTemplate" type="text/x-jQuery-tmpl">
<div>
<img src="BookPictures/${picture}" alt="" />
<h2>${title}</h2>
price: ${formatPrice(price)}
</div>
</script>

Usage:

$("#bookTemplate").tmpl(books).appendTo("#bookContainer");


问:
Using muliple forms in the same view
I am trying to learn django framework with few sample applications. Currently, I am working on a feedback/survey application.
It uses the following models:

```<code>class Survey(models.Model):
    title = models.CharField(_(max_length=255)
    slug = models.SlugField(_(max_length=255, unique=True)
    description= models.TextField(blank=True)

class Question(models.Model):
    survey = models.ForeignKey(Survey, related_name='questions')
    question = models.TextField()

class Answer(models.Model):
    question = models.ForeignKey(Question, related_name='answers')
    answer = models.TextField()
</code>```

Basically a survey will contain questions and their answers will be saved in the answer.

Now what I don't understand is how to create a form which will display all the questions of a survey when the view is called.
I tried to create a form like this

```<code>class BaseAnswerForm(Form):
    answer = None
    def __init__(self, question,*args, **kwdargs):
        self.question = question
        #self.answer = None
        super(BaseAnswerForm, self).__init__(*args, **kwdargs)
        answer = self.fields['answer']
        answer.label = question.question

    def save(self, commit=True):
        ans = self.answer
        if ans is None:
            ans = Answer()
        ans.question = self.question
        ans.answer = self.cleaned_data['answer']
        if commit: ans.save()
        return ans

class TextAnswerForm(BaseAnswerForm):
    answer = CharField()

def forms_for_survey(survey, request):
    if request.POST:
        post = request.POST
    else:
        post = None
    return [TextAnswerForm(q,data=post)
            for q in survey.questions.all()]
</code>```

view for this is like

```<code>def show_questions(request, slug):
    survey = get_object_or_404(Survey.objects, slug=slug)
    forms = forms_for_survey(survey, request)
    context = {
        'survey':survey,
        'forms':forms,
        }
    if (request.POST and all(form.is_valid() for form in forms)):
        for form in forms:
            form.save()
        return HttpResponseRedirect(reverse('show_surveys',))
    return render_to_response(
        'feedback/show_questions.html',
        context,
        context_instance = RequestContext(request)
        )
</code>```

What this does is that, it generates the form as I want, but all the answers are saved from the last answer field.
Please help me out, will this be easier using formsets, Can you tell me how it can implemented easier. Thanks

答:
The prefix argument is there to prevent naming conflict issues when repeatedly using the same form (FormSets use it) or using forms which happen to have clashing field names - give each Form a unique prefix, which will be prepended to each generated field name. Using the Question's id would be ideal:

```<code>return [TextAnswerForm(q,data=post, prefix='q_%s' % q.pk)
        for q in survey.questions.all()]
</code>```

Title: Using muliple forms in the same view

Body:
I am trying to learn django framework with few sample applications. Currently, I am working on a feedback/survey application.
It uses the following models:

class Survey(models.Model):
    title = models.CharField(_(max_length=255)
    slug = models.SlugField(_(max_length=255, unique=True)
    description= models.TextField(blank=True)

class Question(models.Model):
    survey = models.ForeignKey(Survey, related_name='questions')
    question = models.TextField()

class Answer(models.Model):
    question = models.ForeignKey(Question, related_name='answers')
    answer = models.TextField()

Basically a survey will contain questions and their answers will be saved in the answer.

Now what I don't understand is how to create a form which will display all the questions of a survey when the view is called.
I tried to create a form like this

class BaseAnswerForm(Form):
    answer = None
    def __init__(self, question,*args, **kwdargs):
        self.question = question
        #self.answer = None
        super(BaseAnswerForm, self).__init__(*args, **kwdargs)
        answer = self.fields['answer']
        answer.label = question.question

    def save(self, commit=True):
        ans = self.answer
        if ans is None:
            ans = Answer()
        ans.question = self.question
        ans.answer = self.cleaned_data['answer']
        if commit: ans.save()
        return ans

class TextAnswerForm(BaseAnswerForm):
    answer = CharField()

def forms_for_survey(survey, request):
    if request.POST:
        post = request.POST
    else:
        post = None
    return [TextAnswerForm(q,data=post)
            for q in survey.questions.all()]

view for this is like

def show_questions(request, slug):
    survey = get_object_or_404(Survey.objects, slug=slug)
    forms = forms_for_survey(survey, request)
    context = {
        'survey':survey,
        'forms':forms,
        }
    if (request.POST and all(form.is_valid() for form in forms)):
        for form in forms:
            form.save()
        return HttpResponseRedirect(reverse('show_surveys',))
    return render_to_response(
        'feedback/show_questions.html',
        context,
        context_instance = RequestContext(request)
        )

What this does is that, it generates the form as I want, but all the answers are saved from the last answer field.
Please help me out, will this be easier using formsets, Can you tell me how it can implemented easier. Thanks

Body:
The prefix argument is there to prevent naming conflict issues when repeatedly using the same form (FormSets use it) or using forms which happen to have clashing field names - give each Form a unique prefix, which will be prepended to each generated field name. Using the Question's id would be ideal:

return [TextAnswerForm(q,data=post, prefix='q_%s' % q.pk)
        for q in survey.questions.all()]


问:
Ajax Call inside click event is not working
I am trying to make an Ajax call work in a click event but it is giving me an error:

$.ajax is not a function

My call:

```<code>module.exports.doaction = (Identifier) => {
    $(Identifier).modal('show');
    $(`${Identifier} a`).click((event) => {
        $.ajax({
            type: 'POST',
            url: '/action',
            data: event.target.id
        });
    });
};
</code>```

What I am missing?

On my main page the script has been included:

```<code><script src="code.jquery.com/jquery-3.1.1.slim.min.js"></script>
</code>```

答:
$.ajax is not a function means you didn't included jquery properly.

slim build of jquery doesn't include ajax function.

you can include jquery from

https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js

Body:
I am trying to make an Ajax call work in a click event but it is giving me an error:

$.ajax is not a function

My call:

module.exports.doaction = (Identifier) => {
    $(Identifier).modal('show');
    $(`${Identifier} a`).click((event) => {
        $.ajax({
            type: 'POST',
            url: '/action',
            data: event.target.id
        });
    });
};

What I am missing?

On my main page the script has been included:


问:
How to work with dates and calendar in Ruby on Rails to create trips and routes every day?
Started learning Ruby on Rails, I want to create a website online ticket sale.

For example:

https://busfor.com/

http://www.easybook.com/

How to work with dates and calendar in Ruby on Rails (so as not to create every day new flights and routes every day if he repeats).

I would be grateful for feedback

答: Here is a datepicker for rails -- https://github.com/benignware/date_picker</p>


问:
Why does my merge function output an array that is not ordered?
I built a simple function that, given two arrays aa[5] = {5, 4, 9, -1, 3} and bb[2] = {16, -11}, orders them in a third array cc[7].

```<code>#include<stdio.h>
void merge(int *, int *, int *, int, int);

int main(){
    int aa[5] = {5, 4, 9, -1, 3};
    int bb[2] = {16, -11};
    int cc[7];

    merge(aa, bb, cc, 5, 2);

    return 0;
}

void merge(int *aa, int *bb, int *cc, int m, int n){

    int i = 0, j = 0, k = 0;

    while(i < m && j < n){
        if(aa[i] < bb[j])
            cc[k++] = aa[i++];    /*Smallest value should be assigned to cc*/
        else
            cc[k++] = bb[j++];
    }

    while(i < m)              /*Transfer the remaining part of longest array*/
        cc[k++] = aa[i++];

    while(j < n)
        cc[k++] = bb[j++];
}
</code>```

The cc array is correctly filled, but the values are not ordered. Instead of the expected cc = {-11, -1, 3, 4, 5, 9, 16} it returns cc = {5, 4, 9, -1, 3, 16, 11}.
Like the assignments cc[k++] = aa[i++] and cc[k++] = bb[j++] do not work, somehow, or the logical test if aa[i] < bb[j] goes ignored.

I hypothesized operators priority problems, hence I tested with two different standard, with no differences:

```<code>gcc main.c -o main.x -Wall
gcc main.c -o main.x -Wall -std=c89
</code>```

I checked the code many times, unable to find any relevant error. Any suggestion at this point would be appreciated.

答:
You need to think your algorithm through properly. There's no obvious bug in it. The problem is your expectations. One way to make this clear is to think about what would happen if one array was empty. Would the function merge change the order of anything? It will not. In fact, if two elements a and b are from the same array - be it aa or bb - and a comes before b in that array, then a will also come before b in cc.

The function does what you expect on sorted arrays, so make sure they are sorted before. You can use qsort for this.

Other than that, when you use pointers to arrays you do not want to change, use the const qualifier.

```<code>void merge(const int *aa, const int *bb, int *cc, int m, int n)
</code>```

Body:
I built a simple function that, given two arrays aa[5] = {5, 4, 9, -1, 3} and bb[2] = {16, -11}, orders them in a third array cc[7].

#include<stdio.h>
void merge(int *, int *, int *, int, int);

int main(){
    int aa[5] = {5, 4, 9, -1, 3};
    int bb[2] = {16, -11};
    int cc[7];

    merge(aa, bb, cc, 5, 2);

    return 0;
}

void merge(int *aa, int *bb, int *cc, int m, int n){

    int i = 0, j = 0, k = 0;

    while(i < m && j < n){
        if(aa[i] < bb[j])
            cc[k++] = aa[i++];    /*Smallest value should be assigned to cc*/
        else
            cc[k++] = bb[j++];
    }

    while(i < m)              /*Transfer the remaining part of longest array*/
        cc[k++] = aa[i++];

    while(j < n)
        cc[k++] = bb[j++];
}

The cc array is correctly filled, but the values are not ordered. Instead of the expected cc = {-11, -1, 3, 4, 5, 9, 16} it returns cc = {5, 4, 9, -1, 3, 16, 11}.
Like the assignments cc[k++] = aa[i++] and cc[k++] = bb[j++] do not work, somehow, or the logical test if aa[i] < bb[j] goes ignored.

I hypothesized operators priority problems, hence I tested with two different standard, with no differences:

gcc main.c -o main.x -Wall
gcc main.c -o main.x -Wall -std=c89

I checked the code many times, unable to find any relevant error. Any suggestion at this point would be appreciated.

Body:
You need to think your algorithm through properly. There's no obvious bug in it. The problem is your expectations. One way to make this clear is to think about what would happen if one array was empty. Would the function merge change the order of anything? It will not. In fact, if two elements a and b are from the same array - be it aa or bb - and a comes before b in that array, then a will also come before b in cc.

The function does what you expect on sorted arrays, so make sure they are sorted before. You can use qsort for this.

Other than that, when you use pointers to arrays you do not want to change, use the const qualifier.

void merge(const int *aa, const int *bb, int *cc, int m, int n)


问:
Python serial.readline() not blocking
I'm trying to use hardware serial port devices with Python, but I'm having timing issues.  If I send an interrogation command to the device, it should respond with data.  If I try to read the incoming data too quickly, it receives nothing.

```<code>import serial
device = serial.Serial("/dev/ttyUSB0", 9600, timeout=0)
device.flushInput()
device.write("command")
response = device.readline()
print response
''
</code>```

The readline() command isn't blocking and waiting for a new line as it should.  Is there a simple workaround?

答:
readline() uses the same timeout value you passed to serial.Serial().
If you want readline to be blocking, just delete the timeout argument, the default value is None.

You could also set it to None before calling readline(), if you want to have a timeout for openening the device:

```<code>import serial
try:
    device = serial.Serial("/dev/ttyUSB0", 9600, timeout=0.5)
except:
    #Exception handeling
device.flushInput()
device.write("command")
device.timeout=None
response = device.readline()
print response
</code>```

Title: Python serial.readline() not blocking

Body:
I'm trying to use hardware serial port devices with Python, but I'm having timing issues.  If I send an interrogation command to the device, it should respond with data.  If I try to read the incoming data too quickly, it receives nothing.

import serial
device = serial.Serial("/dev/ttyUSB0", 9600, timeout=0)
device.flushInput()
device.write("command")
response = device.readline()
print response
''

The readline() command isn't blocking and waiting for a new line as it should.  Is there a simple workaround?

Body:
readline() uses the same timeout value you passed to serial.Serial().
If you want readline to be blocking, just delete the timeout argument, the default value is None.

You could also set it to None before calling readline(), if you want to have a timeout for openening the device:

import serial
try:
    device = serial.Serial("/dev/ttyUSB0", 9600, timeout=0.5)
except:
    #Exception handeling
device.flushInput()
device.write("command")
device.timeout=None
response = device.readline()
print response


问:
Disabled <input> that allows text selection?
Is it possible for a disabled <input> tag to support text selection?

答:
readonly="readonly" is your answer

you can remove border in CSS or directly in styles, when you "blocked" this field and it will look like regular text, bring back the look when "unblocked"...


答:
Not the most efficient cause it's bobble sort...</p>

```<code>    #include<stdio.h>
    void merge(int *, int *, int *, int, int);
    void sortarray(int array[], int arraySize)
    {
        int c,d,temp;

        for (c = 0 ; c < arraySize-1; c++)
      {
        for (d = 0 ; d < arraySize - c - 1; d++)
        {
          if (array[d] > array[d+1]) /* For decreasing order use < */
          {
            temp       = array[d];
            array[d]   = array[d+1];
            array[d+1] = temp;
          }
        }
      }
    }
    int main(){
        int aa[5] = {5, 4, 9, -1, 3};
        int bb[2] = {16, -11};
        int cc[7];
        int i;
        sortarray(aa,sizeof(aa)/sizeof(aa[0]));

        sortarray(bb,sizeof(bb)/sizeof(bb[0]));

        merge(aa, bb, cc, 5, 2);

         for(i=0;i<sizeof(cc)/sizeof(cc[0]);i++)
         {
            printf("%d,",cc[i]);
         }
        return 0;
    }

    void merge(int *aa, int *bb, int *cc, int m, int n){

        int i = 0, j = 0, k = 0;

        while(i < m && j < n)
        {
            if(aa[i] < bb[j])
                cc[k++] = aa[i++];    /*Smallest value should be assigned to cc*/
            else
                cc[k++] = bb[j++];
        }

        while(i < m)              /*Transfer the remaining part of longest array*/
            cc[k++] = aa[i++];

        while(j < n)
            cc[k++] = bb[j++];
    }
</code>```

Title: Why does my merge function output an array that is not ordered?

Body:
Not the most efficient cause it's bobble sort...

    #include<stdio.h>
    void merge(int *, int *, int *, int, int);
    void sortarray(int array[], int arraySize)
    {
        int c,d,temp;

        for (c = 0 ; c < arraySize-1; c++)
      {
        for (d = 0 ; d < arraySize - c - 1; d++)
        {
          if (array[d] > array[d+1]) /* For decreasing order use < */
          {
            temp       = array[d];
            array[d]   = array[d+1];
            array[d+1] = temp;
          }
        }
      }
    }
    int main(){
        int aa[5] = {5, 4, 9, -1, 3};
        int bb[2] = {16, -11};
        int cc[7];
        int i;
        sortarray(aa,sizeof(aa)/sizeof(aa[0]));

        sortarray(bb,sizeof(bb)/sizeof(bb[0]));

        merge(aa, bb, cc, 5, 2);

         for(i=0;i<sizeof(cc)/sizeof(cc[0]);i++)
         {
            printf("%d,",cc[i]);
         }
        return 0;
    }

    void merge(int *aa, int *bb, int *cc, int m, int n){

        int i = 0, j = 0, k = 0;

        while(i < m && j < n)
        {
            if(aa[i] < bb[j])
                cc[k++] = aa[i++];    /*Smallest value should be assigned to cc*/
            else
                cc[k++] = bb[j++];
        }

        while(i < m)              /*Transfer the remaining part of longest array*/
            cc[k++] = aa[i++];

        while(j < n)
            cc[k++] = bb[j++];
    }


问:
Ignore client certificate popup for a click once landing page - but still require cert for service
I have a WCF service hosted in IIS with a default .aspx file that serves as the landing page for a clickonce application. The .svc file and .aspx file are in the same root directory of the application: i.e. the following folder structure:

```<code>MyService
 --  MyService.svc
 --  Default.aspx
 --  Web.config
</code>```

If I browse MyService and view Default.aspx (my click once landing page) from IIS, I do not want to be prompted for a client cert, as the client cert is actually selected from the click once directly and attached to the call of the WCF service (i.e. client.ClientCredentials.ClientCertificate.Certificate = UserCertificate;).

I can get around this in IIS Manager by setting MyService application to Ignore client certs and setting MyService.svc to Accept client certs. This all works as expected (browsing to Default.aspx doesn't prompt me but browsing to the .svc does), but for deployment & testing reasons, I'd like to automate this in the Web.config. I've tried the following but with no luck.

```<code><location path="MyService">
<system.webServer>
  <security>
    <access sslFlags="None" />
  </security>
</system.webServer>
</code>```

```<code><location path="MyService.svc">
<system.webServer>
  <security>
    <access sslFlags="SslRequireCert" />
  </security>
</system.webServer>
</code>```

I'm assuming by setting MyService to "None" initially messes it up.

I also ran into similar issues when attempting to move my svc to another folder and having it as a sub application in IIS.

Any help would be great, thanks.

答:
I ended up fixing this issue by adding a custom action in my Advanced Installer project that wrote the XML configuration into the ApplicationHost.config using something along the lines of</p>

```<code>    using (ServerManager manager = new ServerManager())
        {
            var config = manager.GetApplicationHostConfiguration();

            try
            {
                ConfigurationSection accessSection = config.GetSection("system.webServer/security/access", site);

                if (accessSection != null)
                {
                    Console.WriteLine("Opened app host config successfully.");
                    accessSection["sslFlags"] = @"None";
                }

                accessSection = config.GetSection("system.webServer/security/access", "Default Web Site/MyService/MyService.svc");

                if (accessSection != null)
                {
                    Console.WriteLine("Opened app host config successfully.");
                    accessSection["sslFlags"] = @"Ssl, SslNegotiateCert, SslRequireCert";
                }

                manager.CommitChanges();
                Console.WriteLine("Successfully committed changes");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to open the app host config.");
            }
        }
</code>```

Body:
I have a WCF service hosted in IIS with a default .aspx file that serves as the landing page for a clickonce application. The .svc file and .aspx file are in the same root directory of the application: i.e. the following folder structure:

MyService
 --  MyService.svc
 --  Default.aspx
 --  Web.config

If I browse MyService and view Default.aspx (my click once landing page) from IIS, I do not want to be prompted for a client cert, as the client cert is actually selected from the click once directly and attached to the call of the WCF service (i.e. client.ClientCredentials.ClientCertificate.Certificate = UserCertificate;).

I can get around this in IIS Manager by setting MyService application to Ignore client certs and setting MyService.svc to Accept client certs. This all works as expected (browsing to Default.aspx doesn't prompt me but browsing to the .svc does), but for deployment & testing reasons, I'd like to automate this in the Web.config. I've tried the following but with no luck.

<location path="MyService">
<system.webServer>
  <security>
    <access sslFlags="None" />
  </security>
</system.webServer>

<location path="MyService.svc">
<system.webServer>
  <security>
    <access sslFlags="SslRequireCert" />
  </security>
</system.webServer>

I'm assuming by setting MyService to "None" initially messes it up.

I also ran into similar issues when attempting to move my svc to another folder and having it as a sub application in IIS.

Any help would be great, thanks.

Body:
I ended up fixing this issue by adding a custom action in my Advanced Installer project that wrote the XML configuration into the ApplicationHost.config using something along the lines of

    using (ServerManager manager = new ServerManager())
        {
            var config = manager.GetApplicationHostConfiguration();

            try
            {
                ConfigurationSection accessSection = config.GetSection("system.webServer/security/access", site);

                if (accessSection != null)
                {
                    Console.WriteLine("Opened app host config successfully.");
                    accessSection["sslFlags"] = @"None";
                }

                accessSection = config.GetSection("system.webServer/security/access", "Default Web Site/MyService/MyService.svc");

                if (accessSection != null)
                {
                    Console.WriteLine("Opened app host config successfully.");
                    accessSection["sslFlags"] = @"Ssl, SslNegotiateCert, SslRequireCert";
                }

                manager.CommitChanges();
                Console.WriteLine("Successfully committed changes");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to open the app host config.");
            }
        }


问:
How does Azure Active Directory support federation with Okta as an IDP?
Is it possible to integrate Okta as an IDP (Identity Provider) for an application in Azure, where Azure would be the Service Provider?

Presently the authentication is managed by Azure AD, we have AD users that have been granted access to these applications hosted in Azure, and Use ADAL for logging in users, and obtaining tokens for securing API calls to the Backend APIs.

Can Okta be added as an IDP and added to the AAD, through SAML or WS-Federation?

答:
Yes, OKTA is listed as one of the third-party IDPs in the Azure AD federation compatibility list which can support federation with Azure Active Directory (AAD).

The supported scenario matrix is listed here.

Hope this clarifies your doubt.


问:
convert json text entries to a dataframe in r
I have a text file with json like structure that contains values for certain variables as below.

```<code>[{"variable1":"111","variable2":"666","variable3":"11","variable4":"aaa","variable5":"0"}]
[{"variable1":"34","variable2":"12","variable3":"78","variable4":"qqq","variable5":"-9"}]
</code>```

Every line is a new set of values for the same variables 1 through 5. There can be 1000s of lines in a text file but the variables would always remain the same. I want to extract variable 1 through 5 along with their values and convert into a dataframe. Currently I perform these operations in excel using string manipulation and transpose. Here is what it looks like in excel -

How to do this in R? Much appreciated. Thanks.
J

答:
There is a package named jsonlite that you can use.

```<code>library("jsonlite")
df<- fromJSON("YourPathToTheFile")
</code>```

You can find more info here.

Body:
I have a text file with json like structure that contains values for certain variables as below.

[{"variable1":"111","variable2":"666","variable3":"11","variable4":"aaa","variable5":"0"}]
[{"variable1":"34","variable2":"12","variable3":"78","variable4":"qqq","variable5":"-9"}]

Every line is a new set of values for the same variables 1 through 5. There can be 1000s of lines in a text file but the variables would always remain the same. I want to extract variable 1 through 5 along with their values and convert into a dataframe. Currently I perform these operations in excel using string manipulation and transpose. Here is what it looks like in excel -

How to do this in R? Much appreciated. Thanks.
J

Body:
There is a package named jsonlite that you can use.

library("jsonlite")
df<- fromJSON("YourPathToTheFile")

You can find more info here.


问:
fetch response.json() and response.status
Is this the only way to use the body.json() and also get the status code?

```<code>let status;

return fetch(url)
    .then((response => {
         status = response.status;
         return response.json()
     })
    .then(response => {
        return {
            response: response,
            status: status
        }
    });
</code>```

This doesn't work as it returns a promise in the response field:

```<code>.then((response)=> {return {response: response.json(), status: response.status}})
</code>```

答:
The .json method returns a promise, not the parsed value itself. If you want to access both the response and the parsed value in the same callback, you'll need to use nested functions like this:

```<code>fetch(url)
    .then(response => {
        response.json().then(parsedValue => {
            // code that can access both here
        })
    });
</code>```

Alternatively, you can use await inside an asynchronous function to eliminate the need for callbacks.

```<code>const response = await fetch(url);
const parsedValue = await response.json();

// code that can access both here
</code>```

Of course, you'll want to check for errors, either with a .catch(...) call on a Promise or with a try...catch block in an async function. You could make a function that handles JSON and error cases, and then reuse it for all fetches. For example, something like this:

```<code>function handle(response) {
    if (response.ok) {
        return response.json().then(parsedValue => {
            // the status was ok and the body could be parsed
            return Promise.resolve({ response, parsedValue });
        }).catch(err => {
            // the status was ok but the body was empty or not JSON
            return Promise.resolve({ response });
        });

    } else {
        return response.json().catch(err => {
            // the status was not ok and the body was unobtainable/empty/not JSON
            throw new Error(response.statusText);
        }).then(parsedValue => {
            // the status was not ok and the body was JSON
            throw new Error(parsedValue.error.message); // assuming an error message is returned by our REST API
        });
    }
}
</code>```

I don't think it's the best design pattern, but hopefully this clarifies how the fetch API works.

PS: I avoided naming any variable or property json since that is the name of the text format. Once it's been parsed, it is no longer JSON.

Body:
Is this the only way to use the body.json() and also get the status code?

let status;

return fetch(url)
    .then((response => {
         status = response.status;
         return response.json()
     })
    .then(response => {
        return {
            response: response,
            status: status
        }
    });

This doesn't work as it returns a promise in the response field:

.then((response)=> {return {response: response.json(), status: response.status}})

Body:
The .json method returns a promise, not the parsed value itself. If you want to access both the response and the parsed value in the same callback, you'll need to use nested functions like this:

fetch(url)
    .then(response => {
        response.json().then(parsedValue => {
            // code that can access both here
        })
    });

Alternatively, you can use await inside an asynchronous function to eliminate the need for callbacks.

const response = await fetch(url);
const parsedValue = await response.json();

// code that can access both here

Of course, you'll want to check for errors, either with a .catch(...) call on a Promise or with a try...catch block in an async function. You could make a function that handles JSON and error cases, and then reuse it for all fetches. For example, something like this:

function handle(response) {
    if (response.ok) {
        return response.json().then(parsedValue => {
            // the status was ok and the body could be parsed
            return Promise.resolve({ response, parsedValue });
        }).catch(err => {
            // the status was ok but the body was empty or not JSON
            return Promise.resolve({ response });
        });

    } else {
        return response.json().catch(err => {
            // the status was not ok and the body was unobtainable/empty/not JSON
            throw new Error(response.statusText);
        }).then(parsedValue => {
            // the status was not ok and the body was JSON
            throw new Error(parsedValue.error.message); // assuming an error message is returned by our REST API
        });
    }
}

I don't think it's the best design pattern, but hopefully this clarifies how the fetch API works.

PS: I avoided naming any variable or property json since that is the name of the text format. Once it's been parsed, it is no longer JSON.

ContentLicense: CC BY-SA 4.0


问:
How update infinite scroll js
I this error when un tried after destroy infiniteScroll object, to init new instance :

main.js:1 Uncaught TypeError: o._init is not a function

In my ajax call :

```<code>$.ajax({
  url : $('form').attr('action'),
  data: $('form').serialize(),
  type: 'GET',
  encode: 1,
  success: function(reponseHTML){
     $('.products').infiniteScroll('destroy');

     $('.products').infiniteScroll({
        path: '.next a',
        append: '.product-wrapper',
        history: true,
      });
   }});
</code>```

I follow the official documentation of the plugin :
https://infinite-scroll.com/api.html

答:
after destroy call, I remove DOM Element of infinite Scroll. </p>

```<code>$('.product').remove();
</code>```

<p>to recreate them with reponseHTML.
:)
Thx, </p>

Title: How update infinite scroll js

Body:
I this error when un tried after destroy infiniteScroll object, to init new instance :

main.js:1 Uncaught TypeError: o._init is not a function

In my ajax call :

$.ajax({
  url : $('form').attr('action'),
  data: $('form').serialize(),
  type: 'GET',
  encode: 1,
  success: function(reponseHTML){
     $('.products').infiniteScroll('destroy');

     $('.products').infiniteScroll({
        path: '.next a',
        append: '.product-wrapper',
        history: true,
      });
   }});

I follow the official documentation of the plugin :
https://infinite-scroll.com/api.html

Body:
after destroy call, I remove DOM Element of infinite Scroll.

$('.product').remove();

to recreate them with reponseHTML.
:)
Thx,


问:
How to get a list of all the weather stations, in a given state, using wolfram mathematica
I am currently working on making a 3D plot with Latitude on the x, Longitude on the y, and total rainfall during hurricane Harvey on the z.

The weatherdata function in wolfram mathematica requires you to pass in a name of a weather station as a parameter.

Is there a way to use the Entity or EntityList function to get a list off all the names of weather stations in a given state.

答:
This method works, although there is probably a more direct way.  To find the weather stations in Illinois, for example, find the nearest 100 from Springfield, then select the ones in Illinois.

```<code>coordinates = CityData["Springfield", "Coordinates"];

weatherstations = WeatherData[{coordinates, 100}];

entityvalues = EntityValue[
   weatherstations, "PropertyAssociation"];

properties = {
     #[[Key[EntityProperty[
         "WeatherStation", "Name"]]]],
     #[[Key[EntityProperty[
         "WeatherStation", "Coordinates"]]]]} & /@
   entityvalues;

states = {GeoNearest["USState", Last[#]],
     First[#]} & /@ properties;

Last /@ Select[states, #[[1, 1]] == Entity[
     "AdministrativeDivision",
     List["Illinois", "UnitedStates"]] &]
</code>```

{KCPS, KSAR, KBLV, KALN, KPPQ, KUIN, KCIR, KMDH, KMWA, K3LF}

Body:
This method works, although there is probably a more direct way.  To find the weather stations in Illinois, for example, find the nearest 100 from Springfield, then select the ones in Illinois.

coordinates = CityData["Springfield", "Coordinates"];

weatherstations = WeatherData[{coordinates, 100}];

entityvalues = EntityValue[
   weatherstations, "PropertyAssociation"];

properties = {
     #[[Key[EntityProperty[
         "WeatherStation", "Name"]]]],
     #[[Key[EntityProperty[
         "WeatherStation", "Coordinates"]]]]} & /@
   entityvalues;

states = {GeoNearest["USState", Last[#]],
     First[#]} & /@ properties;

Last /@ Select[states, #[[1, 1]] == Entity[
     "AdministrativeDivision",
     List["Illinois", "UnitedStates"]] &]

{KCPS, KSAR, KBLV, KALN, KPPQ, KUIN, KCIR, KMDH, KMWA, K3LF}


问:
Compile error in ruby on rails application (error is with rails form helpers)
I'm writing a ruby on rails application, and am getting a compile error for the following code

```<code><%= form_tag(search_path, :method => "get") do %>
<%= label_tag(:q, "Search for:") %>
<%= text_field_tag(:q) %>
<%= submit_tag("Search") %>
<% end %>
</code>```

this is sample code from the ruby on rails forms guide:
http://guides.rubyonrails.org/form_helpers.html

The error generated is,

compile error
/Users/kmb89144/Desktop/Stoastic/app/views/application/index.html.erb:3: syntax error, unexpected ')'
...h_path, :method => "get") do ).to_s); @output_buffer.concat ...
                              ^
/Users/kmb89144/Desktop/Stoastic/app/views/application/index.html.erb:13: syntax error, unexpected kENSURE, expecting ')'
/Users/kmb89144/Desktop/Stoastic/app/views/application/index.html.erb:15: syntax error, unexpected kEND, expecting ')'

Extracted source (around line #3):

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

2:

3:   <%= form_tag(search_path, :method => "get") do %>

4:     <%= label_tag(:q, "Search for:") %>

5:     <%= text_field_tag(:q) %>

6:     <%= submit_tag("Search") %>

Any suggestions?

Thanks

答:
Please use form_with, because in the new versions of Rails 5 the functions form_for and form_tag will be discontinued.

Use that:

```<code><%= form_with(url: search_path, method: :get, local:true) do |f|%>
  <%= f.label 'Search for:' %>
  <%= f.text_field :q, id: :q %>
  <%= f.submit 'Search' %>
<% end %>
</code>```

References:
https://m.patrikonrails.com/rails-5-1s-form-with-vs-old-form-helpers-3a5f72a8c78a

Body:
I'm writing a ruby on rails application, and am getting a compile error for the following code

<%= form_tag(search_path, :method => "get") do %>
<%= label_tag(:q, "Search for:") %>
<%= text_field_tag(:q) %>
<%= submit_tag("Search") %>
<% end %>

this is sample code from the ruby on rails forms guide:
http://guides.rubyonrails.org/form_helpers.html

The error generated is,

compile error
/Users/kmb89144/Desktop/Stoastic/app/views/application/index.html.erb:3: syntax error, unexpected ')'
...h_path, :method => "get") do ).to_s); @output_buffer.concat ...
                              ^
/Users/kmb89144/Desktop/Stoastic/app/views/application/index.html.erb:13: syntax error, unexpected kENSURE, expecting ')'
/Users/kmb89144/Desktop/Stoastic/app/views/application/index.html.erb:15: syntax error, unexpected kEND, expecting ')'

Extracted source (around line #3):

1:

2:

3:   <%= form_tag(search_path, :method => "get") do %>

4:     <%= label_tag(:q, "Search for:") %>

5:     <%= text_field_tag(:q) %>

6:     <%= submit_tag("Search") %>

Any suggestions?

Thanks

Body:
Please use form_with, because in the new versions of Rails 5 the functions form_for and form_tag will be discontinued.

Use that:

<%= form_with(url: search_path, method: :get, local:true) do |f|%>
  <%= f.label 'Search for:' %>
  <%= f.text_field :q, id: :q %>
  <%= f.submit 'Search' %>
<% end %>

References:
https://m.patrikonrails.com/rails-5-1s-form-with-vs-old-form-helpers-3a5f72a8c78a


问:
move UITextField up when keyboard present
I have recently started to develop my own app following the instructions on internet. I am just a beginner (with no knowledge of coding) and hence may be doing very stupid mistake that I am not able to catch.

In my app I am facing a situation where my email text field is hiding behind the keyboard whenever I try to type email address. I did some research (on stack overflow) and wrote a piece of code that suppose to move my text field up but it is not ... I believe overall structure of code is right (I may be wrong here though) but it may be just tiny mistake that making my code ineffective.

can anyone guide me on what I am doing wrong here?

below is the piece of code I wrote:
{

```<code>import UIKit
import WebKit
import CoreGraphics
import AVFoundation
import QuartzCore
import Foundation

class StudentSignUpViewController: UIViewController,UIScrollViewDelegate, UITextFieldDelegate {

@IBOutlet weak var yourEmail: UITextField!
@IBOutlet weak var scrollView: UIScrollView!

override func viewDidLoad() {
    super.viewDidLoad()

    //setting portrait
    AppUtility.lockOrientation(.portrait)

    //hide keyboard when click outside
    self.hideKeyboardWhenTappedAround()

    //hide keyboard when click on return
    self.yourEmail.delegate = self
    self.scrollView.delegate = self

    //boarder line for yourEmail
    yourEmail.frame.size.height =  UIScreen.main.fixedCoordinateSpace.bounds.size.width * CGFloat(0.05)
    yourEmail.font = UIFont.italicSystemFont(ofSize: UIScreen.main.fixedCoordinateSpace.bounds.size.width * CGFloat(0.04))
    bottomBoader(BottomLine: "UrEmailTextBottomLine", length: 1.0, yourTextBox: yourEmail)
    yourEmail.applyCustomClearButton(yourTextBox: yourEmail)

    registerForKeyboardNotifications()
    deregisterFromKeyboardNotifications()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    AppUtility.lockOrientation(.portrait)
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    AppUtility.lockOrientation(.all)
}

// ***************************************************  moving textfiles when keyborad present ***********************************************************

func registerForKeyboardNotifications(){
    //Adding notifies on keyboard appearing
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

func deregisterFromKeyboardNotifications(){
    //Removing notifies on keyboard appearing
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

@objc func keyboardWasShown(notification: NSNotification){
    //Need to calculate keyboard exact size due to Apple suggestions
    self.scrollView.isScrollEnabled = true
    var info = notification.userInfo!
    let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
    let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height, 0.0)

    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets

    var aRect : CGRect = self.view.frame
    aRect.size.height -= keyboardSize!.height
    if let activeField = self.yourEmail {
        if (!aRect.contains(activeField.frame.origin)){
            self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
        }
    }
}

@objc func keyboardWillBeHidden(notification: NSNotification){
    //Once keyboard disappears, restore original positions
    var info = notification.userInfo!
    let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
    let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, -keyboardSize!.height, 0.0)
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
    self.view.endEditing(true)
    self.scrollView.isScrollEnabled = false
    //self.scrollView.contentInset = UIEdgeInsets.zero
}

func textFieldDidBeginEditing( textField: UITextField){
    yourEmail = textField
}

func textFieldDidEndEditing(textField: UITextField){
    yourEmail = nil
}
</code>```

答: Embedding your controls in a UITableView with static cells on a Storyboard will let the system take care of the scrolling for you.</p>

Body:
I have recently started to develop my own app following the instructions on internet. I am just a beginner (with no knowledge of coding) and hence may be doing very stupid mistake that I am not able to catch.

In my app I am facing a situation where my email text field is hiding behind the keyboard whenever I try to type email address. I did some research (on stack overflow) and wrote a piece of code that suppose to move my text field up but it is not ... I believe overall structure of code is right (I may be wrong here though) but it may be just tiny mistake that making my code ineffective.

can anyone guide me on what I am doing wrong here?

below is the piece of code I wrote:
{

import UIKit
import WebKit
import CoreGraphics
import AVFoundation
import QuartzCore
import Foundation

class StudentSignUpViewController: UIViewController,UIScrollViewDelegate, UITextFieldDelegate {

@IBOutlet weak var yourEmail: UITextField!
@IBOutlet weak var scrollView: UIScrollView!

override func viewDidLoad() {
    super.viewDidLoad()

    //setting portrait
    AppUtility.lockOrientation(.portrait)

    //hide keyboard when click outside
    self.hideKeyboardWhenTappedAround()

    //hide keyboard when click on return
    self.yourEmail.delegate = self
    self.scrollView.delegate = self

    //boarder line for yourEmail
    yourEmail.frame.size.height =  UIScreen.main.fixedCoordinateSpace.bounds.size.width * CGFloat(0.05)
    yourEmail.font = UIFont.italicSystemFont(ofSize: UIScreen.main.fixedCoordinateSpace.bounds.size.width * CGFloat(0.04))
    bottomBoader(BottomLine: "UrEmailTextBottomLine", length: 1.0, yourTextBox: yourEmail)
    yourEmail.applyCustomClearButton(yourTextBox: yourEmail)

    registerForKeyboardNotifications()
    deregisterFromKeyboardNotifications()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    AppUtility.lockOrientation(.portrait)
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    AppUtility.lockOrientation(.all)
}

// ***************************************************  moving textfiles when keyborad present ***********************************************************

func registerForKeyboardNotifications(){
    //Adding notifies on keyboard appearing
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

func deregisterFromKeyboardNotifications(){
    //Removing notifies on keyboard appearing
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

@objc func keyboardWasShown(notification: NSNotification){
    //Need to calculate keyboard exact size due to Apple suggestions
    self.scrollView.isScrollEnabled = true
    var info = notification.userInfo!
    let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
    let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height, 0.0)

    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets

    var aRect : CGRect = self.view.frame
    aRect.size.height -= keyboardSize!.height
    if let activeField = self.yourEmail {
        if (!aRect.contains(activeField.frame.origin)){
            self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
        }
    }
}

@objc func keyboardWillBeHidden(notification: NSNotification){
    //Once keyboard disappears, restore original positions
    var info = notification.userInfo!
    let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
    let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, -keyboardSize!.height, 0.0)
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
    self.view.endEditing(true)
    self.scrollView.isScrollEnabled = false
    //self.scrollView.contentInset = UIEdgeInsets.zero
}

func textFieldDidBeginEditing( textField: UITextField){
    yourEmail = textField
}

func textFieldDidEndEditing(textField: UITextField){
    yourEmail = nil
}


问:
cpp preprocessor doesn’t recognise UTF-32 string
I am doing some compiler research work. For this code:

```<code>static const unsigned char *dir= U"pragma dependency";
</code>```

cpp4.2 on Ubuntu 14 works, whereas cpp6 on Ubuntu 16 will throw an error. If U is deleted, it's OK.

So what's wrong with cpp6?

Updates:
I tested this code in a C project and there is no error. If it's in a C++ project, it'll be the case as someone mentioned below.

答:
There isn't anything wrong with your compiler. When you prefix a string literal with U , it means it will be an array of  const char32_t , not an array of const unsigned char

You have to change your code to

```<code> static const char32_t *dir= U"pragma dependency";
</code>```

Body:
I am doing some compiler research work. For this code:

static const unsigned char *dir= U"pragma dependency";

cpp4.2 on Ubuntu 14 works, whereas cpp6 on Ubuntu 16 will throw an error. If U is deleted, it's OK.

So what's wrong with cpp6?

Updates:
I tested this code in a C project and there is no error. If it's in a C++ project, it'll be the case as someone mentioned below.

Body:
There isn't anything wrong with your compiler. When you prefix a string literal with U , it means it will be an array of  const char32_t , not an array of const unsigned char

You have to change your code to

 static const char32_t *dir= U"pragma dependency";


问:
Ideal practice for implementing a 1:1 relationship
In a webshop, there are two (relevant to this question) tables: UserSnapshot and Purchase. Upon making a purchase, the user's current information is snapshot so that the purchase records are intact even if the user is later removed or changed. This gives a 1:1 relationship, where each purchase has only one user snapshot, and each user snapshot has only one purchase.

My question is, how should I implement this? Should I have a foreign key pointing to the user snapshot in the purchase table, the other way around, or should I use both (redundant)? Should I combine the two (messy)? Serialise the user snapshot (does not obey 'one value per field')?

答:
I'd suggest looking at the likely queries you want to run, and design your model on that basis.

For instance, I guess you want to know "which orders has this customer placed?". The most natural way of expressing that would be something like:

```<code>select *
from customer c
inner join customer_snapshot cs
  on c.customer_id = cs.customer_id
inner join orders o
  on cs.order_id = o.order_id
</code>```

where c.customer_id = ?

Or: "What is the current status of the customer who placed this order?".

```<code>select *
from order o
inner join customer_snapshot cs
  on o.order_id = cs.order_id
inner join customer c
  on cs.customer_id = c.customer_id
where o.order_id = ?
</code>```

This feels natural to me, as it almost uses the customer_snapshot table as a "many to many" joining table.

But that's mostly stylistic - the join could just as easily be on o.customer_snapshot_id = cs.customer_snapshot_id.

How about "how many orders were sent to customers living in city x?"

```<code>select *
from order o
inner join customer_snapshot cs
  on o.order_id = cs.order_id
inner join customer c
  on cs.customer_id = c.customer_id
and cs.city = ?
</code>```

You don't need "redundant" columns - all queries work without jumping through hoops. You could serialize the snapshot data, but then the "which orders were for customers living in city x" query would be painful.

Body:
I'd suggest looking at the likely queries you want to run, and design your model on that basis.

For instance, I guess you want to know "which orders has this customer placed?". The most natural way of expressing that would be something like:

select *
from customer c
inner join customer_snapshot cs
  on c.customer_id = cs.customer_id
inner join orders o
  on cs.order_id = o.order_id

where c.customer_id = ?

Or: "What is the current status of the customer who placed this order?".

select *
from order o
inner join customer_snapshot cs
  on o.order_id = cs.order_id
inner join customer c
  on cs.customer_id = c.customer_id
where o.order_id = ?

This feels natural to me, as it almost uses the customer_snapshot table as a "many to many" joining table.

But that's mostly stylistic - the join could just as easily be on o.customer_snapshot_id = cs.customer_snapshot_id.

How about "how many orders were sent to customers living in city x?"

select *
from order o
inner join customer_snapshot cs
  on o.order_id = cs.order_id
inner join customer c
  on cs.customer_id = c.customer_id
and cs.city = ?

You don't need "redundant" columns - all queries work without jumping through hoops. You could serialize the snapshot data, but then the "which orders were for customers living in city x" query would be painful.