问:
How to create android button bar?
I need to create a horizontal list of buttons without a separating space like this one

each button will contain a text and an icon I know about buttonbarlayout but it didn't work for me, please can someone help me, Thanks in advance

答:
```<code><LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:drawableTop="@drawable/read"
        android:text="Rewards" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:drawableTop="@drawable/read"
        android:text="Places" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:drawableTop="@drawable/read"
        android:text="Challenges" />
</LinearLayout>
</code>```

Use LinearLayout with horizontal orientation and three buttons with layout_weight=1

Title: How to create android button bar?

Body:
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:drawableTop="@drawable/read"
        android:text="Rewards" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:drawableTop="@drawable/read"
        android:text="Places" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:drawableTop="@drawable/read"
        android:text="Challenges" />
</LinearLayout>

Use LinearLayout with horizontal orientation and three buttons with layout_weight=1


来源: stackexchange

问:
MaterializeCSS make rows aligned
I am using materializecss and I have products in a grid system. Each product is wrapped in a div
 but when the products have varying heights, the products become staggered. I want to make it so that each row is separated and the products align to the left side.

答:
You have to wrap it into .row class

Example :

```<code><div class="row">
   <div class="col s4">Your  Your contentYour contentYour contentYour contentYour contentYour contentYour contentYour contentYour contentYour contentYour contentYour contentYour contentYour content</div>
   <div class="col s4">Your content</div>
   <div class="col s4">Your content</div>
</div>
<div class="row">
   <div class="col s4">Your content</div>
   <div class="col s4">Your content</div>
   <div class="col s4">Your content</div>
</div>
<div class="row">
   <div class="col s4">Your content</div>
   <div class="col s4">Your content</div>
   <div class="col s4">Your content</div>
</div>
</code>```

See this fiddle

ContentLicense: CC BY-SA 3.0

Title: MaterializeCSS make rows aligned

Body:
You have to wrap it into .row class

Example :

<div class="row">
   <div class="col s4">Your  Your contentYour contentYour contentYour contentYour contentYour contentYour contentYour contentYour contentYour contentYour contentYour contentYour contentYour content</div>
   <div class="col s4">Your content</div>
   <div class="col s4">Your content</div>
</div>
<div class="row">
   <div class="col s4">Your content</div>
   <div class="col s4">Your content</div>
   <div class="col s4">Your content</div>
</div>
<div class="row">
   <div class="col s4">Your content</div>
   <div class="col s4">Your content</div>
   <div class="col s4">Your content</div>
</div>

See this fiddle


问:
How important are data types to memory in Spark/Scala?
As a general rule of thumb, how important is it to optimize when it comes to Spark Scala datatypes? I'm interesting in saving memory, but if there are other considerations, I'd be happy to hear them.

Does Spark do any casting which would make, say, using a Short instead of an Int or Long superfluous?

Or does it create multiple references which would makes these savings a small part of the memory usage of the application?

If not, what about if I have a decimal value for which I need very little precision. Say three digits, from 0 to 1. I could use a Short to represent this (16 bits) instead of a Float (32 bits). Is this a reasonable optimization?

答:
There are some optimizations available in Spark SQL's Optimizer that comes for example with DecimalAggregates logical optimization that replaces Decimal-based calculations with optimized operators (see How (if at all) could rounding Decimals improve performance?).

