问:
Problems when sending XML data from HTTP Java client to a servlet with HttpURLConnection
I have standalone java client sending xml data to http servlet using httpURLconnection class.but data appearing in non printable character format.

For simulation i have been trying to send simple string but still it was appearing in non printable format.

I have written the following client code to communicate with servlet,

```<code>import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;

public class HttpClient implements IClient {

    private static IClient client = null;

    private HttpURLConnection httpConn = null;

    private OutputStream output = null;

    private InputStream input = null;

    private OutputStreamWriter out = null;

    private HttpClient() {
    }

    public static IClient getHttpClient() {
        if (client == null) {
            client = new HttpClient();
        }
        return client;
    }

    @Override
    public void connect(String urlString) throws IOException {
        URL url = new URL(urlString);
        httpConn = (HttpURLConnection) url.openConnection();
        initConnection();
        httpConn.connect();
        output = httpConn.getOutputStream();
        input = httpConn.getInputStream();
        System.out.println("Connection Response:" + httpConn.getResponseCode());
    }

    @Override
    public void sendFile(File file) throws IOException {
        // BufferedOutputStream bos = new BufferedOutputStream(output);
        // InputStream fis = new FileInputStream(file);
        // int bytesRead = 0;
        // byte[] buffer = new byte[8192];
        // while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
        // bos.write(buffer, 0, bytesRead);
        // System.out.println("write:"+buffer);
        // }
        // bos.close();
        // fis.close();

        OutputStreamWriter out = new OutputStreamWriter(output, "UTF-16");
        out.write("test me");
    }

    @Override
    public boolean isConnected() {
        return httpConn != null ? true : false;
    }

    @Override
    public void close() {
        httpConn.disconnect();
    }

    private void initConnection() throws ProtocolException {
        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);
        httpConn.setRequestMethod("POST");
        httpConn.setUseCaches(false);
        httpConn.setRequestProperty("Content-Type",
                "text/xml; charset=\"UTF-16\"");
        httpConn.setRequestProperty("Connection", "Keep-Alive");

    }

    private static byte[] getBytesFromFile(File file) throws IOException {

        InputStream is = new FileInputStream(file);
        System.out.println("\nDEBUG: FileInputStream is " + file);

        // Get the size of the file
        long length = file.length();
        System.out.println("DEBUG: Length of " + file + " is " + length + "\n");

        /*
         * You cannot create an array using a long type. It needs to be an int
         * type. Before converting to an int type, check to ensure that file is
         * not loarger than Integer.MAX_VALUE;
         */
        if (length > Integer.MAX_VALUE) {
            System.out.println("File is too large to process");
            return null;
        }

        // Create the byte array to hold the data
        byte[] bytes = new byte[(int) length];

        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        while ((offset < bytes.length)
                && ((numRead = is.read(bytes, offset, bytes.length - offset)) >= 0)) {

            offset += numRead;

        }

        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file "
                    + file.getName());
        }

        return bytes;

    }

}
</code>```

and servlet code is given below,

```<code>import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class XMLServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println("=========inside doPost=========");
//      BufferedInputStream bis = new BufferedInputStream(req.getInputStream());
//      OutputStream fos = new FileOutputStream("test.xml");
//      int bytesRead = 0;
//      byte[] buffer = new byte[8192];
//      while ((bytesRead = bis.read(buffer, 0, 8192)) != -1) {
//          System.out.println("read:"+buffer);
//          fos.write(buffer, 0, bytesRead);
//      }
//      fos.close();
//      bis.close();
//

        req.setCharacterEncoding("UTF-16");
        InputStreamReader isr = new InputStreamReader(req.getInputStream(),"UTF-16");
        char[] data = new char[10];
        isr.read(data);
        System.out.println(data);
        for (char c : data) {
            System.out.println(c);
        }
    }

}
</code>```

Please any help me to get out of this problem.

答:
I think you are overcomplicating it.  I JUST wrote something similar that takes any file and transfers it through HTTP to a servlet.  Just remember:  All data is binary (including a text file)-- period.  It's up to the given application to interpret that binary data. For example, notepad.exe simply reads a binary set of data and attempts to format it using ASCII standard.  So knowing that, simply read a file using a raw stream, set the mime-type of the connection to application/octet-stream and send it via "PUT" method.  The servlet code should be reading the file using the raw InputStream from the request and creating the corresponding file in its space.

From the client code:

```<code>URL url = new URL(urlString);
HttpURLConnection cnx = (HttpURLConnection)url.openConnection();
cnx.setRequestMethod("PUT");
cnx.setRequestProperty("Content-Type", "application/octet-stream");
// optional request property
cnx.setRequestProperty("filename", filename);
cnx.setDoOutput(true);
cnx.connect();
BufferedInputStream fileIn =
       new BufferedInputStream(new FileInputStream(fileName), BUFFER_SIZE);
BufferedOutputStream out =
       new BufferedOutputStream(cnx.getOutputStream(), BUFFER_SIZE);
byte[] bytes = new byte[BUFFER_SIZE];
int bytesRead;
while((bytesRead = fileIn.read(bytes)) != -1){
   out.write(bytes, 0, bytesRead);
}
</code>```

That's it.

Now the servlet code....

```<code>public void doPut(HttpServletRequest request, HttpServletResponse response){
    String filename = (String)request.getHeader("filename");
    StringBuilder fullPath = new StringBuilder(100);
    ServletContext ctxt = getServletContext();
    fullPath.append(ctxt.getRealPath(""))
      .append("uploads\\").append(filename);
    File f = new File(fullPath.toString());
    f.createNewFile();
    InputStream in = request.getInputStream();
    BufferedOutputStream fileOut =
        new BufferedOutputStream(new FileOutputStream(f));
    byte[] bytes = new byte[BUFFER_SIZE];
    int bytesRead;
    while((bytesRead = in.read(bytes)) != -1){
       fileOut.write(bytes, 0, bytesRead);
    }
    fileOut.flush();
    fileOut.close();
    response.setStatus(HttpServletResponse.SC_CREATED);
}
</code>```

Body:
I have standalone java client sending xml data to http servlet using httpURLconnection class.but data appearing in non printable character format.

For simulation i have been trying to send simple string but still it was appearing in non printable format.

I have written the following client code to communicate with servlet,

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;

public class HttpClient implements IClient {

    private static IClient client = null;

    private HttpURLConnection httpConn = null;

    private OutputStream output = null;

    private InputStream input = null;

    private OutputStreamWriter out = null;

    private HttpClient() {
    }

    public static IClient getHttpClient() {
        if (client == null) {
            client = new HttpClient();
        }
        return client;
    }

    @Override
    public void connect(String urlString) throws IOException {
        URL url = new URL(urlString);
        httpConn = (HttpURLConnection) url.openConnection();
        initConnection();
        httpConn.connect();
        output = httpConn.getOutputStream();
        input = httpConn.getInputStream();
        System.out.println("Connection Response:" + httpConn.getResponseCode());
    }

    @Override
    public void sendFile(File file) throws IOException {
        // BufferedOutputStream bos = new BufferedOutputStream(output);
        // InputStream fis = new FileInputStream(file);
        // int bytesRead = 0;
        // byte[] buffer = new byte[8192];
        // while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
        // bos.write(buffer, 0, bytesRead);
        // System.out.println("write:"+buffer);
        // }
        // bos.close();
        // fis.close();

        OutputStreamWriter out = new OutputStreamWriter(output, "UTF-16");
        out.write("test me");
    }

    @Override
    public boolean isConnected() {
        return httpConn != null ? true : false;
    }

    @Override
    public void close() {
        httpConn.disconnect();
    }

    private void initConnection() throws ProtocolException {
        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);
        httpConn.setRequestMethod("POST");
        httpConn.setUseCaches(false);
        httpConn.setRequestProperty("Content-Type",
                "text/xml; charset=\"UTF-16\"");
        httpConn.setRequestProperty("Connection", "Keep-Alive");

    }

    private static byte[] getBytesFromFile(File file) throws IOException {

        InputStream is = new FileInputStream(file);
        System.out.println("\nDEBUG: FileInputStream is " + file);

        // Get the size of the file
        long length = file.length();
        System.out.println("DEBUG: Length of " + file + " is " + length + "\n");

        /*
         * You cannot create an array using a long type. It needs to be an int
         * type. Before converting to an int type, check to ensure that file is
         * not loarger than Integer.MAX_VALUE;
         */
        if (length > Integer.MAX_VALUE) {
            System.out.println("File is too large to process");
            return null;
        }

        // Create the byte array to hold the data
        byte[] bytes = new byte[(int) length];

        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        while ((offset < bytes.length)
                && ((numRead = is.read(bytes, offset, bytes.length - offset)) >= 0)) {

            offset += numRead;

        }

        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file "
                    + file.getName());
        }

        return bytes;

    }

}

and servlet code is given below,

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class XMLServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println("=========inside doPost=========");
//      BufferedInputStream bis = new BufferedInputStream(req.getInputStream());
//      OutputStream fos = new FileOutputStream("test.xml");
//      int bytesRead = 0;
//      byte[] buffer = new byte[8192];
//      while ((bytesRead = bis.read(buffer, 0, 8192)) != -1) {
//          System.out.println("read:"+buffer);
//          fos.write(buffer, 0, bytesRead);
//      }
//      fos.close();
//      bis.close();
//

        req.setCharacterEncoding("UTF-16");
        InputStreamReader isr = new InputStreamReader(req.getInputStream(),"UTF-16");
        char[] data = new char[10];
        isr.read(data);
        System.out.println(data);
        for (char c : data) {
            System.out.println(c);
        }
    }

}

Please any help me to get out of this problem.

Body:
I think you are overcomplicating it.  I JUST wrote something similar that takes any file and transfers it through HTTP to a servlet.  Just remember:  All data is binary (including a text file)-- period.  It's up to the given application to interpret that binary data. For example, notepad.exe simply reads a binary set of data and attempts to format it using ASCII standard.  So knowing that, simply read a file using a raw stream, set the mime-type of the connection to application/octet-stream and send it via "PUT" method.  The servlet code should be reading the file using the raw InputStream from the request and creating the corresponding file in its space.

From the client code:

URL url = new URL(urlString);
HttpURLConnection cnx = (HttpURLConnection)url.openConnection();
cnx.setRequestMethod("PUT");
cnx.setRequestProperty("Content-Type", "application/octet-stream");
// optional request property
cnx.setRequestProperty("filename", filename);
cnx.setDoOutput(true);
cnx.connect();
BufferedInputStream fileIn =
       new BufferedInputStream(new FileInputStream(fileName), BUFFER_SIZE);
BufferedOutputStream out =
       new BufferedOutputStream(cnx.getOutputStream(), BUFFER_SIZE);
byte[] bytes = new byte[BUFFER_SIZE];
int bytesRead;
while((bytesRead = fileIn.read(bytes)) != -1){
   out.write(bytes, 0, bytesRead);
}

That's it.

Now the servlet code....

public void doPut(HttpServletRequest request, HttpServletResponse response){
    String filename = (String)request.getHeader("filename");
    StringBuilder fullPath = new StringBuilder(100);
    ServletContext ctxt = getServletContext();
    fullPath.append(ctxt.getRealPath(""))
      .append("uploads\\").append(filename);
    File f = new File(fullPath.toString());
    f.createNewFile();
    InputStream in = request.getInputStream();
    BufferedOutputStream fileOut =
        new BufferedOutputStream(new FileOutputStream(f));
    byte[] bytes = new byte[BUFFER_SIZE];
    int bytesRead;
    while((bytesRead = in.read(bytes)) != -1){
       fileOut.write(bytes, 0, bytesRead);
    }
    fileOut.flush();
    fileOut.close();
    response.setStatus(HttpServletResponse.SC_CREATED);
}


