问:
How can I plot the surface of a structure which is given by vectors in python?

I would like to plot the surface of my data which is given by 3D vectors in cartesian coordinates x,y,z. The data can not be represented by a smooth function.

So first we generate some dummy data with the function eq_points(N_count, r) which returns an array points with the x,y,z coordinates of each point on the surface of our object. The quantity omega is the solid angle, and not of interest right now.

```<code>#credit to Markus Deserno from MPI
#https://www.cmu.edu/biolphys/deserno/pdf/sphere_equi.pdf
def eq_points(N_count, r):
    points = []
    a = 4*np.pi*r**2/N_count
    d = np.sqrt(a)
    M_theta = int(np.pi/d)
    d_theta = np.pi/M_theta
    d_phi = a/d_theta
    for m in range(M_theta):
        theta = np.pi*(m+0.5)/M_theta
        M_phi = int(2*np.pi*np.sin(theta)/d_phi)
        for n in range(M_phi):
            phi = 2*np.pi*n/M_phi

            points.append(np.array([r*np.sin(theta)*np.cos(phi),
                                    r*np.sin(theta)*np.sin(phi),
                                    r*np.cos(theta)]))

    omega = 4*np.pi/N_count

    return np.array(points), omega

#starting plotting sequence

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

points, omega = eq_points(400, 1.)

ax.scatter(points[:,0], points[:,1], points[:,2])
ax.scatter(0., 0., 0., c="r")
ax.set_xlabel(r'$x$ axis')
ax.set_ylabel(r'$y$ axis')
ax.set_zlabel(r'$Z$ axis')

plt.savefig("./sphere.png", format="png", dpi=300)
plt.clf()
</code>```

The result is a sphere shown in the following figure.  The blue points mark the data from the points array, while the red point is the origin.

I would like to get something like this
taken from here. However the data in the mplot3d tutorial is always a result of a smooth function. Except to the ax.scatter() function which I used for my sphere plot.

So in the end my goal would be to plot some data showing only its surface. This data is produced by changing the radial distance to the origin of each blue point. Further more it would be necessary to make sure each point is in contact with the surface. How are the surfaces which are plotted here e.g. in plot_surface() constructed in detail? Some actual live data looks like this:

答:
Solution to the question with the new specification that all points are touching the surface. Assuming that the angles are set by the user as shown in the example, it is easy to precompute the indices of the points forming the simplices making up the surface by computing the simplices of the hull formed by points on the unit sphere with the same angles as in the data set of interest. We can then use these indices to get the surface of interest.

```<code>import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
from scipy.spatial import ConvexHull

def eq_points(N_count, r):
    points = []
    a = 4*np.pi*r**2/N_count
    d = np.sqrt(a)
    M_theta = int(np.pi/d)
    d_theta = np.pi/M_theta
    d_phi = a/d_theta
    for m in range(M_theta):
        theta = np.pi*(m+0.5)/M_theta
        M_phi = int(2*np.pi*np.sin(theta)/d_phi)
        for n in range(M_phi):
            phi = 2*np.pi*n/M_phi

            points.append(np.array([r*np.sin(theta)*np.cos(phi),
                                    r*np.sin(theta)*np.sin(phi),
                                    r*np.cos(theta)]))

    omega = 4*np.pi/N_count

    return np.array(points), omega

def eq_points_with_random_radius(N_count, r):
    points = []
    a = 4*np.pi*r**2/N_count
    d = np.sqrt(a)
    M_theta = int(np.pi/d)
    d_theta = np.pi/M_theta
    d_phi = a/d_theta
    for m in range(M_theta):
        theta = np.pi*(m+0.5)/M_theta
        M_phi = int(2*np.pi*np.sin(theta)/d_phi)
        for n in range(M_phi):
            phi = 2*np.pi*n/M_phi
            rr = r * np.random.rand()
            points.append(np.array([rr*np.sin(theta)*np.cos(phi),
                                    rr*np.sin(theta)*np.sin(phi),
                                    rr*np.cos(theta)]))

    omega = 4*np.pi/N_count

    return np.array(points), omega

N = 400
pts, _ = eq_points(N, 1.)
pts_rescaled, _ = eq_points_with_random_radius(N, 1.)
extremum = 2.

# plot points
fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(pts_rescaled[:,0], pts_rescaled[:,1], pts_rescaled[:,2])
ax.set_xlim(-extremum, extremum)
ax.set_ylim(-extremum, extremum)
ax.set_zlim(-extremum, extremum)
</code>```

```<code># get indices of simplices making up the surface using points on unit sphere;
# index into rescaled points
hull = ConvexHull(pts)
vertices = [pts_rescaled[s] for s in hull.simplices]

fig = plt.figure()
ax = Axes3D(fig)
triangles = Poly3DCollection(vertices, edgecolor='k')
ax.add_collection3d(triangles)
ax.set_xlim(-extremum, extremum)
ax.set_ylim(-extremum, extremum)
ax.set_zlim(-extremum, extremum)
plt.show()
</code>```

Body:
I would like to plot the surface of my data which is given by 3D vectors in cartesian coordinates x,y,z. The data can not be represented by a smooth function.

So first we generate some dummy data with the function eq_points(N_count, r) which returns an array points with the x,y,z coordinates of each point on the surface of our object. The quantity omega is the solid angle, and not of interest right now.

#credit to Markus Deserno from MPI
#https://www.cmu.edu/biolphys/deserno/pdf/sphere_equi.pdf
def eq_points(N_count, r):
    points = []
    a = 4*np.pi*r**2/N_count
    d = np.sqrt(a)
    M_theta = int(np.pi/d)
    d_theta = np.pi/M_theta
    d_phi = a/d_theta
    for m in range(M_theta):
        theta = np.pi*(m+0.5)/M_theta
        M_phi = int(2*np.pi*np.sin(theta)/d_phi)
        for n in range(M_phi):
            phi = 2*np.pi*n/M_phi

            points.append(np.array([r*np.sin(theta)*np.cos(phi),
                                    r*np.sin(theta)*np.sin(phi),
                                    r*np.cos(theta)]))

    omega = 4*np.pi/N_count

    return np.array(points), omega

#starting plotting sequence

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

points, omega = eq_points(400, 1.)

ax.scatter(points[:,0], points[:,1], points[:,2])
ax.scatter(0., 0., 0., c="r")
ax.set_xlabel(r'$x$ axis')
ax.set_ylabel(r'$y$ axis')
ax.set_zlabel(r'$Z$ axis')

plt.savefig("./sphere.png", format="png", dpi=300)
plt.clf()

The result is a sphere shown in the following figure.  The blue points mark the data from the points array, while the red point is the origin.

I would like to get something like this
taken from here. However the data in the mplot3d tutorial is always a result of a smooth function. Except to the ax.scatter() function which I used for my sphere plot.

So in the end my goal would be to plot some data showing only its surface. This data is produced by changing the radial distance to the origin of each blue point. Further more it would be necessary to make sure each point is in contact with the surface. How are the surfaces which are plotted here e.g. in plot_surface() constructed in detail? Some actual live data looks like this:

Body:
Solution to the question with the new specification that all points are touching the surface. Assuming that the angles are set by the user as shown in the example, it is easy to precompute the indices of the points forming the simplices making up the surface by computing the simplices of the hull formed by points on the unit sphere with the same angles as in the data set of interest. We can then use these indices to get the surface of interest.

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
from scipy.spatial import ConvexHull

def eq_points(N_count, r):
    points = []
    a = 4*np.pi*r**2/N_count
    d = np.sqrt(a)
    M_theta = int(np.pi/d)
    d_theta = np.pi/M_theta
    d_phi = a/d_theta
    for m in range(M_theta):
        theta = np.pi*(m+0.5)/M_theta
        M_phi = int(2*np.pi*np.sin(theta)/d_phi)
        for n in range(M_phi):
            phi = 2*np.pi*n/M_phi

            points.append(np.array([r*np.sin(theta)*np.cos(phi),
                                    r*np.sin(theta)*np.sin(phi),
                                    r*np.cos(theta)]))

    omega = 4*np.pi/N_count

    return np.array(points), omega

def eq_points_with_random_radius(N_count, r):
    points = []
    a = 4*np.pi*r**2/N_count
    d = np.sqrt(a)
    M_theta = int(np.pi/d)
    d_theta = np.pi/M_theta
    d_phi = a/d_theta
    for m in range(M_theta):
        theta = np.pi*(m+0.5)/M_theta
        M_phi = int(2*np.pi*np.sin(theta)/d_phi)
        for n in range(M_phi):
            phi = 2*np.pi*n/M_phi
            rr = r * np.random.rand()
            points.append(np.array([rr*np.sin(theta)*np.cos(phi),
                                    rr*np.sin(theta)*np.sin(phi),
                                    rr*np.cos(theta)]))

    omega = 4*np.pi/N_count

    return np.array(points), omega

N = 400
pts, _ = eq_points(N, 1.)
pts_rescaled, _ = eq_points_with_random_radius(N, 1.)
extremum = 2.

# plot points
fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(pts_rescaled[:,0], pts_rescaled[:,1], pts_rescaled[:,2])
ax.set_xlim(-extremum, extremum)
ax.set_ylim(-extremum, extremum)
ax.set_zlim(-extremum, extremum)

# get indices of simplices making up the surface using points on unit sphere;
# index into rescaled points
hull = ConvexHull(pts)
vertices = [pts_rescaled[s] for s in hull.simplices]

fig = plt.figure()
ax = Axes3D(fig)
triangles = Poly3DCollection(vertices, edgecolor='k')
ax.add_collection3d(triangles)
ax.set_xlim(-extremum, extremum)
ax.set_ylim(-extremum, extremum)
ax.set_zlim(-extremum, extremum)
plt.show()


来源: stackexchange

问:
I have completed building an angular application. How to build it to run on server i.e cordova
I have completed an angular application. I ran ng build command and I got dist folder. No I want to run in Apache Cordova server. How to do it?

答:
First you need to run the build with ng build and by default the dist folder will have the compiled files. You should use the option --production to reduce the bundle size and perform other optimisations on the compiled files. You can change the output folder to a custom one with --output-path.
Then you need to copy those files to your server and configure it to serve the index.html file when the user hits the main url of your site.

ContentLicense: CC BY-SA 3.0


问:
The use of backspace character ( char(8) ) in Fortran
For "flavorful" output during iteration procedure, I'd like to use following approach (I saw it for some program written in C++) in Fortran.
Every new iteration gives me the line in the console with corresponding information:

```<code>Iteration XX Accuracy X.XXXXE-XX Time spent XX seconds
</code>```

I want every new line to replace the previous one (i.e. labels "Iteration" "Accuracy" ... etc. remain unchanged, while values change).

I tried different variants including

```<code>backspace(6)
backspace(0)
write (*,*) char(8)//'Accuracy ...'
</code>```

Of course, first two lines give a runtime error and the last gives nothing.