I would also expect some more optimizations in InternalRow when it converts your data set from its unserialized format to its internal columnar representation (but that's something I have not explored in enough detail).


问:
omnet++ Inet - Simulating dynamic access point behaviour
I have to create a particular simulation for a college project. The simulation should feature several mobile nodes cyclically switch between 802.11 access point and station modes. While in station mode, nodes should read the SSIDs of access points around them, and then they should change their SSID in AP mode accordingly. There is no need for connections or data exchange between the nodes beside the SSID reading.

Now, I've been through Omnet/Inet tutorials/documentation (all two of them), and I feel pretty much stuck.
What I could use right now is someone confirming my understanding of the framework giving me some directions on how exactly I should proceed.

From what I understand is Inet does not implement any direct/easy way to do what I'm trying to do. Most examples have fixed connections declared in NED files and hosts with a fixed status (AP or STA) defined in the .ini file.

So my question is basically how do I do that: do I need to extend a module (say, wirelessHost), modifying its runtime behaviour, or should I implement a new application (like UDPApp) to have my node read other SSIDs and change his accordingly? And what is the best way to access an host's SSID?

答:
You may utilize two radios for each mobile node e.g. **.mobilenode[*].numRadios = 2 (see also example in /inet/examples/wireless/multiradio/).

The first radio operates as AP **.mobilenode[*].wlan[0].mgmtType = "Ieee80211MgmtAPSimplified" which has to adapt its SSID.

The second radio serves as STA **.mobilenode[*].wlan[1].mgmtType = "Ieee80211MgmtSTA". Now, you have to sub-class Ieee80211AgentSTA which handles the SSID scanning procedure and has to change the first radio's SSID upon new SSID detection. Then you utilize the adopted sub-class within the simulation. Finally, active scanning has to  be activated **.mobilenode[*].wlan[1].agent.activeScan = true.


问:
IsNull function in DB2 SQL?
Is there a performant equivalent to the isnull function for DB2?

Imagine some of our products are internal, so they don't have names:

```<code>Select product.id, isnull(product.name, "Internal)
From product
</code>```

Might return:

```<code>1 Socks
2 Shoes
3 Internal
4 Pants
</code>```

答:
In DB2 there is a function NVL(field, value if null).

Example:

SELECT ID, NVL(NAME, "Internal) AS NAME, NVL(PRICE,0) AS PRICE FROM PRODUCT WITH UR;

ContentLicense: CC BY-SA 2.5

Title: IsNull function in DB2 SQL?

Body:
Is there a performant equivalent to the isnull function for DB2?

Imagine some of our products are internal, so they don't have names:

Select product.id, isnull(product.name, "Internal)
From product

Might return:

1 Socks
2 Shoes
3 Internal
4 Pants


问:
Product of two matrices with pthreads in C
i have a problem with a C Pthreaded program. I have to do the product of two matrices m1 (nr1 rows and nc1 columns) and m2 (nr2 rows and nc2 columns).
I create nr1 * nc2 threads run time passing to each thread the number of row of m1 and the number of column of m2 to multiply. The thread, save the result in another matrice. The code is this:

```<code>#include <stdio.h>
#include <stdlib.h>
#include "pthread.h"
#include "semaphore.h"

struct prodmat{
int  row;
int  col;
};

int number;
double **dmat1;
double **dmat2;
double **dmatprod;

void ** allocaM2d (int nr, int nc, int dim);
void prodmat(double ** a,  double ** b, double ** c, int nr1, int nc1nr2,
               int nc2);

void * prodthread(struct prodmat * prod){

pthread_detach (pthread_self ());
//printf("THREAD");
 int r,c,k;
 r = prod->row;
 c = prod->col;

 printf("Thread for product of row = %i, column = %i and number = %i\n",r,c,number);

      for (k=0; k<number; k++){
        //dmatprod[r][c] += dmat1[r][k]*dmat2[k][c];
        printf("product of dmat1[%i][%i]=%i * dmat2[%i][%i] = %i\n",r,k,dmat1[r][k],k,c, dmat2[k][c]);

         }

}

int main(void) {

int  nr1, nc1, nr2, nc2, dim, i, j, k,r,c;

printf("Rows and Columns of the first matrix: ");
scanf ("%d%d",&nr1,  &nc1);
do {
  printf("Rows and Columns of the second matrix\n");
  printf("The number of rows must be equal to nc1 ");
  scanf ("%d%d",&nr2,  &nc2);
} while (nr2 != nc1);

number = nr2;
//  dynamic allocation

dim = sizeof(double);

dmat1 = (double **) allocaM2d(nr1,  nc1, dim);
dmat2 = (double **) allocaM2d(nr2,  nc2, dim);
dmatprod = (double **) allocaM2d(nr1, nc2, dim);

// in this for i create m1 and m2 and then i print these
k=0;
for(i=0;i<nr1;i++)
  for(j=0;j<nc1;j++)
    dmat1[i][j] = k++;

for(i=0;i<nr1;i++){
  for(j=0;j<nc1;j++)
    printf("%lf ", dmat1[i][j]);
  printf("\n");
}

printf("\n");
k=0;
for(i=0;i<nr2;i++)
  for(j=0;j<nc2;j++)
    dmat2[i][j] = k++;

for(i=0;i<nr2;i++){
  for(j=0;j<nc2;j++)
    printf("%lf ", dmat2[i][j]);
  printf("\n");
}

//This is the cycle where i create the threads
r=0; c=0;
for(r=0; r<nr1 ; r++)
{

  for(c=0; c<nc2; c++){

   struct prodmat * prod; prod= malloc(sizeof(struct prodmat *));
   pthread_t * th; th= malloc(sizeof(pthread_t *));

   prod->row = r;
   prod->col = c;

   pthread_create(th,NULL,prodthread,prod);
  }

}
/*
prodmat( dmat1, dmat2, dmatprod, nr1, nc1, nc2);

printf("\n");
for(i=0;i<nr1;i++){
  for(j=0;j<nc2;j++)
    printf("%lf ", dmatprod[i][j]);
  printf("\n");
}
*/

//is not important this sleep(100). I will replace in future.
sleep(100);
}

/************************************************************/

void ** allocaM2d (int nr, int nc, int dim){
int i;
void ** m;
char * vd;  //  byte pointer

m = (void **) malloc(nr * sizeof(void *));
vd = (char *) malloc(nr * nc * dim);

for(i=0;i<nr;i++)
  m[i] = &vd[i * nc * dim];

return (void **) m; // return matrix pointer
}
</code>```

Then i receive the print of the m1 and m2 and the print of the product, something like this:

```<code>   0.000000 1.000000 2.000000 3.000000 4.000000
   5.000000 6.000000 7.000000 8.000000 9.000000
   10.000000 11.000000 12.000000 13.000000 14.000000
   15.000000 16.000000 17.000000 18.000000 19.000000

   0.000000 1.000000 2.000000 3.000000
   4.000000 5.000000 6.000000 7.000000
   8.000000 9.000000 10.000000 11.000000
   12.000000 13.000000 14.000000 15.000000
   16.000000 17.000000 18.000000 19.000000

    Thread for product of row = 3, column = 2 and number = 5
    product of dmat1[3][0]=0 * dmat2[2][0] = 0
    product of dmat1[3][1]=1 * dmat2[2][0] = 0
    product of dmat1[3][2]=2 * dmat2[2][0] = 0
    product of dmat1[3][3]=3 * dmat2[2][0] = 0
    product of dmat1[3][4]=4 * dmat2[2][0] = 0
</code>```

But, in the second part seems like if the m2 is never been initialized (even if in the 1 part the print tells different).

SOLVED:
The correct code is this:

```<code>#include <stdio.h>
#include <stdlib.h>
#include "pthread.h"
#include "semaphore.h"

struct prodmat{
int  row;
int  col;
};

int number;
double **dmat1;
double **dmat2;
double **dmatprod;

void ** allocaM2d (int nr, int nc, int dim);
void prodmat(double ** a,  double ** b, double ** c, int nr1, int nc1nr2,
               int nc2);

void * prodthread(struct prodmat * prod){

pthread_detach (pthread_self ());
//printf("THREAD");
 int r,c,k;
 r = prod->row;
 c = prod->col;

 //printf("Thread for product of row = %i, column = %i \n",r,c);

      for (k=0; k<number; k++){
        dmatprod[r][c] += dmat1[r][k]*dmat2[k][c];
        //printf("product of dmat1[%i][%i]=%lf * dmat2[%i][%i] = %lf\n",r,k,dmat1[r][k],k,c, dmat2[k][c]);

         }

  pthread_exit(pthread_self ());

}

void * printer(struct prodmat * prod){

pthread_detach (pthread_self ());
//printf("THREAD");
 int r,c,i,j;
 r = prod->row;
 c = prod->col;

 //printf("Thread for product of row = %i, column = %i \n",r,c);

    printf("\n\n --> PRODUCT: \n\n");
      for(i=0;i<r;i++){
         for(j=0;j<c;j++)
          printf("%lf ", dmatprod[i][j]);
          printf("\n");
         }

  printf("\n\n ");
  pthread_exit(pthread_self ());

}

int main(void) {

int  nr1, nc1, nr2, nc2, dim, i, j, k,r,c;

printf("Rows and Columns of the first matrix: ");
scanf ("%d%d",&nr1,  &nc1);
do {
  printf("Rows and Columns of the second matrix\n");
  printf("The number of rows must be equal to nc1 ");
  scanf ("%d%d",&nr2,  &nc2);
} while (nr2 != nc1);

number = nr2;
//  dynamic allocation

dim = sizeof(double);

dmat1 = (double **) allocaM2d(nr1,  nc1, dim);
dmat2 = (double **) allocaM2d(nr2,  nc2, dim);
dmatprod = (double **) allocaM2d(nr1, nc2, dim);

k=0;
for(i=0;i<nr1;i++)
  for(j=0;j<nc1;j++)
    dmat1[i][j] = k++;

for(i=0;i<nr1;i++){
  for(j=0;j<nc1;j++)
    printf("%lf ", dmat1[i][j]);
  printf("\n");
}

printf("\n");
k=0;
for(i=0;i<nr2;i++)
  for(j=0;j<nc2;j++)
    dmat2[i][j] = k++;

for(i=0;i<nr2;i++){
  for(j=0;j<nc2;j++)
    printf("%lf ", dmat2[i][j]);
  printf("\n");
}

r=0; c=0;
for(r=0; r<nr1 ; r++)
{

  for(c=0; c<nc2; c++){

   struct prodmat * prod; prod= malloc(sizeof(struct prodmat));
   pthread_t * th; th= malloc(sizeof(pthread_t ));

   prod->row = r;
   prod->col = c;

   pthread_create(th,NULL,prodthread,prod);
  }

}

sleep(1);
 struct prodmat * prod; prod= malloc(sizeof(struct prodmat));
 pthread_t * th; th= malloc(sizeof(pthread_t ));

 prod->row = nr1;
 prod->col = nc2;

 pthread_create(th,NULL,printer,prod);

/*
prodmat( dmat1, dmat2, dmatprod, nr1, nc1, nc2);

printf("\n");
for(i=0;i<nr1;i++){
  for(j=0;j<nc2;j++)
    printf("%lf ", dmatprod[i][j]);
  printf("\n");
}
*/

pthread_exit(pthread_self ());

}

/************************************************************/

void ** allocaM2d (int nr, int nc, int dim){
int i;
void ** m;
char * vd;  //  byte pointer

m = (void **) malloc(nr * sizeof(void *));
vd = (char *) malloc(nr * nc * dim);

for(i=0;i<nr;i++)
  m[i] = &vd[i * nc * dim];

return (void **) m; // return matrix pointer
}
</code>```

That produces, for an input of 5x5 and 5x5 for ex, this:

```<code>0.000000 1.000000 2.000000 3.000000 4.000000
5.000000 6.000000 7.000000 8.000000 9.000000
10.000000 11.000000 12.000000 13.000000 14.000000
15.000000 16.000000 17.000000 18.000000 19.000000
20.000000 21.000000 22.000000 23.000000 24.000000

0.000000 1.000000 2.000000 3.000000 4.000000
5.000000 6.000000 7.000000 8.000000 9.000000
10.000000 11.000000 12.000000 13.000000 14.000000
15.000000 16.000000 17.000000 18.000000 19.000000
20.000000 21.000000 22.000000 23.000000 24.000000

 --> PRODUCT:

150.000000 160.000000 170.000000 180.000000 190.000000
400.000000 435.000000 470.000000 505.000000 540.000000
650.000000 710.000000 770.000000 830.000000 890.000000
900.000000 985.000000 1070.000000 1155.000000 1240.000000
1150.000000 1260.000000 1370.000000 1480.000000 1590.000000
</code>```

答:
Your printf for the products is incorrect.

```<code>printf("product of dmat1[%i][%i]=%i * dmat2[%i][%i] = %i\n",r,k,dmat1[r][k],k,c, dmat2[k][c]);
//                                ^ wrong              ^ wrong
</code>```

The contents in your matrices are double precision floating point numbers, you should use %f or other suitable floating point format specifier.

Body:
i have a problem with a C Pthreaded program. I have to do the product of two matrices m1 (nr1 rows and nc1 columns) and m2 (nr2 rows and nc2 columns).
I create nr1 * nc2 threads run time passing to each thread the number of row of m1 and the number of column of m2 to multiply. The thread, save the result in another matrice. The code is this:

#include <stdio.h>
#include <stdlib.h>
#include "pthread.h"
#include "semaphore.h"

struct prodmat{
int  row;
int  col;
};

int number;
double **dmat1;
double **dmat2;
double **dmatprod;

void ** allocaM2d (int nr, int nc, int dim);
void prodmat(double ** a,  double ** b, double ** c, int nr1, int nc1nr2,
               int nc2);

void * prodthread(struct prodmat * prod){

pthread_detach (pthread_self ());
//printf("THREAD");
 int r,c,k;
 r = prod->row;
 c = prod->col;

 printf("Thread for product of row = %i, column = %i and number = %i\n",r,c,number);

      for (k=0; k<number; k++){
        //dmatprod[r][c] += dmat1[r][k]*dmat2[k][c];
        printf("product of dmat1[%i][%i]=%i * dmat2[%i][%i] = %i\n",r,k,dmat1[r][k],k,c, dmat2[k][c]);

         }

}

int main(void) {

int  nr1, nc1, nr2, nc2, dim, i, j, k,r,c;

printf("Rows and Columns of the first matrix: ");
scanf ("%d%d",&nr1,  &nc1);
do {
  printf("Rows and Columns of the second matrix\n");
  printf("The number of rows must be equal to nc1 ");
  scanf ("%d%d",&nr2,  &nc2);
} while (nr2 != nc1);

number = nr2;
//  dynamic allocation

dim = sizeof(double);

dmat1 = (double **) allocaM2d(nr1,  nc1, dim);
dmat2 = (double **) allocaM2d(nr2,  nc2, dim);
dmatprod = (double **) allocaM2d(nr1, nc2, dim);

// in this for i create m1 and m2 and then i print these
k=0;
for(i=0;i<nr1;i++)
  for(j=0;j<nc1;j++)
    dmat1[i][j] = k++;

for(i=0;i<nr1;i++){
  for(j=0;j<nc1;j++)
    printf("%lf ", dmat1[i][j]);
  printf("\n");
}

printf("\n");
k=0;
for(i=0;i<nr2;i++)
  for(j=0;j<nc2;j++)
    dmat2[i][j] = k++;

for(i=0;i<nr2;i++){
  for(j=0;j<nc2;j++)
    printf("%lf ", dmat2[i][j]);
  printf("\n");
}

//This is the cycle where i create the threads
r=0; c=0;
for(r=0; r<nr1 ; r++)
{

  for(c=0; c<nc2; c++){

   struct prodmat * prod; prod= malloc(sizeof(struct prodmat *));
   pthread_t * th; th= malloc(sizeof(pthread_t *));

   prod->row = r;
   prod->col = c;

   pthread_create(th,NULL,prodthread,prod);
  }

}
/*
prodmat( dmat1, dmat2, dmatprod, nr1, nc1, nc2);

printf("\n");
for(i=0;i<nr1;i++){
  for(j=0;j<nc2;j++)
    printf("%lf ", dmatprod[i][j]);
  printf("\n");
}
*/

//is not important this sleep(100). I will replace in future.
sleep(100);
}

/************************************************************/

void ** allocaM2d (int nr, int nc, int dim){
int i;
void ** m;
char * vd;  //  byte pointer

m = (void **) malloc(nr * sizeof(void *));
vd = (char *) malloc(nr * nc * dim);

for(i=0;i<nr;i++)
  m[i] = &vd[i * nc * dim];

return (void **) m; // return matrix pointer
}

Then i receive the print of the m1 and m2 and the print of the product, something like this:

   0.000000 1.000000 2.000000 3.000000 4.000000
   5.000000 6.000000 7.000000 8.000000 9.000000
   10.000000 11.000000 12.000000 13.000000 14.000000
   15.000000 16.000000 17.000000 18.000000 19.000000

   0.000000 1.000000 2.000000 3.000000
   4.000000 5.000000 6.000000 7.000000
   8.000000 9.000000 10.000000 11.000000
   12.000000 13.000000 14.000000 15.000000
   16.000000 17.000000 18.000000 19.000000

    Thread for product of row = 3, column = 2 and number = 5
    product of dmat1[3][0]=0 * dmat2[2][0] = 0
    product of dmat1[3][1]=1 * dmat2[2][0] = 0
    product of dmat1[3][2]=2 * dmat2[2][0] = 0
    product of dmat1[3][3]=3 * dmat2[2][0] = 0
    product of dmat1[3][4]=4 * dmat2[2][0] = 0

But, in the second part seems like if the m2 is never been initialized (even if in the 1 part the print tells different).

SOLVED:
The correct code is this:

#include <stdio.h>
#include <stdlib.h>
#include "pthread.h"
#include "semaphore.h"

struct prodmat{
int  row;
int  col;
};

int number;
double **dmat1;
double **dmat2;
double **dmatprod;

void ** allocaM2d (int nr, int nc, int dim);
void prodmat(double ** a,  double ** b, double ** c, int nr1, int nc1nr2,
               int nc2);

void * prodthread(struct prodmat * prod){

pthread_detach (pthread_self ());
//printf("THREAD");
 int r,c,k;
 r = prod->row;
 c = prod->col;

 //printf("Thread for product of row = %i, column = %i \n",r,c);

      for (k=0; k<number; k++){
        dmatprod[r][c] += dmat1[r][k]*dmat2[k][c];
        //printf("product of dmat1[%i][%i]=%lf * dmat2[%i][%i] = %lf\n",r,k,dmat1[r][k],k,c, dmat2[k][c]);

         }

  pthread_exit(pthread_self ());

}

void * printer(struct prodmat * prod){

pthread_detach (pthread_self ());
//printf("THREAD");
 int r,c,i,j;
 r = prod->row;
 c = prod->col;

 //printf("Thread for product of row = %i, column = %i \n",r,c);

    printf("\n\n --> PRODUCT: \n\n");
      for(i=0;i<r;i++){
         for(j=0;j<c;j++)
          printf("%lf ", dmatprod[i][j]);
          printf("\n");
         }

  printf("\n\n ");
  pthread_exit(pthread_self ());

}

int main(void) {

int  nr1, nc1, nr2, nc2, dim, i, j, k,r,c;

printf("Rows and Columns of the first matrix: ");
scanf ("%d%d",&nr1,  &nc1);
do {
  printf("Rows and Columns of the second matrix\n");
  printf("The number of rows must be equal to nc1 ");
  scanf ("%d%d",&nr2,  &nc2);
} while (nr2 != nc1);

number = nr2;
//  dynamic allocation

dim = sizeof(double);

dmat1 = (double **) allocaM2d(nr1,  nc1, dim);
dmat2 = (double **) allocaM2d(nr2,  nc2, dim);
dmatprod = (double **) allocaM2d(nr1, nc2, dim);

k=0;
for(i=0;i<nr1;i++)
  for(j=0;j<nc1;j++)
    dmat1[i][j] = k++;

for(i=0;i<nr1;i++){
  for(j=0;j<nc1;j++)
    printf("%lf ", dmat1[i][j]);
  printf("\n");
}

printf("\n");
k=0;
for(i=0;i<nr2;i++)
  for(j=0;j<nc2;j++)
    dmat2[i][j] = k++;

for(i=0;i<nr2;i++){
  for(j=0;j<nc2;j++)
    printf("%lf ", dmat2[i][j]);
  printf("\n");
}

r=0; c=0;
for(r=0; r<nr1 ; r++)
{

  for(c=0; c<nc2; c++){

   struct prodmat * prod; prod= malloc(sizeof(struct prodmat));
   pthread_t * th; th= malloc(sizeof(pthread_t ));

   prod->row = r;
   prod->col = c;

   pthread_create(th,NULL,prodthread,prod);
  }

}

sleep(1);
 struct prodmat * prod; prod= malloc(sizeof(struct prodmat));
 pthread_t * th; th= malloc(sizeof(pthread_t ));

 prod->row = nr1;
 prod->col = nc2;

 pthread_create(th,NULL,printer,prod);

/*
prodmat( dmat1, dmat2, dmatprod, nr1, nc1, nc2);

printf("\n");
for(i=0;i<nr1;i++){
  for(j=0;j<nc2;j++)
    printf("%lf ", dmatprod[i][j]);
  printf("\n");
}
*/

pthread_exit(pthread_self ());

}

/************************************************************/

void ** allocaM2d (int nr, int nc, int dim){
int i;
void ** m;
char * vd;  //  byte pointer

m = (void **) malloc(nr * sizeof(void *));
vd = (char *) malloc(nr * nc * dim);

for(i=0;i<nr;i++)
  m[i] = &vd[i * nc * dim];

return (void **) m; // return matrix pointer
}

That produces, for an input of 5x5 and 5x5 for ex, this:

0.000000 1.000000 2.000000 3.000000 4.000000
5.000000 6.000000 7.000000 8.000000 9.000000
10.000000 11.000000 12.000000 13.000000 14.000000
15.000000 16.000000 17.000000 18.000000 19.000000
20.000000 21.000000 22.000000 23.000000 24.000000

0.000000 1.000000 2.000000 3.000000 4.000000
5.000000 6.000000 7.000000 8.000000 9.000000
10.000000 11.000000 12.000000 13.000000 14.000000
15.000000 16.000000 17.000000 18.000000 19.000000
20.000000 21.000000 22.000000 23.000000 24.000000

 --> PRODUCT:

150.000000 160.000000 170.000000 180.000000 190.000000
400.000000 435.000000 470.000000 505.000000 540.000000
650.000000 710.000000 770.000000 830.000000 890.000000
900.000000 985.000000 1070.000000 1155.000000 1240.000000
1150.000000 1260.000000 1370.000000 1480.000000 1590.000000

Body:
Your printf for the products is incorrect.

printf("product of dmat1[%i][%i]=%i * dmat2[%i][%i] = %i\n",r,k,dmat1[r][k],k,c, dmat2[k][c]);
//                                ^ wrong              ^ wrong

The contents in your matrices are double precision floating point numbers, you should use %f or other suitable floating point format specifier.


问:
Any better approach for layout design?
just wondering if anyone else has a better suggestion that what I'm coming up with.

The issue is to do with a TabLayout, 5 Tabs all using a single Activity.  Each Tab layout contains quite a few fields so the main parent on each tab is a ScrollView.

What I currently have is a 'Save' & 'Cancel' button sitting outside the scrollviews so theyre always visible and there for the user regardless which tab they're on.  The problem is that since I'm using Tabs and always have these buttons visible when they are editing and the IME is displayed, they'res barely any of the form visible.

So I think the best thing for me to do is to probably show the buttons at the end of each scrollview.  What I don't like about this is as I have 5 tabs, it will mean I have to declare 5 sets of the buttons, and of course define them and bind them in the Activity.. which seems rather messy and inefficient.

So if anyone has any better ideas I sure would love to hear them :-)

Thanks

Rgds,

Dave

答:
Define programmatically the buttons inside a LinearLayout and add them to each ScrollView with addView. The code of the buttons should check in what tab are we at that moment, and act accordingly.

Then you'll have the same two buttons arranged in the same way in all your ScrollViews.

Or, if you dislike doing it programmatically, do a layout for the buttons and use View.inflate of that layout, and add them via addView to the ScrollView.

Title: Any better approach for layout design?


问:
Java: java.lang.UnsatisfiedLinkError Failed to call native method in .cpp file using JNI
as mentioned in title my java program is unable to invoke or call the native method in .cpp file where the library .dll gets loaded successfully in program.
but while running it throws an exception java.lang.UnsatisfiedLinkError.
I had correctly set a library path to project.

here is my cpp file:

```<code>#include "jni.h"
#include "Demojni.h"
#include <iostream>
using namespace std;

extern "c"{
   JNIEXPORT jint JNICALL _Java_demojni_Demojni_printm(JNIEnv *env, jobject   object){
      cout<<"call from c++";
      return 1;
   }
}

int main(){
   return 1;
}
</code>```

and here is .java file:

```<code>package demojni;

public class Jni1{
   private native int printm();
   static{
      try{
         System.out.println(System.getProperty("java.library.path"));
         System.loadLibrary("libCppJNILibrary_1");
         System.out.println("loaded");
      }
      catch(Exception e){
         System.out.println("can't load\n"+e.getMessage());
      }
   }

   public static void main(String[] arg){
      Jni1 api=new Jni1();
      int a=api.printm();
   }
}
</code>```

答: You changed the name of the class from DemoJNI1 to Jni1 without regenerating the .h file and/or without adjusting the name of the JNI method in the .c file.

Body:
as mentioned in title my java program is unable to invoke or call the native method in .cpp file where the library .dll gets loaded successfully in program.
but while running it throws an exception java.lang.UnsatisfiedLinkError.
I had correctly set a library path to project.

here is my cpp file:

#include "jni.h"
#include "Demojni.h"
#include <iostream>
using namespace std;

extern "c"{
   JNIEXPORT jint JNICALL _Java_demojni_Demojni_printm(JNIEnv *env, jobject   object){
      cout<<"call from c++";
      return 1;
   }
}

int main(){
   return 1;
}

and here is .java file:

package demojni;

public class Jni1{
   private native int printm();
   static{
      try{
         System.out.println(System.getProperty("java.library.path"));
         System.loadLibrary("libCppJNILibrary_1");
         System.out.println("loaded");
      }
      catch(Exception e){
         System.out.println("can't load\n"+e.getMessage());
      }
   }

   public static void main(String[] arg){
      Jni1 api=new Jni1();
      int a=api.printm();
   }
}


问:
UIDatePicker outputs different formats of string of date between simulator and iPhone
I ran the UIDatePicker on my iPhone and on the simulator, they both show output in different formats?

How can i solve the problem? Is there a format that can work around? I know it is because of NSLocale. as I want my app not only to work on one country. I need save the date to the server for searching and comparing. Therefore, I need a format to work around.

Thanks.

答:
I would recommend to keep the date format a user had selected and NOT modify it, because this is what users do expect.

Step 1)
In case you need to further process the selected date by another function or want to send it to a server in a certain format, create a NSDate object with the locale specific dateformatter:
https://developer.apple.com/library/content/documentation/MacOSX/Conceptual/BPInternational/InternationalizingLocaleData/InternationalizingLocaleData.html

Step 2)
And use another NSDateFormatter that firs to your needs to now transform the NSDate to a NSSTring you can send to somehwere else in a standardizes format.
https://developer.apple.com/reference/foundation/nsdateformatter