来源: stackexchange

答:
If you change
declare @poly geography and set @poly=geography::STPolyFromText...
to
declare @poly geometry and set @poly=geometry ::STPolyFromText...

you will see polygon drawn in the spatial results tab.

ContentLicense: CC BY-SA 3.0

Title: SQL Server doesn´t recognize polygon

Body:
I extracted the polygon coordinates from a bunch of districts from openstreetmap. To my surprise when I run it, it doesn´t recognize it as a polygon while when I draw it by linestring it draws it correctly. Can anyone tell me why and how to fix it?

I am using SQL server 2016

declare @poly geography
declare @linestring geography
set @poly=geography::STPolyFromText('POLYGON((-3.7251721 40.3346954,-3.7211547 40.3654057,-3.7190862 40.3649337,-3.7160496 40.3645544,-3.711698 40.3641097,-3.7059412 40.3638936,-3.7022824 40.3635865,-3.6997332 40.3640443,-3.6977591 40.3643909,-3.6961026 40.3645347,-3.6927981 40.3645086,-3.6915554 40.364468,-3.6903977 40.3642285,-3.6886353 40.3637042,-3.6830306 40.3617095,-3.6819717 40.3614412,-3.6814057 40.3600219,-3.6806572 40.3595494,-3.6792339 40.3581255,-3.6785129 40.3577919,-3.6778348 40.3575499,-3.6773971 40.357151,-3.6771124 40.3566378,-3.6768833 40.3557292,-3.6766677 40.3550021,-3.676415 40.3542448,-3.6758092 40.3537694,-3.6747621 40.3535601,-3.674187 40.3533181,-3.6738523 40.3530892,-3.6736806 40.3528145,-3.6736034 40.3521342,-3.6734648 40.3514367,-3.6732923 40.3509194,-3.6729425 40.3504859,-3.6725305 40.3502111,-3.6719211 40.3499822,-3.670256 40.3495178,-3.6697974 40.3492625,-3.6694766 40.3489478,-3.668994 40.3474553,-3.6690075 40.3468868,-3.6690911 40.3463332,-3.6692012 40.3459511,-3.6693869 40.3456349,-3.6694909 40.3454513,-3.6693897 40.3452304,-3.6689857 40.3449649,-3.6684603 40.3447916,-3.6680641 40.344684,-3.6666032 40.3443162,-3.6651576 40.3440622,-3.6646598 40.3438528,-3.6642958 40.3434826,-3.6640332 40.3427015,-3.6636899 40.3422435,-3.6631578 40.3412164,-3.6628402 40.3391622,-3.66272 40.3388874,-3.6622308 40.3385734,-3.6617983 40.3382015,-3.6615613 40.3379977,-3.661424 40.3375986,-3.6613982 40.3370556,-3.6612094 40.3363882,-3.6605485 40.3354265,-3.6596387 40.3346545,-3.6587804 40.3337254,-3.6585229 40.3332674,-3.6584628 40.3324953,-3.6582568 40.3316317,-3.657816 40.3307174,-3.6576732 40.3304212,-3.657359 40.3290369,-3.6592657 40.3282873,-3.660041 40.3281207,-3.6606531 40.3281172,-3.6612437 40.328321,-3.662074 40.328965,-3.6628079 40.3293842,-3.663539 40.3295061,-3.6662634 40.3276346,-3.6669148 40.3268381,-3.6676037 40.3262755,-3.6686923 40.3256476,-3.6693252 40.3253737,-3.6704523 40.3250789,-3.67128 40.3254525,-3.674173 40.3263726,-3.6755624 40.3264096,-3.6776978 40.3268926,-3.6786043 40.3269053,-3.6794497 40.3266931,-3.6799414 40.32642,-3.6804064 40.3258407,-3.6808917 40.3249369,-3.681206 40.3245837,-3.6830826 40.323915,-3.6834104 40.3237328,-3.6848 40.3226345,-3.6859754 40.3224744,-3.6876934 40.3224282,-3.6889852 40.3221322,-3.693432 40.3207453,-3.6964539 40.3227452,-3.7014914 40.3227148,-3.7037032 40.3226113,-3.7044926 40.3226876,-3.7099055 40.3236726,-3.712603 40.3238632,-3.7130333 40.3256084,-3.7135981 40.326704,-3.7148182 40.3285524,-3.7161782 40.3291476,-3.7201193 40.3311322,-3.7228013 40.3328939,-3.723 40.3330242,-3.7235589 40.3335523,-3.7251721 40.3346954))',4326)
set @linestring=geography::STLineFromText('LINESTRING(-3.7251721 40.3346954,-3.7211547 40.3654057,-3.7190862 40.3649337,-3.7160496 40.3645544,-3.711698 40.3641097,-3.7059412 40.3638936,-3.7022824 40.3635865,-3.6997332 40.3640443,-3.6977591 40.3643909,-3.6961026 40.3645347,-3.6927981 40.3645086,-3.6915554 40.364468,-3.6903977 40.3642285,-3.6886353 40.3637042,-3.6830306 40.3617095,-3.6819717 40.3614412,-3.6814057 40.3600219,-3.6806572 40.3595494,-3.6792339 40.3581255,-3.6785129 40.3577919,-3.6778348 40.3575499,-3.6773971 40.357151,-3.6771124 40.3566378,-3.6768833 40.3557292,-3.6766677 40.3550021,-3.676415 40.3542448,-3.6758092 40.3537694,-3.6747621 40.3535601,-3.674187 40.3533181,-3.6738523 40.3530892,-3.6736806 40.3528145,-3.6736034 40.3521342,-3.6734648 40.3514367,-3.6732923 40.3509194,-3.6729425 40.3504859,-3.6725305 40.3502111,-3.6719211 40.3499822,-3.670256 40.3495178,-3.6697974 40.3492625,-3.6694766 40.3489478,-3.668994 40.3474553,-3.6690075 40.3468868,-3.6690911 40.3463332,-3.6692012 40.3459511,-3.6693869 40.3456349,-3.6694909 40.3454513,-3.6693897 40.3452304,-3.6689857 40.3449649,-3.6684603 40.3447916,-3.6680641 40.344684,-3.6666032 40.3443162,-3.6651576 40.3440622,-3.6646598 40.3438528,-3.6642958 40.3434826,-3.6640332 40.3427015,-3.6636899 40.3422435,-3.6631578 40.3412164,-3.6628402 40.3391622,-3.66272 40.3388874,-3.6622308 40.3385734,-3.6617983 40.3382015,-3.6615613 40.3379977,-3.661424 40.3375986,-3.6613982 40.3370556,-3.6612094 40.3363882,-3.6605485 40.3354265,-3.6596387 40.3346545,-3.6587804 40.3337254,-3.6585229 40.3332674,-3.6584628 40.3324953,-3.6582568 40.3316317,-3.657816 40.3307174,-3.6576732 40.3304212,-3.657359 40.3290369,-3.6592657 40.3282873,-3.660041 40.3281207,-3.6606531 40.3281172,-3.6612437 40.328321,-3.662074 40.328965,-3.6628079 40.3293842,-3.663539 40.3295061,-3.6662634 40.3276346,-3.6669148 40.3268381,-3.6676037 40.3262755,-3.6686923 40.3256476,-3.6693252 40.3253737,-3.6704523 40.3250789,-3.67128 40.3254525,-3.674173 40.3263726,-3.6755624 40.3264096,-3.6776978 40.3268926,-3.6786043 40.3269053,-3.6794497 40.3266931,-3.6799414 40.32642,-3.6804064 40.3258407,-3.6808917 40.3249369,-3.681206 40.3245837,-3.6830826 40.323915,-3.6834104 40.3237328,-3.6848 40.3226345,-3.6859754 40.3224744,-3.6876934 40.3224282,-3.6889852 40.3221322,-3.693432 40.3207453,-3.6964539 40.3227452,-3.7014914 40.3227148,-3.7037032 40.3226113,-3.7044926 40.3226876,-3.7099055 40.3236726,-3.712603 40.3238632,-3.7130333 40.3256084,-3.7135981 40.326704,-3.7148182 40.3285524,-3.7161782 40.3291476,-3.7201193 40.3311322,-3.7228013 40.3328939,-3.723 40.3330242,-3.7235589 40.3335523,-3.7251721 40.3346954)',4326)

select @poly as polygon, @linestring as linestring


问:
How can I write XML which is divided into three horizontal columns and four vertical rows?
How can I write xml which is divided into three horizontal columns and four vertical rows?

It should be divide into three columns while three columns further divided into four rows as per screenshot shown below.

How can I get views like attached image through XML?

For horizontal:

```<code><LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal" android:layout_width="match_parent"
        android:layout_marginTop="2dp"
        android:layout_height="wrap_content"
        android:weightSum="3"
        android:id="@+id/l1"
        android:background="#ffff">

        <ImageView
            android:id="@+id/glassconsumed1"
            android:src="@drawable/icon2"
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:textColor="#ffff"
            android:paddingLeft="40dp"
            android:paddingRight="@dimen/desc_padding"
            android:layout_height="20.7dp" />

        <ImageView
            android:id="@+id/glassconsumed22"
            android:src="@drawable/icon2"
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:textColor="#ffff"
            android:paddingLeft="40dp"
            android:paddingRight="@dimen/desc_padding"
            android:layout_height="20.7dp" />

        <ImageView
            android:id="@+id/glassconsumed32"
            android:src="@drawable/icon2"
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:textColor="#ffff"
            android:paddingLeft="40dp"
            android:paddingRight="@dimen/desc_padding"
            android:layout_height="20.7dp" />
        </LinearLayout>
</code>```

for Vertical

```<code><LinearLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:orientation="vertical" android:layout_width="match_parent"
            android:layout_marginTop="2dp"
            android:layout_height="wrap_content"
            android:weightSum="3"
            android:layout_below="@+id/glassconsumed1"
            android:id="@+id/l2"
            android:background="#ffff">
        <TextView
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:layout_weight="1"
            android:layout_below="@+id/glassconsumed1"
            android:hint="   14/16"
            android:textSize="16dp"
            android:layout_width="wrap_content"
            android:background="@color/white"
            android:textColorHint="#8E8E8E"
            android:layout_marginTop="2dp"
            android:paddingLeft="@dimen/desc_padding"
            android:paddingRight="@dimen/desc_padding"
            android:textColor="#000000"
            android:id="@+id/editTextvalue1" />
            <TextView

                android:layout_height="wrap_content"
                android:inputType="textPersonName"
                android:layout_below="@+id/editTextvalue1"
                android:layout_weight="1"
                android:hint="  Glasses"
                android:textSize="16dp"
                android:layout_width="wrap_content"
                android:background="@color/white"
                android:textColorHint="#8E8E8E"

                android:layout_marginTop="2dp"
                android:paddingLeft="@dimen/desc_padding"
                android:paddingRight="@dimen/desc_padding"
                android:textColor="#000000"
                android:id="@+id/editTextvalue2" />
            <TextView

                android:layout_height="wrap_content"
                android:inputType="textPersonName"
                android:layout_below="@+id/editTextvalue2"
                android:layout_weight="1"
                android:hint="Consumed"
                android:textSize="16dp"
                android:layout_width="wrap_content"
                android:background="@color/white"
                android:textColorHint="#8E8E8E"

                android:layout_marginTop="2dp"
                android:paddingLeft="@dimen/desc_padding"
                android:paddingRight="@dimen/desc_padding"
                android:textColor="#000000"
                android:id="@+id/editTextvalue3" />
            </LinearLayout>
</code>```