How can I implement such an approach?

答:
It's perhaps a bit rather complicated solution, but one option would be to use the ncurses library - http://genepi.qimr.edu.au/staff/davidD/

Below is a modification of the program testcurs.f90available for download from the linked page. It just displays a progress message which is being progressively updated. In order to test it, you will need also the ncurses.f90 module and then link with -lncurses, i.e.,

```<code>gfortran -c ncurses.f95
gfortran -o test testcurs.f95 -lncurses
</code>```

The example (showing just the program itself, testcurs.f90 contains also the definition of initTest etc.):

```<code>program testcurses
  use curses
  use commands
  type (C_PTR) :: iwin = C_NULL_PTR
  integer (C_INT) :: key
  integer :: istat, new_option=1, old_option=0
  CHARACTER(LEN=1024) :: msg

  call initTest(iwin, istat)

  if (istat /= 0) then
    write(*,'(a)') 'ERROR: initscr failed!'
    stop
  end if

  ierr = wbkgd(iwin, curses_a_reverse)
  ierr = erase()
  ierr = attrset(curses_a_bold)
  DO i = 10, 100, 10
    WRITE(msg, '(''Progress '', I0, ''%'')') i

    ierr = mvaddstr(20, 20, TRIM(msg) // C_NULL_CHAR)
    ierr = refresh()
    CALL SLEEP(1)
  END DO
  key = getch()

  ierr = delwin(iwin)
  ierr = endwin()
end program testcurses
</code>```

Body:
For "flavorful" output during iteration procedure, I'd like to use following approach (I saw it for some program written in C++) in Fortran.
Every new iteration gives me the line in the console with corresponding information:

Iteration XX Accuracy X.XXXXE-XX Time spent XX seconds

I want every new line to replace the previous one (i.e. labels "Iteration" "Accuracy" ... etc. remain unchanged, while values change).

I tried different variants including

backspace(6)
backspace(0)
write (*,*) char(8)//'Accuracy ...'

Of course, first two lines give a runtime error and the last gives nothing.

How can I implement such an approach?

Body:
It's perhaps a bit rather complicated solution, but one option would be to use the ncurses library - http://genepi.qimr.edu.au/staff/davidD/

Below is a modification of the program testcurs.f90available for download from the linked page. It just displays a progress message which is being progressively updated. In order to test it, you will need also the ncurses.f90 module and then link with -lncurses, i.e.,

gfortran -c ncurses.f95
gfortran -o test testcurs.f95 -lncurses

The example (showing just the program itself, testcurs.f90 contains also the definition of initTest etc.):