Another option would be to only display the locale formatted date, but keep a reference to the original Date Object, this way you could skip step 1


问:
JSON to XML class conversions
I cannot seem to line up the class of the Json into Linq XML.

The c.first, c.second and the c.third are highlighted and states:

"Are you missing a using directive or assembly reference."

```<code>var serializer = new JavaScriptSerializer();
var json1 = "[count:[place:{first:1,second:2,third:3}],[place:{first:11,second:22,third:33}],[place:{first:111,second:222,third:333}]]]";
var jsons = serializer.Serialize(json1);
var jsona = serializer.Deserialize<List<jClass>>(jsons);
var xmld = new XDocument(
    new XElement("count", jsona.Select(c =>
        new XElement("place",
            new XElement("first", c.first),
            new XElement("second", c.second),
            new XElement("third", c.third)
        )
    ))
);
</code>```

Class.cs

```<code>public class jClass
{
    public jNumber[] count { get; set; }
}
public class jNumber
{
    public jTopThree[] place { get; set; }
}
public class jTopThree
{
    public int first { get; set; }
    public int second { get; set; }
    public int third { get; set; }
}
</code>```

答:
So firstly your JSON is formatted badly, based on your example I think it should look like this (to me having "place" seems redundant but I've left it for now):

{

  "count": [

  {"place": [

  {"first":1,"second":2,"third":3}]},

  {"place": [

  {"first":11,"second":22,"third":33}]},

  {"place": [

  {"first":111,"second":222,"third":333}]}

  ]

  }

Your classes should look like this:

```<code>public class RootObject
{
    public List<Count> count { get; set; }
}

public class Count
{
    public List<Place> place { get; set; }
}

public class Place
{
    public int first { get; set; }
    public int second { get; set; }
    public int third { get; set; }
}
</code>```

Lastly you can create XML this way:

```<code>var serializer = new JavaScriptSerializer();
var json = "your json string";
var result= serializer.Deserialize<RootObject>(json);
var xmld = new XDocument(
           new XElement("count", result.count
               .SelectMany(p => p.place)
               .Select(x =>
                   new XElement("place",
                       new XElement("first", x.first),
                       new XElement("second", x.second),
                       new XElement("third", x.third)
                   )
                ))
           );
</code>```

Output:

```<code><count>
  <place>
    <first>1</first>
    <second>2</second>
    <third>3</third>
  </place>
  <place>
    <first>11</first>
    <second>22</second>
    <third>33</third>
  </place>
  <place>
    <first>111</first>
    <second>222</second>
    <third>333</third>
  </place>
</count>
</code>```

Title: JSON to XML class conversions

Body:
I cannot seem to line up the class of the Json into Linq XML.

The c.first, c.second and the c.third are highlighted and states:

"Are you missing a using directive or assembly reference."

var serializer = new JavaScriptSerializer();
var json1 = "[count:[place:{first:1,second:2,third:3}],[place:{first:11,second:22,third:33}],[place:{first:111,second:222,third:333}]]]";
var jsons = serializer.Serialize(json1);
var jsona = serializer.Deserialize<List<jClass>>(jsons);
var xmld = new XDocument(
    new XElement("count", jsona.Select(c =>
        new XElement("place",
            new XElement("first", c.first),
            new XElement("second", c.second),
            new XElement("third", c.third)
        )
    ))
);

Class.cs

public class jClass
{
    public jNumber[] count { get; set; }
}
public class jNumber
{
    public jTopThree[] place { get; set; }
}
public class jTopThree
{
    public int first { get; set; }
    public int second { get; set; }
    public int third { get; set; }
}

Body:
So firstly your JSON is formatted badly, based on your example I think it should look like this (to me having "place" seems redundant but I've left it for now):

{

  "count": [

  {"place": [

  {"first":1,"second":2,"third":3}]},

  {"place": [

  {"first":11,"second":22,"third":33}]},

  {"place": [

  {"first":111,"second":222,"third":333}]}

  ]

  }

Your classes should look like this:

public class RootObject
{
    public List<Count> count { get; set; }
}

public class Count
{
    public List<Place> place { get; set; }
}

public class Place
{
    public int first { get; set; }
    public int second { get; set; }
    public int third { get; set; }
}

Lastly you can create XML this way:

var serializer = new JavaScriptSerializer();
var json = "your json string";
var result= serializer.Deserialize<RootObject>(json);
var xmld = new XDocument(
           new XElement("count", result.count
               .SelectMany(p => p.place)
               .Select(x =>
                   new XElement("place",
                       new XElement("first", x.first),
                       new XElement("second", x.second),
                       new XElement("third", x.third)
                   )
                ))
           );

Output:

<count>
  <place>
    <first>1</first>
    <second>2</second>
    <third>3</third>
  </place>
  <place>
    <first>11</first>
    <second>22</second>
    <third>33</third>
  </place>
  <place>
    <first>111</first>
    <second>222</second>
    <third>333</third>
  </place>
</count>


问:
Is it possible to get code editors in virtualenv?
I recently downloaded virtualenv on my MacOSX Sierra (10.12.2). I'm not very experienced with virtualenv and I've been coding using the interactive interpreter in terminal and I was wondering if there was an alternate way that I could use an editor(IDLE, Sublime, etc.) and still use it in virtualenv. Would I just install an editor into virtualenv or am I limited to only the interactive shell?</p>

答: You can use atom editor, inside that you can use virtualenv plugin


问:
Saving CoreData context and binding problem
I use CoreData for a Mac application which runs under 10.5 and higher. The content of an entity (text attribute) will be displayed in an NSTextView through bindings. The user can edit the text there.

When I try to save the managed object context, the mouse cursor disappears from the text view and the text view scrolls up to the top.

How can I prevent CoreData/binding to do this because it's annoying for the user to lose the focus!

Edit: Added the solution as a separate answer to mark the question as completed!

答: Take a look at commitEditing before save. This causes the textview to lose the focus or even revert all changes in the current textfield. I don't think you can prevent this behavior. You could restore the selection and cursor position after saving. I also would be interested in an actual solution to this problem.</p>


问:
Can't add foreign key to an existing table
I want to add foreign key to an existing table questions which has 1000 above questions of different categories in it. But when I am trying to add foreign key mysql throws error as below.

#1452 - Cannot add or update a child row: a foreign key constraint fails (question_bank.#sql-af8_1d0, CONSTRAINTcat_idFOREIGN KEY (cat_id) REFERENCESdb_category(cat_id) ON DELETE NO ACTION ON UPDATE NO ACTION)

category table db_category structure.

questions table db_questions structure.

答:
You cant add a foreign key to that table because you must check first if the primary key table has a record exists value same with foreign key table.
according to primary column value  and foreign key column value.


问:
Select data from Sybase database but only select the row with the highest sequence
I'm trying to select data from my database from the highest sequence number, I have been struggling with this for a while and cant get it to work.

The database has a lot of Columns with data. I only want data from the row with the highest sequence number to search in, because the data from lower sequences is not of any value for me. Unfortunately the rows from the lower sequences can not be deleted.

Database looks like this:

```<code>-----------------------------
| ID | SEQ | rest of the data
-----------------------------
| 1  |  1  | ..
| 1  |  2  | ....
| 2  |  1  | ..
| 1  |  3  | ....
| 3  |  1  | ..
| 1  |  2  | ....
| 4  |  1  | ........
</code>```

My question is, how can i select only the ID's with the highest sequence number and search in those rows with the WHERE clause?

答:
On oracle11g you can use:</p>

```<code>SELECT *
FROM (
      SELECT YOUR_TABLE.*, RANK() OVER (PARTITION BY ID oRDER BY SEQ DESC) RN
      FROM YOUR_TABLE) A
WHERE RN=1;
</code>```

Body:
I'm trying to select data from my database from the highest sequence number, I have been struggling with this for a while and cant get it to work.

The database has a lot of Columns with data. I only want data from the row with the highest sequence number to search in, because the data from lower sequences is not of any value for me. Unfortunately the rows from the lower sequences can not be deleted.

Database looks like this:

-----------------------------
| ID | SEQ | rest of the data
-----------------------------
| 1  |  1  | ..
| 1  |  2  | ....
| 2  |  1  | ..
| 1  |  3  | ....
| 3  |  1  | ..
| 1  |  2  | ....
| 4  |  1  | ........

My question is, how can i select only the ID's with the highest sequence number and search in those rows with the WHERE clause?

Body:
On oracle11g you can use:

SELECT *
FROM (
      SELECT YOUR_TABLE.*, RANK() OVER (PARTITION BY ID oRDER BY SEQ DESC) RN
      FROM YOUR_TABLE) A
WHERE RN=1;


问:
Gnuplot Histogram key
Am trying to create a histogram showing Internet Packet sizes for UDP and TCP traffic. I am using the following gnuplot code

```<code>set terminal eps
set output 'packet_size_2012.eps'
set boxwidth 0.75 absolute
set style fill   solid 1.00 border lt -1
set key inside noenhanced nobox
set key invert samplen 4 spacing 1 width 0 height 0
set style histogram rowstacked title  offset character 0, 0, 0
set style data histograms
set ylabel "Percentage of Packets (%) "
set xlabel "Frame Size (bytes)"
set xtics border in scale 0,0 nomirror rotate by -45  autojustify
set yrange [ 0 : 50 ] noreverse nowriteback
plot 'packet_size_percent_2012.dat' using 2:xtic(1), for [i=3:3] '' using i
</code>```

and I am using the following dataset file called packet_size_percent_2012.dat.

```<code>Size TCP UDP
>100    37.9751914726   3.8006927347
>200    2.40410662  1.2339364475
>300    1.214213436 0.2644495664
>400    2.8001210777    0.1767652772
>500    0.8650757197    0.0724963219
>600    0.8767813751    0.1582132766
>700    0.4833217953    0.067857265
>800    0.4663420621    0.0625691477
>900    0.4081899064    0.0389895145
>1000   0.4181337618    0.0364423356
>1100   0.5492004791    0.4992289447
>1200   0.3614408031    0.4492694873
>1300   11.1826219794   0.0841426493
>1400   2.2600786977    0.4211750387
>1518   29.0098254538   1.3591273532
</code>```

The plot is generated and looks nice but the key is all wrong. Can anyone explain how I can fix the key?

答: With set key auto columnheader the actual column headers are used as key entries (I guess that is what you intend):

Title: Gnuplot Histogram key

Body:
Am trying to create a histogram showing Internet Packet sizes for UDP and TCP traffic. I am using the following gnuplot code

set terminal eps
set output 'packet_size_2012.eps'
set boxwidth 0.75 absolute
set style fill   solid 1.00 border lt -1
set key inside noenhanced nobox
set key invert samplen 4 spacing 1 width 0 height 0
set style histogram rowstacked title  offset character 0, 0, 0
set style data histograms
set ylabel "Percentage of Packets (%) "
set xlabel "Frame Size (bytes)"
set xtics border in scale 0,0 nomirror rotate by -45  autojustify
set yrange [ 0 : 50 ] noreverse nowriteback
plot 'packet_size_percent_2012.dat' using 2:xtic(1), for [i=3:3] '' using i

and I am using the following dataset file called packet_size_percent_2012.dat.

Size TCP UDP
>100    37.9751914726   3.8006927347
>200    2.40410662  1.2339364475
>300    1.214213436 0.2644495664
>400    2.8001210777    0.1767652772
>500    0.8650757197    0.0724963219
>600    0.8767813751    0.1582132766
>700    0.4833217953    0.067857265
>800    0.4663420621    0.0625691477
>900    0.4081899064    0.0389895145
>1000   0.4181337618    0.0364423356
>1100   0.5492004791    0.4992289447
>1200   0.3614408031    0.4492694873
>1300   11.1826219794   0.0841426493
>1400   2.2600786977    0.4211750387
>1518   29.0098254538   1.3591273532

The plot is generated and looks nice but the key is all wrong. Can anyone explain how I can fix the key?


问:
How and where should I use the keyword "use" in php
I used use the keyword "use" generally above the class definition. Like this:

```<code><?php
namespace suites\plugins\content\agpaypal;
use \Codeception\Util\Fixtures;
use \Codeception\Verify;
use \Codeception\Specify;

class agpaypalTest extends \Codeception\Test\Unit
{
    protected $tester;
    ...
</code>```

But now I realised, that I have to put the line for the trait Specify into the class definition. Like this:

```<code> <?php
namespace suites\plugins\content\agpaypal;
use \Codeception\Util\Fixtures;
use \Codeception\Verify;

class agpaypalTest extends \Codeception\Test\Unit
{
    use \Codeception\Specify;

    protected $tester;
    ...
</code>```

I think it is because the package \Codeception\Specify; is a trait. But I do not understand why I couldn't reuse this trait when I set the line
use \Codeception\Specify;
before the class definition?

I would be happy if someone could point me to a hint or an explanaiton that explains to me where I should use the keyword "use" the best.

答:
use is basically including a class in the file to use it.
There are two ways to include a class file in another file.
The most general is require or include method. Another method is using composer. Assume this Directory Structure

```<code>Project
  |
  |--- Folder A
  |      |
  |      |---UserRegistration.php
  |
  |---Example
         |
         |--TestUserRegistration.php
</code>```

In Folder A there is UserRegistartion.php and you want to use the code in TestUserRegistration.php  In UserRegistration.php It can be  class, trait or Interface

Method 1.

In TestUserRegisteration.php you can include or require file UserRegistartion.php

and use it

Method 2

Using Composer. In UserRegistration.php you define namespace FolderA; as the first line of code. Then write your code as you do. So Now you want to use this file in TestUserRegistration.php you do

```<code>include vendor/autoload.php;
use FolderA\UserRegistration;
</code>```

Which one is better and why?

Method 2 using composer is the best method. In method 1 wherever you want to include UserRegistration you have to find the relative path to UserRegistration file. So lets assume some day you need to change the directory structure your application will break as the relative path you had provided now it does'nt exist.

But in Method 2 you always use the namespace you provided \ The filename instead of where you want to use. So even you change the directory structure you don't have to got all codes and modify the path. It will work as it was.
To know more study about how to use namespace and composer.

Body:
I used use the keyword "use" generally above the class definition. Like this:

<?php
namespace suites\plugins\content\agpaypal;
use \Codeception\Util\Fixtures;
use \Codeception\Verify;
use \Codeception\Specify;

class agpaypalTest extends \Codeception\Test\Unit
{
    protected $tester;
    ...

But now I realised, that I have to put the line for the trait Specify into the class definition. Like this:

 <?php
namespace suites\plugins\content\agpaypal;
use \Codeception\Util\Fixtures;
use \Codeception\Verify;

class agpaypalTest extends \Codeception\Test\Unit
{
    use \Codeception\Specify;

    protected $tester;
    ...

I think it is because the package \Codeception\Specify; is a trait. But I do not understand why I couldn't reuse this trait when I set the line
use \Codeception\Specify;
before the class definition?

I would be happy if someone could point me to a hint or an explanaiton that explains to me where I should use the keyword "use" the best.

Body:
use is basically including a class in the file to use it.
There are two ways to include a class file in another file.
The most general is require or include method. Another method is using composer. Assume this Directory Structure

Project
  |
  |--- Folder A
  |      |
  |      |---UserRegistration.php
  |
  |---Example
         |
         |--TestUserRegistration.php

In Folder A there is UserRegistartion.php and you want to use the code in TestUserRegistration.php  In UserRegistration.php It can be  class, trait or Interface

Method 1.

In TestUserRegisteration.php you can include or require file UserRegistartion.php

and use it

Method 2

Using Composer. In UserRegistration.php you define namespace FolderA; as the first line of code. Then write your code as you do. So Now you want to use this file in TestUserRegistration.php you do

include vendor/autoload.php;
use FolderA\UserRegistration;

Which one is better and why?

Method 2 using composer is the best method. In method 1 wherever you want to include UserRegistration you have to find the relative path to UserRegistration file. So lets assume some day you need to change the directory structure your application will break as the relative path you had provided now it does'nt exist.

But in Method 2 you always use the namespace you provided \ The filename instead of where you want to use. So even you change the directory structure you don't have to got all codes and modify the path. It will work as it was.
To know more study about how to use namespace and composer.


问:
Map to List[Tuple2] in Scala - removes duplicates?
Am trying to convert a map to list of Tuples, given a map like below

```<code>Map("a"->2,"a"->4,"a"->5,"b"->6,"b"->1,"c"->3)
</code>```

i want output like

```<code>List(("a",2),("a",4),("a",5),("b",6),("b",1),("c",3))
</code>```

I tried following

```<code>val seq = inputMap.toList  //output (a,5)(b,1)(c,3)

var list:List[(String,Int)] = Nil
   for((k,v)<-inputMap){
       (k,v) :: list
   }  //output (a,5)(b,1)(c,3)
</code>```

Why does it remove duplicates? I dont see other tuples that has "a" as key.

答:
Since map has duplicate keys, it will remove duplicate entries while map creation itself.

```<code>Map("a"->2,"a"->4,"a"->5,"b"->6,"b"->1,"c"->3)
</code>```

it will turn into,

```<code>Map(a -> 5, b -> 1, c -> 3)
</code>```

so other operations will be performed on short map

Body:
Am trying to convert a map to list of Tuples, given a map like below

Map("a"->2,"a"->4,"a"->5,"b"->6,"b"->1,"c"->3)

i want output like

List(("a",2),("a",4),("a",5),("b",6),("b",1),("c",3))

I tried following

val seq = inputMap.toList  //output (a,5)(b,1)(c,3)

var list:List[(String,Int)] = Nil
   for((k,v)<-inputMap){
       (k,v) :: list
   }  //output (a,5)(b,1)(c,3)

Why does it remove duplicates? I dont see other tuples that has "a" as key.

Body:
Since map has duplicate keys, it will remove duplicate entries while map creation itself.

Map("a"->2,"a"->4,"a"->5,"b"->6,"b"->1,"c"->3)

it will turn into,

Map(a -> 5, b -> 1, c -> 3)

so other operations will be performed on short map


问:
Google Maps V2 not working in production with correct key
I'm having major troubles getting Google Maps working in production within an Android app. This is what I am currently getting (the bottom is just ads).

Key Steps I have followed:

1) I have ensured I have got the correct SHA1 Production Key and have implemented it on the Google Console API as well as within the app (They key that google gives). I have registered two keys - one for the debug and one for production

2) Internet, location, etc is working

3) The app works in DEBUG mode, but does not work when signed and installed on device via USB. I have triple checked the SHA 1 signature of the sign, etc.

4) The MapsFragment comes from the template available in Android Studio.