答:
You can use GridLayout or TableLayout

See these examples: TableLayout, GridLayout

Body:
How can I write xml which is divided into three horizontal columns and four vertical rows?

It should be divide into three columns while three columns further divided into four rows as per screenshot shown below.

How can I get views like attached image through XML?

For horizontal:

<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal" android:layout_width="match_parent"
        android:layout_marginTop="2dp"
        android:layout_height="wrap_content"
        android:weightSum="3"
        android:id="@+id/l1"
        android:background="#ffff">

        <ImageView
            android:id="@+id/glassconsumed1"
            android:src="@drawable/icon2"
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:textColor="#ffff"
            android:paddingLeft="40dp"
            android:paddingRight="@dimen/desc_padding"
            android:layout_height="20.7dp" />

        <ImageView
            android:id="@+id/glassconsumed22"
            android:src="@drawable/icon2"
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:textColor="#ffff"
            android:paddingLeft="40dp"
            android:paddingRight="@dimen/desc_padding"
            android:layout_height="20.7dp" />

        <ImageView
            android:id="@+id/glassconsumed32"
            android:src="@drawable/icon2"
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:textColor="#ffff"
            android:paddingLeft="40dp"
            android:paddingRight="@dimen/desc_padding"
            android:layout_height="20.7dp" />
        </LinearLayout>

for Vertical

<LinearLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:orientation="vertical" android:layout_width="match_parent"
            android:layout_marginTop="2dp"
            android:layout_height="wrap_content"
            android:weightSum="3"
            android:layout_below="@+id/glassconsumed1"
            android:id="@+id/l2"
            android:background="#ffff">
        <TextView
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:layout_weight="1"
            android:layout_below="@+id/glassconsumed1"
            android:hint="   14/16"
            android:textSize="16dp"
            android:layout_width="wrap_content"
            android:background="@color/white"
            android:textColorHint="#8E8E8E"
            android:layout_marginTop="2dp"
            android:paddingLeft="@dimen/desc_padding"
            android:paddingRight="@dimen/desc_padding"
            android:textColor="#000000"
            android:id="@+id/editTextvalue1" />
            <TextView

                android:layout_height="wrap_content"
                android:inputType="textPersonName"
                android:layout_below="@+id/editTextvalue1"
                android:layout_weight="1"
                android:hint="  Glasses"
                android:textSize="16dp"
                android:layout_width="wrap_content"
                android:background="@color/white"
                android:textColorHint="#8E8E8E"

                android:layout_marginTop="2dp"
                android:paddingLeft="@dimen/desc_padding"
                android:paddingRight="@dimen/desc_padding"
                android:textColor="#000000"
                android:id="@+id/editTextvalue2" />
            <TextView

                android:layout_height="wrap_content"
                android:inputType="textPersonName"
                android:layout_below="@+id/editTextvalue2"
                android:layout_weight="1"
                android:hint="Consumed"
                android:textSize="16dp"
                android:layout_width="wrap_content"
                android:background="@color/white"
                android:textColorHint="#8E8E8E"

                android:layout_marginTop="2dp"
                android:paddingLeft="@dimen/desc_padding"
                android:paddingRight="@dimen/desc_padding"
                android:textColor="#000000"
                android:id="@+id/editTextvalue3" />
            </LinearLayout>


问:
fscanf two lines of data, perform calc, print result, fscanf next two lines, in a single loop?
I am using this for loop to bring in data from a file of latitude and longitude coordinates, then converting the coordinates to decimal degrees, degrees to radians, then calculating the angle of separation, and returning the distance between the two cities.  I need to compare the first two lines from the file, calculate the distance, print the results, and then do the next two lines.  I have got it exactly the way I want it, but with five identical for loops, just adjusting the loop control parameters each time.  Is there a way to accomplish this with only one loop?</p>

```<code>   for(i=0;i<=ndata-9;i++)
   {
       printf("\n%-15s     %3.0f %4.1f %c     %3.0f %4.1f %c",cities[i].location,
         cities[i].latdeg,cities[i].latmin,cities[i].directone,
         cities[i].longdeg,cities[i].longmin,cities[i].directtwo);
       fprintf(surface,"\n%-15s     %3.0f %4.1f %c     %3.0f %4.1f %c",
           cities[i].location,cities[i].latdeg,cities[i].latmin,
           cities[i].directone,cities[i].longdeg,cities[i].longmin,
           cities[i].directtwo);
       if(cities[i-1].directone=='N')
       {
           polarone=(90.0-(cities[i-1].latdeg+(cities[i-1].latmin/60.0)))*(pi/180.0);
       }
       else
       {
           polarone=(90.0+(cities[i-1].latdeg+(cities[i-1].latmin/60.0)))*(pi/180.0);
       }
       if(cities[i].directone=='N')
       {
            polartwo=(90.0-(cities[i].latdeg+(cities[i].latmin/60.0)))*(pi/180.0);
       }
       else
       {
           polartwo=(90.0+(cities[i].latdeg+(cities[i].latmin/60.0)))*(pi/180.0);
       }
       if(cities[i-1].directtwo=='W')
       {
           azimuthone=(cities[i-1].longdeg+(cities[i-1].longmin/60.0))*(pi/180.0);
       }
       else
       {
           azimuthone=(360.0-(cities[i-1].longdeg+(cities[i-1].longmin/60.0)))*(pi/180.0);
       }
       if(cities[i].directtwo=='W')
       {
           azimuthtwo=(cities[i].longdeg+(cities[i].longmin/60.0))*(pi/180.0);
       }
       else
       {
           azimuthtwo=(360.0-(cities[i].longdeg+(cities[i].longmin/60.0)))*(pi/180.0);
       }
       angle=acos(cos(polarone)*cos(polartwo)+sin(polarone)*sin(polartwo)*cos(azimuthtwo-azimuthone));
       distance=angle*radius;
   }
   printf("\nDistance between the two cities = %6.1f miles\n",distance);
   fprintf(surface,"\nDistance between the two cities = %6.1f miles\n", distance);
</code>```

答:
DIVIDE AND CONQUER!!!

(What follows is for demonstration purposes. I assume everything is double, and cities have type struct City. Change the types if neccessary. Also, I did not debug it.)

```<code>const double deg_to_rad = pi/180, half_pi = pi/2, two_pi = pi*2;

inline double RadFromDeg(double degrees, double minutes) {
    return (degrees+minutes/60)*deg_to_rad;
}

// not sure if we really need inline here
inline void ObtainPolarAzimuth(double* polar, double* azimuth, struct City* city) {
    double temp = RadFromDeg(city->latdeg, city->latmin);
    if (city->directone == 'N')
        *polar = half_pi - temp;
    else
        *polar = half_pi + temp;
    // ... blablabla longdeg blablabla longmin blablabla *azimuth
}

// ...

    ObtainPolarAzimuth(*polar1, *azimuth1, city[i-1]);
    ObtainPolarAzimuth(*polar2, *azimuth2, city[i]);
    // ... blablabla angle blablabla cos blablabla sin
</code>```

Also, imho it would be better to write direct1 and direct2 instead of directone and directtwo.

Body:
I am using this for loop to bring in data from a file of latitude and longitude coordinates, then converting the coordinates to decimal degrees, degrees to radians, then calculating the angle of separation, and returning the distance between the two cities.  I need to compare the first two lines from the file, calculate the distance, print the results, and then do the next two lines.  I have got it exactly the way I want it, but with five identical for loops, just adjusting the loop control parameters each time.  Is there a way to accomplish this with only one loop?

   for(i=0;i<=ndata-9;i++)
   {
       printf("\n%-15s     %3.0f %4.1f %c     %3.0f %4.1f %c",cities[i].location,
         cities[i].latdeg,cities[i].latmin,cities[i].directone,
         cities[i].longdeg,cities[i].longmin,cities[i].directtwo);
       fprintf(surface,"\n%-15s     %3.0f %4.1f %c     %3.0f %4.1f %c",
           cities[i].location,cities[i].latdeg,cities[i].latmin,
           cities[i].directone,cities[i].longdeg,cities[i].longmin,
           cities[i].directtwo);
       if(cities[i-1].directone=='N')
       {
           polarone=(90.0-(cities[i-1].latdeg+(cities[i-1].latmin/60.0)))*(pi/180.0);
       }
       else
       {
           polarone=(90.0+(cities[i-1].latdeg+(cities[i-1].latmin/60.0)))*(pi/180.0);
       }
       if(cities[i].directone=='N')
       {
            polartwo=(90.0-(cities[i].latdeg+(cities[i].latmin/60.0)))*(pi/180.0);
       }
       else
       {
           polartwo=(90.0+(cities[i].latdeg+(cities[i].latmin/60.0)))*(pi/180.0);
       }
       if(cities[i-1].directtwo=='W')
       {
           azimuthone=(cities[i-1].longdeg+(cities[i-1].longmin/60.0))*(pi/180.0);
       }
       else
       {
           azimuthone=(360.0-(cities[i-1].longdeg+(cities[i-1].longmin/60.0)))*(pi/180.0);
       }
       if(cities[i].directtwo=='W')
       {
           azimuthtwo=(cities[i].longdeg+(cities[i].longmin/60.0))*(pi/180.0);
       }
       else
       {
           azimuthtwo=(360.0-(cities[i].longdeg+(cities[i].longmin/60.0)))*(pi/180.0);
       }
       angle=acos(cos(polarone)*cos(polartwo)+sin(polarone)*sin(polartwo)*cos(azimuthtwo-azimuthone));
       distance=angle*radius;
   }
   printf("\nDistance between the two cities = %6.1f miles\n",distance);
   fprintf(surface,"\nDistance between the two cities = %6.1f miles\n", distance);

Body:
DIVIDE AND CONQUER!!!

(What follows is for demonstration purposes. I assume everything is double, and cities have type struct City. Change the types if neccessary. Also, I did not debug it.)

const double deg_to_rad = pi/180, half_pi = pi/2, two_pi = pi*2;

inline double RadFromDeg(double degrees, double minutes) {
    return (degrees+minutes/60)*deg_to_rad;
}

// not sure if we really need inline here
inline void ObtainPolarAzimuth(double* polar, double* azimuth, struct City* city) {
    double temp = RadFromDeg(city->latdeg, city->latmin);
    if (city->directone == 'N')
        *polar = half_pi - temp;
    else
        *polar = half_pi + temp;
    // ... blablabla longdeg blablabla longmin blablabla *azimuth
}

// ...

    ObtainPolarAzimuth(*polar1, *azimuth1, city[i-1]);
    ObtainPolarAzimuth(*polar2, *azimuth2, city[i]);
    // ... blablabla angle blablabla cos blablabla sin

Also, imho it would be better to write direct1 and direct2 instead of directone and directtwo.


问:
PL SQL : Create oracle record dynamically
I dont know if it is possible but I would like to do this in PL/SQL

Let's say I have a parameter in my procedure, a number : numberColumns.

Inside the procedure I would like to create a record :

```<code>TYPE arrayColumn IS RECORD (
   column1 VARCHAR2(200),
   column2 VARCHAR2(200)...
   ... as much à numberColumns value
   ....
);
</code>```

ty

答:
This can be achieved easily with with OBJECT type in Oracle. But this kind of architecture is not at all suggested. Hope this below solution helps.</p>