program testcurses
  use curses
  use commands
  type (C_PTR) :: iwin = C_NULL_PTR
  integer (C_INT) :: key
  integer :: istat, new_option=1, old_option=0
  CHARACTER(LEN=1024) :: msg

  call initTest(iwin, istat)

  if (istat /= 0) then
    write(*,'(a)') 'ERROR: initscr failed!'
    stop
  end if

  ierr = wbkgd(iwin, curses_a_reverse)
  ierr = erase()
  ierr = attrset(curses_a_bold)
  DO i = 10, 100, 10
    WRITE(msg, '(''Progress '', I0, ''%'')') i

    ierr = mvaddstr(20, 20, TRIM(msg) // C_NULL_CHAR)
    ierr = refresh()
    CALL SLEEP(1)
  END DO
  key = getch()

  ierr = delwin(iwin)
  ierr = endwin()
end program testcurses


问:
Why I have different result conversion text to double
I have code here which will convert String value to Double with 2 decimal places.
 When the myStrValue is 820 the final result is 8.2 - which is wrong result it should be 8.20

I have code here:

```<code>string myStrValue = "820";

double myDblValue = Convert.ToDouble(myStrValue) * 0.01;
double finalValue = Math.Round(myDblValue, 2);
</code>```

How to correct it?

答:
final result is 8.2 - which is wrong result it should be 8.20

please don't mix up the number at hand and it's represenation as string when you display it. Mathematically 8.2 and 8.20 are the same numbers and are treated the same way.

On the other hand the string representation is controled by you when you decide to display it.

You can determine the format of display in different ways:

```<code>finalValue.ToString("0.00");
string rep = $"{finalValue:0.00}";
// and many more, google will find it
</code>```

so there are no chance to make it 8.20? in double datatype?

Actually NO, because in datatype double it is saved entirely different, with an exponent and mantissa. If you are interested have a look at this page

But the representation of it will have no effect if you want to use the number.
Because finalValue + 0.001 will result in 8.201.

Body:
I have code here which will convert String value to Double with 2 decimal places.
 When the myStrValue is 820 the final result is 8.2 - which is wrong result it should be 8.20

I have code here:

string myStrValue = "820";

double myDblValue = Convert.ToDouble(myStrValue) * 0.01;
double finalValue = Math.Round(myDblValue, 2);

How to correct it?

Body:
final result is 8.2 - which is wrong result it should be 8.20

please don't mix up the number at hand and it's represenation as string when you display it. Mathematically 8.2 and 8.20 are the same numbers and are treated the same way.

On the other hand the string representation is controled by you when you decide to display it.

You can determine the format of display in different ways:

finalValue.ToString("0.00");
string rep = $"{finalValue:0.00}";
// and many more, google will find it

so there are no chance to make it 8.20? in double datatype?

Actually NO, because in datatype double it is saved entirely different, with an exponent and mantissa. If you are interested have a look at this page

But the representation of it will have no effect if you want to use the number.
Because finalValue + 0.001 will result in 8.201.


问:
Interrupt UrlConnection on back presss
In my Android Application I have two activities: Main and Articles. My application starts with Main. In Articles I am showing Images which are downloaded from server.

Here is the code to download the images from server:

```<code>public class SyncImage extends AsyncTask<Void, Void, Bitmap> {
private String url;
private URLConnection connection;

public SyncImage(String url) {
        this.url = url;
    }

@Override
    protected Bitmap doInBackground(Void... voids) {
        Bitmap img;
        try {
            URL source = new URL(url);
            connection = source.openConnection();
            Handler.addUrlConnection(connection);
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(10000);
            connection.connect();
            img = BitmapFactory.decodeStream(connection.getInputStream());
            return img;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
}
</code>```

Articles activity

```<code>private void downloadImages(ArrayList<String> images) {
        for (String image : images) {
            SyncImage sync = new SyncImage(image);
            sync.execute();
            // Rest of the code
        }
    }
</code>```

What I want that if user press back button to go back to Main Screen, all UrlConnection objects should cancel/stop their executions.

I can cancel the SyncImage object using sync.cancel(true), but it will only stop AsyncTask object, not the URLConnection object in process.

So, how to cancel the ongoing execution UrlConnection objects on Back Press?

答:
try this</p>

```<code>@Override

public void onBackPressed() {
    connection = null;
    url = "";
    finish();
}
</code>```

Title: Interrupt UrlConnection on back presss

Body:
In my Android Application I have two activities: Main and Articles. My application starts with Main. In Articles I am showing Images which are downloaded from server.

Here is the code to download the images from server:

public class SyncImage extends AsyncTask<Void, Void, Bitmap> {
private String url;
private URLConnection connection;

public SyncImage(String url) {
        this.url = url;
    }

@Override
    protected Bitmap doInBackground(Void... voids) {
        Bitmap img;
        try {
            URL source = new URL(url);
            connection = source.openConnection();
            Handler.addUrlConnection(connection);
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(10000);
            connection.connect();
            img = BitmapFactory.decodeStream(connection.getInputStream());
            return img;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
}

Articles activity

private void downloadImages(ArrayList<String> images) {
        for (String image : images) {
            SyncImage sync = new SyncImage(image);
            sync.execute();
            // Rest of the code
        }
    }

What I want that if user press back button to go back to Main Screen, all UrlConnection objects should cancel/stop their executions.

I can cancel the SyncImage object using sync.cancel(true), but it will only stop AsyncTask object, not the URLConnection object in process.

So, how to cancel the ongoing execution UrlConnection objects on Back Press?

Body:
try this

@Override

public void onBackPressed() {
    connection = null;
    url = "";
    finish();
}


问:
Access buttons from layout programmatically inflated within another layout
I am inflating a list of layouts programmatically from a xml into another layout.

The end result looks like the following image.

The number of checkboxes is different on each run, how can i get their state and also add listeners to the image button? Ideally i want only one listener that has an id of the selected layout.

This is the xml code.

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/chk_item_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<CheckBox
    android:id="@+id/checkBox_chkitem"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/textView_chkitem"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="24dp"
    android:text="TextView"
    app:layout_constraintEnd_toStartOf="@+id/imageButton_chkitem"
    app:layout_constraintStart_toEndOf="@+id/checkBox_chkitem"
    app:layout_constraintTop_toTopOf="parent" />

<ImageButton
    android:id="@+id/imageButton_chkitem"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="16dp"
    android:layout_marginTop="16dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:srcCompat="@android:drawable/stat_notify_more" />
</android.support.constraint.ConstraintLayout>
</code>```

And this is how i inflate the layouts

```<code>        val checkitemlist = listOf<ChecklistItem>(ChecklistItem("Categoria", "conteudo"),
            ChecklistItem("Categoria", "conteudo"),
            ChecklistItem("Categoria", "conteudo"),
            ChecklistItem("Categoria", "conteudo"))
    for (item in checkitemlist) {
        val inflater = LayoutInflater.from(context)
        val layout = inflater.inflate(io.ubivis.ier.R.layout.checklistitem_layout, null, false) as ConstraintLayout
        layout.textView_chkitem.text = item.textSimple
        checklist_content_layout.addView(layout)
    }
</code>```

答:
replace your code </p>

```<code>   for (item in checkitemlist) {
            checklist_content_layout.removeAllViews()
            val inflater = LayoutInflater.from(context)
            val layout = inflater.inflate(io.ubivis.ier.R.layout.checklistitem_layout, null, false) as ConstraintLayout
            layout.textView_chkitem.text = item.textSimple
            checklist_content_layout.addView(layout)
        }
</code>```

Body:
I am inflating a list of layouts programmatically from a xml into another layout.

The end result looks like the following image.

The number of checkboxes is different on each run, how can i get their state and also add listeners to the image button? Ideally i want only one listener that has an id of the selected layout.

This is the xml code.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/chk_item_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<CheckBox
    android:id="@+id/checkBox_chkitem"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/textView_chkitem"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="24dp"
    android:text="TextView"
    app:layout_constraintEnd_toStartOf="@+id/imageButton_chkitem"
    app:layout_constraintStart_toEndOf="@+id/checkBox_chkitem"
    app:layout_constraintTop_toTopOf="parent" />

<ImageButton
    android:id="@+id/imageButton_chkitem"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="16dp"
    android:layout_marginTop="16dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:srcCompat="@android:drawable/stat_notify_more" />
</android.support.constraint.ConstraintLayout>

And this is how i inflate the layouts

        val checkitemlist = listOf<ChecklistItem>(ChecklistItem("Categoria", "conteudo"),
            ChecklistItem("Categoria", "conteudo"),
            ChecklistItem("Categoria", "conteudo"),
            ChecklistItem("Categoria", "conteudo"))
    for (item in checkitemlist) {
        val inflater = LayoutInflater.from(context)
        val layout = inflater.inflate(io.ubivis.ier.R.layout.checklistitem_layout, null, false) as ConstraintLayout
        layout.textView_chkitem.text = item.textSimple
        checklist_content_layout.addView(layout)
    }

Body:
replace your code

   for (item in checkitemlist) {
            checklist_content_layout.removeAllViews()
            val inflater = LayoutInflater.from(context)
            val layout = inflater.inflate(io.ubivis.ier.R.layout.checklistitem_layout, null, false) as ConstraintLayout
            layout.textView_chkitem.text = item.textSimple
            checklist_content_layout.addView(layout)
        }


问:
Call two Alamofire Function one after another
I have User class which has a ID property in it. I do a Alamofire request which fulfills this class (ID value). When a button tapped, I do another Alamofire request which sends users id. I have get 7 user in first request so second request done 7th times. When button tapped, I want that process continuously so that when I tapped button It should do first request -> second request (7 times) -> first req -> second req (7 times)..... Problem is that It needs to wait for first request to be completed and also all second requests. What will be the best approach while doing this? I'm thinking of creating group but I'm not sure.

```<code>   func cont_like(){
    for var i in 0..<3{
        let group = DispatchGroup()
        let group2 = DispatchGroup()
        group2.enter()
        group.enter()
        Network.sharedInstance.like_all(completion: {
            group.leave()
        })
        group.enter()
        Network.sharedInstance.get_rec(completion: {response in
            print(response)
            group.leave()
        })

        group.notify(queue: .main){
            print("Both Req Done")
            group2.leave()
        }
    }}
</code>```

Second Request:

```<code>    func like(sender_id: String, completion: @escaping () -> ()){
    if let key = api_key{
        let headers: HTTPHeaders = [
            "X-Auth-Token": key,
            "Accept": "application/json"
        ]
        Alamofire.request(baseUrl + likeURL + sender_id, method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers).responseData(completionHandler: { (response) in
            let jsonData = JSON(response.data!)

            guard response.result.isSuccess else {
                print("Error while fetching tags: \(response.result.error!)")
                return
            }
            if let error = response.error{
                print("Error Occured with Request: \(error)")
            }
            if let matched = jsonData["match"].bool{
                print("Liked!: \(matched)")
                if(matched){

                }
            }else{
                print("There is an error with liking :(")
            }

        })
    }
}
</code>```

First Request:

```<code>    func get_rec(completion: @escaping (String?) -> ()){
    if let key = api_key{
        let headers: HTTPHeaders = [
            "X-Auth-Token": key,
            "Accept": "application/json"
        ]
        Alamofire.request(baseUrl + recom, method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers).responseData(completionHandler: { (response) in
            if response.result.isFailure{
                completion(nil)
                self.delegate?.metaError()
                return
            }else{
                do {
                    let decoder = JSONDecoder()
                    let root = try decoder.decode(Root.self, from: response.data!)
                    SharedUsers.sharedUser.populateData(sender: root.data)
                    print(SharedUsers.sharedUser.users[0].id)
                    self.delegate?.updated()
                    completion("Fetched")
                    self.delegate?.updated()

                } catch {
                    print("error: ", error)
                    completion(nil)
                    self.delegate?.metaError()
                }
            }

        })
    }
    else{
    print("Error")
    }
}
</code>```

Like All Functon:

```<code>func like_all(completion: @escaping() -> ()){
        let group2 = DispatchGroup()
        group2.enter()
        for user in SharedUsers.sharedUser.users{
            if let id = user.id{
                let group = DispatchGroup()
                group.enter()
                let when = DispatchTime.now() + 0.5 // change 2 to desired number of seconds
                DispatchQueue.main.asyncAfter(deadline: when) {
                    Network.sharedInstance.like(sender_id: id) { result in
                        group.leave()
                        print(result)
                    }

                }
            }
            else{
                continue
            }
        }
        group2.leave()
        completion()
    }
</code>```

EDIT: I edited the functions but still First Request are called without waiting all like requests.

答:
There are different approaches one is DispatchGroup

```<code>  let group = DispatchGroup()

    group.enter()
    func like(sender_id: String, completion: @escaping () -> ()){
        group.leave()
    }

    group.enter()
    func get_rec(completion: @escaping (String?) -> ()){
        group.leave()
    }

    group.notify(queue: .main) {
        print("both requests done")
    }
</code>```

Another one is NSOperationQueue by addDependency .

Body:
I have User class which has a ID property in it. I do a Alamofire request which fulfills this class (ID value). When a button tapped, I do another Alamofire request which sends users id. I have get 7 user in first request so second request done 7th times. When button tapped, I want that process continuously so that when I tapped button It should do first request -> second request (7 times) -> first req -> second req (7 times)..... Problem is that It needs to wait for first request to be completed and also all second requests. What will be the best approach while doing this? I'm thinking of creating group but I'm not sure.

   func cont_like(){
    for var i in 0..<3{
        let group = DispatchGroup()
        let group2 = DispatchGroup()
        group2.enter()
        group.enter()
        Network.sharedInstance.like_all(completion: {
            group.leave()
        })
        group.enter()
        Network.sharedInstance.get_rec(completion: {response in
            print(response)
            group.leave()
        })

        group.notify(queue: .main){
            print("Both Req Done")
            group2.leave()
        }
    }}

Second Request:

    func like(sender_id: String, completion: @escaping () -> ()){
    if let key = api_key{
        let headers: HTTPHeaders = [
            "X-Auth-Token": key,
            "Accept": "application/json"
        ]
        Alamofire.request(baseUrl + likeURL + sender_id, method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers).responseData(completionHandler: { (response) in
            let jsonData = JSON(response.data!)

            guard response.result.isSuccess else {
                print("Error while fetching tags: \(response.result.error!)")
                return
            }
            if let error = response.error{
                print("Error Occured with Request: \(error)")
            }
            if let matched = jsonData["match"].bool{
                print("Liked!: \(matched)")
                if(matched){

                }
            }else{
                print("There is an error with liking :(")
            }

        })
    }
}

First Request:

    func get_rec(completion: @escaping (String?) -> ()){
    if let key = api_key{
        let headers: HTTPHeaders = [
            "X-Auth-Token": key,
            "Accept": "application/json"
        ]
        Alamofire.request(baseUrl + recom, method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers).responseData(completionHandler: { (response) in
            if response.result.isFailure{
                completion(nil)
                self.delegate?.metaError()
                return
            }else{
                do {
                    let decoder = JSONDecoder()
                    let root = try decoder.decode(Root.self, from: response.data!)
                    SharedUsers.sharedUser.populateData(sender: root.data)
                    print(SharedUsers.sharedUser.users[0].id)
                    self.delegate?.updated()
                    completion("Fetched")
                    self.delegate?.updated()

                } catch {
                    print("error: ", error)
                    completion(nil)
                    self.delegate?.metaError()
                }
            }

        })
    }
    else{
    print("Error")
    }
}

Like All Functon:

func like_all(completion: @escaping() -> ()){
        let group2 = DispatchGroup()
        group2.enter()
        for user in SharedUsers.sharedUser.users{
            if let id = user.id{
                let group = DispatchGroup()
                group.enter()
                let when = DispatchTime.now() + 0.5 // change 2 to desired number of seconds
                DispatchQueue.main.asyncAfter(deadline: when) {
                    Network.sharedInstance.like(sender_id: id) { result in
                        group.leave()
                        print(result)
                    }

                }
            }
            else{
                continue
            }
        }
        group2.leave()
        completion()
    }

EDIT: I edited the functions but still First Request are called without waiting all like requests.

Body:
There are different approaches one is DispatchGroup

  let group = DispatchGroup()

    group.enter()
    func like(sender_id: String, completion: @escaping () -> ()){
        group.leave()
    }

    group.enter()
    func get_rec(completion: @escaping (String?) -> ()){
        group.leave()
    }

    group.notify(queue: .main) {
        print("both requests done")
    }

Another one is NSOperationQueue by addDependency .


问:
Open external app Ionic 2
How to open an external app installed in a mobile using Ionic 2 framework?
I do not find any plugins in ionic-native.
I tried to use com.lampa.startapp in ionic2 which I was using in ionic1.
But windows.plugins always returns undefined.

答:
I have used Cordova plugin cordova-plugin-inappbrowser, go through installations using Ionic In App Browser.

There is detailed description of same described in Ionic forum.

```<code>import { InAppBrowser } from '@ionic-native/in-app-browser';

constructor(public appBrowser: InAppBrowser) { }

// in some function
this.appBrowser.create('vnd.youtube://', '_system'); // Youtube
this.appBrowser.create('twitter://user?screen_name=', '_system');
</code>```

Title: Open external app Ionic 2

Body:
I have used Cordova plugin cordova-plugin-inappbrowser, go through installations using Ionic In App Browser.

There is detailed description of same described in Ionic forum.

import { InAppBrowser } from '@ionic-native/in-app-browser';

constructor(public appBrowser: InAppBrowser) { }

// in some function
this.appBrowser.create('vnd.youtube://', '_system'); // Youtube
this.appBrowser.create('twitter://user?screen_name=', '_system');


问:
how to solve android.content.res.Resources$NotFoundException: File res/drawable/ic_paper_plane.xml from drawable resource ID #0x7f02008f?
I know this question is asking many time but i tried all of that but nothing meet my requirement i used  android:drawableLeft attribute in XML file for showing vector image in my button and its running on above API 21 but if i am running on same code in below API 21 like 19 then app got crashed, i am already add vectorDrawables.useSupportLibrary = true , and AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); but both not work for me can any one help me out of this,my xml code is:

```<code><android.support.v7.widget.AppCompatButton
      android:id="@+id/shduleSms"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:drawableLeft="@drawable/ic_shedule_sms"
      android:drawablePadding="5dip"
      app:layout_constraintTop_toBottomOf="@+id/textConCount"
      android:padding="15dp"
      android:layout_marginEnd="30dp"
      android:layout_marginRight="30dp"
      app:layout_constraintRight_toRightOf="@+id/textConCount"
      android:layout_marginTop="15dp"
      android:text="@string/sendlater"
      android:textColor="@color/white"
      android:theme="@style/MyButtonTwo"
      />
</code>```

答: Please share your drawable code. There are some properties that cannot be used below SDK version 21 in vector drawable files and might lead to runtime crashes.</p>

Body:
I know this question is asking many time but i tried all of that but nothing meet my requirement i used  android:drawableLeft attribute in XML file for showing vector image in my button and its running on above API 21 but if i am running on same code in below API 21 like 19 then app got crashed, i am already add vectorDrawables.useSupportLibrary = true , and AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); but both not work for me can any one help me out of this,my xml code is:

<android.support.v7.widget.AppCompatButton
      android:id="@+id/shduleSms"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:drawableLeft="@drawable/ic_shedule_sms"
      android:drawablePadding="5dip"
      app:layout_constraintTop_toBottomOf="@+id/textConCount"
      android:padding="15dp"
      android:layout_marginEnd="30dp"
      android:layout_marginRight="30dp"
      app:layout_constraintRight_toRightOf="@+id/textConCount"
      android:layout_marginTop="15dp"
      android:text="@string/sendlater"
      android:textColor="@color/white"
      android:theme="@style/MyButtonTwo"
      />


问:
how to redirect from 1st page to 2nd page when searched in search bar of 1st page and show results on 2nd page
I have a home page in which it shows results when searched in search bar.

I also have another page, in which if searched in that page, it should redirect to home page and show results based on search in previous page.

Thanks in advance

答:
You need to set action="index.php" for that search bar form on all pages.

Or you can shift search bar form in a separate file named search.html and include that in all.


问:
Updating button events in Swift?
I am creating a Check List app and trying to update button event which is set images itself after clicked.

Here is my code:

```<code>protocol CustomeCellDelegate {
   func cell(cell: UITableViewCell, updateTheButton button: UIButton)
}

class Cells: UITableViewCell, UITextFieldDelegate {

@IBOutlet weak var checkBox: UIButton!
    var buttonPressed = true
@IBAction func checkBoxAction(_ sender: UIButton) {
    if buttonPressed {
        sender.setImage(UIImage(named: "checkBoxB"), for: UIControlState.normal)
        buttonPressed = false
    } else {
        sender.setImage(UIImage(named:""), for: UIControlState.normal)
        buttonPressed = true
    }
}
 @objc func recordButtonImage(_ button: UIButton) {
    cellDelegate?.cell(cell: self, updateTheButton: button)  // cell notify the button that touched.
}
override func awakeFromNib() {
    checkBox.addTarget(self, action: #selector(recordButtonImage(_:)), for: UIControlEvents.touchUpInside)
    }
}

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, CustomeCellDelegate {

@IBOutlet weak var tableView: UITableView!

var myImages: [UIImage?]!

override func viewDidLoad() {
  super.viewDidLoad()
    self.tableView.delegate   = self
    self.tableView.dataSource = self
    myImages = Array(repeatElement(nil, count: 50))
    let nib = UINib(nibName: "Cells", bundle: nil)
    tableView.register(nib, forCellReuseIdentifier: "Cells")
 }

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 50
}

internal func tableView(_ tableView:UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "theCells") as? Cells
        cell?.theTextField.delegate = self
        cell?.cellDelegate = self
        cell?.checkBox.setImage(myImages[indexPath.row], for: UIControlState.normal)

    return cell!
}

// This function from protocol and it helps to update button images.
func cell(cell: UITableViewCell, updateTheButton button: UIButton) {
    print("Delegate method Update Button Images.")
    if let indexPath = tableView.indexPath(for: cell), let buttonImage = button.image(for: UIControlState.normal) {
        myImages[indexPath.row] = buttonImage
    }
}
</code>```

I would like to update both events of the button that set image after checked and unchecked. Therefore, my table view can dequeue Reusable Cell and have those events updated.

But the result is just one event of button which is checked updated but not the unchecked one. The checked button still repeats whatever I do to uncheck it.

答:
I think you don't need recordButtonImage method, you should call the delegate method from the button tapped action i.e. checkBoxAction, just like below

```<code>class Cells: UITableViewCell, UITextFieldDelegate {
  @IBOutlet weak var checkBox: UIButton!
  var buttonPressed = true
  @IBAction func checkBoxAction(_ sender: UIButton) {
    if buttonPressed {
      sender.setImage(UIImage(named: "checkBoxB"), for: UIControlState.normal)
      buttonPressed = false
    } else {
      sender.setImage(UIImage(named:""), for: UIControlState.normal)
      buttonPressed = true
    }
    // cell notify the button that touched.
    cellDelegate?.cell(cell: self, updateTheButton: button)
  }
}
</code>```

Also your data source method, doesn't tell the cell whether the button was pressed or not. It just sets the image but doesn't set the variable buttonPressed

```<code> internal func tableView(_ tableView:UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  let cell = tableView.dequeueReusableCell(withIdentifier: "theCells") as? Cells
  cell?.theTextField.delegate = self
  cell?.cellDelegate = self
  cell?.checkBox.setImage(myImages[indexPath.row], for: UIControlState.normal)

  return cell!
}
</code>```

Title: Updating button events in Swift?

Body:
I am creating a Check List app and trying to update button event which is set images itself after clicked.

Here is my code:

protocol CustomeCellDelegate {
   func cell(cell: UITableViewCell, updateTheButton button: UIButton)
}

class Cells: UITableViewCell, UITextFieldDelegate {

@IBOutlet weak var checkBox: UIButton!
    var buttonPressed = true
@IBAction func checkBoxAction(_ sender: UIButton) {
    if buttonPressed {
        sender.setImage(UIImage(named: "checkBoxB"), for: UIControlState.normal)
        buttonPressed = false
    } else {
        sender.setImage(UIImage(named:""), for: UIControlState.normal)
        buttonPressed = true
    }
}
 @objc func recordButtonImage(_ button: UIButton) {
    cellDelegate?.cell(cell: self, updateTheButton: button)  // cell notify the button that touched.
}
override func awakeFromNib() {
    checkBox.addTarget(self, action: #selector(recordButtonImage(_:)), for: UIControlEvents.touchUpInside)
    }
}

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, CustomeCellDelegate {

@IBOutlet weak var tableView: UITableView!

var myImages: [UIImage?]!

override func viewDidLoad() {
  super.viewDidLoad()
    self.tableView.delegate   = self
    self.tableView.dataSource = self
    myImages = Array(repeatElement(nil, count: 50))
    let nib = UINib(nibName: "Cells", bundle: nil)
    tableView.register(nib, forCellReuseIdentifier: "Cells")
 }

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 50
}

internal func tableView(_ tableView:UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "theCells") as? Cells
        cell?.theTextField.delegate = self
        cell?.cellDelegate = self
        cell?.checkBox.setImage(myImages[indexPath.row], for: UIControlState.normal)

    return cell!
}

// This function from protocol and it helps to update button images.
func cell(cell: UITableViewCell, updateTheButton button: UIButton) {
    print("Delegate method Update Button Images.")
    if let indexPath = tableView.indexPath(for: cell), let buttonImage = button.image(for: UIControlState.normal) {
        myImages[indexPath.row] = buttonImage
    }
}

I would like to update both events of the button that set image after checked and unchecked. Therefore, my table view can dequeue Reusable Cell and have those events updated.

But the result is just one event of button which is checked updated but not the unchecked one. The checked button still repeats whatever I do to uncheck it.

Body:
I think you don't need recordButtonImage method, you should call the delegate method from the button tapped action i.e. checkBoxAction, just like below

class Cells: UITableViewCell, UITextFieldDelegate {
  @IBOutlet weak var checkBox: UIButton!
  var buttonPressed = true
  @IBAction func checkBoxAction(_ sender: UIButton) {
    if buttonPressed {
      sender.setImage(UIImage(named: "checkBoxB"), for: UIControlState.normal)
      buttonPressed = false
    } else {
      sender.setImage(UIImage(named:""), for: UIControlState.normal)
      buttonPressed = true
    }
    // cell notify the button that touched.
    cellDelegate?.cell(cell: self, updateTheButton: button)
  }
}

Also your data source method, doesn't tell the cell whether the button was pressed or not. It just sets the image but doesn't set the variable buttonPressed

 internal func tableView(_ tableView:UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  let cell = tableView.dequeueReusableCell(withIdentifier: "theCells") as? Cells
  cell?.theTextField.delegate = self
  cell?.cellDelegate = self
  cell?.checkBox.setImage(myImages[indexPath.row], for: UIControlState.normal)

  return cell!
}


问:
Setting up a display environment variable for a remote unix system
Trying to get some graphical network simulator (ns2) code to display from my university's unix system. My local OS is Ubuntu 10 and I am accessing the unix system through PuTTY SSH client. When some prewritten code is executed, the following error prompt occurs:

```<code>no display name and no $DISPLAY environment variable</code>```

What can be done to get remotely executed code to display on my system? I am a total novice with unix and my attempts at redefining the $DISPLAY env var were spectacular failures. Thanks. Appreciated.

答: Enable X forwarding in PuTTY. Option is in Connection/SSH/Tunnels.</p>

ContentLicense: CC BY-SA 2.5

Body:
Trying to get some graphical network simulator (ns2) code to display from my university's unix system. My local OS is Ubuntu 10 and I am accessing the unix system through PuTTY SSH client. When some prewritten code is executed, the following error prompt occurs:

no display name and no $DISPLAY environment variable

What can be done to get remotely executed code to display on my system? I am a total novice with unix and my attempts at redefining the $DISPLAY env var were spectacular failures. Thanks. Appreciated.


问:
Ionic framework 3, how to REPLACE a view? How to Pop() and the Push()

I would like to be able to replace the current view in the navigation
  stack.

I'm designing a layout for a book which is split into 9 parts. These parts are connected together using pagination at the bottom of each part e.g. previous and next buttons.

Current structure of pages is the following: I have 1 main page (the overview) that links to all parts using this.navCtrl.push(PartXPage) (I've created pages for all 9 parts).
.

Each page, also links to the next and previous pages as so:

However, here comes the problem

When I read part1, then part2, then part3 and so on, the back button always goes back 1 view at a time. So for example, if I read all the way to part 9 in 1 go and I would like to go to the overview or the main screen, I would have to click back 9 times.

What I wanted to do is create the following logic. When a user goes to the next part, we remove the current part from the view and push the next one, so the back button always returns to the overview.

I'm looking for something like (if I am on part 1, the next button would):

```<code>  go_to_part_2() {
    this.navCtrl.pop()  // to forget the current view
    this.navCtrl.push(Part2Page) // push a new view
  }
</code>```

However, this code doesn't work, nor does this.navCtrl.pop().push()

答:
You can add custom back button from ionic in navigation bar and after that when user click on back button you can set the Root page whatever you want to show to user

this.navCtrl.setRoot(PageName)

Body:
I would like to be able to replace the current view in the navigation
  stack.

I'm designing a layout for a book which is split into 9 parts. These parts are connected together using pagination at the bottom of each part e.g. previous and next buttons.

Current structure of pages is the following: I have 1 main page (the overview) that links to all parts using this.navCtrl.push(PartXPage) (I've created pages for all 9 parts).
.

Each page, also links to the next and previous pages as so:

However, here comes the problem

When I read part1, then part2, then part3 and so on, the back button always goes back 1 view at a time. So for example, if I read all the way to part 9 in 1 go and I would like to go to the overview or the main screen, I would have to click back 9 times.

What I wanted to do is create the following logic. When a user goes to the next part, we remove the current part from the view and push the next one, so the back button always returns to the overview.

I'm looking for something like (if I am on part 1, the next button would):

  go_to_part_2() {
    this.navCtrl.pop()  // to forget the current view
    this.navCtrl.push(Part2Page) // push a new view
  }

However, this code doesn't work, nor does this.navCtrl.pop().push()


问:
PHP File if Condition get different result and error
I have Three queries execute at the same time and its declared one object $sql.
In result "Product" Array Actually Four Record display only one Record,Three Record is not Display. In "total" Array Percentage Value Display null.

I have need this Result

```<code>  {"success":1,"product":[{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-10-06 00:00:00.000000","timezone_type":3,"timezone":"UTC"},"subject":"MATHS","ExamName":"WT","Marks":"30.00","TotalMarks":"30.00","PassingMarks":"10"},{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-10-07 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Kolkata"},"subject":"PHYSICS","ExamName":"WT","Marks":"15.00","TotalMarks":"30.00","PassingMarks":"10"},{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-10-08 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Kolkata"},"subject":"PHYSICS","ExamName":"WT","Marks":"25.00","TotalMarks":"30.00","PassingMarks":"10"},{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-11-22 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Kolkata"},"subject":"PHYSICS","ExamName":"WT","Marks":"25.00","TotalMarks":"30.00","PassingMarks":"10"},],"total":[{"Marks":"30.00","TotalMarks":"30.00","Percentage":"79.166600"}],"exam":[{"ExamName":"WT"}]}
</code>```

I have show Error Image below the Code. In image only one record display but in above resulr Four Record and Percentage Value Display null in image.

Marks.php

```<code>if(isset($_REQUEST["insert"]))
{
$reg = $_GET['reg'];

$sql = "select b.std_Name,d.Standard,e.Division,a.ExamDate,f.subject,a.ExamName,a.Marks,a.TotalMarks,a.PassingMarks
                                  from Marks_mas a  inner join std_reg b on a.regno=b.regno
                                  INNER JOIN Subject_mas as f ON a.Subject_ID = f.Subject_ID
                                  inner join StandardMaster d on a.standard = d.STDID
                                  inner join DivisionMaster e on a.Division = e.DivisionID
                                  where a.RegNo= '$reg' order by a.ExamDate; select   sum(a.Marks) as Marks,sum(a.TotalMarks) as TotalMarks, sum(a.Marks)/sum(a.TotalMarks) * 100 as Percentage
                                   from Marks_mas a
                                   where a.RegNo= '$reg'; select distinct ExamName From Marks_mas;";

$stmt = sqlsrv_query($conn, $sql);

$result = array();

 if (!empty($stmt)) {
        // check for empty result
        if (sqlsrv_has_rows($stmt) > 0) {

            $stmt = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);

            $product = array();
            $product["std_Name"] = $stmt["std_Name"];
            $product["Standard"] = $stmt["Standard"];
            $product["Division"] = $stmt["Division"];
            $product["ExamDate"] = $stmt["ExamDate"];
            $product["subject"] = $stmt["subject"];
            $product["ExamName"] = $stmt["ExamName"];
            $product["Marks"] = $stmt["Marks"];
            $product["TotalMarks"] = $stmt["TotalMarks"];
            $product["PassingMarks"] = $stmt["PassingMarks"];

            $total = array();
            $total["Marks"] = $stmt["Marks"];
            $total["TotalMarks"] = $stmt["TotalMarks"];
            $total["Percentage"] = $stmt["Percentage"];

            $exam = array();
            $exam["ExamName"] = $stmt["ExamName"];

            // success
            $result["success"] = 1;

            // user node
            $result["product"] = array();
            $result["total"] = array();
            $result["exam"] = array();

            array_push($result["product"],$product);
            array_push($result["total"],$total);
            array_push($result["exam"],$exam);

            // echoing JSON response
            echo json_encode($result);

        } else {
            // no product found
            $result["success"] = 0;
            $result["message"] = "No product found";

            // echo no users JSON
            echo json_encode($result);

        }

        //sqlsrv_free_stmt($stmt);
        sqlsrv_close($conn); //Close the connnection first

    }

}
</code>```

This is Error:

enter image description here

答:
just put below percentage calculation section in brackets and try</p>

```<code>(sum(a.Marks)/sum(a.TotalMarks) * 100) as Percentage
</code>```

Body:
I have Three queries execute at the same time and its declared one object $sql.
In result "Product" Array Actually Four Record display only one Record,Three Record is not Display. In "total" Array Percentage Value Display null.

I have need this Result

  {"success":1,"product":[{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-10-06 00:00:00.000000","timezone_type":3,"timezone":"UTC"},"subject":"MATHS","ExamName":"WT","Marks":"30.00","TotalMarks":"30.00","PassingMarks":"10"},{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-10-07 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Kolkata"},"subject":"PHYSICS","ExamName":"WT","Marks":"15.00","TotalMarks":"30.00","PassingMarks":"10"},{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-10-08 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Kolkata"},"subject":"PHYSICS","ExamName":"WT","Marks":"25.00","TotalMarks":"30.00","PassingMarks":"10"},{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-11-22 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Kolkata"},"subject":"PHYSICS","ExamName":"WT","Marks":"25.00","TotalMarks":"30.00","PassingMarks":"10"},],"total":[{"Marks":"30.00","TotalMarks":"30.00","Percentage":"79.166600"}],"exam":[{"ExamName":"WT"}]}

I have show Error Image below the Code. In image only one record display but in above resulr Four Record and Percentage Value Display null in image.

Marks.php

if(isset($_REQUEST["insert"]))
{
$reg = $_GET['reg'];

$sql = "select b.std_Name,d.Standard,e.Division,a.ExamDate,f.subject,a.ExamName,a.Marks,a.TotalMarks,a.PassingMarks
                                  from Marks_mas a  inner join std_reg b on a.regno=b.regno
                                  INNER JOIN Subject_mas as f ON a.Subject_ID = f.Subject_ID
                                  inner join StandardMaster d on a.standard = d.STDID
                                  inner join DivisionMaster e on a.Division = e.DivisionID
                                  where a.RegNo= '$reg' order by a.ExamDate; select   sum(a.Marks) as Marks,sum(a.TotalMarks) as TotalMarks, sum(a.Marks)/sum(a.TotalMarks) * 100 as Percentage
                                   from Marks_mas a
                                   where a.RegNo= '$reg'; select distinct ExamName From Marks_mas;";

$stmt = sqlsrv_query($conn, $sql);

$result = array();

 if (!empty($stmt)) {
        // check for empty result
        if (sqlsrv_has_rows($stmt) > 0) {

            $stmt = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);

            $product = array();
            $product["std_Name"] = $stmt["std_Name"];
            $product["Standard"] = $stmt["Standard"];
            $product["Division"] = $stmt["Division"];
            $product["ExamDate"] = $stmt["ExamDate"];
            $product["subject"] = $stmt["subject"];
            $product["ExamName"] = $stmt["ExamName"];
            $product["Marks"] = $stmt["Marks"];
            $product["TotalMarks"] = $stmt["TotalMarks"];
            $product["PassingMarks"] = $stmt["PassingMarks"];

            $total = array();
            $total["Marks"] = $stmt["Marks"];
            $total["TotalMarks"] = $stmt["TotalMarks"];
            $total["Percentage"] = $stmt["Percentage"];

            $exam = array();
            $exam["ExamName"] = $stmt["ExamName"];

            // success
            $result["success"] = 1;

            // user node
            $result["product"] = array();
            $result["total"] = array();
            $result["exam"] = array();

            array_push($result["product"],$product);
            array_push($result["total"],$total);
            array_push($result["exam"],$exam);

            // echoing JSON response
            echo json_encode($result);

        } else {
            // no product found
            $result["success"] = 0;
            $result["message"] = "No product found";

            // echo no users JSON
            echo json_encode($result);

        }

        //sqlsrv_free_stmt($stmt);
        sqlsrv_close($conn); //Close the connnection first

    }

}

This is Error:

enter image description here

Body:
just put below percentage calculation section in brackets and try

(sum(a.Marks)/sum(a.TotalMarks) * 100) as Percentage


问:
Sampling patches of points
Given an array of shape (N,2) I want to take a patch of size d x d for every point.
for example if

```<code>d = 3
points = [[3, 2], [1, 2]]
patchs = array([[[[2, 1],[3, 1],[4, 1]],
                 [[2, 2],[3, 2],[4, 2]],
                 [[2, 3],[3, 3],[4, 3]]], [[[0, 1],[1, 1],[2, 1]],
                                           [[0, 2],[1, 2],[2, 2]],
                                           [[0, 3],[1, 3],[2, 3]]]])