In production mode, the log cat displays this:

01-11 16:04:54.511  19346-19437/com.mike.mapstest E/Google Maps Android API﹕ Authorization failure.  Please see https://developers.google.com/maps/documentation/android/start for how to correctly set up the map.
01-11 16:04:54.516  19346-19437/com.mike.mapstest E/Google Maps Android API﹕ In the Google Developer Console (https://console.developers.google.com)
    Ensure that the "Google Maps Android API v2" is enabled.
    Ensure that the following Android Key exists:
    API Key: YOUR_KEY_HERE
    Android Application (<cert_fingerprint>;<package_name>): <SHA1 Removed for this> ;com.mike.mapstest
```

This error obviously says something is wrong with my auth?
What am I doing wrong?

答: Solved, I put on the Manifest the "Key for browser apps (with referers)" instead of the "Key for Android apps (with certificates)" from the Google API Console</p>

Body:
I'm having major troubles getting Google Maps working in production within an Android app. This is what I am currently getting (the bottom is just ads).

Key Steps I have followed:

1) I have ensured I have got the correct SHA1 Production Key and have implemented it on the Google Console API as well as within the app (They key that google gives). I have registered two keys - one for the debug and one for production

2) Internet, location, etc is working

3) The app works in DEBUG mode, but does not work when signed and installed on device via USB. I have triple checked the SHA 1 signature of the sign, etc.

4) The MapsFragment comes from the template available in Android Studio.

In production mode, the log cat displays this:

01-11 16:04:54.511  19346-19437/com.mike.mapstest E/Google Maps Android API﹕ Authorization failure.  Please see https://developers.google.com/maps/documentation/android/start for how to correctly set up the map.
01-11 16:04:54.516  19346-19437/com.mike.mapstest E/Google Maps Android API﹕ In the Google Developer Console (https://console.developers.google.com)
    Ensure that the "Google Maps Android API v2" is enabled.
    Ensure that the following Android Key exists:
    API Key: YOUR_KEY_HERE
    Android Application (<cert_fingerprint>;<package_name>): <SHA1 Removed for this> ;com.mike.mapstest

This error obviously says something is wrong with my auth?
What am I doing wrong?


问:
How can I put an icon and an input text on the same line?
I want to put an icon on the left and an input type text on the right occupying all the remaining space.

```<code>----------------------------------------------------
| [ico]  ----------------------------------------  |
|        |   input type="text"                  |  |
|        ----------------------------------------  |
----------------------------------------------------
</code>```

If I set both with display: inline-block and set the input's width to 100% it jumps the line, because 100% is not considering the space - icosize...

I want to expand the input to the remaining available space (I don't care for vertical align). Is there a way to achieve this behavior without using tables?

An example of the problem on jsFiddle.

答:
Did you try to use align="absmiddle" in the icon?</p>

```<code><img src="img.jpg" align="absmiddle">
</code>```

Body:
I want to put an icon on the left and an input type text on the right occupying all the remaining space.

----------------------------------------------------
| [ico]  ----------------------------------------  |
|        |   input type="text"                  |  |
|        ----------------------------------------  |
----------------------------------------------------

If I set both with display: inline-block and set the input's width to 100% it jumps the line, because 100% is not considering the space - icosize...

I want to expand the input to the remaining available space (I don't care for vertical align). Is there a way to achieve this behavior without using tables?

An example of the problem on jsFiddle.

Body:
Did you try to use align="absmiddle" in the icon?

<img src="img.jpg" align="absmiddle">


问:
Php mysql table column name conflict
Running into an issue here caused by something beyond my control.
I am running a DB query on a table I did not create, it has a table column named "end".  This is screwing up my foreach loop as it only gets the first instance and then stops on that particular variable.

Here is my current code:

```<code>$eventDates = array();
  foreach( $events as $event ) :
    $eventDates[ $event->post_id ] = $event->start;
    $eventEnd[ $event->post_id ] = $event->end;
    $eventVenue[ $event->post_id ] = $event->venue;
endforeach;
</code>```

The $event->end; is the problem.  Is there another way I can output that data that won't cause a conflict?

答:
Try aliasing the column name in the request otherwise.

select end as thisIsTheEnd ...

Title: Php mysql table column name conflict

Body:
Running into an issue here caused by something beyond my control.
I am running a DB query on a table I did not create, it has a table column named "end".  This is screwing up my foreach loop as it only gets the first instance and then stops on that particular variable.

Here is my current code:

$eventDates = array();
  foreach( $events as $event ) :
    $eventDates[ $event->post_id ] = $event->start;
    $eventEnd[ $event->post_id ] = $event->end;
    $eventVenue[ $event->post_id ] = $event->venue;
endforeach;

The $event->end; is the problem.  Is there another way I can output that data that won't cause a conflict?


问:
Angular and TypeScript looping through object
I am trying to learn TypeScript and Angular. I have an object that I would like to loop through and pull key:value pairs so I can create buttons dynamically in HTML. In HTML when I <<variable>> my object I get "[object Object]" as my output. When I do standard ng-repeat="o in variable" I get nothing.

My question is how do I loop through it so I can get values stored in that object.

```<code>HTML
    <div id="main_menu" class="container" role="main">
      <div class="container-fluid">
        <div class="row">
          <div class="page-header">WebJB</div>
          <div class="col-md-6">
            <div class="panel panel-default">
              <button href="#" class="panel-body btn btn-primary form-control">
                <h3 class="panel-title"></h3>
              </button>
          </div>

          <div ng-repeat="o in menu_parts"> <<--- I TRIED THIS
            {{menu_parts}}
          </div>

          </div>
        </div>
      </div>
    </div>
</code>```

TypeScript

```<code>import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-index',
  templateUrl: './index.component.html',
  styleUrls: ['./index.component.css']
})