```<code>CREATE OR REPLACE
PROCEDURE test_obj_form(
    a NUMBER )
AS
  lv_sql VARCHAR2(32676);
BEGIN
  SELECT '('
    ||listagg(str,',') WITHIN GROUP (
  ORDER BY lvl)
    ||')'
  INTO lv_sql
  FROM
    (SELECT 1 dum,
      'column'
      ||LEVEL
      ||' '
      ||'varchar2(200)' str,
      level lvl
    FROM dual
      CONNECT BY LEVEL < A
    ORDER BY LEVEL
    )
  GROUP BY dum;
  EXECUTE IMMEDIATE 'CREATE OR REPLACE TYPE name_rec IS OBJECT '||lv_sql;
  dbms_output.put_line(lv_sql);
END;
/
</code>```

Body:
I dont know if it is possible but I would like to do this in PL/SQL

Let's say I have a parameter in my procedure, a number : numberColumns.

Inside the procedure I would like to create a record :

TYPE arrayColumn IS RECORD (
   column1 VARCHAR2(200),
   column2 VARCHAR2(200)...
   ... as much à numberColumns value
   ....
);

ty

Body:
This can be achieved easily with with OBJECT type in Oracle. But this kind of architecture is not at all suggested. Hope this below solution helps.

CREATE OR REPLACE
PROCEDURE test_obj_form(
    a NUMBER )
AS
  lv_sql VARCHAR2(32676);
BEGIN
  SELECT '('
    ||listagg(str,',') WITHIN GROUP (
  ORDER BY lvl)
    ||')'
  INTO lv_sql
  FROM
    (SELECT 1 dum,
      'column'
      ||LEVEL
      ||' '
      ||'varchar2(200)' str,
      level lvl
    FROM dual
      CONNECT BY LEVEL < A
    ORDER BY LEVEL
    )
  GROUP BY dum;
  EXECUTE IMMEDIATE 'CREATE OR REPLACE TYPE name_rec IS OBJECT '||lv_sql;
  dbms_output.put_line(lv_sql);
END;
/


问:
Re-using PreparedStatement when using Datastax Cassandra Driver?
I'm currently using the Datastax Cassandra driver for Cassandra 2 to execute cql3. This works correctly. I started using PreparedStatement's:

```<code>Session session = sessionProvider.getSession();
try {
    PreparedStatement ps = session.prepare(cql);
    ResultSet rs = session.execute(ps.bind(objects));
    if (irsr != null) {
       irsr.read(rs);
    }
}
</code>```

Sometimes I get a warning from the driver in my log:

```<code>Re-preparing already prepared query . Please note that preparing the same query more than once is generally an anti-pattern and will likely affect performance. Consider preparing the statement only once.
</code>```

This warning makes sense, but i'm not sure how i should reuse the PreparedStatement?

Should I just create all my PreparedStatement in a constructor/init method and than simply use them?

But does this go well when multiple threads use the same PreparedStatement at the same time (especially calling PreparedStatement.bind() to bind objects)

答:
```<code>03-Apr-2017 10:02:24,120 WARN  [com.datastax.driver.core.Cluster] (cluster1-worker-2851) Re-preparing already prepared query is generally an anti-pattern and will likely affect performance. Consider preparing the statement only once. Query='select * from xxxx where cjpid=? and cjpsnapshotid =?'
</code>```

Create a pool of PreparedStatement objects, one for each CQL query.

Then, when these queries are being requested by client, fetch the respective cached PS object and supply values by calling bind().

as explained by Daniel, bind() does new BoundStmt(param) which makes this thread safe.

Body:
I'm currently using the Datastax Cassandra driver for Cassandra 2 to execute cql3. This works correctly. I started using PreparedStatement's:

Session session = sessionProvider.getSession();
try {
    PreparedStatement ps = session.prepare(cql);
    ResultSet rs = session.execute(ps.bind(objects));
    if (irsr != null) {
       irsr.read(rs);
    }
}

Sometimes I get a warning from the driver in my log:

Re-preparing already prepared query . Please note that preparing the same query more than once is generally an anti-pattern and will likely affect performance. Consider preparing the statement only once.

This warning makes sense, but i'm not sure how i should reuse the PreparedStatement?

Should I just create all my PreparedStatement in a constructor/init method and than simply use them?

But does this go well when multiple threads use the same PreparedStatement at the same time (especially calling PreparedStatement.bind() to bind objects)

Body:
03-Apr-2017 10:02:24,120 WARN  [com.datastax.driver.core.Cluster] (cluster1-worker-2851) Re-preparing already prepared query is generally an anti-pattern and will likely affect performance. Consider preparing the statement only once. Query='select * from xxxx where cjpid=? and cjpsnapshotid =?'

Create a pool of PreparedStatement objects, one for each CQL query.

Then, when these queries are being requested by client, fetch the respective cached PS object and supply values by calling bind().

as explained by Daniel, bind() does new BoundStmt(param) which makes this thread safe.


问:
pg_query(): Query failed: ERROR: more than one row returned by a subquery used as an expression
what's wrong with my query ? im sure its work a few days ago, but today i dont know why its happen. how i can solve this ?
sorry my bad english

error :

query :

```<code>function getUserGroupList() {
    $rulesQuery = "SELECT * FROM t_rules";
    $rulesResult = pg_query($this->DB, $rulesQuery);

    $nextQuery = '';

    while ($data = pg_fetch_array($rulesResult)) {
        $nextQuery .= ",(SELECT COUNT(*) FROM t_user_group_rules ugp WHERE ugp.ref_user_group = ug.id AND ugp.ref_rules = ".$data['id'].") as ".str_replace(' ', '_', $data['c_name'])."_count,(SELECT c_status FROM t_user_group_rules ugp WHERE ugp.ref_user_group = ug.id AND ugp.ref_rules = ".$data['id'].") as ".str_replace(' ', '_', $data['c_name']);
    }

    $query = "SELECT ug.id, ug.c_name $nextQuery
        FROM t_user_group ug
        WHERE ug.c_active = 1";

    $result = pg_query($this->DB, $query);
    // echo $query;
    // exit();
    $all = array();

    while ($data = pg_fetch_assoc($result)) {
        array_push($all, $data);
    }

    echo json_encode($all);
}
</code>```

if I echo $query, it will become like this

```<code>SELECT
   ug.id,
   ug.c_name,
   (SELECT count(*)
    FROM t_user_group_rules ugp
    WHERE ugp.ref_user_group = ug.id
       AND ugp.ref_rules = 1
   ) AS command_count,
   (SELECT c_status
    FROM t_user_group_rules ugp
    WHERE ugp.ref_user_group = ug.id
       AND ugp.ref_rules = 1
   ) AS command,
   (SELECT count(*)
    FROM t_user_group_rules ugp
    WHERE ugp.ref_user_group = ug.id
       AND ugp.ref_rules = 2
   ) AS user_count,
   (SELECT c_status
    FROM t_user_group_rules ugp
    WHERE ugp.ref_user_group = ug.id
       AND ugp.ref_rules = 2
   ) AS USER,
   (SELECT count(*)
    FROM t_user_group_rules ugp
    WHERE ugp.ref_user_group = ug.id
       AND ugp.ref_rules = 3
   ) AS executive_count,
   (SELECT c_status
    FROM t_user_group_rules ugp
    WHERE ugp.ref_user_group = ug.id
       AND ugp.ref_rules = 3
   ) AS executive,
   (SELECT count(*)
    FROM t_user_group_rules ugp
    WHERE ugp.ref_user_group = ug.id
       AND ugp.ref_rules = 4
   ) AS rekon_count,
   (SELECT c_status
    FROM t_user_group_rules ugp
    WHERE ugp.ref_user_group = ug.id
       AND ugp.ref_rules = 4
   ) AS rekon,
   (SELECT count(*)
    FROM t_user_group_rules ugp
    WHERE ugp.ref_user_group = ug.id
       AND ugp.ref_rules = 5
   ) AS ej_count,
   (SELECT c_status
    FROM t_user_group_rules ugp
    WHERE ugp.ref_user_group = ug.id
       AND ugp.ref_rules = 5
   ) AS ej,
   (SELECT count(*)
    FROM t_user_group_rules ugp
    WHERE ugp.ref_user_group = ug.id
       AND ugp.ref_rules = 12
   ) AS tes_count,
   (SELECT c_status
    FROM t_user_group_rules ugp
    WHERE ugp.ref_user_group = ug.id
       AND ugp.ref_rules = 12
   ) AS tes
FROM t_user_group ug
WHERE ug.c_active = 1;
</code>```

答:
If any of the count(*) in your query would return a value greater than 1, you will get this error.

That is because a subselect in the SELECT list may not return more than a single value, since it will result in a single value (if there is no result, you will get an SQL NULL).

Body:
what's wrong with my query ? im sure its work a few days ago, but today i dont know why its happen. how i can solve this ?
sorry my bad english

error :

query :

function getUserGroupList() {
    $rulesQuery = "SELECT * FROM t_rules";
    $rulesResult = pg_query($this->DB, $rulesQuery);

    $nextQuery = '';

    while ($data = pg_fetch_array($rulesResult)) {
        $nextQuery .= ",(SELECT COUNT(*) FROM t_user_group_rules ugp WHERE ugp.ref_user_group = ug.id AND ugp.ref_rules = ".$data['id'].") as ".str_replace(' ', '_', $data['c_name'])."_count,(SELECT c_status FROM t_user_group_rules ugp WHERE ugp.ref_user_group = ug.id AND ugp.ref_rules = ".$data['id'].") as ".str_replace(' ', '_', $data['c_name']);
    }

    $query = "SELECT ug.id, ug.c_name $nextQuery
        FROM t_user_group ug
        WHERE ug.c_active = 1";

    $result = pg_query($this->DB, $query);
    // echo $query;
    // exit();
    $all = array();

    while ($data = pg_fetch_assoc($result)) {
        array_push($all, $data);
    }

    echo json_encode($all);
}

if I echo $query, it will become like this

SELECT
   ug.id,
   ug.c_name,
   (SELECT count(*)
    FROM t_user_group_rules ugp
    WHERE ugp.ref_user_group = ug.id
       AND ugp.ref_rules = 1
   ) AS command_count,
   (SELECT c_status
    FROM t_user_group_rules ugp
    WHERE ugp.ref_user_group = ug.id
       AND ugp.ref_rules = 1
   ) AS command,
   (SELECT count(*)
    FROM t_user_group_rules ugp
    WHERE ugp.ref_user_group = ug.id
       AND ugp.ref_rules = 2
   ) AS user_count,
   (SELECT c_status
    FROM t_user_group_rules ugp
    WHERE ugp.ref_user_group = ug.id
       AND ugp.ref_rules = 2
   ) AS USER,
   (SELECT count(*)
    FROM t_user_group_rules ugp
    WHERE ugp.ref_user_group = ug.id
       AND ugp.ref_rules = 3
   ) AS executive_count,
   (SELECT c_status
    FROM t_user_group_rules ugp
    WHERE ugp.ref_user_group = ug.id
       AND ugp.ref_rules = 3
   ) AS executive,
   (SELECT count(*)
    FROM t_user_group_rules ugp
    WHERE ugp.ref_user_group = ug.id
       AND ugp.ref_rules = 4
   ) AS rekon_count,
   (SELECT c_status
    FROM t_user_group_rules ugp
    WHERE ugp.ref_user_group = ug.id
       AND ugp.ref_rules = 4
   ) AS rekon,
   (SELECT count(*)
    FROM t_user_group_rules ugp
    WHERE ugp.ref_user_group = ug.id
       AND ugp.ref_rules = 5
   ) AS ej_count,
   (SELECT c_status
    FROM t_user_group_rules ugp
    WHERE ugp.ref_user_group = ug.id
       AND ugp.ref_rules = 5
   ) AS ej,
   (SELECT count(*)
    FROM t_user_group_rules ugp
    WHERE ugp.ref_user_group = ug.id
       AND ugp.ref_rules = 12
   ) AS tes_count,
   (SELECT c_status
    FROM t_user_group_rules ugp
    WHERE ugp.ref_user_group = ug.id
       AND ugp.ref_rules = 12
   ) AS tes