</code>```

I've managed to do it with one point only, but I can't find a smart way to avoid loops over N. this is what I did:

```<code>p = [3,2]
xs = p[0] + [-1,0,1]
ys = p[1] + [-1,0,1]
res = np.transpose([np.tile(xs, len(ys)), np.repeat(ys, len(xs))])
</code>```

答:
Here's one vectorized approach leveraging broadcasting for assignments -

```<code>hd = d//2 # half patch size
r = np.arange(-hd,hd+1)

out = np.empty((len(points),d,d,2), dtype=points.dtype)
out[...,0] = points[:,0,None,None] + r
out[...,1] = points[:,1,None,None] + r[:,None]
</code>```

Runtime test on one million points -

```<code>In [372]: points = np.random.randint(0,9,(1000000,2))

In [373]: %%timeit
     ...: hd = d//2 # half patch size
     ...: r = np.arange(-hd,hd+1)
     ...:
     ...: out = np.empty((len(points),d,d,2), dtype=points.dtype)
     ...: out[...,0] = points[:,0,None,None] + r
     ...: out[...,1] = points[:,1,None,None] + r[:,None]
10 loops, best of 3: 69.9 ms per loop
</code>```

Title: Sampling patches of points

Body:
Given an array of shape (N,2) I want to take a patch of size d x d for every point.
for example if

d = 3
points = [[3, 2], [1, 2]]
patchs = array([[[[2, 1],[3, 1],[4, 1]],
                 [[2, 2],[3, 2],[4, 2]],
                 [[2, 3],[3, 3],[4, 3]]], [[[0, 1],[1, 1],[2, 1]],
                                           [[0, 2],[1, 2],[2, 2]],
                                           [[0, 3],[1, 3],[2, 3]]]])

I've managed to do it with one point only, but I can't find a smart way to avoid loops over N. this is what I did:

p = [3,2]
xs = p[0] + [-1,0,1]
ys = p[1] + [-1,0,1]
res = np.transpose([np.tile(xs, len(ys)), np.repeat(ys, len(xs))])

Body:
Here's one vectorized approach leveraging broadcasting for assignments -

hd = d//2 # half patch size
r = np.arange(-hd,hd+1)

out = np.empty((len(points),d,d,2), dtype=points.dtype)
out[...,0] = points[:,0,None,None] + r
out[...,1] = points[:,1,None,None] + r[:,None]

Runtime test on one million points -

In [372]: points = np.random.randint(0,9,(1000000,2))

In [373]: %%timeit
     ...: hd = d//2 # half patch size
     ...: r = np.arange(-hd,hd+1)
     ...:
     ...: out = np.empty((len(points),d,d,2), dtype=points.dtype)
     ...: out[...,0] = points[:,0,None,None] + r
     ...: out[...,1] = points[:,1,None,None] + r[:,None]
10 loops, best of 3: 69.9 ms per loop


问:
JDO querys with OR in GAE
Got an entity A with like this

```<code>public class A
 private String a;
 private String b;