export class IndexComponent implements OnInit {
  menu_parts = {
    "CRM": {
      "name": "CRM",
      "link": "/",
      "colour": "white",
      "label": "CRM"
    },
    "Admin": {
      "name": "Admin",
      "link": "/admin",
      "colour": "red",
      "label": "Admin"
    },
    "Dashboard": {
      "name": "Dashboard",
      "link": "/dashboard",
      "colour": "white",
      "label": "Dashboard"
    },
    "Settings": {
      "name": "Settings",
      "link": "/settings",
      "colour": "white",
      "label": "Settings"
    }
  }

  constructor(){
    var x = this.menu_parts;
    console.log(x);
  }

  ngOnInit() {

  }

}
</code>```

答:
If are you using angular 2, then use ngFor instead of ngRepeat

```<code><div *ngFor="let o in menu_parts">
     {{o}}
 </div>
</code>```

As for [object object] you have to use json filter to show all the content a JSON array

```<code>{{menu_parts | json}}
</code>```

Body:
I am trying to learn TypeScript and Angular. I have an object that I would like to loop through and pull key:value pairs so I can create buttons dynamically in HTML. In HTML when I <<variable>> my object I get "[object Object]" as my output. When I do standard ng-repeat="o in variable" I get nothing.

My question is how do I loop through it so I can get values stored in that object.

HTML

WebJB

              <button href="#" class="panel-body btn btn-primary form-control">

              </button>

 <<--- I TRIED THIS
            {{menu_parts}}

TypeScript

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-index',
  templateUrl: './index.component.html',
  styleUrls: ['./index.component.css']
})

export class IndexComponent implements OnInit {
  menu_parts = {
    "CRM": {
      "name": "CRM",
      "link": "/",
      "colour": "white",
      "label": "CRM"
    },
    "Admin": {
      "name": "Admin",
      "link": "/admin",
      "colour": "red",
      "label": "Admin"
    },
    "Dashboard": {
      "name": "Dashboard",
      "link": "/dashboard",
      "colour": "white",
      "label": "Dashboard"
    },
    "Settings": {
      "name": "Settings",
      "link": "/settings",
      "colour": "white",
      "label": "Settings"
    }
  }

  constructor(){
    var x = this.menu_parts;
    console.log(x);
  }

  ngOnInit() {

  }

}

Body:
If are you using angular 2, then use ngFor instead of ngRepeat

<div *ngFor="let o in menu_parts">
     {{o}}
 </div>

As for [object object] you have to use json filter to show all the content a JSON array

{{menu_parts | json}}


问:
Captive Dependency with Autofac
I’m looking for the cleanest way to solve the Captive Dependency problem with autofac.

I have a short lived class that will be registerd per LifeTimeScope:

```<code>public class ShortLived
{
    public void DoSomethingUsefull() {}
}
</code>```

And I have a long living class that will be registered as single instance. It has a dependency on the ShortLived class:

```<code>public class LongLived
{
    private readonly Func<ShortLived> _getCurrentShortLived;

    public LongLived(Func<ShortLived> getCurrentShortLived)
    {
        _getCurrentShortLived = getCurrentShortLived;
    }

    public void DoSomethingWithShortLived()
    {
        var currentShortLived = _getCurrentShortLived();
        currentShortLived.DoSomethingUsefull();
    }
}
</code>```

The following attempt doesn't work. It throws an Autofac.Core.DependencyResolutionException.

```<code>public void CaptiveDependencyTest()
{
    var builder = new ContainerBuilder();
    builder.RegisterType<LongLived>()
        .SingleInstance();
    var container = builder.Build();

    using (var scope = container.BeginLifetimeScope(b => b.RegisterType<ShortLived>()))
    {
        var longLived = scope.Resolve<LongLived>();
        longLived.DoSomethingWithShortLived();
    }
}
</code>```

The following does work. But I realy hope there is a better solution to the problem than relying on a somehow static variable.

```<code>private static ILifetimeScope currentLifetimeScope;