FROM t_user_group ug
WHERE ug.c_active = 1;


问:
Using a struct which implements a traits from a different crate
Crate sha2 contains the type Sha256 which implements the trait Digest defined in the crate digest. This trait is also reexported from sha2.

I want to write a file which doesn't mention sha2, just digest:

merkle_tree.rs:

```<code>use digest::Digest;

#[derive(Default)]
pub struct MerkleTree<T: Digest> {
    digest: T,
}

impl<T: Digest+Default> MerkleTree<T> {
    pub fn new() -> MerkleTree<T> {
        MerkleTree{ ..Default::default() }
    }
}
</code>```

main.rs:

```<code>extern crate digest;
extern crate sha2;

mod merkle_tree;

use sha2::{Digest, Sha256};
use merkle_tree::MerkleTree;

fn main() {
    let mut mt = MerkleTree::<Sha256>::new();
    println!("Hello, world!");
}
</code>```

I have the following output:

error: no associated item named new found for type
  merkle_tree::MerkleTree<sha2::Sha256> in the current scope
  the trait digest::Digest is not implemented for sha2::Sha256

Cargo.toml:

```<code>[package]
name = "merkle_tree"
version = "0.1.0"
authors = ["Simon Prykhodko <semion.ababo@gmail.com>"]

[dependencies]
digest = "0.4.0"
sha2 = "0.3.0"
</code>```

What's wrong here?

答:
I just ran your code and it compiled fine with these dependency versions:

```<code>[dependencies]
sha2 = "0.4.2"
digest = "0.4.0"
</code>```

Try updating one or both.

Body:
Crate sha2 contains the type Sha256 which implements the trait Digest defined in the crate digest. This trait is also reexported from sha2.

I want to write a file which doesn't mention sha2, just digest:

merkle_tree.rs:

use digest::Digest;

#[derive(Default)]
pub struct MerkleTree<T: Digest> {
    digest: T,
}

impl<T: Digest+Default> MerkleTree<T> {
    pub fn new() -> MerkleTree<T> {
        MerkleTree{ ..Default::default() }
    }
}

main.rs:

extern crate digest;
extern crate sha2;

mod merkle_tree;

use sha2::{Digest, Sha256};
use merkle_tree::MerkleTree;

fn main() {
    let mut mt = MerkleTree::<Sha256>::new();
    println!("Hello, world!");
}

I have the following output:

error: no associated item named new found for type
  merkle_tree::MerkleTree<sha2::Sha256> in the current scope
  the trait digest::Digest is not implemented for sha2::Sha256

Cargo.toml:

[package]
name = "merkle_tree"
version = "0.1.0"
authors = ["Simon Prykhodko <semion.ababo@gmail.com>"]

[dependencies]
digest = "0.4.0"
sha2 = "0.3.0"

What's wrong here?

Body:
I just ran your code and it compiled fine with these dependency versions:

[dependencies]
sha2 = "0.4.2"
digest = "0.4.0"

Try updating one or both.


问:
Combobox with image - passing value to drawItem event
I have a C# app with a combo box.  I was add items to it in the usual way using a loop to loop through some objects and add each name property value to the combobox:

```<code>comboBox1.Items.Add(object.name);
</code>```

But then I decided I would like to display an image by the text, so I changed the drawMode and the dropDownStyle and set up an event handler on drawItem to draw first the image and then the text.

The image draws correctly, and then comes the problem.  I am using something like

```<code> e.Graphics.DrawString("What goes here?", e.Font, new SolidBrush(e.ForeColor), e.Bounds.Left,e.Bounds.Top);
</code>```

I cant get the object.name value into the DrawString parameter.  Does the DrawItemEventArgs object e have the value, and if so how do I access it?

If it doesnt what are my real options?  I have seem some examples that maintain a list to keep the values and then reference that using e.Index.  Is this really the best way?

Thanks in advance

答: It looks like the DrawItemEventArgs gives you the index.  Use that index to index into comboBox1.Items.</p>

ContentLicense: CC BY-SA 2.5

Body:
I have a C# app with a combo box.  I was add items to it in the usual way using a loop to loop through some objects and add each name property value to the combobox:

comboBox1.Items.Add(object.name);

But then I decided I would like to display an image by the text, so I changed the drawMode and the dropDownStyle and set up an event handler on drawItem to draw first the image and then the text.

The image draws correctly, and then comes the problem.  I am using something like

 e.Graphics.DrawString("What goes here?", e.Font, new SolidBrush(e.ForeColor), e.Bounds.Left,e.Bounds.Top);

I cant get the object.name value into the DrawString parameter.  Does the DrawItemEventArgs object e have the value, and if so how do I access it?

If it doesnt what are my real options?  I have seem some examples that maintain a list to keep the values and then reference that using e.Index.  Is this really the best way?

Thanks in advance

OwnerDisplayName: Sean


问:
Storing historical data with Java and Hibernate
This is a problem about historical data handling.
Suppose you have a class MyClass like the following one:

```<code>class MyClass {
    String field1;
    Integer field2;
    Long field3;

    getField1() {...}
    setField1(String ...) {...}

    ...
}
</code>```

Now, suppose I need to make MyClass able to store and retrieve old data, what's the best way to do this?

The requirements are to persist the classes through Hibernate, too. And to have at most two tables per "entity": only one table or one table for the "continuity" class (the one which represents the entity which evolves over the time) and another table for the historical data (as it's suggested here)

Please note that I have to be able to assign an arbitrary valid time to the values of the fields.

The class should have an interface like:

```<code>class MyClass {
    // how to store the fields????

    getField1At(Instant i) {...}
    setField1At(Instant i, String ...) {...}

    ...
}
</code>```

I'm currently using the JTemporal library, and it has a TemporalAttribute<T> class, which is like a map: you can do things like T myAttr.get(Instant i) to get the version of myAttr at Instant i. I know how to persist a TemporalAttribute in a table with Hibernate (it's simple: I persist the SortedMap used by the TemporalAttribute and you get a table with start and end valid time and the value of the attribute).

The real problem is that here we have multiple attributes.

I have a solution in mind but it's not clear, and I'd like to hear your ideas.

答:
You can do something like this simply by adding a version number to your domain class.  I did something like this where the Id was a composite between an db assigned number and the version number, but I would advise against that.  Use a normal surrogate key, and if you really want, make the [id, version] tuple a natural key.

You can actually version entire object graphs that way, just by ensuring that the version number is the same for all elements on the graph.  You can then easily go back to any previous version.

You should write a lot of service tests to insure the integrity of the code that manages the version.

Body:
This is a problem about historical data handling.
Suppose you have a class MyClass like the following one:

class MyClass {
    String field1;
    Integer field2;
    Long field3;

    getField1() {...}
    setField1(String ...) {...}

    ...
}

Now, suppose I need to make MyClass able to store and retrieve old data, what's the best way to do this?

The requirements are to persist the classes through Hibernate, too. And to have at most two tables per "entity": only one table or one table for the "continuity" class (the one which represents the entity which evolves over the time) and another table for the historical data (as it's suggested here)

Please note that I have to be able to assign an arbitrary valid time to the values of the fields.

The class should have an interface like:

class MyClass {
    // how to store the fields????

    getField1At(Instant i) {...}
    setField1At(Instant i, String ...) {...}

    ...
}

I'm currently using the JTemporal library, and it has a TemporalAttribute<T> class, which is like a map: you can do things like T myAttr.get(Instant i) to get the version of myAttr at Instant i. I know how to persist a TemporalAttribute in a table with Hibernate (it's simple: I persist the SortedMap used by the TemporalAttribute and you get a table with start and end valid time and the value of the attribute).

The real problem is that here we have multiple attributes.

I have a solution in mind but it's not clear, and I'd like to hear your ideas.


问:
Prevent extra newline after heading in md to rst conversion
I have some markdown files that I want to convert to reStructuredText files. I have just started using Pandoc for this particular requirement. So far I am using the following simple command

```<code>> pandoc --from markdown --to rst --columns 80 --output foo.rst foo.md
</code>```

Now in my markdown I have laid out the text, such that there is no new line after the headings, for example:

```<code># Some heading
Some text that follows on the line immediately after the heading
</code>```

The result from the mentioned command inserts an extra new-line though:

```<code>Some heading
============

Some text that follows after the heading *and* a new-line
</code>```

If I'm correct in thinking that this added new-line is not a requirement for reStructuredText, is there some simple way that I can prevent Pandoc from inserting it?

答: As @Waylan commented, having a new line after a heading is considered the best practice style for markdown and thus Pandoc's insertion of them was correct.</p>

Body:
I have some markdown files that I want to convert to reStructuredText files. I have just started using Pandoc for this particular requirement. So far I am using the following simple command

> pandoc --from markdown --to rst --columns 80 --output foo.rst foo.md

Now in my markdown I have laid out the text, such that there is no new line after the headings, for example:

# Some heading
Some text that follows on the line immediately after the heading

The result from the mentioned command inserts an extra new-line though:

Some heading
============

Some text that follows after the heading *and* a new-line

If I'm correct in thinking that this added new-line is not a requirement for reStructuredText, is there some simple way that I can prevent Pandoc from inserting it?


问:
covariant type A occurs in contravariant position in type A of value a
I have following class:

```<code>case class Box[+A](value: A) {

  def set(a: A): Box[A] = Box(a)

}
</code>```

And the compiler complain:

```<code>Error:(4, 11) covariant type A occurs in contravariant position in type A of value a
  def set(a: A): Box[A] = Box(a)
</code>```

I was searching a lot about the error, but could not find something useful that
help me to understand the error.

Could someone please explain, why the error occurs?

答:
The error message is actually very clear once you understand it. Let's get there together.

You are declaring class Box as covariant in its type parameter A. This means that for any type X extending A (i.e. X <: A), Box[X] can be seen as a Box[A].

To give a clear example, let's consider the Animal type:

```<code>sealed abstract class Animal
case class Cat extends Animal
case class Dog extends Animal
</code>```

If you define Dog <: Animal and Cat <: Animal, then both Box[Dog] and Box[Cat] can be seen as Box[Animal] and you can e.g. create a single collection containing both types and preserve the Box[Animal] type.

Although this property can be very handy in some cases, it also imposes constraints on the operations you can make available on Box. This is why the compiler doesn't allow you to define def set.

If you allow defining

```<code>def set(a:A): Unit
</code>```

then the following code is valid:

```<code>val catBox = new Box[Cat]
val animalBox: Box[Animal] = catBox // valid because `Cat <: Animal`
val dog = new Dog
animalBox.set(dog) // This is non-sensical: if `set` mutates `animalBox`, it also mutates `catBox` to no longer contain a `Cat` but a `Dog`
</code>```

The last line is obviously a problem because catBox will now contain a Dog! The arguments of a method appear in what is called "contravariant position", which is the opposite of covariance. Indeed, if you define Box[-A], then Cat <: Animal implies Box[Cat] >: Box[Animal] (Box[Cat] is a supertype of Box[Animal]). For our example, this is of course non-sensical.