..
..
..
</code>```

How do I write a JDO query that select all the A objects that matches either keyword==a OR keyword ==b

Full code looks something like this:

```<code>Query q = pm.newQuery(SELECT FROM A WHERE a == keyword || b == keyword ORDER BY date DESC");

        List<A> results = (List<A>)q.execute(keyword);
</code>```

This code does not give any error but does not give any results. Removing the || part gives results.

Thanks

答:
You can't do an OR on two different fields.  Here is a snippet from the docs:

In the JDOQL string syntax, you can
  separate multiple filters with ||
  (logical "or") and && (logical "and"),
  although keep in mind that || can only
  be employed when the filters it
  separates all have the same field
  name. In other words, || is only legal
  in situations where the filters it
  separates can be combined into a
  single contains() filter:

```<code>// legal, all filters separated by || are on the same field
Query query = pm.newQuery(Employee.class,
                          "(lastName == 'Smith' || lastName == 'Jones')" +
                          " && firstName == 'Harold'");

// not legal, filters separated by || are on different fields
Query query = pm.newQuery(Employee.class,
                          "lastName == 'Smith' || firstName == 'Harold'");
</code>```

One way around this might be to store your a and b in a list.  If you have a list of items called foo, you could do a query where foo = keyword, and if any item in foo matches, you will get that object back in your results.  You don't say much about what a and b are, so I don't know if this will work for you or not :)

Update:

```<code>public class Example {
    String firstName;
    String lastName;
    List<String> allNames;

    public Example(String first, String last){
        firstName = first;
        lastName = last;
        allNames = new ArrayList<String>();
        allNames.add(first);
        allNames.add(last);
    }
 }
</code>```

With something like that, you could then do a query where "allNames == 'Smith' || allNames=='Jones'".

Title: JDO querys with OR in GAE

Body:
Got an entity A with like this

public class A
 private String a;
 private String b;
..
..
..

How do I write a JDO query that select all the A objects that matches either keyword==a OR keyword ==b

Full code looks something like this:

Query q = pm.newQuery(SELECT FROM A WHERE a == keyword || b == keyword ORDER BY date DESC");

        List results = (List)q.execute(keyword);

This code does not give any error but does not give any results. Removing the || part gives results.

Thanks

Body:
You can't do an OR on two different fields.  Here is a snippet from the docs:

In the JDOQL string syntax, you can
  separate multiple filters with ||
  (logical "or") and && (logical "and"),
  although keep in mind that || can only
  be employed when the filters it
  separates all have the same field
  name. In other words, || is only legal
  in situations where the filters it
  separates can be combined into a
  single contains() filter:

// legal, all filters separated by || are on the same field
Query query = pm.newQuery(Employee.class,
                          "(lastName == 'Smith' || lastName == 'Jones')" +
                          " && firstName == 'Harold'");

// not legal, filters separated by || are on different fields
Query query = pm.newQuery(Employee.class,
                          "lastName == 'Smith' || firstName == 'Harold'");

One way around this might be to store your a and b in a list.  If you have a list of items called foo, you could do a query where foo = keyword, and if any item in foo matches, you will get that object back in your results.  You don't say much about what a and b are, so I don't know if this will work for you or not :)

Update:

public class Example {
    String firstName;
    String lastName;
    List<String> allNames;

    public Example(String first, String last){
        firstName = first;
        lastName = last;
        allNames = new ArrayList<String>();
        allNames.add(first);
        allNames.add(last);
    }
 }

With something like that, you could then do a query where "allNames == 'Smith' || allNames=='Jones'".


问:
how to call function in div tag without using *ngIf In Angular 2
In I want to filter JSON in nested loop I have filters in child loop, but ngFor but I also want that filter at parent level also angular 2 I am using nglf To call the function it working but I want another method because it calls contentiously</p>

```<code><div *ngFor="let partyAddress of addressDataShow?.data" >
    <div class="row bg-greybg"  *ngIf="companyFilter(partyAddress) || selectedaddress === 'ALL' || isAddressAvailabale > 0">
 <div *ngFor="let partyAddressDetails of partyAddress?.company_address">
          <div *ngIf="selectedaddress === 'ALL' || partyAddressDetails.address_type.indexOf(selectedaddress) > -1">
            <p>Filter data</p>
          </div>
        </div>
<div>
</div>
</code>```

答:
If you want to call that function only. Then just call the function using  double curly brace {{functionName()}}

```<code><div *ngFor="let partyAddress of addressDataShow?.data" >
    <div class="row bg-greybg"  > {{companyFilter(partyAddress)}}
        <div *ngFor="let partyAddressDetails of partyAddress?.company_address">
          <div *ngIf="selectedaddress === 'ALL' || partyAddressDetails.address_type.indexOf(selectedaddress) > -1">
            <p>Filter data</p>
          </div>
        </div>
    <div>
</div>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In I want to filter JSON in nested loop I have filters in child loop, but ngFor but I also want that filter at parent level also angular 2 I am using nglf To call the function it working but I want another method because it calls contentiously

 0">

 -1">

Filter data

Body:
If you want to call that function only. Then just call the function using  double curly brace {{functionName()}}

<div *ngFor="let partyAddress of addressDataShow?.data" >
    <div class="row bg-greybg"  > {{companyFilter(partyAddress)}}
        <div *ngFor="let partyAddressDetails of partyAddress?.company_address">
          <div *ngIf="selectedaddress === 'ALL' || partyAddressDetails.address_type.indexOf(selectedaddress) > -1">
            <p>Filter data</p>
          </div>
        </div>
    <div>
</div>


问:
Caused by: java.lang.ClassNotFoundException - multidex not work properly
I've installed multidex solution in my android app project and in "Google Play Dev" people encounter errors like this:

```<code>java.lang.RuntimeException:
  at android.app.ActivityThread.handleReceiver (ActivityThread.java:2591)
  at android.app.ActivityThread.access$1700 (ActivityThread.java:157)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1450)
  at android.os.Handler.dispatchMessage (Handler.java:110)
  at android.os.Looper.loop (Looper.java:193)
  at android.app.ActivityThread.main (ActivityThread.java:5398)
  at java.lang.reflect.Method.invokeNative (Native Method)
  at java.lang.reflect.Method.invoke (Method.java:515)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:940)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:756)
  at dalvik.system.NativeStart.main (Native Method)
Caused by: java.lang.ClassNotFoundException:
  at dalvik.system.BaseDexClassLoader.findClass (BaseDexClassLoader.java:56)
  at java.lang.ClassLoader.loadClass (ClassLoader.java:497)
  at java.lang.ClassLoader.loadClass (ClassLoader.java:457)
  at android.app.ActivityThread.handleReceiver (ActivityThread.java:2586)
</code>```

As far as I know, I've installed multidex correctly (readed other sources about this error & multidex)

Things I did:

MyApplication class inherits from MultiDexApplication

gradle file:

android {
    defaultConfig {
        multiDexEnabled true
    }
    dexOptions {
        javaMaxHeapSize "2048M"
    }
}

dependencies {
    compile 'com.android.support:multidex:1.0.1'
}

Yes. I use proguard.

答:
update manifest like:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapp">
    <application
            android:name="android.support.multidex.MultiDexApplication" >
        ...
    </application>
</manifest>
</code>```

Body:
I've installed multidex solution in my android app project and in "Google Play Dev" people encounter errors like this:

java.lang.RuntimeException:
  at android.app.ActivityThread.handleReceiver (ActivityThread.java:2591)
  at android.app.ActivityThread.access$1700 (ActivityThread.java:157)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1450)
  at android.os.Handler.dispatchMessage (Handler.java:110)
  at android.os.Looper.loop (Looper.java:193)
  at android.app.ActivityThread.main (ActivityThread.java:5398)
  at java.lang.reflect.Method.invokeNative (Native Method)
  at java.lang.reflect.Method.invoke (Method.java:515)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:940)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:756)
  at dalvik.system.NativeStart.main (Native Method)
Caused by: java.lang.ClassNotFoundException:
  at dalvik.system.BaseDexClassLoader.findClass (BaseDexClassLoader.java:56)
  at java.lang.ClassLoader.loadClass (ClassLoader.java:497)
  at java.lang.ClassLoader.loadClass (ClassLoader.java:457)
  at android.app.ActivityThread.handleReceiver (ActivityThread.java:2586)

As far as I know, I've installed multidex correctly (readed other sources about this error & multidex)

Things I did:

MyApplication class inherits from MultiDexApplication

gradle file:

android {
    defaultConfig {
        multiDexEnabled true
    }
    dexOptions {
        javaMaxHeapSize "2048M"
    }
}

dependencies {
    compile 'com.android.support:multidex:1.0.1'
}

Yes. I use proguard.

Body:
update manifest like:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapp">
    <application
            android:name="android.support.multidex.MultiDexApplication" >
        ...
    </application>
</manifest>


问:
Cannot install NodeJs: /usr/bin/env: node: No such file or directory
I'm trying to install nodeJs into my Ubuntu 14.04 in order to use GruntJs.

I've read about Ubuntu different way of doing it (issues?), so this is what I've done in order to install it:

```<code>sudo apt-get install npm

sudo npm install -g grunt-cli
</code>```

Typing grunt after that I've got the error:

```<code>/usr/bin/env: node: No such file or directory
</code>```

So, I've tried:

```<code>curl -sL https://deb.nodesource.com/setup | sudo bash -

sudo apt-get install -y nodejs

sudo apt-get update
</code>```

And trying again, and still getting the error, I've tried:

```<code>sudo add-apt-repository https://launchpad.net/~chris-lea/+archive/node.js/

sudo apt-get install -y nodejs
</code>```

I've got this message:

```<code>nodejs is already the newest version.
0 to upgrade, 0 to newly install, 0 to remove and 3 not to upgrade.
</code>```

I did try a cleanup just in case:

```<code>sudo apt-get autoremove
</code>```

But nope, the error is still there: when I type grunt I still get /usr/bin/env: node: No such file or directory

What should I do?

答:
For my case link did NOT work as follow

ln -s /usr/bin/nodejs /usr/bin/node

But you can open /usr/local/bin/lessc as root, and change the first line from node to nodejs.

-#!/usr/bin/env node

+#!/usr/bin/env nodejs

Body:
I'm trying to install nodeJs into my Ubuntu 14.04 in order to use GruntJs.

I've read about Ubuntu different way of doing it (issues?), so this is what I've done in order to install it:

sudo apt-get install npm

sudo npm install -g grunt-cli

Typing grunt after that I've got the error:

/usr/bin/env: node: No such file or directory

So, I've tried:

curl -sL https://deb.nodesource.com/setup | sudo bash -

sudo apt-get install -y nodejs

sudo apt-get update

And trying again, and still getting the error, I've tried:

sudo add-apt-repository https://launchpad.net/~chris-lea/+archive/node.js/

sudo apt-get install -y nodejs

I've got this message:

nodejs is already the newest version.
0 to upgrade, 0 to newly install, 0 to remove and 3 not to upgrade.

I did try a cleanup just in case:

sudo apt-get autoremove

But nope, the error is still there: when I type grunt I still get /usr/bin/env: node: No such file or directory

What should I do?


问:
Either use @Param on all parameters except Pageable and Sort typed once Spring boot
I saw some questions about this error but I could not find a solution for my case.

I'm implementing a paging in the spring boot application.

I Have this method in my controller

```<code>@RequestMapping(method = RequestMethod.GET, value = "/distrito",  params = { "page", "size" })
    public ResponseEntity<Page<Distritos>> buscarTodosDistritos(HttpServletRequest request, @RequestParam("page") int page, @RequestParam("size") int size) throws ServletException {
        Map<String, String>informacaoUsuario = uService.getInformacoesUsuario(request);

        Page<Distritos> distritosBuscados = distritosService.buscarFiltro(Long.parseLong(informacaoUsuario.get("idEntidadeSelecionada")), page, size);
            return new ResponseEntity<>(distritosBuscados, HttpStatus.OK);
    }
</code>```

and my service

```<code>    public Page<Distritos> buscarFiltro(Long usuarioEntidade ,int size, int page){
        return distritosRepository.encontrar(usuarioEntidade, size, page);
    }
</code>```

my repository

```<code>@Query( nativeQuery=true, value="SELECT dist.nome, dist.id_distrito, dist.id_entidade, dist.id_municipio, dist.id_uf, dist.codigo_dne, dist.flag_ativo,  enti.nome Entidade, muni.nome Municipio, unfe.nome UF FROM glb.distritos  dist, glb.entidades  enti, glb.municipios muni, glb.ufs unfe WHERE dist.id_entidade  = enti.id_entidade AND dist.id_municipio = muni.id_municipio AND muni.id_uf = unfe.id_uf and enti.id_entidade = :parametroId order by nome   ")
    public  Page<Distritos>  encontrar(@Param ("parametroId")Long usuarioEntidade, int size, int page);
</code>```

and i got this error

```<code>Caused by: java.lang.IllegalArgumentException: Either use @Param on all parameters except Pageable and Sort typed once, or none at all!
    at org.springframework.util.Assert.isTrue(Assert.java:92) ~[spring-core-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.data.repository.query.Parameters.assertEitherAllParamAnnotatedOrNone(Parameters.java:297) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
    at org.springframework.data.repository.query.Parameters.<init>(Parameters.java:91) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
</code>```

how can i solve that ???

答: Check org.springframework.data.domain.Pageable class which is provided by Spring for pagination. Controller will extract your parameters and build it automatically.

Body:
I saw some questions about this error but I could not find a solution for my case.

I'm implementing a paging in the spring boot application.

I Have this method in my controller

@RequestMapping(method = RequestMethod.GET, value = "/distrito",  params = { "page", "size" })
    public ResponseEntity<Page<Distritos>> buscarTodosDistritos(HttpServletRequest request, @RequestParam("page") int page, @RequestParam("size") int size) throws ServletException {
        Map<String, String>informacaoUsuario = uService.getInformacoesUsuario(request);

        Page<Distritos> distritosBuscados = distritosService.buscarFiltro(Long.parseLong(informacaoUsuario.get("idEntidadeSelecionada")), page, size);
            return new ResponseEntity<>(distritosBuscados, HttpStatus.OK);
    }

and my service

    public Page<Distritos> buscarFiltro(Long usuarioEntidade ,int size, int page){
        return distritosRepository.encontrar(usuarioEntidade, size, page);
    }

my repository

@Query( nativeQuery=true, value="SELECT dist.nome, dist.id_distrito, dist.id_entidade, dist.id_municipio, dist.id_uf, dist.codigo_dne, dist.flag_ativo,  enti.nome Entidade, muni.nome Municipio, unfe.nome UF FROM glb.distritos  dist, glb.entidades  enti, glb.municipios muni, glb.ufs unfe WHERE dist.id_entidade  = enti.id_entidade AND dist.id_municipio = muni.id_municipio AND muni.id_uf = unfe.id_uf and enti.id_entidade = :parametroId order by nome   ")
    public  Page<Distritos>  encontrar(@Param ("parametroId")Long usuarioEntidade, int size, int page);

and i got this error

Caused by: java.lang.IllegalArgumentException: Either use @Param on all parameters except Pageable and Sort typed once, or none at all!
    at org.springframework.util.Assert.isTrue(Assert.java:92) ~[spring-core-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.data.repository.query.Parameters.assertEitherAllParamAnnotatedOrNone(Parameters.java:297) ~[spring-data-commons-1.13.4.RELEASE.jar:na]
    at org.springframework.data.repository.query.Parameters.<init>(Parameters.java:91) ~[spring-data-commons-1.13.4.RELEASE.jar:na]

how can i solve that ???


问:
Camera Permission always denied without dialog shown on Google Pixel when running instant app
I am porting an existing application to an instant app that requires a camera permission to run. On Pixel 2 device and Samsung S8 the permission dialogue gets shown and I can request the permission. On the Pixel 1 Device the dialogue does not get shown and the Permission grant result is immediately returning -1 in onActivityResult.

All of the devices run Android 8.0.0

I tried a full grandle sync, clean, deleting the instant app, installing the full version and deinstalling it, completely removing the instant app support for the device and re-enabling it, restarting the device, invalidating Android Studios cache and add the clear the cache flags to the run configuration as described here Android Instant Apps not running on Pixel .

If I access the permission settings by category, the application is listed, with the camera permission set to off. If I grant the permission there, and return to the screen the camera permission is again disabled. In the application details the instant app is shown as that it does not require any permissions.

Are the permission settings for instant apps cached in some location on the device ? How can I purge that cache ?

答: Installing the latest Android 8.0.0 security update on the Pixel phone resolved the issue. Permissions were asked again.</p>


问:
regex replace not working in HIVE
I want to replace the ; in data to : in HIVE
tried the following but not working

```<code>hive> select REGEXP_REPLACE('Mozilla/5.0 (Macintosh; Intel',';',':');
</code>```

How to achieve this in HIVE. I am getting issues while transforming this.

答:
You need to escape the semicolon. Please see below</p>

```<code>hive> select REGEXP_REPLACE("Mozilla/5.0 (Macintosh\; Intel","\;",":");
OK
Mozilla/5.0 (Macintosh: Intel
Time taken: 0.082 seconds, Fetched: 1 row(s)
</code>```

Title: regex replace not working in HIVE

Body:
I want to replace the ; in data to : in HIVE
tried the following but not working

hive> select REGEXP_REPLACE('Mozilla/5.0 (Macintosh; Intel',';',':');

How to achieve this in HIVE. I am getting issues while transforming this.

Body:
You need to escape the semicolon. Please see below

hive> select REGEXP_REPLACE("Mozilla/5.0 (Macintosh\; Intel","\;",":");
OK
Mozilla/5.0 (Macintosh: Intel
Time taken: 0.082 seconds, Fetched: 1 row(s)


问:
C# Console?
Does anyone know if there is a c# Console app, similar to the Python or Ruby console? I know the whole "Compiled versus Interpreted" difference, but with C#'s reflection power I think it could be done.

UPDATE
Well, it only took about 200 lines, but I wrote a simple one...It works a lot like osql. You enter commands and then run them with go.

SharpConsole http://www.gfilter.net/junk/sharpconsole.jpg

If anyone wants it, let me know.

答:
I am not sure what you are looking for this application to accomplish.  If it is just to try some code without having to create a project and all the overhead to just test an idea, then SnippetCompiler could be a good fit.

I just wanted to give you another option.

OwnerDisplayName: Jonathan Holland

Title: C# Console?

LastEditorDisplayName: Jonathan Holland

OwnerDisplayName: Dale Ragan


问:
I'm not typing something right
```<code>return Convert.ToInt32(myClass2.Digit(bmp, nX1, nY1)
                                 + myClass2.Digit(bmp, nX2, nY2)
                                 + myClass2.Digit(bmp, nX3, nY3)
                                 + myClass2.Digit(bmp, nX4, nY4)
                                 + myClass2.Digit(bmp, nX5, nY5));
</code>```

...finds this test method:

```<code>class Class2 {
    public string Digit(Bitmap bmp, int x, int y) {
//Please drop any logic using bmp, x, and y for the sake of this post.  Let's just...
        return "3";
    }
}
</code>```

and returns 33333 as an int.  As a preliminary to get something going so far, so good.

The problem comes when I want to return "0"; there's literally no output, not even an 0 much less an 00000.  Instead, a line isn't even written to the console.

Thanks for any help.

答: Solved.  My code as originally posted proved in the final analysis to be fine.  Question is moot.</p>

Title: I'm not typing something right

Body:
return Convert.ToInt32(myClass2.Digit(bmp, nX1, nY1)
                                 + myClass2.Digit(bmp, nX2, nY2)
                                 + myClass2.Digit(bmp, nX3, nY3)
                                 + myClass2.Digit(bmp, nX4, nY4)
                                 + myClass2.Digit(bmp, nX5, nY5));

...finds this test method:

class Class2 {
    public string Digit(Bitmap bmp, int x, int y) {
//Please drop any logic using bmp, x, and y for the sake of this post.  Let's just...
        return "3";
    }
}

and returns 33333 as an int.  As a preliminary to get something going so far, so good.

The problem comes when I want to return "0"; there's literally no output, not even an 0 much less an 00000.  Instead, a line isn't even written to the console.

Thanks for any help.


问:
Failed to add new osd into monitor node in ceph
I am trying to add a osd node  by following command

```<code>ceph-deploy osd prepare ceph-02:/dev/sdb
</code>```

Found error that config file /etc/ceph/ceph.conf exists
with different content. used --overwrite-conf to overwrite.

How do I use overwrite-conf?

Error log:

```<code>[ceph_deploy.osd][INFO  ] Distro info: CentOS Linux 7.4.1708 Core

[ceph_deploy.osd][DEBUG ] Deploying osd to ceph-02

[ceph-02][DEBUG ] write cluster configuration to /etc/ceph/{cluster}.conf

[ceph_deploy.osd][ERROR ] RuntimeError: config file /etc/ceph/ceph.conf exists

with different content; use --overwrite-conf to overwrite

[ceph_deploy][ERROR ] GenericError: Failed to create 1 OSDs
</code>```

答:
This is a normal behavior for a ceph-deploy command. Just run ceph-deploy --overwrite-conf osd prepare ceph-02:/dev/sdb. This will replace your existing /etc/ceph/ceph.conf.
This will resolve your issue.

Body:
I am trying to add a osd node  by following command

ceph-deploy osd prepare ceph-02:/dev/sdb

Found error that config file /etc/ceph/ceph.conf exists
with different content. used --overwrite-conf to overwrite.

How do I use overwrite-conf?

Error log:

[ceph_deploy.osd][INFO  ] Distro info: CentOS Linux 7.4.1708 Core

[ceph_deploy.osd][DEBUG ] Deploying osd to ceph-02

[ceph-02][DEBUG ] write cluster configuration to /etc/ceph/{cluster}.conf

[ceph_deploy.osd][ERROR ] RuntimeError: config file /etc/ceph/ceph.conf exists

with different content; use --overwrite-conf to overwrite

[ceph_deploy][ERROR ] GenericError: Failed to create 1 OSDs


问:
How to get the dropdown nav child elements to follow the parent position from top
Progress and what I want to do should be clear here:

https://codepen.io/RautSamir/pen/RjzEKY

Under Offices, I need the child objects to show right under and hopefully same width as parent.

code:

```<code>    <div class="navItem" style="display:inline">
<button class="dropbtn"> Home </button>
</div>

<div class="dropdown" style="display:inline">
<button onclick="myFunction()" class="dropbtn">Offices</button>
  <div id="myDropdown" class="dropdown-content">
    <a href="#home">Regional</a>
    <a href="#about">Global</a>
    <a href="#contact">Local</a>
  </div>
</div>

<div class="navItem" style="display:inline">
<button class="dropbtn"> Who we are</button>
</div>

<div class="navItem" style="display:inline">
<button class="dropbtn"> Contact </button>
</div>

<div class="navItem" style="display:inline">
<button class="dropbtn" id="searchBox"> Search </button>
</div>
</code>```

答:
1) You have set the parents to display as inline so that everything aligns next to each other.

2) Change that to inline-block and you will see the drop-down lines up.
I'd advise you look into display types and get an understanding of how they each behave. At that point, it should become a lot more useful to you

3) Then the width on the buttons needs to be removed so that the button is not cut off. Rather set the width on the parents and have the button and drop-down widths set to 100%. They will then take the parents full width.

That should do it.

Body:
Progress and what I want to do should be clear here:

https://codepen.io/RautSamir/pen/RjzEKY

Under Offices, I need the child objects to show right under and hopefully same width as parent.

code:

<button class="dropbtn"> Home </button>

<button onclick="myFunction()" class="dropbtn">Offices</button>

    Regional
    Global
    Local

<button class="dropbtn"> Who we are</button>

<button class="dropbtn"> Contact </button>

<button class="dropbtn" id="searchBox"> Search </button>


答:
In your sql query there is no field with name "Percentage" so that is why you are getting this error

$sql = "select b.std_Name,d.Standard,e.Division,a.ExamDate,f.subject,a.ExamName,a.Marks,a.TotalMarks,a.PassingMarks,    Percentage missing "

Title: PHP File if Condition get different result and error

Body:
I have Three queries execute at the same time and its declared one object $sql.
In result "Product" Array Actually Four Record display only one Record,Three Record is not Display. In "total" Array Percentage Value Display null.

I have need this Result

  {"success":1,"product":[{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-10-06 00:00:00.000000","timezone_type":3,"timezone":"UTC"},"subject":"MATHS","ExamName":"WT","Marks":"30.00","TotalMarks":"30.00","PassingMarks":"10"},{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-10-07 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Kolkata"},"subject":"PHYSICS","ExamName":"WT","Marks":"15.00","TotalMarks":"30.00","PassingMarks":"10"},{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-10-08 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Kolkata"},"subject":"PHYSICS","ExamName":"WT","Marks":"25.00","TotalMarks":"30.00","PassingMarks":"10"},{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-11-22 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Kolkata"},"subject":"PHYSICS","ExamName":"WT","Marks":"25.00","TotalMarks":"30.00","PassingMarks":"10"},],"total":[{"Marks":"30.00","TotalMarks":"30.00","Percentage":"79.166600"}],"exam":[{"ExamName":"WT"}]}

I have show Error Image below the Code. In image only one record display but in above resulr Four Record and Percentage Value Display null in image.

Marks.php

if(isset($_REQUEST["insert"]))
{
$reg = $_GET['reg'];

$sql = "select b.std_Name,d.Standard,e.Division,a.ExamDate,f.subject,a.ExamName,a.Marks,a.TotalMarks,a.PassingMarks
                                  from Marks_mas a  inner join std_reg b on a.regno=b.regno
                                  INNER JOIN Subject_mas as f ON a.Subject_ID = f.Subject_ID
                                  inner join StandardMaster d on a.standard = d.STDID
                                  inner join DivisionMaster e on a.Division = e.DivisionID
                                  where a.RegNo= '$reg' order by a.ExamDate; select   sum(a.Marks) as Marks,sum(a.TotalMarks) as TotalMarks, sum(a.Marks)/sum(a.TotalMarks) * 100 as Percentage
                                   from Marks_mas a
                                   where a.RegNo= '$reg'; select distinct ExamName From Marks_mas;";

$stmt = sqlsrv_query($conn, $sql);

$result = array();

 if (!empty($stmt)) {
        // check for empty result
        if (sqlsrv_has_rows($stmt) > 0) {

            $stmt = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);

            $product = array();
            $product["std_Name"] = $stmt["std_Name"];
            $product["Standard"] = $stmt["Standard"];
            $product["Division"] = $stmt["Division"];
            $product["ExamDate"] = $stmt["ExamDate"];
            $product["subject"] = $stmt["subject"];
            $product["ExamName"] = $stmt["ExamName"];
            $product["Marks"] = $stmt["Marks"];
            $product["TotalMarks"] = $stmt["TotalMarks"];
            $product["PassingMarks"] = $stmt["PassingMarks"];

            $total = array();
            $total["Marks"] = $stmt["Marks"];
            $total["TotalMarks"] = $stmt["TotalMarks"];
            $total["Percentage"] = $stmt["Percentage"];

            $exam = array();
            $exam["ExamName"] = $stmt["ExamName"];

            // success
            $result["success"] = 1;

            // user node
            $result["product"] = array();
            $result["total"] = array();
            $result["exam"] = array();

            array_push($result["product"],$product);
            array_push($result["total"],$total);
            array_push($result["exam"],$exam);

            // echoing JSON response
            echo json_encode($result);

        } else {
            // no product found
            $result["success"] = 0;
            $result["message"] = "No product found";

            // echo no users JSON
            echo json_encode($result);

        }

        //sqlsrv_free_stmt($stmt);
        sqlsrv_close($conn); //Close the connnection first

    }

}

This is Error:

enter image description here


问:
How to update a record in csv file using Apache commons csv api in java?
I have a csv file written using Apache commons API and I also can read the file, however I'm unable to know how to edit a record value in the csv file using Apache commons API, need help on this.</p>

答:
I tried the below code and it worked exactly the way I expected.  </p>

```<code>public static void updateCsvFile(File f) throws Exception {
        CSVParser parser = new CSVParser(new FileReader(f), CSVFormat.DEFAULT);
        List<CSVRecord> list = parser.getRecords();
        String edited = f.getAbsolutePath();

        f.delete();
        CSVPrinter printer = new CSVPrinter(new FileWriter(edited), CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR));
        for (CSVRecord record : list) {
            String[] s = toArray(record);

            if(s[0].equalsIgnoreCase("Actual Text")){
                s[0] = "Replacement Text";
            }
            print(printer, s);
        }
        parser.close();
        printer.close();

        System.out.println("CSV file was updated successfully !!!");
    }

 public static String[] toArray(CSVRecord rec) {
            String[] arr = new String[rec.size()];
            int i = 0;
            for (String str : rec) {
                arr[i++] = str;
            }
            return arr;
        }

    public static void print(CSVPrinter printer, String[] s) throws Exception {
        for (String val : s) {
            printer.print(val != null ? String.valueOf(val) : "");
        }
        printer.println();
    }
</code>```

Body:
I tried the below code and it worked exactly the way I expected.

public static void updateCsvFile(File f) throws Exception {
        CSVParser parser = new CSVParser(new FileReader(f), CSVFormat.DEFAULT);
        List<CSVRecord> list = parser.getRecords();
        String edited = f.getAbsolutePath();

        f.delete();
        CSVPrinter printer = new CSVPrinter(new FileWriter(edited), CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR));
        for (CSVRecord record : list) {
            String[] s = toArray(record);

            if(s[0].equalsIgnoreCase("Actual Text")){
                s[0] = "Replacement Text";
            }
            print(printer, s);
        }
        parser.close();
        printer.close();

        System.out.println("CSV file was updated successfully !!!");
    }

 public static String[] toArray(CSVRecord rec) {
            String[] arr = new String[rec.size()];
            int i = 0;
            for (String str : rec) {
                arr[i++] = str;
            }
            return arr;
        }

    public static void print(CSVPrinter printer, String[] s) throws Exception {
        for (String val : s) {
            printer.print(val != null ? String.valueOf(val) : "");
        }
        printer.println();
    }


问:
What's the difference between Hyperledger Fabric and Sawtooth?
Both Hyperledger Fabric and Hyperledger Sawtooth are platforms for building distributed ledger applications, supporting pluggable consensus mechanisms and smart contracts (chaincodes).

What are the main differences between then? When to choose one over the other to implement a blockchain solution?

答:
In my view, Hyperledger Sawtooth is more related asset management and tracking, basically related to provenance and authenticity of an asset.

As far as Hyperledger Fabric is considered, it is pure DLT with smart contract capabilities for businesses.


问:
how to handle after Certificate Expiry or Renew
This is different block-chain data level from tradition web application.I generated self-signed ca certification and client nodes could communicate with each other after signed. so I have below questions:

how to process if ca certification expiry?

if ca certification didn't expiry how to process client certification
expiry?

if both didn't    expiry how to process certification encrypt for
revocation like    changed algorithm?

if from own node, I can re-import data after renew cert. how about client node?

答:
Corda is agnostic on this. It is up to the certificate authority. They decide whether certificates expire and how they revoke certificates.

If you choose to have a system where certificates expire, you need to also provide your own mechanism for provisioning the new certificates to the nodes. The nodes then need to update the keystores in their <workspace>/certificates/ folders accordingly (see https://docs.corda.net/permissioning.html).