public void CaptiveDependencyTest2()
{
    var builder = new ContainerBuilder();
    builder.Register(c =>
    {
        Func<ShortLived> shortLivedFacotry = () => currentLifetimeScope.Resolve<ShortLived>();
        return new LongLived(shortLivedFacotry);
    })
    .SingleInstance();
    var container = builder.Build();

    using (var scope = container.BeginLifetimeScope(b => b.RegisterType<ShortLived>()))
    {
        currentLifetimeScope = scope;
        var longLived = scope.Resolve<LongLived>();
        longLived.DoSomethingWithShortLived();
    }
}
</code>```

Some Backround Infos:
I’m working on an OWIN hosted ASP.Net WebApi2 Microservice. When calling other services, I need to read values from the currentOwinContext.Request.User.Identity and add them to the RequestMessage I send to the next service. My LongLived class is a DelegatingHandler (i.e. part of the HttpClient "HttpMessageHandler-Pipeline"), and the HttpClient needs to be .SingleInstance() so I don’t have to instantiate new HttpClients for each request I make. The ShortLived class is IOwinContext, which is registered in a LifeTimeScope in the Owin Pipeline.

Instead of a static variable for the currentLifeTimeScope I could register the HttpConfiguration in autofac. Then I could get the currentLifeTimeScope with httpConfig.DependencyResolver.GetRequestLifetimeScope(); I haven’t tested this approach yet. I still hope to find something cleaner.

答:
If type T is registered with the container, Autofac will automatically resolve dependencies on Func as factories that create T instances through the container please find more info about Delegate Factories

Register your ShortLived class as below that's it all's working fine now.

```<code>public void CaptiveDependencyTest()
{
    var builder = new ContainerBuilder();
    builder.RegisterType<ShortLived>()
        .SingleInstance();
    builder.RegisterType<LongLived>()
        .SingleInstance();
    var container = builder.Build();

    //using (var scope = container.BeginLifetimeScope(b => b.RegisterType<ShortLived>()))
    //{
        var longLived = container.Resolve<LongLived>();
        longLived.DoSomethingWithShortLived();
    //}
}
</code>```

and you can directly resolve as well from container using is no longer needed but at the end choice is yours

Title: Captive Dependency with Autofac

Body:
I’m looking for the cleanest way to solve the Captive Dependency problem with autofac.

I have a short lived class that will be registerd per LifeTimeScope:

public class ShortLived
{
    public void DoSomethingUsefull() {}
}

And I have a long living class that will be registered as single instance. It has a dependency on the ShortLived class:

public class LongLived
{
    private readonly Func<ShortLived> _getCurrentShortLived;

    public LongLived(Func<ShortLived> getCurrentShortLived)
    {
        _getCurrentShortLived = getCurrentShortLived;
    }

    public void DoSomethingWithShortLived()
    {
        var currentShortLived = _getCurrentShortLived();
        currentShortLived.DoSomethingUsefull();
    }
}

The following attempt doesn't work. It throws an Autofac.Core.DependencyResolutionException.

public void CaptiveDependencyTest()
{
    var builder = new ContainerBuilder();
    builder.RegisterType<LongLived>()
        .SingleInstance();
    var container = builder.Build();

    using (var scope = container.BeginLifetimeScope(b => b.RegisterType<ShortLived>()))
    {
        var longLived = scope.Resolve<LongLived>();
        longLived.DoSomethingWithShortLived();
    }
}

The following does work. But I realy hope there is a better solution to the problem than relying on a somehow static variable.

private static ILifetimeScope currentLifetimeScope;

public void CaptiveDependencyTest2()
{
    var builder = new ContainerBuilder();
    builder.Register(c =>
    {
        Func<ShortLived> shortLivedFacotry = () => currentLifetimeScope.Resolve<ShortLived>();
        return new LongLived(shortLivedFacotry);
    })
    .SingleInstance();
    var container = builder.Build();

    using (var scope = container.BeginLifetimeScope(b => b.RegisterType<ShortLived>()))
    {
        currentLifetimeScope = scope;
        var longLived = scope.Resolve<LongLived>();
        longLived.DoSomethingWithShortLived();
    }
}

Some Backround Infos:
I’m working on an OWIN hosted ASP.Net WebApi2 Microservice. When calling other services, I need to read values from the currentOwinContext.Request.User.Identity and add them to the RequestMessage I send to the next service. My LongLived class is a DelegatingHandler (i.e. part of the HttpClient "HttpMessageHandler-Pipeline"), and the HttpClient needs to be .SingleInstance() so I don’t have to instantiate new HttpClients for each request I make. The ShortLived class is IOwinContext, which is registered in a LifeTimeScope in the Owin Pipeline.

Instead of a static variable for the currentLifeTimeScope I could register the HttpConfiguration in autofac. Then I could get the currentLifeTimeScope with httpConfig.DependencyResolver.GetRequestLifetimeScope(); I haven’t tested this approach yet. I still hope to find something cleaner.

Body:
If type T is registered with the container, Autofac will automatically resolve dependencies on Func as factories that create T instances through the container please find more info about Delegate Factories

Register your ShortLived class as below that's it all's working fine now.

public void CaptiveDependencyTest()
{
    var builder = new ContainerBuilder();
    builder.RegisterType<ShortLived>()
        .SingleInstance();
    builder.RegisterType<LongLived>()
        .SingleInstance();
    var container = builder.Build();

    //using (var scope = container.BeginLifetimeScope(b => b.RegisterType<ShortLived>()))
    //{
        var longLived = container.Resolve<LongLived>();
        longLived.DoSomethingWithShortLived();
    //}
}

and you can directly resolve as well from container using is no longer needed but at the end choice is yours


问:
how to send location data (latitude, longitude) periodically to web server
I am developing real time application so i need to send continuous or some periodic (in seconds) location data as latitude and longitude to web service using rest API. so what can i use to send continuous or periodic data to server? do i need to use back ground service or anything else? i don't know how background service work and how to use it? so can anyone help me for this? thanks in advance.</p>

```<code>protected void startLocationUpdates() {

        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);

    }

    protected void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(
                mGoogleApiClient, this);
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
                + result.getErrorCode());
    }

    @Override
    public void onConnected(Bundle arg0) {

        displayLocation();

        if (mRequestingLocationUpdates) {
            startLocationUpdates();
        }
    }

    @Override
    public void onConnectionSuspended(int arg0) {
        mGoogleApiClient.connect();
    }

    @Override
    public void onLocationChanged(Location location) {
        mLastLocation = location;

        Toast.makeText(getApplicationContext(), "Location changed!",
                Toast.LENGTH_SHORT).show();

        displayLocation();
    }
</code>```

答:
Get the lat and Long Values, then Schedule a periodic task to run the method to send value to the server

you can use Job Scheduler (https://developer.android.com/reference/android/app/job/JobScheduler.html)

or

You can use  android-job/evernote to do a periodic Task
(https://github.com/evernote/android-job)

```<code>private void schedulePeriodicJob() {
    int jobId = new JobRequest.Builder(DemoSyncJob.TAG)
            .setPeriodic(TimeUnit.MINUTES.toMillis(15), TimeUnit.MINUTES.toMillis(5))
            .setPersisted(true)
            .build()
            .schedule();
}
</code>```

Body:
I am developing real time application so i need to send continuous or some periodic (in seconds) location data as latitude and longitude to web service using rest API. so what can i use to send continuous or periodic data to server? do i need to use back ground service or anything else? i don't know how background service work and how to use it? so can anyone help me for this? thanks in advance.

protected void startLocationUpdates() {

        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);

    }

    protected void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(
                mGoogleApiClient, this);
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
                + result.getErrorCode());
    }

    @Override
    public void onConnected(Bundle arg0) {

        displayLocation();

        if (mRequestingLocationUpdates) {
            startLocationUpdates();
        }
    }

    @Override
    public void onConnectionSuspended(int arg0) {
        mGoogleApiClient.connect();
    }

    @Override
    public void onLocationChanged(Location location) {
        mLastLocation = location;

        Toast.makeText(getApplicationContext(), "Location changed!",
                Toast.LENGTH_SHORT).show();

        displayLocation();
    }

Body:
Get the lat and Long Values, then Schedule a periodic task to run the method to send value to the server

you can use Job Scheduler (https://developer.android.com/reference/android/app/job/JobScheduler.html)

or

You can use  android-job/evernote to do a periodic Task
(https://github.com/evernote/android-job)

private void schedulePeriodicJob() {
    int jobId = new JobRequest.Builder(DemoSyncJob.TAG)
            .setPeriodic(TimeUnit.MINUTES.toMillis(15), TimeUnit.MINUTES.toMillis(5))
            .setPersisted(true)
            .build()
            .schedule();
}

ContentLicense: CC BY-SA 4.0


问:
Time Series Stata date convert daily to quarterly returns scientific notation
I have data with daily frequency from 01Jan2000 to 30Dec2015, this series was formatted as date (format date %d). I was able to extract day, month and year using day(date), month(date), and year(date).

I also need to generate a variable indicating its quarter, I used gen quarterly=dofq(date), and then format quarterly %tq. Instead of returning the format 2000q1, I got bunches of scientific notations (eg. 1.2e+06). Does anyone know why and how I can fix that?

Thanks in advance!

答: To build on what you have done so far: you should realize that the same way you extracted the variables day, month, and year from date you can extract the quarter (e.g., gen quarter = quarter(date) in your case). Then, using the variables quarter and year as input you can generate a new variable gen year_quarter = yq(year,quarter) and format it with %tq. Essentially, this is what the function qofd() (taken from William's example) does in the background without generating the additional variables quarter and year.


问:
Convert long format with only unique comparisons to full square matrix with the diag
Let's say I have that kind of input data
A file with a data.frame with data in long format, and only uniques comparisons between Species_A and Species_B as follow:

```<code>Species_A Species_B values
A B 58
A C 64
A D 78
A E 32
B C 10
B D 12
B E 54
C D 99
C E 84
D E 42
</code>```

I wonder how I can easily convert the input file into the square matrix

```<code>    A   B   C   D   E
A   100 58  64  78  32
B   58  100 10  12  54
C   64  10  100 99  84
D   78  12  99  100 42
E   32  54  84  42  100
</code>```

答:
A solution using  tidyverse functions:

```<code>library(tidyverse)