One solution to your problem is to make the Box class immutable (i.e. to not provide any way to change the content of a Box), and instead use the apply method defined in your case class companion to create new boxes. If you need to, you can also define set locally and not expose it anywhere outside Box by declaring it as private[this]. The compiler will allow this because the private[this] guarantees that the last line of our faulty example will not compile since the set method is completely invisible outside of a specific instance of Box.

If for some reason you do not want to create new instances using the apply method, you can also define set as follows.

```<code>def set[B >: A](b: B): Box[B] = Box(b)
</code>```

Body:
I have following class:

case class Box[+A](value: A) {

  def set(a: A): Box[A] = Box(a)

}

And the compiler complain:

Error:(4, 11) covariant type A occurs in contravariant position in type A of value a
  def set(a: A): Box[A] = Box(a)

I was searching a lot about the error, but could not find something useful that
help me to understand the error.

Could someone please explain, why the error occurs?

Body:
The error message is actually very clear once you understand it. Let's get there together.

You are declaring class Box as covariant in its type parameter A. This means that for any type X extending A (i.e. X <: A), Box[X] can be seen as a Box[A].

To give a clear example, let's consider the Animal type:

sealed abstract class Animal
case class Cat extends Animal
case class Dog extends Animal

If you define Dog <: Animal and Cat <: Animal, then both Box[Dog] and Box[Cat] can be seen as Box[Animal] and you can e.g. create a single collection containing both types and preserve the Box[Animal] type.

Although this property can be very handy in some cases, it also imposes constraints on the operations you can make available on Box. This is why the compiler doesn't allow you to define def set.

If you allow defining

def set(a:A): Unit

then the following code is valid:

val catBox = new Box[Cat]
val animalBox: Box[Animal] = catBox // valid because `Cat <: Animal`
val dog = new Dog
animalBox.set(dog) // This is non-sensical: if `set` mutates `animalBox`, it also mutates `catBox` to no longer contain a `Cat` but a `Dog`

The last line is obviously a problem because catBox will now contain a Dog! The arguments of a method appear in what is called "contravariant position", which is the opposite of covariance. Indeed, if you define Box[-A], then Cat <: Animal implies Box[Cat] >: Box[Animal] (Box[Cat] is a supertype of Box[Animal]). For our example, this is of course non-sensical.

One solution to your problem is to make the Box class immutable (i.e. to not provide any way to change the content of a Box), and instead use the apply method defined in your case class companion to create new boxes. If you need to, you can also define set locally and not expose it anywhere outside Box by declaring it as private[this]. The compiler will allow this because the private[this] guarantees that the last line of our faulty example will not compile since the set method is completely invisible outside of a specific instance of Box.

If for some reason you do not want to create new instances using the apply method, you can also define set as follows.

def set[B >: A](b: B): Box[B] = Box(b)

ContentLicense: CC BY-SA 4.0


问:
How to load/read binary file into an "vector<vector< bitset<32> >" in c++?
I have a problem with loading/reading an

```<code>vector<vector< bitset<32> >
</code>```

(called/typedef'ed as population in my code)

which it stored using the following code:

```<code>void genetic_algorithm::save_generation(population pop_to_save, string filename){
  std::ofstream file(filename, std::ofstream::binary);
  unsigned long n;
  for(size_t i = 0; i < pop_to_save.size(); i++ )
  {
    if ( pop_to_save[i].size() > 0 )
    {
      n = pop_to_save[i][0].to_ulong();
      const char* buffer = reinterpret_cast<const char*>(&n);
      file.write(buffer, pop_to_save[i].size());
    }
  }
}
</code>```

The thing i need is therefore a function that can load, i.e.:

```<code>population genetic_algorithm::load_generation(string filename){
  // TODO
}
</code>```

Best Regards,

Mathias.

EDIT

I have solved the problem on my own (with a bit of help from the comment)
Here is the final code for any that might face the same problem:

```<code>void genetic_algorithm::save_generation(population pop_to_save, string filename){
  std::ofstream file(filename, std::ofstream::binary);
  unsigned long n;
  for(size_t i = 0; i < pop_to_save.size(); i++ ) {
    for (size_t j = 0; j < pop_to_save[i].size(); j++) {
      n = pop_to_save[i][j].to_ulong();
      file.write(reinterpret_cast<const char*>(&n), sizeof(n));
    }
  }

  std::cout << "Saved population to: " << filename << '\n';
}

population genetic_algorithm::load_generation(string filename){
  std::ifstream file(filename, std::ofstream::binary);
  population loaded_pop (20, std::vector<bitset<32>> (394,0));
  unsigned long n;
  for(size_t i = 0; i < 20; i++ ) {
    for (size_t j = 0; j < 394; j++) {
      file.read( reinterpret_cast<char*>(&n), sizeof(n) );
      loaded_pop[i][j] = n;
    }
  }

  std::cout << "Loaded population from: " << filename << '\n';
  return loaded_pop;
}
</code>```

答:
I examined your method genetic_algorithm::save_generation() and this what I  found out:

bitset<32> stores 32 bits in packed form (probably an unsigned int with 32 bits or something similar).

vector<bitset<32> > stores a dynamic array of such bit sets.

vector<vector<bitset<32> > > stores a dynamic array of such dynamic arrays of bit sets.

So far, so good. In your method genetic_algorithm::save_generation(), you loop through all elements of the outer vector to dump the contents of each inner vector (if not empty).

The file.write(buffer, pop_to_save[i].size()); does probably not what you want. The 2nd arg. of std::ostream::write() is the number of characters. You pass the size() of the resp. inner vector which returns the number of elements (but not the size in bytes). But the element size (bitset<32>) is probably bigger than a character. A better approach (though not the best) would be to use instead file.write(buffer, 4 * pop_to_save[i].size());. (sizeof (char): 1, sizeof bitset<32>: hopefully 4 but I would check this.)

Thus, more safe would be to use file.write(buffer, pop_to_save[i].size() * sizeof pop_to_save[i][0]);. This is better but still not perfect. If you want to use your application on multiple platforms this may fail because the file format becomes platform dependent now. (It depends on sizeof pop_to_save[i][0].)

Thus, the best approach would be to make a nested loop for the inner vectors also and to store the elements of them individually with a type of platform independent size (e.g. std::uint32_t).

However, my actual concern is a design issue:

If you store a dynamic array of dynamic arrays (where each inner array might be of arbitrary size) then you have to store the number of elements for these inner arrays also. This is what I miss in your method genetic_algorithm::save_generation().

May be, your problem of loading is caused by the fact that you have to reserve or resize the inner vectors for the bits to load but you do not know with which size. My answer: You cannot know. This info is missing (and had to be provided somehow, e.g. by the file itself).

Body:
I have a problem with loading/reading an

vector<vector< bitset<32> >

(called/typedef'ed as population in my code)

which it stored using the following code:

void genetic_algorithm::save_generation(population pop_to_save, string filename){
  std::ofstream file(filename, std::ofstream::binary);
  unsigned long n;
  for(size_t i = 0; i < pop_to_save.size(); i++ )
  {
    if ( pop_to_save[i].size() > 0 )
    {
      n = pop_to_save[i][0].to_ulong();
      const char* buffer = reinterpret_cast<const char*>(&n);
      file.write(buffer, pop_to_save[i].size());
    }
  }
}

The thing i need is therefore a function that can load, i.e.:

population genetic_algorithm::load_generation(string filename){
  // TODO
}

Best Regards,

Mathias.

EDIT

I have solved the problem on my own (with a bit of help from the comment)
Here is the final code for any that might face the same problem:

void genetic_algorithm::save_generation(population pop_to_save, string filename){
  std::ofstream file(filename, std::ofstream::binary);
  unsigned long n;
  for(size_t i = 0; i < pop_to_save.size(); i++ ) {
    for (size_t j = 0; j < pop_to_save[i].size(); j++) {
      n = pop_to_save[i][j].to_ulong();
      file.write(reinterpret_cast<const char*>(&n), sizeof(n));
    }
  }

  std::cout << "Saved population to: " << filename << '\n';
}

population genetic_algorithm::load_generation(string filename){
  std::ifstream file(filename, std::ofstream::binary);
  population loaded_pop (20, std::vector<bitset<32>> (394,0));
  unsigned long n;
  for(size_t i = 0; i < 20; i++ ) {
    for (size_t j = 0; j < 394; j++) {
      file.read( reinterpret_cast<char*>(&n), sizeof(n) );
      loaded_pop[i][j] = n;
    }
  }

  std::cout << "Loaded population from: " << filename << '\n';
  return loaded_pop;
}


问:
Query showing records that do NOT match in between tables
I have two tables. One is a table of the reports that have been submitted to us. Another is a temp table with the records of reports that should eventually be submitted to us. I would like to show only the records in the temp table that do not match the ones in the reports table (so the reports that still must be submitted are displayed).

Example data is:

```<code>Reports table:

CREATE TABLE [dbo].[Reports]
(
    [ReportID] [int] IDENTITY(1,1) NOT NULL,
    [ReportDate] [date] NULL,
    [AssessmentID] [int] NOT NULL,
    [ReportType] [varchar](50) NULL
);

AssessmentID    ReportType  ReportID
1   1st Quarterly   27
2   1st Quarterly   30
2   2nd Quarterly   31
2   3rd Quarterly   32

QuarterlyReportsDue table:

CREATE TABLE #QuarterlyReportsDue
(
AssessmentID INT,
InstallationDate DATE,
QuarterlyReportType VARCHAR(50)
);

AssessmentID    InstallationDate    QuarterlyReportType
1   2009-08-14  1st Quarterly
1   2009-08-14  2nd Quarterly
1   2009-08-14  3rd Quarterly
1   2009-08-14  4th Quarterly
2   2008-05-16  4th Quarterly
2   2008-05-16  3rd Quarterly
2   2008-05-16  2nd Quarterly
2   2008-05-16  1st Quarterly
</code>```

I have tried LEFT OUTER JOINS but am running into issues. Please see my below SQL:

```<code>SELECT #QuarterlyReportsDue.InstallationDate, #QuarterlyReportsDue.QuarterlyReportType, Reports.ReportType
FROM #QuarterlyReportsDue
LEFT OUTER JOIN Reports ON #QuarterlyReportsDue.AssessmentID = Reports.AssessmentID
WHERE Reports.ReportType IN ('1st Quarterly', '2nd Quarterly', '3rd Quarterly', '4th Quarterly')
AND Reports.ReportType <> #QuarterlyReportsDue.QuarterlyReportType
ORDER BY #QuarterlyReportsDue.AssessmentID
</code>```

And my results:

```<code>AssessmentID    QuarterlyReportType ReportType  ReportID
1   2nd Quarterly   1st Quarterly   27
1   3rd Quarterly   1st Quarterly   27
1   4th Quarterly   1st Quarterly   27
2   4th Quarterly   1st Quarterly   30
2   4th Quarterly   2nd Quarterly   31
2   4th Quarterly   3rd Quarterly   32
2   1st Quarterly   2nd Quarterly   31
2   1st Quarterly   3rd Quarterly   32
2   3rd Quarterly   1st Quarterly   30
2   3rd Quarterly   2nd Quarterly   31
2   2nd Quarterly   1st Quarterly   30
2   2nd Quarterly   3rd Quarterly   32
</code>```

For assessment 1 it works great, assessment 2 has many duplicates. How can I get around this to only show the ideal results?

```<code>AssessmentID    QuarterlyReportType ReportType
1   2nd Quarterly   1st Quarterly
1   3rd Quarterly   1st Quarterly
1   4th Quarterly   1st Quarterly
2       4th Quarterly
</code>```

答: You should use NOT EXISTS to find entries in the temp table that do not have matching entries in the submitted reports table.

Body:
I have two tables. One is a table of the reports that have been submitted to us. Another is a temp table with the records of reports that should eventually be submitted to us. I would like to show only the records in the temp table that do not match the ones in the reports table (so the reports that still must be submitted are displayed).

Example data is:

Reports table:

CREATE TABLE [dbo].[Reports]
(
    [ReportID] [int] IDENTITY(1,1) NOT NULL,
    [ReportDate] [date] NULL,
    [AssessmentID] [int] NOT NULL,
    [ReportType] [varchar](50) NULL
);

AssessmentID    ReportType  ReportID
1   1st Quarterly   27
2   1st Quarterly   30
2   2nd Quarterly   31
2   3rd Quarterly   32

QuarterlyReportsDue table:

CREATE TABLE #QuarterlyReportsDue
(
AssessmentID INT,
InstallationDate DATE,
QuarterlyReportType VARCHAR(50)
);

AssessmentID    InstallationDate    QuarterlyReportType
1   2009-08-14  1st Quarterly
1   2009-08-14  2nd Quarterly
1   2009-08-14  3rd Quarterly
1   2009-08-14  4th Quarterly
2   2008-05-16  4th Quarterly
2   2008-05-16  3rd Quarterly
2   2008-05-16  2nd Quarterly
2   2008-05-16  1st Quarterly

I have tried LEFT OUTER JOINS but am running into issues. Please see my below SQL:

SELECT #QuarterlyReportsDue.InstallationDate, #QuarterlyReportsDue.QuarterlyReportType, Reports.ReportType
FROM #QuarterlyReportsDue
LEFT OUTER JOIN Reports ON #QuarterlyReportsDue.AssessmentID = Reports.AssessmentID
WHERE Reports.ReportType IN ('1st Quarterly', '2nd Quarterly', '3rd Quarterly', '4th Quarterly')
AND Reports.ReportType <> #QuarterlyReportsDue.QuarterlyReportType
ORDER BY #QuarterlyReportsDue.AssessmentID

And my results:

AssessmentID    QuarterlyReportType ReportType  ReportID
1   2nd Quarterly   1st Quarterly   27
1   3rd Quarterly   1st Quarterly   27
1   4th Quarterly   1st Quarterly   27
2   4th Quarterly   1st Quarterly   30
2   4th Quarterly   2nd Quarterly   31
2   4th Quarterly   3rd Quarterly   32
2   1st Quarterly   2nd Quarterly   31
2   1st Quarterly   3rd Quarterly   32
2   3rd Quarterly   1st Quarterly   30
2   3rd Quarterly   2nd Quarterly   31
2   2nd Quarterly   1st Quarterly   30
2   2nd Quarterly   3rd Quarterly   32

For assessment 1 it works great, assessment 2 has many duplicates. How can I get around this to only show the ideal results?

AssessmentID    QuarterlyReportType ReportType
1   2nd Quarterly   1st Quarterly
1   3rd Quarterly   1st Quarterly
1   4th Quarterly   1st Quarterly
2       4th Quarterly


问:
How to cache results in scala?
This page has a description of Map's getOrElseUpdate usage method:

```<code>object WithCache{
  val cacheFun1 = collection.mutable.Map[Int, Int]()
  def fun1(i:Int) = i*i
  def catchedFun1(i:Int) = cacheFun1.getOrElseUpdate(i, fun1(i))
}
</code>```

So you can use catchedFun1 which will check if cacheFun1 contains key and return value associated with it. Otherwise, it will invoke fun1, then cache fun1's result in cacheFun1, then return fun1's result.

I can see one potential danger - cacheFun1 can became to large.  So cacheFun1 must be cleaned somehow by garbage collector?

P.S. What about scala.collection.mutable.WeakHashMap and java.lang.ref.*  ?

答:
For simple caching needs, I'm still using Guava cache solution in Scala as well.
Lightweight and battle tested.

If it fit's your requirements and constraints generally outlined below, it could be a great option:

Willing to spend some memory to improve speed.

Expecting that keys will sometimes get queried more than once.

Your cache will not need to store more data than what would fit in RAM. (Guava caches    are local to a single run of your application.
They do not store data    in files, or on outside servers.)

Example for using it will be something like this:

```<code>  lazy val cachedData = CacheBuilder.newBuilder()
    .expireAfterWrite(60, TimeUnit.MINUTES)
    .maximumSize(10)
    .build(
      new CacheLoader[Key, Data] {
        def load(key: Key): Data = {
          veryExpansiveDataCreation(key)
        }
      }
    )
</code>```

To read from it, you can use something like:

```<code>  def cachedData(ketToData: Key): Data = {
    try {
      return cachedData.get(ketToData)
    } catch {
      case ee: Exception => throw new YourSpecialException(ee.getMessage);
    }
  }
</code>```

Title: How to cache results in scala?

Body:
This page has a description of Map's getOrElseUpdate usage method:

object WithCache{
  val cacheFun1 = collection.mutable.Map[Int, Int]()
  def fun1(i:Int) = i*i
  def catchedFun1(i:Int) = cacheFun1.getOrElseUpdate(i, fun1(i))
}

So you can use catchedFun1 which will check if cacheFun1 contains key and return value associated with it. Otherwise, it will invoke fun1, then cache fun1's result in cacheFun1, then return fun1's result.

I can see one potential danger - cacheFun1 can became to large.  So cacheFun1 must be cleaned somehow by garbage collector?

P.S. What about scala.collection.mutable.WeakHashMap and java.lang.ref.*  ?

Body:
For simple caching needs, I'm still using Guava cache solution in Scala as well.
Lightweight and battle tested.

If it fit's your requirements and constraints generally outlined below, it could be a great option:

Willing to spend some memory to improve speed.

Expecting that keys will sometimes get queried more than once.

Your cache will not need to store more data than what would fit in RAM. (Guava caches    are local to a single run of your application.
They do not store data    in files, or on outside servers.)

Example for using it will be something like this:

  lazy val cachedData = CacheBuilder.newBuilder()
    .expireAfterWrite(60, TimeUnit.MINUTES)
    .maximumSize(10)
    .build(
      new CacheLoader[Key, Data] {
        def load(key: Key): Data = {
          veryExpansiveDataCreation(key)
        }
      }
    )

To read from it, you can use something like:

  def cachedData(ketToData: Key): Data = {
    try {
      return cachedData.get(ketToData)
    } catch {
      case ee: Exception => throw new YourSpecialException(ee.getMessage);
    }
  }


问:
How to play video from youku using javascript?
How to play video from youku using javascript ?

I tried to do like this but not work, how can i do that ?

```<code><iframe id="test" src="https://player.youku.com/embed/XMjUzMzY2ODQ4OA==" frameborder="0" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen="" style="position: absolute; top: 0; left: 0; width: 50%; height: 50%;"></iframe>

<div style=" position: fixed; top: 56%; " onclick="play_fn()">Play</div>

<script>
function play_fn(){
    var test = document.getElementById('test');
    test.play();
}
</script>
</code>```

答:
Refer this code</p>

```<code>    <!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <meta name="robots" content="noindex, nofollow">
  <meta name="googlebot" content="noindex, nofollow">
  <script type="text/javascript" src="/js/lib/dummy.js"></script>
  <link rel="stylesheet" type="text/css" href="/css/result-light.css">

  <style type="text/css">
      #overlay {
  position: absolute;
  top: 100px;
  color: #FFF;
  text-align: center;
  font-size: 20px;
  background-color: rgba(221, 221, 221, 0.3);
  width: 640px;
  padding: 10px 0;
  z-index: 2147483647;
}

#v {
  z-index: 1;
}
  </style>

  <title>Overlay HTML over video player</title>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">//<![CDATA[
window.onload=function() {
  var video = document.getElementById('v');
  video.play();
}//]]>

</script>

</head>

<body>
    <video id="v" controls="">
    <source id="webm" src="https://www.html5rocks.com/en/tutorials/video/basics/devstories.webm" type="video/webm">

    <p>Your user agent does not support the HTML5 Video element.</p>

  </video>
  <div id="overlay" style='display: none;'>This is HTML overlay on top of the video! </div>

</body>
</html>
</code>```

Body:
How to play video from youku using javascript ?

I tried to do like this but not work, how can i do that ?

Play

Body:
Refer this code

    <!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <meta name="robots" content="noindex, nofollow">
  <meta name="googlebot" content="noindex, nofollow">
  <script type="text/javascript" src="/js/lib/dummy.js"></script>
  <link rel="stylesheet" type="text/css" href="/css/result-light.css">

  <style type="text/css">
      #overlay {
  position: absolute;
  top: 100px;
  color: #FFF;
  text-align: center;
  font-size: 20px;
  background-color: rgba(221, 221, 221, 0.3);
  width: 640px;
  padding: 10px 0;
  z-index: 2147483647;
}

#v {
  z-index: 1;
}
  </style>

  <title>Overlay HTML over video player</title>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">//<![CDATA[
window.onload=function() {
  var video = document.getElementById('v');
  video.play();
}//]]>

</script>

</head>

<body>
    <video id="v" controls="">
    <source id="webm" src="https://www.html5rocks.com/en/tutorials/video/basics/devstories.webm" type="video/webm">

    <p>Your user agent does not support the HTML5 Video element.</p>

  </video>
  <div id="overlay" style='display: none;'>This is HTML overlay on top of the video! </div>

</body>
</html>


问:
View outside a Dialogs bounds
I want something like this:

The users profile picture is "popping out" over the dialogs bounds.

I've tried everything: messing with clipping with every possibly combination under the sun, dynamically creating the view after the dialog and adding it to the root content view, using a seperate view and loading that in with Dialog.setCustomTitle(), hacking the Images onDraw() methods and applying all-sorts of bounds/positional hacks --- but no matter what the image always gets clipped and split in half.

I've even gone to the extent of decompiling the Play Store APK and seeing how they did it. Unfortunately the resource files don't give much away and I can't find anything in the Smali.