cor_data <- tribble(
~Species_A, ~Species_B, ~values,
"A","B",58,
"A","C",64,
"A","D",78,
"A","E",32,
"B","C",10,
"B","D",12,
"B","E",54,
"C","D",99,
"C","E",84,
"D","E",42)

expand.grid(unique(cor_data[["Species_A"]]), unique(cor_data[["Species_A"]])) %>%
  left_join(cor_data, by =c("Var1" = "Species_A", "Var2" = "Species_B")) %>%
  left_join(cor_data, by =c("Var1" = "Species_B", "Var2" = "Species_A")) %>%
  transmute(Species_A = Var1, Species_B = Var2, values = coalesce(values.x, values.y)) %>%
  spread(Species_B, values)
</code>```

Body:
Let's say I have that kind of input data
A file with a data.frame with data in long format, and only uniques comparisons between Species_A and Species_B as follow:

Species_A Species_B values
A B 58
A C 64
A D 78
A E 32
B C 10
B D 12
B E 54
C D 99
C E 84
D E 42

I wonder how I can easily convert the input file into the square matrix

    A   B   C   D   E
A   100 58  64  78  32
B   58  100 10  12  54
C   64  10  100 99  84
D   78  12  99  100 42
E   32  54  84  42  100

Body:
A solution using  tidyverse functions:

library(tidyverse)

cor_data <- tribble(
~Species_A, ~Species_B, ~values,
"A","B",58,
"A","C",64,
"A","D",78,
"A","E",32,
"B","C",10,
"B","D",12,
"B","E",54,
"C","D",99,
"C","E",84,
"D","E",42)

expand.grid(unique(cor_data[["Species_A"]]), unique(cor_data[["Species_A"]])) %>%
  left_join(cor_data, by =c("Var1" = "Species_A", "Var2" = "Species_B")) %>%
  left_join(cor_data, by =c("Var1" = "Species_B", "Var2" = "Species_A")) %>%
  transmute(Species_A = Var1, Species_B = Var2, values = coalesce(values.x, values.y)) %>%
  spread(Species_B, values)


问:
jQuery not triggering .click function from a jQuery generated HTML tags
I have a button on my document, upon clicking will generate certain html tags.

```<code><a type="button" name="repbut" >Reply</a> //on button click

    <script type="text/javascript"> // this script will be executed
    $(document).ready(function(){
    $('a[name=repbut]').click(function(){
        var boxid=$(this).attr("id");
        $("#"+boxid+"1").html('<ul><li><div class="comment"><div class="comment-content"><div class="comment-meta-author">Post your reply</div><br><div class="comment-body"><div class="form-group"><label>Message</label><textarea id="reep" class="form-control" rows="2"></textarea><br><span id="'+boxid+'2"></span><a type="button" name="repcom" id="test" value="'+boxid+'" class="btn btn-primary pull-right">Reply</a></div><br></div></div></div></li></ul>');
    });
    });
    </script>
</code>```

The problem is when i click the generated button nothing happens, not even alert function.

```<code><a type="button" name="repcom" id="test" class="btn btn-primary pull-right">

<script type="text/javascript">
$('a[name=repcom]').click(function(){
        alert("yes"); // not triggered
        });