Can anyone help? Please... :-(

EDIT: I'm just specifically talking about the user profile image at the top of the dialog, not the dialog itself.

答:
Just to improve @MHP's answer, you can also add cardView to make the corner of your dialog rounded.

Something like:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@android:color/transparent">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="57dp"
    android:background="@android:color/transparent"
    android:orientation="vertical">

    <android.support.v7.widget.CardView xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/llMainContents"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#FAFAFA"
        android:orientation="vertical"
        app:cardCornerRadius="2dp" />
</LinearLayout>

<ImageView
    android:id="@+id/ivIcon"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:padding="8dp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:contentDescription="@null"
    android:src="@mipmap/ic_launcher" />

</RelativeLayout>
</code>```

Result would be:

Title: View outside a Dialogs bounds

Body:
Just to improve @MHP's answer, you can also add cardView to make the corner of your dialog rounded.

Something like:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@android:color/transparent">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="57dp"
    android:background="@android:color/transparent"
    android:orientation="vertical">

    <android.support.v7.widget.CardView xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/llMainContents"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#FAFAFA"
        android:orientation="vertical"
        app:cardCornerRadius="2dp" />
</LinearLayout>

<ImageView
    android:id="@+id/ivIcon"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:padding="8dp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:contentDescription="@null"
    android:src="@mipmap/ic_launcher" />

</RelativeLayout>

Result would be:


问:
How to overwrite Admin.js in Sonata Admin?
How to overwrite file Admin.js in Sonata Admin?
I tried create this file in:

/app/Resources/SonataAdminBundle/public/Admin.js

but this not working.

In standard_layout.html.twig this file is included by:

```<code>        {% block sonata_javascript_pool %}
            {% for javascript in sonata_admin.adminPool.getOption('javascripts', []) %}
                <script src="{{ asset(javascript) }}"></script>
            {% endfor %}
        {% endblock %}
</code>```

答:
You can tweak the javascripts option:</p>

```<code>app/console -vvv config:dump-reference sonata_admin
sonata_admin:
    …
    assets:
        …
        javascripts:

            # Defaults:
            - bundles/sonatacore/vendor/jquery/dist/jquery.min.js
            - bundles/sonataadmin/vendor/jquery.scrollTo/jquery.scrollTo.min.js
            - bundles/sonatacore/vendor/moment/min/moment.min.js
            - bundles/sonataadmin/vendor/jqueryui/ui/minified/jquery-ui.min.js
            - bundles/sonataadmin/vendor/jqueryui/ui/minified/i18n/jquery-ui-i18n.min.js
            - bundles/sonatacore/vendor/bootstrap/dist/js/bootstrap.min.js
            - bundles/sonatacore/vendor/eonasdan-bootstrap-datetimepicker/build/js/bootstrap-datetimepicker.min.js
            - bundles/sonataadmin/vendor/jquery-form/jquery.form.js
            - bundles/sonataadmin/jquery/jquery.confirmExit.js
            - bundles/sonataadmin/vendor/x-editable/dist/bootstrap3-editable/js/bootstrap-editable.min.js
            - bundles/sonatacore/vendor/select2/select2.min.js
            - bundles/sonataadmin/vendor/admin-lte/dist/js/app.min.js
            - bundles/sonataadmin/vendor/iCheck/icheck.min.js
            - bundles/sonataadmin/vendor/slimScroll/jquery.slimscroll.min.js
            - bundles/sonataadmin/vendor/waypoints/lib/jquery.waypoints.min.js
            - bundles/sonataadmin/vendor/waypoints/lib/shortcuts/sticky.min.js
            - bundles/sonataadmin/vendor/readmore-js/readmore.min.js
            - bundles/sonataadmin/Admin.js
            - bundles/sonataadmin/treeview.js
</code>```

Body:
How to overwrite file Admin.js in Sonata Admin?
I tried create this file in:

/app/Resources/SonataAdminBundle/public/Admin.js

but this not working.

In standard_layout.html.twig this file is included by:

        {% block sonata_javascript_pool %}
            {% for javascript in sonata_admin.adminPool.getOption('javascripts', []) %}

            {% endfor %}
        {% endblock %}

Body:
You can tweak the javascripts option:

app/console -vvv config:dump-reference sonata_admin
sonata_admin:
    …
    assets:
        …
        javascripts:

            # Defaults:
            - bundles/sonatacore/vendor/jquery/dist/jquery.min.js
            - bundles/sonataadmin/vendor/jquery.scrollTo/jquery.scrollTo.min.js
            - bundles/sonatacore/vendor/moment/min/moment.min.js
            - bundles/sonataadmin/vendor/jqueryui/ui/minified/jquery-ui.min.js
            - bundles/sonataadmin/vendor/jqueryui/ui/minified/i18n/jquery-ui-i18n.min.js
            - bundles/sonatacore/vendor/bootstrap/dist/js/bootstrap.min.js
            - bundles/sonatacore/vendor/eonasdan-bootstrap-datetimepicker/build/js/bootstrap-datetimepicker.min.js
            - bundles/sonataadmin/vendor/jquery-form/jquery.form.js
            - bundles/sonataadmin/jquery/jquery.confirmExit.js
            - bundles/sonataadmin/vendor/x-editable/dist/bootstrap3-editable/js/bootstrap-editable.min.js
            - bundles/sonatacore/vendor/select2/select2.min.js
            - bundles/sonataadmin/vendor/admin-lte/dist/js/app.min.js
            - bundles/sonataadmin/vendor/iCheck/icheck.min.js
            - bundles/sonataadmin/vendor/slimScroll/jquery.slimscroll.min.js
            - bundles/sonataadmin/vendor/waypoints/lib/jquery.waypoints.min.js
            - bundles/sonataadmin/vendor/waypoints/lib/shortcuts/sticky.min.js
            - bundles/sonataadmin/vendor/readmore-js/readmore.min.js
            - bundles/sonataadmin/Admin.js
            - bundles/sonataadmin/treeview.js


问:
Fresco - Support multiple OKHttp Clients
My android app supports multiple user logins.
I user Dagger2 to maintain the UserScope dependencies which get created and destroyed as user switch happens.
One of these dependencies is an OkHttpClient for every user, with its own authentication/cookies.

I am looking to use Fresco for my app, but I am not able to find a way where I can switch the OKHttpClient at runtime in Fresco, since the initialization only happens once for it.
From the documentation :

OkHttpClient okHttpClient; //my per user session client
ImagePipelineConfig config = OkHttpImagePipelineConfigFactory
    .newBuilder(context, okHttpClient)
    .build();
Fresco.initialize(context, config);

Any ideas to achieve this multi user scenario with Fresco ?

答:
You can simply create a custom network fetcher that holds multiple OkHttpClients and change them when needed or create a new fetcher that holds multiple OPkHttpNetworkFetchers.

Just use the original OkHttpNetworkFetcher code as a reference: https://github.com/facebook/fresco/blob/master/imagepipeline-backends/imagepipeline-okhttp3/src/main/java/com/facebook/imagepipeline/backends/okhttp3/OkHttpNetworkFetcher.java


问:
Single Quotes Instead of Double Quotes?
Since both are acceptable by HTML as well as languages like ASP.NET and PHP when using attributes or strings, why is it that some people use single quotes and double quotes interchangeably?

It is my understanding that it is syntactically correct to use double quotes where possible, single when you need to embed a double quote for inline logic.

Is there something I am missing?

For examples:

HTML

```<code><a href='http://google.com'>Google</a>
</code>```

PHP

```<code><? echo 'Hello World!'; ?>
</code>```

ASP.NET

```<code><form id='myForm' runat='server'></form>
</code>```

答:
I find the use of single quotes advantageous when I'm embedding html into strings, mainly when dealing with templating. Here is an example: </p>

```<code>public string EmailTemplate =
@"<div style='color:red'>HEY {0}! BUY MORE STUFF</div>"

// later in code

instanceOfStringBuilder.AppendFormat(EmailTemplate, firstNameVariable);
</code>```

<p>I don't have any hierarchy in my mind for whether single or double quotes are "better." It is purely a matter of being consistent and having something that programmatically works. </p>

Title: Single Quotes Instead of Double Quotes?

Body:
Since both are acceptable by HTML as well as languages like ASP.NET and PHP when using attributes or strings, why is it that some people use single quotes and double quotes interchangeably?

It is my understanding that it is syntactically correct to use double quotes where possible, single when you need to embed a double quote for inline logic.

Is there something I am missing?

For examples:

HTML

Google

PHP

<? echo 'Hello World!'; ?>

ASP.NET

<form id='myForm' runat='server'></form>

Body:
I find the use of single quotes advantageous when I'm embedding html into strings, mainly when dealing with templating. Here is an example:

public string EmailTemplate =
@"<div style='color:red'>HEY {0}! BUY MORE STUFF</div>"

// later in code

instanceOfStringBuilder.AppendFormat(EmailTemplate, firstNameVariable);

I don't have any hierarchy in my mind for whether single or double quotes are "better." It is purely a matter of being consistent and having something that programmatically works.


问:
Apache 2.4 - How to redirect images to a php file?
I need to redirect all images to a php file, including the path and file name.

Imagine my domain is example.com
I might have https://example.com/art/logo.png and want to do redirect this to https://example.com/scripts/image_loader.php?a:art&b=logo.png

So, I would force any request to be redirected to a php-file which will display the image. I am doing this to control who can access the images and also to prevent hotlinking.
I also want html-files to use this redirect and use the php file to display the image, e.g. for included 'img src=/art/logo.png'

I already did the mod_rewrite using the referral header method but it's not working and I am not sure why. I am assuming that the https protocol doesn't use a referrer in the header.

For the php I need to know how I can stop someone from hotlinking my images and from just downloading them as files.
Can I determine if the user is a person or a bot or some kind of site ripper?

I know I can't stop a person from downloading images. I just want to make it harder for them. So, they cannot just easily download them or use a site ripper software.

Any suggestions would be great. My website uses or runs on HTTPS. A lot of solutions for hotlinking online only shows examples using http.

答:
1. Can you determine wether the request is from a user or a bot?

NYeah, more or less^^ You can use the UserAgent-Header field to determine if the request was sent via a browser or not. But then the question is do you want to blacklist all site-rippers (like HTTrack) or whitelist all common Browsers? Both will be an incomplete and pretty long list.

2. How to rewrite all images to your php-file

```<code>RewriteEngine On
RedirectRule ^/(.+/(.+\.(jpe?g|gif|png|tif|bmp))$ /scripts/image_loader.php?a:$1&b=$2
</code>```

This rewrites all requests for standard-images, if the called URI-pattern follows your specified '/path/image.png' to /scripts/image_loader.php?a:path&b=image.png

update

```<code>RedirectRule ^^/(.+/)+(.+\.(jpe?g|gif|png|tif|bmp))$ /scripts/image_loader.php?a:$1&b=$2
</code>```

The first bracket (.+) includes the part after the servername up to the last file name, so in the example /path/example/image.png it would contain path/example. The second bracket (.+) only includes the file name, so in the example /path/example/image.png it would contain image.png. Now both values are assigned to the target-URL -->

```<code>/scripts/image_loader.php?a:path/example&b=image.png
</code>```

Hopefully I got your question right...

Body:
1. Can you determine wether the request is from a user or a bot?

NYeah, more or less^^ You can use the UserAgent-Header field to determine if the request was sent via a browser or not. But then the question is do you want to blacklist all site-rippers (like HTTrack) or whitelist all common Browsers? Both will be an incomplete and pretty long list.

2. How to rewrite all images to your php-file

RewriteEngine On
RedirectRule ^/(.+/(.+\.(jpe?g|gif|png|tif|bmp))$ /scripts/image_loader.php?a:$1&b=$2

This rewrites all requests for standard-images, if the called URI-pattern follows your specified '/path/image.png' to /scripts/image_loader.php?a:path&b=image.png

update

RedirectRule ^^/(.+/)+(.+\.(jpe?g|gif|png|tif|bmp))$ /scripts/image_loader.php?a:$1&b=$2

The first bracket (.+) includes the part after the servername up to the last file name, so in the example /path/example/image.png it would contain path/example. The second bracket (.+) only includes the file name, so in the example /path/example/image.png it would contain image.png. Now both values are assigned to the target-URL -->

/scripts/image_loader.php?a:path/example&b=image.png

Hopefully I got your question right...


问:
Why is there a nongreedy version of {m} in PHP regex?
On page 107 of the book Programming PHP by Kevin Tatroe and Peter MacIntyre, 3rd edition, it is stated that in PHP regular expressions, there is a nongreedy version {m}? of the quantifier {m}. The latter quantifier means "exactly m times" and I am wondering how this can be greedy or nongreedy?

答:
A limiting quantifier can be both greedy and lazy (reluctant). The difference is only visible when you use both minimum and maximum values, e.g. {1,5} and {1,5}?.

When you use just the minimum threshold value, greedy and lazy versions yield the same behavior.

It seems that the {m}? is just there to keep consistency ({n} and {n,m} are both forms of the same limiting quantifier that can be lazy or greedy), but is really redundant.