</script>
</code>```

Am i doing something wrong? i am new to jQuery.
Any help is appreciated.

答:
```<code>$('#test').on("click", function(){
    alert("yes");
});
</code>```

Body:
I have a button on my document, upon clicking will generate certain html tags.

Reply //on button click

The problem is when i click the generated button nothing happens, not even alert function.

Am i doing something wrong? i am new to jQuery.
Any help is appreciated.


问:
How to get different max id from database at a time
hello i am creating an hotel app in that when i am inserting order into database at that time i am fetching max orderid from database and inserting order and orderid in database. but my problem is that when i am installing that apps in two different devices at that time when i am placing order at time it gets same orderid to different table and insert into database and order is inserted in one table so please give me any solution

```<code>    private void openAlert(View view) {
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(DisplayActivity.this);
    new AsyncLoadOrderId().execute();
    alertDialogBuilder.setTitle("Restrosoft");
    alertDialogBuilder.setMessage("Are you sure?");
    // set positive button: Yes message
    alertDialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // go to a new activity of the app

            for (int i = 0; i < user_fName.size(); i++) {
                System.out.println(user_fName.get(i)); //prints element i
                menulists = user_fName.get(i);
                if (tabletypes.equals("A/C")) {

                    getAcrate(menulists);
                    getTotalamount(menulists, convertedvaluefororderid);
                    getmenuidofperticular(menulists);
                    getButtonfinalordertodb();
                    String conquantity = String.valueOf(quantity);
                    new AsyncInsertIntoTemp().execute(menulists, conquantity, OrderIdFromService, WaiterName, str1);
                } else if (tabletypes.equals("Non A/C")) {

                    getProfilesCount(menulists);
                    getTotalamount(menulists, convertedvaluefororderid);
                    getmenuidofperticular(menulists);
                    getButtonfinalordertodb();
                    String conquantity = String.valueOf(quantity);
                    new AsyncInsertIntoTemp().execute(menulists, conquantity, OrderIdFromService, WaiterName, str1);
                } else {
                    Toast.makeText(DisplayActivity.this, "Closed", Toast.LENGTH_SHORT).show();
                }
            }

            Insertingintotableorder inserttableorder = new Insertingintotableorder(OrderIdFromService, str1, currentDateTimeString, intentfromTwolistwid, ordertype, tablestatustblord, discvaluefortblord, discamount);
            new AsyncCreatetableOrder().execute(inserttableorder);
            new AsyncCreateTemporder().execute(OrderIdFromService, KOTIDFromTwolist, str1, "", "", WaiterName);
            ForupdateStatus updatestatushere = new ForupdateStatus(str1);
            new AsyncupdateStatus().execute(updatestatushere);
            Intent intents = new Intent(DisplayActivity.this, MainActivity.class);
            intents.putExtra("Uname", WaiterName);
            intents.putExtra("ForButton", cntforb);
            startActivity(intents);
            mHelper.remove();
            Toast.makeText(DisplayActivity.this, "Successfully inserted...", Toast.LENGTH_LONG).show();
        }
    });
    // set negative button: No message
    alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // cancel the alert box and put a Toast to the user
            dialog.cancel();

        }
    });
    // set neutral button: Exit the app message
    alertDialogBuilder.setNeutralButton("Exit the app", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // exit the app and go to the HOME
            DisplayActivity.this.finish();
        }
    });

    AlertDialog alertDialog = alertDialogBuilder.create();
    // show alert
    alertDialog.show();
}
</code>```

Here is async task:

```<code> protected class AsyncLoadOrderId extends
            AsyncTask<String, String, JSONObject> {
        JSONObject jsonObj = null;
        //ArrayList<UserOrder> subTablea = null;

        @Override
        protected JSONObject doInBackground(String... args) {
            // TODO Auto-generated method stub

            RestAPI api = new RestAPI();
            try {

                jsonObj = api.GetOrdertopid();
                JSONParser parser = new JSONParser();

                //subTablea = parser.parsOrderid(jsonObj);

            } catch (Exception e) {
                // TODO Auto-generated catch block
                Log.d("AsyncLoadDeptDetails", e.getMessage());

            }
            return jsonObj;

        }

        @Override
        protected void onPostExecute(JSONObject json) {
            // TODO Auto-generated method stub
            try {
                JSONArray jsonArray = json.getJSONArray("Value");

                for (int i = 0; i < jsonArray.length(); i++) {
                    jsonObj = jsonArray.getJSONObject(i);

                }
                OrderIdFromService = jsonObj.getString("order_id");
                convertedorderid = Integer.parseInt(OrderIdFromService);
                orderidfortable.setText(OrderIdFromService);

                if (intentresponse.equals("Yes")) {

                     serveroid = String.valueOf(orderid);
                    orderidfortable.setText(serveroid);

                }
            } catch (Exception e) {

                e.printStackTrace();

            }

        }
</code>```

答:
Your Async work is completely wrong

For example if I call

```<code>new AsyncLoadOrderId().execute();
</code>```

And then immidiatly click "Yes" button of your AlertDialog I will get wrong results because OrderIdFromService can have previous value. In other words OrderIdFromService gets value after AsyncLoadOrderId() will do its work but other actions are synchronious. With slow/bad internet connection that will not work at all.

So this line

```<code>new AsyncInsertIntoTemp().execute(menulists, conquantity, OrderIdFromService, WaiterName, str1);
</code>```

Doesnt do anything because OrderIdFromService probably has wrong value.

So you should do it in chain like

AsyncLoadOrderId()

wait for its done

get value and run new AsyncCreatetableOrder() inside
AsyncLoadOrderId().onPostExecute();

wait until AsyncCreatetableOrder() is done

get value and run  new AsyncCreateTemporder() inside AsyncCreatetableOrder().onPostExecute()

etc

Its the one way to do it with your AsyncTasks.

Usually developers use something like rxJava for same functional

Body:
hello i am creating an hotel app in that when i am inserting order into database at that time i am fetching max orderid from database and inserting order and orderid in database. but my problem is that when i am installing that apps in two different devices at that time when i am placing order at time it gets same orderid to different table and insert into database and order is inserted in one table so please give me any solution

    private void openAlert(View view) {
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(DisplayActivity.this);
    new AsyncLoadOrderId().execute();
    alertDialogBuilder.setTitle("Restrosoft");
    alertDialogBuilder.setMessage("Are you sure?");
    // set positive button: Yes message
    alertDialogBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // go to a new activity of the app

            for (int i = 0; i < user_fName.size(); i++) {
                System.out.println(user_fName.get(i)); //prints element i
                menulists = user_fName.get(i);
                if (tabletypes.equals("A/C")) {

                    getAcrate(menulists);
                    getTotalamount(menulists, convertedvaluefororderid);
                    getmenuidofperticular(menulists);
                    getButtonfinalordertodb();
                    String conquantity = String.valueOf(quantity);
                    new AsyncInsertIntoTemp().execute(menulists, conquantity, OrderIdFromService, WaiterName, str1);
                } else if (tabletypes.equals("Non A/C")) {

                    getProfilesCount(menulists);
                    getTotalamount(menulists, convertedvaluefororderid);
                    getmenuidofperticular(menulists);
                    getButtonfinalordertodb();
                    String conquantity = String.valueOf(quantity);
                    new AsyncInsertIntoTemp().execute(menulists, conquantity, OrderIdFromService, WaiterName, str1);
                } else {
                    Toast.makeText(DisplayActivity.this, "Closed", Toast.LENGTH_SHORT).show();
                }
            }

            Insertingintotableorder inserttableorder = new Insertingintotableorder(OrderIdFromService, str1, currentDateTimeString, intentfromTwolistwid, ordertype, tablestatustblord, discvaluefortblord, discamount);
            new AsyncCreatetableOrder().execute(inserttableorder);
            new AsyncCreateTemporder().execute(OrderIdFromService, KOTIDFromTwolist, str1, "", "", WaiterName);
            ForupdateStatus updatestatushere = new ForupdateStatus(str1);
            new AsyncupdateStatus().execute(updatestatushere);
            Intent intents = new Intent(DisplayActivity.this, MainActivity.class);
            intents.putExtra("Uname", WaiterName);
            intents.putExtra("ForButton", cntforb);
            startActivity(intents);
            mHelper.remove();
            Toast.makeText(DisplayActivity.this, "Successfully inserted...", Toast.LENGTH_LONG).show();
        }
    });
    // set negative button: No message
    alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // cancel the alert box and put a Toast to the user
            dialog.cancel();

        }
    });
    // set neutral button: Exit the app message
    alertDialogBuilder.setNeutralButton("Exit the app", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // exit the app and go to the HOME
            DisplayActivity.this.finish();
        }
    });

    AlertDialog alertDialog = alertDialogBuilder.create();
    // show alert
    alertDialog.show();
}

Here is async task:

 protected class AsyncLoadOrderId extends
            AsyncTask<String, String, JSONObject> {
        JSONObject jsonObj = null;
        //ArrayList<UserOrder> subTablea = null;

        @Override
        protected JSONObject doInBackground(String... args) {
            // TODO Auto-generated method stub

            RestAPI api = new RestAPI();
            try {

                jsonObj = api.GetOrdertopid();
                JSONParser parser = new JSONParser();

                //subTablea = parser.parsOrderid(jsonObj);

            } catch (Exception e) {
                // TODO Auto-generated catch block
                Log.d("AsyncLoadDeptDetails", e.getMessage());

            }
            return jsonObj;

        }

        @Override
        protected void onPostExecute(JSONObject json) {
            // TODO Auto-generated method stub
            try {
                JSONArray jsonArray = json.getJSONArray("Value");

                for (int i = 0; i < jsonArray.length(); i++) {
                    jsonObj = jsonArray.getJSONObject(i);

                }
                OrderIdFromService = jsonObj.getString("order_id");
                convertedorderid = Integer.parseInt(OrderIdFromService);
                orderidfortable.setText(OrderIdFromService);

                if (intentresponse.equals("Yes")) {

                     serveroid = String.valueOf(orderid);
                    orderidfortable.setText(serveroid);

                }
            } catch (Exception e) {

                e.printStackTrace();

            }

        }

Body:
Your Async work is completely wrong

For example if I call

new AsyncLoadOrderId().execute();

And then immidiatly click "Yes" button of your AlertDialog I will get wrong results because OrderIdFromService can have previous value. In other words OrderIdFromService gets value after AsyncLoadOrderId() will do its work but other actions are synchronious. With slow/bad internet connection that will not work at all.

So this line

new AsyncInsertIntoTemp().execute(menulists, conquantity, OrderIdFromService, WaiterName, str1);

Doesnt do anything because OrderIdFromService probably has wrong value.

So you should do it in chain like

AsyncLoadOrderId()

wait for its done

get value and run new AsyncCreatetableOrder() inside
AsyncLoadOrderId().onPostExecute();

wait until AsyncCreatetableOrder() is done

get value and run  new AsyncCreateTemporder() inside AsyncCreatetableOrder().onPostExecute()

etc

Its the one way to do it with your AsyncTasks.

Usually developers use something like rxJava for same functional


问:
Write CSV To File Without Enclosures In PHP
Is there a native function or solid class/library for writing an array as a line in a CSV file without enclosures? fputcsv will default to " if nothing is passed in for the enclosure param. Google is failing me (returning results for a whole bunch of pages about fputcsv), and PEAR's libraries do more or less the same things as fputcsv.

Something that works exactly like fputcsv, but will allow the fields to remain unquoted.

currently: "field 1","field 2",field3hasNoSpaces

desired: field 1,field 2,field3hasNoSpaces

答: fputcsv($file, $data, ';', chr(127));

Body: fputcsv($file, $data, ';', chr(127));


问:
Microsoft.Web.Atlas.dll and IIS7 Integrated mode
I'm moving a website from IIS6 to IIS7 and I can’t get Microsoft.Web.Atlas.dll to work when IIS7 is running in integrated mode. It works fine in classic mode. I just get an unknown error dialog and I can see it's a 500 error on the server. When doing a trace the only information I get is that it's the error is from ManagedPipelineHandler. Ideas?</p>

答:
As you're probably aware, Microsoft.Web.Atlas.dll was the CTP of the ASP.NET AJAX components (from circa 2005/6). Unfortunately I and probably many others have long disposed of this CTP so I can only speculate as to what may be wrong and some possible fixes:

Try adding any Atlas specific handlers and modules to the <system.webServer> section of your web.config file.

If the new server is running 64-bit windows try switching the application pool the site resides in to 32-bit mode.

Configure the site's application pool to run ASP.NET 2.0 and not ASP.NET 4.0.

Because it's so old and it was a CTP, Atlas may not even be compatible with Integrated Pipeline mode.

Consider updating the code to use Microsoft AJAX 2.0 RTM.


问:
Mockito when() on method of field
I'm trying to test with Mockito the interactor in simple application, that works as Finite state machine.

```<code>public class Machine {

private OnActionListener mListener;
private ArrayList<State> mStates;
private FSMJsonParser parser;

private State mCurrentState;

public Machine(String jsonConfig, OnActionListener listener, FSMJsonParser parser) throws IOException {

    this.mListener = listener;
    this.parser = parser;
    initStates(jsonConfig);
    mCurrentState = getStateByName("AlarmArmed_AllLocked");
}

private void initStates(String jsonConfig) throws IOException{

    mStates = parser.parseFSMFromJson(jsonConfig);
}
</code>```

There is test:

```<code>@RunWith(PowerMockRunner.class)
@PrepareForTest(FSMJsonParser.class)
public class FSMtest {

@Mock
State state;

@Mock
ControlPresenter presenter;

@Mock
FSMJsonParser parser;

@InjectMocks
Machine machine;

@Before
public void setUp() throws IOException {

    when(parser.parseFSMFromJson(anyString())).thenReturn(parseFSMFromJson(readConfig()));
}

@Test
public void testAlarmArmedAllLockedStateActions() throws IOException{

    machine.lock();
    verify(machine, times(1)).setCurrentState(anyString());

    machine.lockx2();
    verify(machine, times(1)).setCurrentState("AlarmArmed_AllLocked");

    machine.unlock();
    verify(machine, times(1)).setCurrentState("AlarmDisarmed_DriverUnlocked");

    machine.unlockx2();
    verify(machine, times(1)).setCurrentState("AlarmDisarmed_AllUnocked");
}
</code>```

I provide a parse JSON (with states description, stored in assets) with method parseFSMFromJson(readConfig()). When ran test with debug mode, JSON was parsed properly. But fields of Machine mock object didn't initialized, and was null and all tests failed. I need to initialize ArrayList mStates for correct work of Machine class. How to test this class properly??

答:
You need MockitoAnnotations.initMocks(this) inside your @Before method, since you are not running the test case with MockitoJUnitRunner (refer to https://static.javadoc.io/org.mockito/mockito-core/2.7.20/org/mockito/Mockito.html#mock_annotation).

Like this:

```<code>@Before
public void setUp() throws IOException {
    MockitoAnnotations.initMocks(this);
    when(parser.parseFSMFromJson(anyString())).thenReturn(parseFSMFromJson(readConfig()));
}
</code>```

Title: Mockito when() on method of field

Body:
I'm trying to test with Mockito the interactor in simple application, that works as Finite state machine.

public class Machine {

private OnActionListener mListener;
private ArrayList<State> mStates;
private FSMJsonParser parser;

private State mCurrentState;

public Machine(String jsonConfig, OnActionListener listener, FSMJsonParser parser) throws IOException {

    this.mListener = listener;
    this.parser = parser;
    initStates(jsonConfig);
    mCurrentState = getStateByName("AlarmArmed_AllLocked");
}

private void initStates(String jsonConfig) throws IOException{

    mStates = parser.parseFSMFromJson(jsonConfig);
}

There is test:

@RunWith(PowerMockRunner.class)
@PrepareForTest(FSMJsonParser.class)
public class FSMtest {

@Mock
State state;

@Mock
ControlPresenter presenter;

@Mock
FSMJsonParser parser;

@InjectMocks
Machine machine;

@Before
public void setUp() throws IOException {

    when(parser.parseFSMFromJson(anyString())).thenReturn(parseFSMFromJson(readConfig()));
}

@Test
public void testAlarmArmedAllLockedStateActions() throws IOException{

    machine.lock();
    verify(machine, times(1)).setCurrentState(anyString());

    machine.lockx2();
    verify(machine, times(1)).setCurrentState("AlarmArmed_AllLocked");

    machine.unlock();
    verify(machine, times(1)).setCurrentState("AlarmDisarmed_DriverUnlocked");

    machine.unlockx2();
    verify(machine, times(1)).setCurrentState("AlarmDisarmed_AllUnocked");
}

I provide a parse JSON (with states description, stored in assets) with method parseFSMFromJson(readConfig()). When ran test with debug mode, JSON was parsed properly. But fields of Machine mock object didn't initialized, and was null and all tests failed. I need to initialize ArrayList mStates for correct work of Machine class. How to test this class properly??

Body:
You need MockitoAnnotations.initMocks(this) inside your @Before method, since you are not running the test case with MockitoJUnitRunner (refer to https://static.javadoc.io/org.mockito/mockito-core/2.7.20/org/mockito/Mockito.html#mock_annotation).

Like this:

@Before
public void setUp() throws IOException {
    MockitoAnnotations.initMocks(this);
    when(parser.parseFSMFromJson(anyString())).thenReturn(parseFSMFromJson(readConfig()));
}


问:
Fineuploader - OnComplete Method can't call a value outside the function
I have a problem with fineuploader in the OnComplete() function when I try to call "customer" value inside it. I'm using Angular and TypeScript for frontside.

The "customer" value is undefined because it is not found in the onComplete() bloc (no auto-completion). So how can I call my importCustomers function? any idea?

Thank you in advance for any help.

答:
You have an issue with this scoping

```<code>ngAfterViewInit(){

var self = this; //<-- assign this before setting the new Uploader class

this.uploader = new Uploader({

....

   self.customer.importCustomers(name); //<-- use the assigned self here

}
</code>```

Body:
You have an issue with this scoping

ngAfterViewInit(){

var self = this; //<-- assign this before setting the new Uploader class

this.uploader = new Uploader({

....

   self.customer.importCustomers(name); //<-- use the assigned self here

}