问:
PHP - How to carry on the SESSION variables after a form submit
Im having issues  while using the SESSION variables. Im planning to add data to a SQL each time the user hit "Submit" on the generar.php script. I'm also counting on the login data of the first pag index.html here is where im having issues, whenever i hit "Submit" it will clean the variables. I checked several
forums looking for an answer but still i dont have an answer. Any ideas?

index.html

<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>Creacion de receta</title>
<link rel="stylesheet" type="text/css" href="default.css">

<form method="post" action="generar.php">

Codigo del Medico
<input name="v_codigo">

Cedula del paciente
<input name="v_cedula">

 Enviar
<input name="submit" value="Enviar" type="submit">

</form>

```
</div>
</div>
</p>

<p>generar.php
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>Creacion de receta</title>
<link rel="stylesheet" type="text/css" href="default.css">
</head>
<body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<tbody>
<tr>
<td>Medicamento</td>
<td>
<select name="v_meds"><option>Seleccionar</option><option>Rojo</option><option>Verde</option><option>Azul</option><option>Amarillo</option><option>Blanco</option><option>Negro</option></select>
<br>
</td>
</tr>
<tr>
<td>Via</td>
<td>
<select name="v_via"><option>Seleccionar</option><option>Oral</option><option>Rectal</option><option>Nasal</option><option>Otica</option><option>Oftalmica</option><option>Vaginal</option><option>Topica</option></select>
<br>
</td>
</tr>
<tr>
<td>Frecuencia</td>
<td>
<select name="v_frec"><option>Seleccionar</option><option>6</option><option>8</option><option>12</option><option>24</option></select>
<br>
</td>
</tr>
<tr>
<td>Duracion</td>
<td>
<select name="v_dur"><option>Seleccionar</option><option>5</option><option>7</option><option>15</option><option>30</option><option>PRN10</option><option>PRN20</option><option>PRN30</option></select>
<br>
</td>
</tr>
<tr>
<td> Enviar</td>
<td align="right"><input name="submit" value="Enviar" type="submit"></td>
</tr>
<tr>
<td style="text-align: center;" colspan="2" rowspan="1">Ver historial de recetas</td>
</tr>
</tbody>
</form>

<?php
error_reporting(E_ALL);
session_start();
if (isset($_REQUEST['v_codigo']) || isset($_REQUEST['v_cedula'])) {
 $codigo = $_REQUEST['v_codigo'];
 $cedula = $_REQUEST['v_cedula'];
}
 $_SESSION['sesion_codigo'] = $codigo;
 $_SESSION['sesion_cedula'] = $cedula;

 //$codigo1 = $_SESSION['sesion_codigo'];
 //$cedula1 = $_SESSION['sesion_cedula'];
 $tabla = 'p'.$cedula1;

 print 'Codigo: ' . $codigo . '<br/>';
 print 'Cedula: ' . $cedula . '<br/>';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // collect value of input field
    $name1 = $_POST['v_meds'];
 $name2 = $_POST['v_via'];
 $name3 = $_POST['v_frec'];
 $name4 = $_POST['v_dur'];
    if ($name1 == 'Seleccionar' || $name2 == 'Seleccionar' || $name3 == 'Seleccionar' || $name4 == 'Seleccionar') {
        echo "Receta contiene errores, favor llenar correctamente el formulario.<br/>";
    } else {
        echo $name1 . $name2 . $name3 . $name4;
    }
}
?>

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

EDIT 1:
I change the session_start(); to the very begining of the html file. But had same result. The first time i select the variables $codigo and $cedula they are correctl setup, when i click on submit button they disapear. The idea is that after clicking the submit button I keep the losgin data to send serveral requests in a row.

Below the images of each step. Thanks again to all who take time to answer.

Login data:
codigovar
cedulavar

First time the page is loaded
After clicking the submit button

EDIT 2: I'm also using @RamRaider code suggestions to fill the variables only if they are populated.

答:
Try this</p>

```<code><?php
    session_start();
    ob_start();
?>
<!DOCTYPE html>
<html>
...
</html>
</code>```

Body:
Im having issues  while using the SESSION variables. Im planning to add data to a SQL each time the user hit "Submit" on the generar.php script. I'm also counting on the login data of the first pag index.html here is where im having issues, whenever i hit "Submit" it will clean the variables. I checked several
forums looking for an answer but still i dont have an answer. Any ideas?

index.html

<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>Creacion de receta</title>
<link rel="stylesheet" type="text/css" href="default.css">

<form method="post" action="generar.php">

Codigo del Medico
<input name="v_codigo">

Cedula del paciente
<input name="v_cedula">

 Enviar
<input name="submit" value="Enviar" type="submit">

</form>

generar.php

<!DOCTYPE html>

<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>Creacion de receta</title>
<link rel="stylesheet" type="text/css" href="default.css">

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">

Medicamento

<select name="v_meds"><option>Seleccionar</option><option>Rojo</option><option>Verde</option><option>Azul</option><option>Amarillo</option><option>Blanco</option><option>Negro</option></select>

Via

<select name="v_via"><option>Seleccionar</option><option>Oral</option><option>Rectal</option><option>Nasal</option><option>Otica</option><option>Oftalmica</option><option>Vaginal</option><option>Topica</option></select>

Frecuencia

<select name="v_frec"><option>Seleccionar</option><option>6</option><option>8</option><option>12</option><option>24</option></select>

Duracion

<select name="v_dur"><option>Seleccionar</option><option>5</option><option>7</option><option>15</option><option>30</option><option>PRN10</option><option>PRN20</option><option>PRN30</option></select>

 Enviar
<input name="submit" value="Enviar" type="submit">

Ver historial de recetas

</form>

<?php
error_reporting(E_ALL);
session_start();
if (isset($_REQUEST['v_codigo']) || isset($_REQUEST['v_cedula'])) {
 $codigo = $_REQUEST['v_codigo'];
 $cedula = $_REQUEST['v_cedula'];
}
 $_SESSION['sesion_codigo'] = $codigo;
 $_SESSION['sesion_cedula'] = $cedula;

 //$codigo1 = $_SESSION['sesion_codigo'];
 //$cedula1 = $_SESSION['sesion_cedula'];
 $tabla = 'p'.$cedula1;

 print 'Codigo: ' . $codigo . '
';
 print 'Cedula: ' . $cedula . '
';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // collect value of input field
    $name1 = $_POST['v_meds'];
 $name2 = $_POST['v_via'];
 $name3 = $_POST['v_frec'];
 $name4 = $_POST['v_dur'];
    if ($name1 == 'Seleccionar' || $name2 == 'Seleccionar' || $name3 == 'Seleccionar' || $name4 == 'Seleccionar') {
        echo "Receta contiene errores, favor llenar correctamente el formulario.
";
    } else {
        echo $name1 . $name2 . $name3 . $name4;
    }
}
?>

EDIT 1:
I change the session_start(); to the very begining of the html file. But had same result. The first time i select the variables $codigo and $cedula they are correctl setup, when i click on submit button they disapear. The idea is that after clicking the submit button I keep the losgin data to send serveral requests in a row.

Below the images of each step. Thanks again to all who take time to answer.

Login data:
codigovar
cedulavar

First time the page is loaded
After clicking the submit button

EDIT 2: I'm also using @RamRaider code suggestions to fill the variables only if they are populated.

Body:
Try this

<?php
    session_start();
    ob_start();
?>
<!DOCTYPE html>
<html>
...
</html>


来源: stackexchange

问:
Issue with HTTP request in Objective C
Iam trying to submit values to an external DB using http request

My code is below

```<code>NSString *post =[NSString stringWithFormat:@"user=%@&child=%@&content=%@",userId,childId, crackContent.text];

  responseData = [[NSMutableData data] retain];
  NSString *hostStr = @"http://myhost.com/addItem.php?";
  post = [utilityObj getEncodedUrl:post];
  hostStr = [hostStr stringByAppendingString:post];
  NSLog(hostStr);

  NSLog(hostStr);
  NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:hostStr]];

  [[NSURLConnection alloc] initWithRequest:request delegate:self];
</code>```

My issue is that if any space contains any of the parameter it will not submitted, otherwise it is successfully submitted.

Help is highly appreciated.

答:
You may get the parameter encoded before send.

```<code>NSString* escapedUrlString =
   [unescapedString stringByAddingPercentEscapesUsingEncoding:
                        NSASCIIStringEncoding];
</code>```

Alternative

```<code>  NSString * escapedUrlString = (NSString *)CFURLCreateStringByAddingPercentEscapes(
    NULL,
    (CFStringRef)unescapedString,
    NULL,
    (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
    kCFStringEncodingUTF8 );
</code>```

ContentLicense: CC BY-SA 2.5

Title: Issue with HTTP request in Objective C

Body:
Iam trying to submit values to an external DB using http request

My code is below

NSString *post =[NSString stringWithFormat:@"user=%@&child=%@&content=%@",userId,childId, crackContent.text];

  responseData = [[NSMutableData data] retain];
  NSString *hostStr = @"http://myhost.com/addItem.php?";
  post = [utilityObj getEncodedUrl:post];
  hostStr = [hostStr stringByAppendingString:post];
  NSLog(hostStr);

  NSLog(hostStr);
  NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:hostStr]];

  [[NSURLConnection alloc] initWithRequest:request delegate:self];

My issue is that if any space contains any of the parameter it will not submitted, otherwise it is successfully submitted.

Help is highly appreciated.

Body:
You may get the parameter encoded before send.

NSString* escapedUrlString =
   [unescapedString stringByAddingPercentEscapesUsingEncoding:
                        NSASCIIStringEncoding];

Alternative

  NSString * escapedUrlString = (NSString *)CFURLCreateStringByAddingPercentEscapes(
    NULL,
    (CFStringRef)unescapedString,
    NULL,
    (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
    kCFStringEncodingUTF8 );


问:
MongoDb Logical Query Operators and Braces
What is the Rule with using Braces when nesting and using logical operators in mongoDB when running aggregation queries some queries work and others don't as shown below ?

scenario 1 (works) :

```<code> $project:
 {
  $and: [ { $gt: [ "$qty", 100 ] }, { $lt: [ "$qty", 250 ] }]
 }
</code>```

```<code>scenario 2 (works):

$project:
{
 $and:[{"data":"Residential"},{"status":true}],
}
</code>```

scenario 3 (works)

```<code>$and:
[
 {
  $and:[{"data":"Residential"},{"status":true}],
  $and:[{"data":"Lobby"},{"status":true}],
 }
]
</code>```

scenario 3 (would give a different result from scenario 2 result)

```<code>$and:
[
  {
    $and:[{"data":"Residential"},{"status":true}],
  },
  {
    $and:[{"data":"Lobby"},{"status":true}],
  }
]
</code>```

scenario 4 (works):

```<code>$and:[
  {
    $or:[
         {
          $and:[
                 {"data":"Kids"},
                 {"status":true}
               ]
         },
        {
         $and:[
                 {"data":"Adults"},
                 {"status":true}
             ]
         }
       ]
      }
]
</code>```

Scenario 4 would give a different result if i was to do :

```<code>$and:[
{
 $or:
 [
  {
    $and:[{"data":"Kids"},{“status":true} ].
    $and:[{"data":"Adults"},{"status":true} ]
  }
 ]
}
],
</code>```

Such details are not indicated in the documentation any where.

答:
So One thing i have realized is that nested braces with $and or $or can be treated as a separate step/stage depending on how we use them. This concept is called Coalescence and its discussed in details under aggregation pipelines optimizations (https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/#match-match-coalescence).
let me explain more with an example.

lets say we have x = [1,2,3,5,8,13,21,34,55];  and we want to filter that in our aggregates. case one.
I have made a comparison of first greater than and then less than for a reason.

```<code>$project:
 {
  $and: [ { $gt: [ "$qty", 25 ] },{ $lt: [ "$qty", 5 ] }]
 }
</code>```

we should get a result of  8,13,21

Next lets try this one

$project:

```<code>$and:
[
 {
  $and:[{ $gt: [ "$qty", 25 ] }],
  $and:[{ $lt: [ "$qty", 5 ] }],
 }
]
</code>```

we should get a result of  8,13,21 the reason being its gone do this in one go

Last Example

```<code>$and:
[
  {
    $and:[{ $gt: [ "$qty", 25 ] }],
  },
  {
    $and:[{ $lt: [ "$qty", 5 ] }],
  }
]
</code>```

we should get [] or empty as a result.

The reason we will get an empty list as a result is the fact that we will be running the above query in two stages. The First Stage will filter our value x for numbers greater than 25 and it will return a new list. The next stage then will go on to filter the results of our first stage for numbers less than 5 which will be empty since the result set only contains numbers greater than 25.

So the lesson here is if you are gone nest portions of your query inside $and, $or be advised that each brace is treated as a separate stage and the following stages act upon the result from the previous stage.

ContentLicense: CC BY-SA 3.0

Body:
What is the Rule with using Braces when nesting and using logical operators in mongoDB when running aggregation queries some queries work and others don't as shown below ?

scenario 1 (works) :

 $project:
 {
  $and: [ { $gt: [ "$qty", 100 ] }, { $lt: [ "$qty", 250 ] }]
 }

scenario 2 (works):

$project:
{
 $and:[{"data":"Residential"},{"status":true}],
}

scenario 3 (works)

$and:
[
 {
  $and:[{"data":"Residential"},{"status":true}],
  $and:[{"data":"Lobby"},{"status":true}],
 }
]

scenario 3 (would give a different result from scenario 2 result)

$and:
[
  {
    $and:[{"data":"Residential"},{"status":true}],
  },
  {
    $and:[{"data":"Lobby"},{"status":true}],
  }
]

scenario 4 (works):

$and:[
  {
    $or:[
         {
          $and:[
                 {"data":"Kids"},
                 {"status":true}
               ]
         },
        {
         $and:[
                 {"data":"Adults"},
                 {"status":true}
             ]
         }
       ]
      }
]

Scenario 4 would give a different result if i was to do :

$and:[
{
 $or:
 [
  {
    $and:[{"data":"Kids"},{“status":true} ].
    $and:[{"data":"Adults"},{"status":true} ]
  }
 ]
}
],

Such details are not indicated in the documentation any where.

Body:
So One thing i have realized is that nested braces with $and or $or can be treated as a separate step/stage depending on how we use them. This concept is called Coalescence and its discussed in details under aggregation pipelines optimizations (https://docs.mongodb.com/manual/core/aggregation-pipeline-optimization/#match-match-coalescence).
let me explain more with an example.

lets say we have x = [1,2,3,5,8,13,21,34,55];  and we want to filter that in our aggregates. case one.
I have made a comparison of first greater than and then less than for a reason.

$project:
 {
  $and: [ { $gt: [ "$qty", 25 ] },{ $lt: [ "$qty", 5 ] }]
 }

we should get a result of  8,13,21

Next lets try this one

$project:

$and:
[
 {
  $and:[{ $gt: [ "$qty", 25 ] }],
  $and:[{ $lt: [ "$qty", 5 ] }],
 }
]

we should get a result of  8,13,21 the reason being its gone do this in one go

Last Example

$and:
[
  {
    $and:[{ $gt: [ "$qty", 25 ] }],
  },
  {
    $and:[{ $lt: [ "$qty", 5 ] }],
  }
]

we should get [] or empty as a result.

The reason we will get an empty list as a result is the fact that we will be running the above query in two stages. The First Stage will filter our value x for numbers greater than 25 and it will return a new list. The next stage then will go on to filter the results of our first stage for numbers less than 5 which will be empty since the result set only contains numbers greater than 25.

So the lesson here is if you are gone nest portions of your query inside $and, $or be advised that each brace is treated as a separate stage and the following stages act upon the result from the previous stage.


问:
What is the most universal 3D file format?
After googling I learned there are different 3D files

*.obj & *.mtl    (Wavefront)

*.dae    (Collada)

*.u3d      (Universal format)

*.3ds      (3D Studio Max)

*.ma, *.mb  (Maya  files)

*.blend   (Blender)
and many more.

Just wanted to know which one is most used file in Augmented Reality application?

答: I would say OBJ. It's commonly used in CAD, gaming and movie industries.</p>


问:
Changing the height of a html div down to top without using transition
I need to do tank animation, where according to the liquid level, the height of the tank(image) changes. For this I have written HTML code as below:

```<code><div>
<img id='T1' style="height:0px;position:absolute">
</div>
</code>```

Now I am obtaining the level information from database using ajax and trying to change the height of the image according to the value of the level parameter using JavaScript.

```<code>  var level=response;
 document.getElementById('T1').height=level."px";
</code>```

This is changing the height from top to down, but I want down to top.
Inverting the div using transform is not working. Also transition is not working as transition-time cannot be specified in this case.
Please provide me some suggestions.

答:
Hard to figure out what you are trying to do. Maybe a link would help. Only thing I could see is style.height is written incorrectly.</p>

```<code>document.getElementById("T1").style.height = level + "px";
</code>```

Body:
I need to do tank animation, where according to the liquid level, the height of the tank(image) changes. For this I have written HTML code as below:

Now I am obtaining the level information from database using ajax and trying to change the height of the image according to the value of the level parameter using JavaScript.

  var level=response;
 document.getElementById('T1').height=level."px";

This is changing the height from top to down, but I want down to top.
Inverting the div using transform is not working. Also transition is not working as transition-time cannot be specified in this case.
Please provide me some suggestions.

Body:
Hard to figure out what you are trying to do. Maybe a link would help. Only thing I could see is style.height is written incorrectly.

document.getElementById("T1").style.height = level + "px";


问:
NavigableMap throwing unwanted exception
From java docs of NavigableMap :firstKey() of Navigable map

Returns a key-value mapping associated with the least key in this map, or null if the map is empty.

However, when i run the following program i am getting NoSuchElementException

```<code> public class Test1 {
        public static void main(String a[]) {
            NavigableMap<Object, Object> map = new TreeMap<>();
            Object obj = map.firstKey();
        }
    }
</code>```

I am not sure if i am missing something here, Please let me know why it is behaving like this?

答:
As the firstKey() function's documentation states:

```<code>/**
 * Returns the first (lowest) key currently in this map.
 *
 * @return the first (lowest) key currently in this map
 * @throws NoSuchElementException if this map is empty
 */
K firstKey();
</code>```

So In your case the map is empty and therefore the exception

If you look at TreeMap's implementation for the method then you see:

```<code>/**
 * @throws NoSuchElementException {@inheritDoc}
 */
public K firstKey() {
    return key(getFirstEntry());
}
</code>```

The getFirstEntry returns null in case of an empty set and then the key method:

```<code>/**
 * Returns the key corresponding to the specified Entry.
 * @throws NoSuchElementException if the Entry is null
 */
static <K> K key(Entry<K,?> e) {
    if (e==null)
        throw new NoSuchElementException();
    return e.key;
}
</code>```

Because the object itself is TreeMap and not NavigableMap you need to check the derived's implementation and documentation, even if the reference is to the base

Body:
From java docs of NavigableMap :firstKey() of Navigable map

Returns a key-value mapping associated with the least key in this map, or null if the map is empty.

However, when i run the following program i am getting NoSuchElementException

 public class Test1 {
        public static void main(String a[]) {
            NavigableMap<Object, Object> map = new TreeMap<>();
            Object obj = map.firstKey();
        }
    }

I am not sure if i am missing something here, Please let me know why it is behaving like this?

Body:
As the firstKey() function's documentation states:

/**
 * Returns the first (lowest) key currently in this map.
 *
 * @return the first (lowest) key currently in this map
 * @throws NoSuchElementException if this map is empty
 */
K firstKey();

So In your case the map is empty and therefore the exception

If you look at TreeMap's implementation for the method then you see:

/**
 * @throws NoSuchElementException {@inheritDoc}
 */
public K firstKey() {
    return key(getFirstEntry());
}

The getFirstEntry returns null in case of an empty set and then the key method:

/**
 * Returns the key corresponding to the specified Entry.
 * @throws NoSuchElementException if the Entry is null
 */
static <K> K key(Entry<K,?> e) {
    if (e==null)
        throw new NoSuchElementException();
    return e.key;
}

Because the object itself is TreeMap and not NavigableMap you need to check the derived's implementation and documentation, even if the reference is to the base


问:
Android: Keep asynctask even after app is killed
I have this code below that I'm using to test the life cycle of the asynctask. What I want to do is to let the asynctask finish even if the app is forcibly closed by the user. It shows a notification which increments the progress every second. The asynctask is called from a Fragment. However, when I forcibly terminate the app by pressing all apps then swiping it off, the notification stops and no longer increments. See my code below.

Is this the case or am I doing something wrong?

Also, the reason I'm using asynctask is because I want to allow the user to cancel the task whenever possible. I believe this can't be done with IntentService? (Correct me if I'm wrong on this).

Appreciate any help.

UPDATE: I am now trying foreground service as suggested by @John Wick and @Abishek. However, I am not able to stop the service the way I want it to. When I click stop, the loop goes on and does not stop.

public class ForegroundService extends Service {

```<code>    boolean isCancelled = false;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if (intent.getAction().equals("Start")) {
            Log.d("Action", "Start");
            Intent notificationIntent = new Intent(this, MainActivity.class);
            notificationIntent.setAction("Start");
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

            Intent closeIntent = new Intent(this, ForegroundService.class);
            closeIntent.setAction("Stop");
            PendingIntent pCloseIntent = PendingIntent.getService(this, 0, closeIntent, 0);

            Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);

            NotificationManagerCompat manager = (NotificationManagerCompat.from(this));
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

            builder.setContentTitle("Truiton Music Player");
            builder.setTicker("Truiton Music Player");
            builder.setContentText("My Music");
            builder.setSmallIcon(R.mipmap.ic_launcher);
            builder.setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false));
            builder.setContentIntent(pendingIntent);
            builder.addAction(android.R.drawable.ic_media_pause, "Stop", pCloseIntent);

            startForeground(1, builder.build());
            for (int i = 0; i < 10; i++) {
                Log.d("Service", String.valueOf(i));
                builder.setProgress(9, i, false);

                if (isCancelled) {
                    builder.setContentTitle("Cancelled");
                    builder.setContentText("");
                    builder.setProgress(0, 0, false);
                    builder.mActions.clear();
                    manager.notify(1, builder.build());
                } else {
                    if (i == 9) {
                        builder.setContentTitle("Done");
                        builder.setContentText("");
                        builder.setProgress(0, 0, false);
                        manager.notify(1, builder.build());
                    } else {
                        manager.notify(1, builder.build());
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

            stopForeground(true);
        } else {
            Log.d("Action", "Start");
            isCancelled = true;
            stopForeground(true);
            stopSelf();
        }

        return START_STICKY;
    }

}
</code>```

答:
You need to use a Foreground Service to make it work even if app is closed. See this link for a demo implementation.

http://www.truiton.com/2014/10/android-foreground-service-example/

Body:
I have this code below that I'm using to test the life cycle of the asynctask. What I want to do is to let the asynctask finish even if the app is forcibly closed by the user. It shows a notification which increments the progress every second. The asynctask is called from a Fragment. However, when I forcibly terminate the app by pressing all apps then swiping it off, the notification stops and no longer increments. See my code below.

Is this the case or am I doing something wrong?

Also, the reason I'm using asynctask is because I want to allow the user to cancel the task whenever possible. I believe this can't be done with IntentService? (Correct me if I'm wrong on this).

Appreciate any help.

UPDATE: I am now trying foreground service as suggested by @John Wick and @Abishek. However, I am not able to stop the service the way I want it to. When I click stop, the loop goes on and does not stop.

public class ForegroundService extends Service {

    boolean isCancelled = false;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if (intent.getAction().equals("Start")) {
            Log.d("Action", "Start");
            Intent notificationIntent = new Intent(this, MainActivity.class);
            notificationIntent.setAction("Start");
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

            Intent closeIntent = new Intent(this, ForegroundService.class);
            closeIntent.setAction("Stop");
            PendingIntent pCloseIntent = PendingIntent.getService(this, 0, closeIntent, 0);

            Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);

            NotificationManagerCompat manager = (NotificationManagerCompat.from(this));
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

            builder.setContentTitle("Truiton Music Player");
            builder.setTicker("Truiton Music Player");
            builder.setContentText("My Music");
            builder.setSmallIcon(R.mipmap.ic_launcher);
            builder.setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false));
            builder.setContentIntent(pendingIntent);
            builder.addAction(android.R.drawable.ic_media_pause, "Stop", pCloseIntent);

            startForeground(1, builder.build());
            for (int i = 0; i < 10; i++) {
                Log.d("Service", String.valueOf(i));
                builder.setProgress(9, i, false);

                if (isCancelled) {
                    builder.setContentTitle("Cancelled");
                    builder.setContentText("");
                    builder.setProgress(0, 0, false);
                    builder.mActions.clear();
                    manager.notify(1, builder.build());
                } else {
                    if (i == 9) {
                        builder.setContentTitle("Done");
                        builder.setContentText("");
                        builder.setProgress(0, 0, false);
                        manager.notify(1, builder.build());
                    } else {
                        manager.notify(1, builder.build());
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

            stopForeground(true);
        } else {
            Log.d("Action", "Start");
            isCancelled = true;
            stopForeground(true);
            stopSelf();
        }

        return START_STICKY;
    }

}


问:
Bulk Excel data import with nested relationships
I am getting slow performance issue in excel data import with nested relationships.

I have two main tables to insert and other four tables which have one-to-many and many-to-many relationships with main tables.

I check imported data for four tables are existing or new before data is inserted for two main tables as imported file may have same data for four tables and same data cannot insert multiple times.

That's why performance is slow.

How could I solve this issue?

答:
Read the entire file into a string array object using the .Net ReadAllLines() method, then run a Parallel For loop to process all the lines in parallel.</p>

```<code>private bool ProcessFile(string FolderPath, string FileExtension)
{
    try
    {
        //all files with requisite file extension
        DirectoryInfo dinfo = new DirectoryInfo(FolderPath);
        FileInfo[] Files = dinfo.GetFiles(FileExtension);
        foreach (FileInfo file in Files)
        {
            List<String> AllLines = new List<String>();
            using (StreamReader sr = File.OpenText(file.FullName))
            {
                int x = 0;
                while (!sr.EndOfStream)
                {
                    AllLines.Add(sr.ReadLine());
                    x += 1;
                }
                sr.Close();
            }

            Parallel.For(0, AllLines.Count, x =>
            {
                InsertDataCheck(AllLines[x]);
            });

        }
        GC.Collect();
        return true;
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    return false;
}

private void InsertDataCheck(string Line)
{
   //check if you want to insert data on the basis of your condition
   //and then insert your data
}
</code>```

Body:
Read the entire file into a string array object using the .Net ReadAllLines() method, then run a Parallel For loop to process all the lines in parallel.

private bool ProcessFile(string FolderPath, string FileExtension)
{
    try
    {
        //all files with requisite file extension
        DirectoryInfo dinfo = new DirectoryInfo(FolderPath);
        FileInfo[] Files = dinfo.GetFiles(FileExtension);
        foreach (FileInfo file in Files)
        {
            List<String> AllLines = new List<String>();
            using (StreamReader sr = File.OpenText(file.FullName))
            {
                int x = 0;
                while (!sr.EndOfStream)
                {
                    AllLines.Add(sr.ReadLine());
                    x += 1;
                }
                sr.Close();
            }

            Parallel.For(0, AllLines.Count, x =>
            {
                InsertDataCheck(AllLines[x]);
            });

        }
        GC.Collect();
        return true;
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    return false;
}

private void InsertDataCheck(string Line)
{
   //check if you want to insert data on the basis of your condition
   //and then insert your data
}


问:
.nextval JDBC insert problem
I try to insert into table with sequence .nextval as primary key, the sql in Java is

```<code>sql = "INSERT INTO USER
         (USER_PK, ACCOUNTNUMBER, FIRSTNAME, LASTNAME, EMAIL )
       VALUES
         (?,?,?,?,?)";
   ps = conn.prepareStatement(sql);
   ps.setString(1, "User.nextval");
   ps.setString(2, accountNumber);
   ps.setString(3, firstName);
   ps.setString(4, lastName);
   ps.setString(5, email);
</code>```

However, the error is ORA-01722: invalid number

All the other fields are correct, I think it is the problem of sequence, is this correct?

答:
The problem is that the first column is a numeric data type, but your prepared statement is submitting a string/VARCHAR data type.  The statement is run as-is, there's no opportunity for Oracle to convert your use of nextval to get the sequence value.

Here's an alternative via Java's PreparedStatement syntax:

```<code>sql = "INSERT INTO USER
        (USER_PK, ACCOUNTNUMBER, FIRSTNAME, LASTNAME, EMAIL )
       VALUES
        (user.nextval, ?, ?, ?, ?)";
ps = conn.prepareStatement(sql);
ps.setString(1, accountNumber);
ps.setString(2, firstName);
ps.setString(3, lastName);
ps.setString(4, email);
</code>```

This assumes that user is an existing sequence -- change to suit.

Title: .nextval JDBC insert problem

Body:
I try to insert into table with sequence .nextval as primary key, the sql in Java is

sql = "INSERT INTO USER
         (USER_PK, ACCOUNTNUMBER, FIRSTNAME, LASTNAME, EMAIL )
       VALUES
         (?,?,?,?,?)";
   ps = conn.prepareStatement(sql);
   ps.setString(1, "User.nextval");
   ps.setString(2, accountNumber);
   ps.setString(3, firstName);
   ps.setString(4, lastName);
   ps.setString(5, email);

However, the error is ORA-01722: invalid number

All the other fields are correct, I think it is the problem of sequence, is this correct?

Body:
The problem is that the first column is a numeric data type, but your prepared statement is submitting a string/VARCHAR data type.  The statement is run as-is, there's no opportunity for Oracle to convert your use of nextval to get the sequence value.

Here's an alternative via Java's PreparedStatement syntax:

sql = "INSERT INTO USER
        (USER_PK, ACCOUNTNUMBER, FIRSTNAME, LASTNAME, EMAIL )
       VALUES
        (user.nextval, ?, ?, ?, ?)";
ps = conn.prepareStatement(sql);
ps.setString(1, accountNumber);
ps.setString(2, firstName);
ps.setString(3, lastName);
ps.setString(4, email);

This assumes that user is an existing sequence -- change to suit.


问:
How to place the div around the div?
I want to design the
s using CSS like the following image. I didn’t get any clue. Please provide the idea for this design.

答:
To give you and idea, even though you should have tried something yourself.

What still has to be done is set the postions of all the arrows ...

.wrap {
  position: relative;
}

.wrap > div {
  position: absolute;
  width: 90px;
  height: 90px;
  background-color: #AFAFAF;
  border-radius: 50%;
}

.wrap > div.gray {
  position: absolute;
  top: 100px;
  left: 50px;
  width: 200px;
  height: 200px;
  background-color: #CFCFCF;
}

.wrap > div.gray:before {
  position: relative;
  top: -20px;
  left: -20px;
  content: '';
  display: block;
  width: 200px;
  height: 200px;
  border-radius: 50%;
  z-index: -1;
  border: solid 1px #CFCFCF;
  padding: 20px;
}

.wrap > div.orange {
  background-color: orange;
  top: 0px;
  left: 200px;
}
.wrap > div.green {
  background-color: green;
  top: 80px;
  left: 270px;
}
.wrap > div.purple {
  background-color: purple;
  top: 180px;
  left: 290px;
}
.wrap > div.blue {
  background-color: blue;
  top: 290px;
  left: 290px;
}

/* arrows */
.wrap > div:not(.gray):before {
  position: absolute;
  left: -40px;
  top: 60%;
  content: '';
  display: inline-block;
  width: 30px;
  height: 3px;
  background-color: inherit;
}
.wrap > div:not(.gray):after {
  position: absolute;
  content: '';
  display: block;
  width: 0;
  height: 0;
  border-style: solid;
  border-width: 0 10px 10px 10px;
  border-color: transparent transparent fuchsia transparent;
}

.wrap > div.orange:before {
  left: -40px;
  top: 100%;
  transform: rotate(-40deg);
}
.wrap > div.orange:after {
  left: -20px;
  top: 75px;
  transform: rotate(44deg);
  border-color: transparent transparent orange transparent;
}

.wrap > div.green:before {
  /* needs position and transform */
  /* see .wrap > div.orange:before {} */
}
.wrap > div.green:after {
  /* needs position, transform  and border-color */
  /* see .wrap > div.orange:after {} */
}

.wrap > div.purple:before {
  /* needs position and transform */
  /* see .wrap > div.orange:before {} */
}
.wrap > div.purple:after {
  /* needs position, transform  and border-color */
  /* see .wrap > div.orange:after {} */
}

.wrap > div.blue:before {
  /* needs position and transform */
  /* see .wrap > div.orange:before {} */
}
.wrap > div.blue:after {
  /* needs position, transform  and border-color */
  /* see .wrap > div.orange:after {} */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrap">
  <div class="gray"></div>
  <div class="orange"></div>
  <div class="green"></div>
  <div class="purple"></div>
  <div class="blue"></div>
</div></code>```

Title: How to place the div around the div?

Body:
To give you and idea, even though you should have tried something yourself.

What still has to be done is set the postions of all the arrows ...

.wrap {
  position: relative;
}

.wrap > div {
  position: absolute;
  width: 90px;
  height: 90px;
  background-color: #AFAFAF;
  border-radius: 50%;
}

.wrap > div.gray {
  position: absolute;
  top: 100px;
  left: 50px;
  width: 200px;
  height: 200px;
  background-color: #CFCFCF;
}

.wrap > div.gray:before {
  position: relative;
  top: -20px;
  left: -20px;
  content: '';
  display: block;
  width: 200px;
  height: 200px;
  border-radius: 50%;
  z-index: -1;
  border: solid 1px #CFCFCF;
  padding: 20px;
}

.wrap > div.orange {
  background-color: orange;
  top: 0px;
  left: 200px;
}
.wrap > div.green {
  background-color: green;
  top: 80px;
  left: 270px;
}
.wrap > div.purple {
  background-color: purple;
  top: 180px;
  left: 290px;
}
.wrap > div.blue {
  background-color: blue;
  top: 290px;
  left: 290px;
}

/* arrows */
.wrap > div:not(.gray):before {
  position: absolute;
  left: -40px;
  top: 60%;
  content: '';
  display: inline-block;
  width: 30px;
  height: 3px;
  background-color: inherit;
}
.wrap > div:not(.gray):after {
  position: absolute;
  content: '';
  display: block;
  width: 0;
  height: 0;
  border-style: solid;
  border-width: 0 10px 10px 10px;
  border-color: transparent transparent fuchsia transparent;
}

.wrap > div.orange:before {
  left: -40px;
  top: 100%;
  transform: rotate(-40deg);
}
.wrap > div.orange:after {
  left: -20px;
  top: 75px;
  transform: rotate(44deg);
  border-color: transparent transparent orange transparent;
}

.wrap > div.green:before {
  /* needs position and transform */
  /* see .wrap > div.orange:before {} */
}
.wrap > div.green:after {
  /* needs position, transform  and border-color */
  /* see .wrap > div.orange:after {} */
}

.wrap > div.purple:before {
  /* needs position and transform */
  /* see .wrap > div.orange:before {} */
}
.wrap > div.purple:after {
  /* needs position, transform  and border-color */
  /* see .wrap > div.orange:after {} */
}

.wrap > div.blue:before {
  /* needs position and transform */
  /* see .wrap > div.orange:before {} */
}
.wrap > div.blue:after {
  /* needs position, transform  and border-color */
  /* see .wrap > div.orange:after {} */
}

<div class="wrap">
  <div class="gray"></div>
  <div class="orange"></div>
  <div class="green"></div>
  <div class="purple"></div>
  <div class="blue"></div>
</div>


问:
Is there any way to get numbers separated by comma?
I have

```<code>line = "abcde:abc/abcd=(12, 20)"
</code>```

and I want to get 12 and 20 in an array. My solution is:

```<code>array_line = line[/\(.*?\)/].delete('()').delete(' ').split(",")
</code>```

Is there any better way to solve it using ruby?

答:
This one could be a good answer as well:</p>

```<code>line[/\((.*?)\)/, 1].delete(' ').split(",")
</code>```

Body:
I have

line = "abcde:abc/abcd=(12, 20)"

and I want to get 12 and 20 in an array. My solution is:

array_line = line[/\(.*?\)/].delete('()').delete(' ').split(",")

Is there any better way to solve it using ruby?

Body:
This one could be a good answer as well:

line[/\((.*?)\)/, 1].delete(' ').split(",")


问:
Why does Visual Studio give you Page_Load for WebForms as a default?
When creating a new WebForm, Visual Studios creates a Page_Load handler in the code behind as a default, which is cool.  So for years, I have always put code for doing things like set properties of controls in Page_Load.  Recently, I used Reflector to look at some assemblies written by Microsoft and saw that they have put the same type of logic in a method called OnLoad (which supposedly raises the load event).  So I started to wonder, where is the best place really to set the properties of controls, in OnLoad or Page_Load?  Or in a different method altogether?  And if not Page_Load, why does Studio add that to the code behind?

My final thought:  Although I know that putting logic in OnLoad works fine, I will probably stick with Page_Load for now because that's conventional.  I asked the question really to find out if I had been missing out on something new after I started seeing OnLoad come up in other people's code.  Thank you all for your thoughtful answers!

答:
Typically, OnX methods are methods that raise the event X. They are kind of like the class' internal event handlers. That means, when you code a class which, among other things, detects a certain event occuring, you'd typically call a method that: 1. does what your class needs to do in that case, 2. fires up the external event.

I believe one of the core reasons why this has caught on was that, as it stands, you can't just call the event delegate to fire an event, you have to always check if said delegate is null. So you want to encapsulate this check in a method.

In short, unless you're writing your own class that has a Load event, you don't need to think of an OnLoad method.

OwnerDisplayName: Barneytron

LastEditorDisplayName: Barneytron

OwnerDisplayName: Danut Enachioiu


问:
Only prints the last server in the list, I want all servers
This only prints the last server in the list, I'm looking to get all servers and print to screen </p>

```<code>$machines = (Get-BrokerMachine -AdminAddress $adminaddress -DesktopGroupName $deliverygroup | Select-Object DNSname).DNSname

foreach($machine in $machines){

$machinelist = Get-BrokerMachine -HostedMachineName $machine
    if($machinelist.InMaintenanceMode -eq $true){
        $status = "$machine is in maintenance mode"
        }else  {
        $status = "$machine is not in maintenance mode"
        }

}
Write-Host $status
</code>```

答:
another funky mode :

```<code>function get-BrokerMachineMode
{
    param (
        [Parameter(Mandatory = $true)]
        [string[]]$machines
    )
    begin
    {
        $ErrorActionPreference = 'Stop'
        Add-Type -Language CSharp @"
public class BrokenBroker {
        qpublic System.String MachineName;
        public System.String MaintenanceMode;

public  BrokenBroker (string MachineName, string MaintenanceMode)
    {
        this.MachineName  = MachineName;
        this.MaintenanceMode = IsInMaintenanceMode;
    }
}
"@

        $status = @()
        Write-Verbose "Created objects..."
    }
    process
    {
        try
        {
            $machines = (Get-BrokerMachine -AdminAddress $adminaddress `
                                           -DesktopGroupName $deliverygroup | Select-Object DNSname).DNSname

            foreach ($machine in $machines)
            {
                Write-Verbose "Checking machine: $machine"

                $machinelist = Get-BrokerMachine -HostedMachineName $machine

                if ($machinelist.InMaintenanceMode -eq $true)
                {
                    $status += New-Object BrokenBroker($machine, $true)
                }
                else
                {
                    $status += New-Object BrokenBroker($machine, $false)
                }

            }
        }
        catch
        {
            Write-Error $error[0].Exception.Message
        }
        $status
    }
    end
    {
        Write-Verbose "Done"
    }

}
</code>```

this is a function you just must to load then you can launch it just by using this command:

```<code>$computers = get-content = {PATH TO TXT FILE}
$list = get-BrokerMachineMode -machines $computers -Verbose
</code>```

Body:
This only prints the last server in the list, I'm looking to get all servers and print to screen

$machines = (Get-BrokerMachine -AdminAddress $adminaddress -DesktopGroupName $deliverygroup | Select-Object DNSname).DNSname

foreach($machine in $machines){

$machinelist = Get-BrokerMachine -HostedMachineName $machine
    if($machinelist.InMaintenanceMode -eq $true){
        $status = "$machine is in maintenance mode"
        }else  {
        $status = "$machine is not in maintenance mode"
        }

}
Write-Host $status

Body:
another funky mode :

function get-BrokerMachineMode
{
    param (
        [Parameter(Mandatory = $true)]
        [string[]]$machines
    )
    begin
    {
        $ErrorActionPreference = 'Stop'
        Add-Type -Language CSharp @"
public class BrokenBroker {
        qpublic System.String MachineName;
        public System.String MaintenanceMode;

public  BrokenBroker (string MachineName, string MaintenanceMode)
    {
        this.MachineName  = MachineName;
        this.MaintenanceMode = IsInMaintenanceMode;
    }
}
"@

        $status = @()
        Write-Verbose "Created objects..."
    }
    process
    {
        try
        {
            $machines = (Get-BrokerMachine -AdminAddress $adminaddress `
                                           -DesktopGroupName $deliverygroup | Select-Object DNSname).DNSname

            foreach ($machine in $machines)
            {
                Write-Verbose "Checking machine: $machine"

                $machinelist = Get-BrokerMachine -HostedMachineName $machine

                if ($machinelist.InMaintenanceMode -eq $true)
                {
                    $status += New-Object BrokenBroker($machine, $true)
                }
                else
                {
                    $status += New-Object BrokenBroker($machine, $false)
                }

            }
        }
        catch
        {
            Write-Error $error[0].Exception.Message
        }
        $status
    }
    end
    {
        Write-Verbose "Done"
    }

}

this is a function you just must to load then you can launch it just by using this command:

$computers = get-content = {PATH TO TXT FILE}
$list = get-BrokerMachineMode -machines $computers -Verbose


问:
Filter <select> options depending on chosen option from another <select>
I need a help with something :

I have two drop down menus (HTML select ) : State and City.

In state select elements, there are choices of different states .

In City there are options which are named in form : State-City (for example Brazil-Sao Paolo). In this second drop down there are all cities with all countries listed.

Now I need to do following :

When I pick up a State from first drop down, I need to make a kind of filter, so when i pick a Brazil from first drop down, second drop-down need to be automatically filtered to only cities which begins with Brazil-...

http://marbestates.com/

The searching form at the top of the page-please look city and location

I suppose that can be done with jQuery , but I need some hints, jsfiddle etc.

Thank you in advance

答:
```<code>$("#select1").change(function() {
if ($(this).data('options') === undefined) {
  /*Taking an array of all options-2 and kind of embedding it on the select1*/
 $(this).data('options', $('#select2 option').clone());
 }
 var id = $(this).val();
 var options = $(this).data('options').filter('[value=' + id + ']');
 $('#select2').html(options);
 });
</code>```


问:
Laravel version: 5.4.28 api routes not working on localhost
I downloaded Laravel 5.4.28 and created one api route. Nothing works on localhost. I am using XAMPP on Windows 8.1 as local development.

But everything is working fine on server. I also notice one strange thing. It will work on localhost if I create virtual host on localhost. like below.

```<code>php artisan serve
</code>```

Is that true? or Am I missing anything?

My api routes are like this...

http://localhost:1234/adminapi/public/api/v1/authenticateuser

答:
First of all you need to create virtual host for your project like yourprojectname.local. and test your app through this url.
If you not create virtualhost then you need to give whole path for access laravel api like localhost/yourprojectdirectory/public/adminapi/public/api/v1/authenticateuser
You can bellow link refer to the creating virtual host

http://foundationphp.com/tutorials/apache_vhosts.php

OR

How To Set Up Apache Virtual Hosts on XAMPP (Windows)

Body:
I downloaded Laravel 5.4.28 and created one api route. Nothing works on localhost. I am using XAMPP on Windows 8.1 as local development.

But everything is working fine on server. I also notice one strange thing. It will work on localhost if I create virtual host on localhost. like below.

php artisan serve

Is that true? or Am I missing anything?

My api routes are like this...

http://localhost:1234/adminapi/public/api/v1/authenticateuser


问:
Retrofit2 - Requests are always status 404 and the response null
I saw 3 other SO posts regarding this but the solutions didn't work. Every endpoint is returned as status code 404 and the response is null in retrofit2. This is my retrofit implementation:

RetrofitService:

```<code>//code setup for HTTP client for Retrofit goes here
......
......
public static void initRetrofit() {
        builder =
                new Retrofit.Builder()
                        .baseUrl(BuildConfig.BASE_URL)
          .addConverterFactory(GsonConverterFactory.create(initGson()));
}
</code>```

BuildConfig

```<code>buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            buildConfigField "String", "BASE_URL", "\"http://MY_SERVICE.azurewebsites.net\""
        }
        debug {
            versionNameSuffix ".staging"
            buildConfigField "String", "BASE_URL", "\"http://MY_SERVICE.azurewebsites.net\""
        }
}
</code>```

Endpoints:

```<code>public interface APIServices {

    @POST("api/users/register.json")
    Call<HttpResponse<Auth>> register(@Body RegisterData data);

}
</code>```

What am I doing wrong here? Other SO threads suggested to remove the / of /api from the /api/users/register.json, which I did and yet no change in the response.

答:
Retrofit2 base url should end with a trailing slash. Try adding it:</p>

```<code>buildConfigField "String", "BASE_URL", "\"http://MY_SERVICE.azurewebsites.net/\""
</code>```

Body:
I saw 3 other SO posts regarding this but the solutions didn't work. Every endpoint is returned as status code 404 and the response is null in retrofit2. This is my retrofit implementation:

RetrofitService:

//code setup for HTTP client for Retrofit goes here
......
......
public static void initRetrofit() {
        builder =
                new Retrofit.Builder()
                        .baseUrl(BuildConfig.BASE_URL)
          .addConverterFactory(GsonConverterFactory.create(initGson()));
}

BuildConfig

buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            buildConfigField "String", "BASE_URL", "\"http://MY_SERVICE.azurewebsites.net\""
        }
        debug {
            versionNameSuffix ".staging"
            buildConfigField "String", "BASE_URL", "\"http://MY_SERVICE.azurewebsites.net\""
        }
}

Endpoints:

public interface APIServices {

    @POST("api/users/register.json")
    Call<HttpResponse<Auth>> register(@Body RegisterData data);

}

What am I doing wrong here? Other SO threads suggested to remove the / of /api from the /api/users/register.json, which I did and yet no change in the response.

Body:
Retrofit2 base url should end with a trailing slash. Try adding it:

buildConfigField "String", "BASE_URL", "\"http://MY_SERVICE.azurewebsites.net/\""


答:
Well, not with arrows but I think this is a good start to learn.

EDIT: Added some arrows.

#bigGrayOneBox {
    position: absolute;
}

#bigGrayOne {
    width: 100px;
    height: 100px;
    background-color: #E9E9E9;
    border-radius: 100%;
    border: 10px solid white;
    position: relative;
    top: 100px;
}

#bigGrayOne:after {
    border-radius: 100%;
    position: absolute;
    width: 118px;
    height: 118px;
    border: 1px solid #E9E9E9;
    content: "";
    z-index: 1;
    top: -10px;
    left: -10px;
}

#yellow,
#green,
#purple,
#blue {
    width: 50px;
    height: 50px;
    border-radius: 100%;
    position: absolute;
}

#yellow {
    background-color: #E2A213;
    top: 35px;
    left: 100px;
}

#yellow::before {
    content: '';
    left: -18px;
    top: 69px;
    transform: rotate(-58deg);
    width: 30px;
    height: 5px;
    display: block;
    background-color: #E2A213;
    position: absolute;
    z-index: 1;
}

#yellow::after {
    content: "";
    transform: rotate(28deg);
    border-color: transparent transparent #E2A213 transparent;
    display: block;
    border-width: 10px;
    border-style: solid;
    width: 0px;
    position: absolute;
    top: 43px;
    left: -2px;
}

#green {
    background-color: #00A19A;
    top: 100px;
    left: 160px;
}

#green::before {
    content: '';
    left: -43px;
    top: 40px;
    transform: rotate(-18deg);
    width: 30px;
    height: 5px;
    display: block;
    background-color: #00A19A;
    position: absolute;
    z-index: 1;
}

#green::after {
    content: "";
    transform: rotate(73deg);
    border-color: transparent transparent #00A19A transparent;
    display: block;
    border-width: 10px;
    border-style: solid;
    width: 0px;
    position: absolute;
    top: 25px;
    left: -15px;
}

#purple {
    background-color: #D63080;
    top: 180px;
    left: 160px;
}

#purple::before {
    content: '';
    left: -41px;
    top: 5px;
    transform: rotate(19deg);
    width: 30px;
    height: 5px;
    display: block;
    background-color: #D63080;
    position: absolute;
    z-index: 1;
}

#purple::after {
    content: "";
    transform: rotate(107deg);
    border-color: transparent transparent #D63080 transparent;
    display: block;
    border-width: 10px;
    border-style: solid;
    width: 0px;
    position: absolute;
    top: 6px;
    left: -13px;
}

#blue {
    background-color: #173DC6;
    top: 245px;
    left: 105px;
}

#blue::before {
    content: '';
    left: -16px;
    top: -22px;
    transform: rotate(61deg);
    width: 30px;
    height: 5px;
    display: block;
    background-color: #173DC6;
    position: absolute;
    z-index: 1;
}

#blue::after {
    content: "";
    transform: rotate(148deg);
    border-color: transparent transparent #173DC6 transparent;
    display: block;
    border-width: 10px;
    border-style: solid;
    width: 0px;
    position: absolute;
    top: -8px;
    left: 1px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="bigGrayOneBox">
    <div id="bigGrayOne">
    </div>
</div>
<div id="yellow">
</div>
<div id="green">
</div>
<div id="purple">
</div>
<div id="blue">
</div></code>```

Title: How to place the div around the div?

Body:
I want to design the
s using CSS like the following image. I didn’t get any clue. Please provide the idea for this design.

Body:
Well, not with arrows but I think this is a good start to learn.

EDIT: Added some arrows.

#bigGrayOneBox {
    position: absolute;
}

#bigGrayOne {
    width: 100px;
    height: 100px;
    background-color: #E9E9E9;
    border-radius: 100%;
    border: 10px solid white;
    position: relative;
    top: 100px;
}

#bigGrayOne:after {
    border-radius: 100%;
    position: absolute;
    width: 118px;
    height: 118px;
    border: 1px solid #E9E9E9;
    content: "";
    z-index: 1;
    top: -10px;
    left: -10px;
}

#yellow,
#green,
#purple,
#blue {
    width: 50px;
    height: 50px;
    border-radius: 100%;
    position: absolute;
}

#yellow {
    background-color: #E2A213;
    top: 35px;
    left: 100px;
}

#yellow::before {
    content: '';
    left: -18px;
    top: 69px;
    transform: rotate(-58deg);
    width: 30px;
    height: 5px;
    display: block;
    background-color: #E2A213;
    position: absolute;
    z-index: 1;
}

#yellow::after {
    content: "";
    transform: rotate(28deg);
    border-color: transparent transparent #E2A213 transparent;
    display: block;
    border-width: 10px;
    border-style: solid;
    width: 0px;
    position: absolute;
    top: 43px;
    left: -2px;
}

#green {
    background-color: #00A19A;
    top: 100px;
    left: 160px;
}

#green::before {
    content: '';
    left: -43px;
    top: 40px;
    transform: rotate(-18deg);
    width: 30px;
    height: 5px;
    display: block;
    background-color: #00A19A;
    position: absolute;
    z-index: 1;
}

#green::after {
    content: "";
    transform: rotate(73deg);
    border-color: transparent transparent #00A19A transparent;
    display: block;
    border-width: 10px;
    border-style: solid;
    width: 0px;
    position: absolute;
    top: 25px;
    left: -15px;
}

#purple {
    background-color: #D63080;
    top: 180px;
    left: 160px;
}

#purple::before {
    content: '';
    left: -41px;
    top: 5px;
    transform: rotate(19deg);
    width: 30px;
    height: 5px;
    display: block;
    background-color: #D63080;
    position: absolute;
    z-index: 1;
}

#purple::after {
    content: "";
    transform: rotate(107deg);
    border-color: transparent transparent #D63080 transparent;
    display: block;
    border-width: 10px;
    border-style: solid;
    width: 0px;
    position: absolute;
    top: 6px;
    left: -13px;
}

#blue {
    background-color: #173DC6;
    top: 245px;
    left: 105px;
}

#blue::before {
    content: '';
    left: -16px;
    top: -22px;
    transform: rotate(61deg);
    width: 30px;
    height: 5px;
    display: block;
    background-color: #173DC6;
    position: absolute;
    z-index: 1;
}

#blue::after {
    content: "";
    transform: rotate(148deg);
    border-color: transparent transparent #173DC6 transparent;
    display: block;
    border-width: 10px;
    border-style: solid;
    width: 0px;
    position: absolute;
    top: -8px;
    left: 1px;
}

<div id="bigGrayOneBox">
    <div id="bigGrayOne">
    </div>
</div>
<div id="yellow">
</div>
<div id="green">
</div>
<div id="purple">
</div>
<div id="blue">
</div>


问:
Python 2 to 3 error
I am trying to convert Python 2 to Python 3 and get the following error:

File "xenia-build", line 48, in main
    vs_version = import_vs_environment()
  File "xenia-build", line 106, in import_vs_environment
TypeError: Type str doesn't support the buffer API

```<code> # Grab Visual Studio version and execute shell to set up environment.
if sys.platform == 'win32':
vs_version = import_vs_environment()
if vs_version == None:
  print('ERROR: Visual Studio not found!')
  print('Please refer to the building guide:')
  print('  https://github.com/benvanik/xenia/blob/master/docs/building.md')
  sys.exit(1)
  return

def import_vs_environment():
"""Finds the installed Visual Studio version and imports
interesting environment variables into os.environ.

Returns:
A version such as 2015 or None if no VS is found.
"""
version = 0

 candidate_path = subprocess.check_output('third_party/vswhere/vswhere.exe -version "[15,)" -latest -format value -property installationPath', shell=False)
 candidate_path = candidate_path.strip()
 tools_path = ''
if candidate_path:
tools_path = os.path.join  (candidate_path, 'vc\\auxiliary\\build\\vcvarsall.bat')
if os.path.isfile(tools_path) and os.access(tools_path, os.X_OK):
  version = 2017
if version == 0 and 'VS140COMNTOOLS' in os.environ:
version = 2015
tools_path = os.environ['VS140COMNTOOLS']
tools_path = os.path.join(tools_path, '..\\..\\vc\\vcvarsall.bat')
if version == 0:
return None
</code>```

答:
I think import_os_environment is returning a byte instead of string. In Python3, subprocess.Popen anything would return a byte.

Try using vs_version = import_os_environment().decode('utf-8')

One suggestion, if not vs_version: is more pythonic than checking if vs_version == None.

Title: Python 2 to 3 error

Body:
I am trying to convert Python 2 to Python 3 and get the following error:

File "xenia-build", line 48, in main
    vs_version = import_vs_environment()
  File "xenia-build", line 106, in import_vs_environment
TypeError: Type str doesn't support the buffer API

 # Grab Visual Studio version and execute shell to set up environment.
if sys.platform == 'win32':
vs_version = import_vs_environment()
if vs_version == None:
  print('ERROR: Visual Studio not found!')
  print('Please refer to the building guide:')
  print('  https://github.com/benvanik/xenia/blob/master/docs/building.md')
  sys.exit(1)
  return

def import_vs_environment():
"""Finds the installed Visual Studio version and imports
interesting environment variables into os.environ.

Returns:
A version such as 2015 or None if no VS is found.
"""
version = 0

 candidate_path = subprocess.check_output('third_party/vswhere/vswhere.exe -version "[15,)" -latest -format value -property installationPath', shell=False)
 candidate_path = candidate_path.strip()
 tools_path = ''
if candidate_path:
tools_path = os.path.join  (candidate_path, 'vc\\auxiliary\\build\\vcvarsall.bat')
if os.path.isfile(tools_path) and os.access(tools_path, os.X_OK):
  version = 2017
if version == 0 and 'VS140COMNTOOLS' in os.environ:
version = 2015
tools_path = os.environ['VS140COMNTOOLS']
tools_path = os.path.join(tools_path, '..\\..\\vc\\vcvarsall.bat')
if version == 0:
return None


问:
Ionic 2: Removing login page from navigation stack, causes nav.push cease to work in Dashboard page
I am having this weird issue. When user logs in, user is forwarded to dashboard. But before this I remove login page from navigation stack so that when user
presses hardware back button they are not taken back to login page (as they're already logged in).

Following is my  login method of login page

```<code>loginUser(){
    this.loading=this.loadingctrl.create({
            content:"Logging in, please wait..."
     });

     this.loading.present();

     this.ajaxRequest = this.webservice.loginUser(params).subscribe(data => {
        this.loading.dismiss();
        if(data.status =="ok"){
            this.navctrl.push(DashboardPage).then(()=>{
                const index = this.viewCtrl.index;
                this.navctrl.remove(index);
                //Above two lines finds index of current page and removes current page, i.e. login page from navigation stack
            });
        }else{
            //show error alert
        }
     }, err =>{
        this.loading.dismiss();
     });

}
</code>```

This code works well but however encountered a weird issue

PROBLEM

Any button in dashboard, or in swipe menu doesn't work.
Each link/buttons calls some method which navigates to some other page. Example method -

```<code>gotoProductsPage(){
 console.log("method gotoProductsPage is called");
 this.navCtrl.push(ProductsPage);
}
</code>```

I can see the methods are being called because i can see log being printed in console. The only thing is this.navCtrl.push(ProductsPage);seems to be not working.

I did further test and commented the lines  const index = this.viewCtrl.index; and this.navctrl.remove(index); in login method of login page.
Now all the button works. But hardware back button takes user back to login page.
Can anybody enlighten me why my app is having this weird behavior??
Thanks

答:
There is no reason to manipulate the Navigation Stack by trying to get LoginPage index and removing it.
I suggest simply setting the DashboardPage as the root of the navigation stack.

```<code>if(data.status =="ok"){
            this.navctrl.setRoot(DashboardPage).then(()=>{
                console.log("done");
            });
}else{
            //show error alert
}
</code>```

Now it will not navigate to login page on back.

Body:
I am having this weird issue. When user logs in, user is forwarded to dashboard. But before this I remove login page from navigation stack so that when user
presses hardware back button they are not taken back to login page (as they're already logged in).

Following is my  login method of login page

loginUser(){
    this.loading=this.loadingctrl.create({
            content:"Logging in, please wait..."
     });

     this.loading.present();

     this.ajaxRequest = this.webservice.loginUser(params).subscribe(data => {
        this.loading.dismiss();
        if(data.status =="ok"){
            this.navctrl.push(DashboardPage).then(()=>{
                const index = this.viewCtrl.index;
                this.navctrl.remove(index);
                //Above two lines finds index of current page and removes current page, i.e. login page from navigation stack
            });
        }else{
            //show error alert
        }
     }, err =>{
        this.loading.dismiss();
     });

}

This code works well but however encountered a weird issue

PROBLEM

Any button in dashboard, or in swipe menu doesn't work.
Each link/buttons calls some method which navigates to some other page. Example method -

gotoProductsPage(){
 console.log("method gotoProductsPage is called");
 this.navCtrl.push(ProductsPage);
}

I can see the methods are being called because i can see log being printed in console. The only thing is this.navCtrl.push(ProductsPage);seems to be not working.

I did further test and commented the lines  const index = this.viewCtrl.index; and this.navctrl.remove(index); in login method of login page.
Now all the button works. But hardware back button takes user back to login page.
Can anybody enlighten me why my app is having this weird behavior??
Thanks

Body:
There is no reason to manipulate the Navigation Stack by trying to get LoginPage index and removing it.
I suggest simply setting the DashboardPage as the root of the navigation stack.

if(data.status =="ok"){
            this.navctrl.setRoot(DashboardPage).then(()=>{
                console.log("done");
            });
}else{
            //show error alert
}

Now it will not navigate to login page on back.


问:
Send HTTP post request to ASP.Net Web API using PHP
```<code><html>
 <body><input type="button" id="send" value="Send"></body>
</html>
</code>```

There'll be a button in my html,
When it's clicked, i'd like to connect to http://localhost:81/Help/Api/POST-Login
which is my api.
Then i'd like to post data to it.
Pretty confused now, any ideas guys. Thanks in advance

```<code><?php

$url = "http://localhost:81/Help/Api/POST-Login";

$data = array(
 'message'      => 'hi,
  mobile'    => 12345678,

);
$options = array(
'http' => array(
'method'  => 'POST',
'content' => json_encode( $data ),
'header'=>  "Content-Type: application/json\r\n" .
            "Accept: application/json\r\n"
)
);

$context  = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
$response = json_decode( $result );
</code>```

答:
Use the below code to get the response from .NET API:</p>

```<code>$url = "http://localhost:81/Help/Api/POST-Login";

$data = array(  'message'      => 'hi,   mobile'    => 12345678,

);

$options = array(
        CURLOPT_CUSTOMREQUEST => "POST", //set request type post or get
        CURLOPT_POST => false, //set to GET
        CURLOPT_COOKIEFILE => "cookie.txt", //set cookie file
        CURLOPT_COOKIEJAR => "cookie.txt", //set cookie jar
        CURLOPT_RETURNTRANSFER => true, // return web page
        CURLOPT_HEADER => false, // don't return headers
        CURLOPT_FOLLOWLOCATION => true, // follow redirects
        CURLOPT_ENCODING => "", // handle all encodings
        CURLOPT_AUTOREFERER => true, // set referer on redirect
        CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
        CURLOPT_TIMEOUT => 120, // timeout on response
        CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => $data
    );

    $ch = curl_init($url);
    curl_setopt_array($ch, $options);
    $content = curl_exec($ch);
    $err = curl_errno($ch);
    $errmsg = curl_error($ch);
    $header = curl_getinfo($ch);
    curl_close($ch);

    $header['errno'] = $err;
    $header['errmsg'] = $errmsg;
    $header['content'] = $content;

echo $header['content'];
</code>```

Body:
 <input type="button" id="send" value="Send">

There'll be a button in my html,
When it's clicked, i'd like to connect to http://localhost:81/Help/Api/POST-Login
which is my api.
Then i'd like to post data to it.
Pretty confused now, any ideas guys. Thanks in advance

<?php

$url = "http://localhost:81/Help/Api/POST-Login";

$data = array(
 'message'      => 'hi,
  mobile'    => 12345678,

);
$options = array(
'http' => array(
'method'  => 'POST',
'content' => json_encode( $data ),
'header'=>  "Content-Type: application/json\r\n" .
            "Accept: application/json\r\n"
)
);

$context  = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
$response = json_decode( $result );

Body:
Use the below code to get the response from .NET API:

$url = "http://localhost:81/Help/Api/POST-Login";

$data = array(  'message'      => 'hi,   mobile'    => 12345678,

);

$options = array(
        CURLOPT_CUSTOMREQUEST => "POST", //set request type post or get
        CURLOPT_POST => false, //set to GET
        CURLOPT_COOKIEFILE => "cookie.txt", //set cookie file
        CURLOPT_COOKIEJAR => "cookie.txt", //set cookie jar
        CURLOPT_RETURNTRANSFER => true, // return web page
        CURLOPT_HEADER => false, // don't return headers
        CURLOPT_FOLLOWLOCATION => true, // follow redirects
        CURLOPT_ENCODING => "", // handle all encodings
        CURLOPT_AUTOREFERER => true, // set referer on redirect
        CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
        CURLOPT_TIMEOUT => 120, // timeout on response
        CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => $data
    );

    $ch = curl_init($url);
    curl_setopt_array($ch, $options);
    $content = curl_exec($ch);
    $err = curl_errno($ch);
    $errmsg = curl_error($ch);
    $header = curl_getinfo($ch);
    curl_close($ch);

    $header['errno'] = $err;
    $header['errmsg'] = $errmsg;
    $header['content'] = $content;

echo $header['content'];


问:
Show all drawable content in Android Studio
In my project I have got a lot of drawable content, and when I need to add new images to drawable I can put a same resource because I forget I have it already.

It is not about preview on XML file, this works well.

Any features in Android Studio to preview all my drawable contents without double-click on every resource? It can save lots of time.

I didn't find anything at Preferences, maybe some plugin or did I miss something?

答: Right click on drawable folder and click 'Show Image Thumbnails'.

ContentLicense: CC BY-SA 4.0


问:
Syntax for strings list with unrepr mode
It works with digit list; I tried with single and double quote without success.

```<code>from configobj import ConfigObj, ConfigObjError
from io import StringIO

specs= """\
Number= [6, 8]
Electric= [`battery`, `solar_panel`]
"""

car1="""\
Number= 6
Electric= battery
"""

car2= """\
Number= 8
Electric= solar_panel
"""

class Processing():
    def __init__(self, car):
        super().__init__()
        try:
            ConfigObj(StringIO(car), configspec= StringIO(specs), unrepr= True)
        except ConfigObjError as e:
            print(e)

if __name__ == "__main__":
    Processing(car1)
    Processing(car2)
</code>```

Result:

Parse error from unrepr-ing value at line 2.
Parse error from unrepr-ing value at line 2.
```

答:
With the unrepr set to true, you must indicate that Electric is given a string. So, you must write:</p>

```<code>car1="""\
Number= 6
Electric= 'battery'
"""

car2= """\
Number= 8
Electric= 'solar_panel'
"""
</code>```

Body:
It works with digit list; I tried with single and double quote without success.

from configobj import ConfigObj, ConfigObjError
from io import StringIO

specs= """\
Number= [6, 8]
Electric= [`battery`, `solar_panel`]
"""

car1="""\
Number= 6
Electric= battery
"""

car2= """\
Number= 8
Electric= solar_panel
"""

class Processing():
    def __init__(self, car):
        super().__init__()
        try:
            ConfigObj(StringIO(car), configspec= StringIO(specs), unrepr= True)
        except ConfigObjError as e:
            print(e)

if __name__ == "__main__":
    Processing(car1)
    Processing(car2)

Result:

Parse error from unrepr-ing value at line 2.
Parse error from unrepr-ing value at line 2.

Body:
With the unrepr set to true, you must indicate that Electric is given a string. So, you must write:

car1="""\
Number= 6
Electric= 'battery'
"""

car2= """\
Number= 8
Electric= 'solar_panel'
"""


问:
Crosstab Dataframe with resampled datetime from table file
Given a file like this:

```<code>date    uselessinfo category    uselessinfo2
2011-07-22 02:56:36 banana  1   apple
2011-02-27 17:15:44 banana  4   apple
2010-12-12 00:13:42 banana  1   apple
2010-10-12 00:13:00 banana  2   apple
</code>```

I am using pandas to build a DataFrame:

```<code>data = pd.read_table(pathToFile, "\t")
</code>```

From this I try to use simple pandas methods to build a crosstab matrix like:

```<code>        1   2   3   4

2010    1   1   0   0
2011    1   0   0   1
</code>```

Where columns are categories, rows are dates bins and values are the occurrence of categories in these bins

My problem is that I don't know how to bin the datetimes either by years or month and then build the crosstab matrix.
I have seen on stackoverflow that the re-sampling function is the best way to bin datetimes and crosstab to then build the matrix:

```<code>data = data.resample('M', on='date').sum()
data = pd.crosstab(data.date,data.category)
</code>```

Is there a way to combine these two functions to get the desired matrix ? Or am I totally doing wrong ?

The goal to achieve is to use this matrix to plot a seaborn heatmap looking like:

答:
It seems you need convert date to year:

```<code>data = pd.read_table(pathToFile, "\t", parse_dates=['date'])

data = pd.crosstab(data.date.dt.year ,data.category)

print (data)
category  1  2  4
date
2010      1  1  0
2011      1  0  1
</code>```

But if need resample first by months:

```<code>data = data.resample('M', on='date').sum().reset_index()
data = pd.crosstab(data.date.dt.year,data.category)
</code>```

Difference best seen if chagned data:

```<code>print (data)
                 date uselessinfo  category uselessinfo2
0 2011-07-22 02:56:36      banana         1        apple
1 2011-07-27 02:56:36      banana         7        apple
2 2011-08-27 17:15:44      banana         4        apple
3 2011-09-12 00:13:42      banana         1        apple
4 2011-09-12 00:13:00      banana         2        apple

data = data.resample('M', on='date').sum().reset_index()
data = pd.crosstab(data.date.dt.year,data.category)
print (data)
category  3  4  8
date
2011      1  1  1
</code>```

```<code>data = pd.crosstab(data.date.dt.year,data.category)
print (data)
category  1  2  4  7
date
2011      2  1  1  1
</code>```

Body:
Given a file like this:

date    uselessinfo category    uselessinfo2
2011-07-22 02:56:36 banana  1   apple
2011-02-27 17:15:44 banana  4   apple
2010-12-12 00:13:42 banana  1   apple
2010-10-12 00:13:00 banana  2   apple

I am using pandas to build a DataFrame:

data = pd.read_table(pathToFile, "\t")

From this I try to use simple pandas methods to build a crosstab matrix like:

        1   2   3   4

2010    1   1   0   0
2011    1   0   0   1

Where columns are categories, rows are dates bins and values are the occurrence of categories in these bins

My problem is that I don't know how to bin the datetimes either by years or month and then build the crosstab matrix.
I have seen on stackoverflow that the re-sampling function is the best way to bin datetimes and crosstab to then build the matrix:

data = data.resample('M', on='date').sum()
data = pd.crosstab(data.date,data.category)

Is there a way to combine these two functions to get the desired matrix ? Or am I totally doing wrong ?

The goal to achieve is to use this matrix to plot a seaborn heatmap looking like:

Body:
It seems you need convert date to year:

data = pd.read_table(pathToFile, "\t", parse_dates=['date'])

data = pd.crosstab(data.date.dt.year ,data.category)

print (data)
category  1  2  4
date
2010      1  1  0
2011      1  0  1

But if need resample first by months:

data = data.resample('M', on='date').sum().reset_index()
data = pd.crosstab(data.date.dt.year,data.category)

Difference best seen if chagned data:

print (data)
                 date uselessinfo  category uselessinfo2
0 2011-07-22 02:56:36      banana         1        apple
1 2011-07-27 02:56:36      banana         7        apple
2 2011-08-27 17:15:44      banana         4        apple
3 2011-09-12 00:13:42      banana         1        apple
4 2011-09-12 00:13:00      banana         2        apple

data = data.resample('M', on='date').sum().reset_index()
data = pd.crosstab(data.date.dt.year,data.category)
print (data)
category  3  4  8
date
2011      1  1  1

data = pd.crosstab(data.date.dt.year,data.category)
print (data)
category  1  2  4  7
date
2011      2  1  1  1


问:
Ordered associative containers with identity-based equality
I am writing a template function, with template argument X. Inside that function, I want to create std::set<std::pair<int, X>> such that:

objects in that set are sorted by the first (int) field of the pair (I don't care about how ties are broken)

I can add multiple objects with the same .first to the set, as long as their .second are not identical

If I knew that template argument X always has < defined, the most basic std::set<std::pair<int, X> (with the default comparator) would have worked perfectly fine. Unfortunately, I cannot assume anything about X.

I was thinking to "cheat" and use pointer-based comparison for the X field:

```<code>template <typename X>
struct DistCmp {
    bool operator()(const std::pair<int, X>& lhs, const std::pair<int, X>& rhs) const {
        return lhs.first < rhs.first || lhs.first == rhs.first && &lhs.second < &rhs.second;
    }
};

template <typename X>
void f() {
    std::set<std::pair<int, X>, DistCmp<X>> s{};
    // ...
}
</code>```

(After all, I don't really care how the .second is compared, as long as it's not compared equally for non-identical objects.)

Unfortunately, I don't think it's correct. Partly because of the quote from C++ standard here (it suggests that pointer comparison, in general, is unspecified, so I can't rely on them being unequal for non-identical objects). And partly I just feel it's suspicious/hacky.

Is there any clean/portable solution for this issue?

Update:

One approach I thought about was to use == for the comparison of pointers instead of <. However, this is no good because it will cause pair<1, x> < pair<1, y> && pair<1, y> < pair<1, x> to be true. This violates the requirement of strict weak ordering and may cause stuff to break.

答:
Short answer: use std::multiset and sidestep whole issue - multiset allows multiple keys, so just compare on first element of pair.

Note, that if you want to disallow the same VALUE of X in your map, you've to add requirement to X, so it were at least EqualityComparable. Otherwise you can't even detect, when values of X are the same and when are different.

Longer answer:
Your code won't produce the result you're hoping for. Consider adding new pair <0, x> to map with <0, x>. std::map will try to find existence of <0, x> using temporary copy of <0, x>. It will use address of x (temporary!), it will compare false to everything, that is inside in map and std::map will find a place to insert based on address of x (temporary!). Then it will COPY x, thus changing address and possibly breaking its own ordering.

Body:
I am writing a template function, with template argument X. Inside that function, I want to create std::set<std::pair<int, X>> such that:

objects in that set are sorted by the first (int) field of the pair (I don't care about how ties are broken)

I can add multiple objects with the same .first to the set, as long as their .second are not identical

If I knew that template argument X always has < defined, the most basic std::set<std::pair<int, X> (with the default comparator) would have worked perfectly fine. Unfortunately, I cannot assume anything about X.

I was thinking to "cheat" and use pointer-based comparison for the X field:

template <typename X>
struct DistCmp {
    bool operator()(const std::pair<int, X>& lhs, const std::pair<int, X>& rhs) const {
        return lhs.first < rhs.first || lhs.first == rhs.first && &lhs.second < &rhs.second;
    }
};

template <typename X>
void f() {
    std::set<std::pair<int, X>, DistCmp<X>> s{};
    // ...
}

(After all, I don't really care how the .second is compared, as long as it's not compared equally for non-identical objects.)

Unfortunately, I don't think it's correct. Partly because of the quote from C++ standard here (it suggests that pointer comparison, in general, is unspecified, so I can't rely on them being unequal for non-identical objects). And partly I just feel it's suspicious/hacky.

Is there any clean/portable solution for this issue?

Update:

One approach I thought about was to use == for the comparison of pointers instead of <. However, this is no good because it will cause pair<1, x> < pair<1, y> && pair<1, y> < pair<1, x> to be true. This violates the requirement of strict weak ordering and may cause stuff to break.


问:
OnclickListener on RecylerView and getting the Id of clicked Item
I need to set onClickListener on RecyclerView which gets the Json Id of an Item Clicked and redirects to the fragment which displays the details of the product based on that Json ID.  How Can I implement this in adapter? I am stuck here. I was able to set onClickListener but I couldn't get the Json ID.

This is my Adapter.

```<code>import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.dell.retroexample.MainActivity;
import com.example.dell.retroexample.R;
import com.example.dell.retroexample.apiHandlers.model.Ad;

import java.util.List;

/**
 * Created by dell on 7/3/2017.
 */

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder>{

    private List<Ad> ads;
    private Context context;

    public RecyclerAdapter(List<Ad> ads, Context context){
        this.ads=ads;
        this.context=context;

    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_item_ads, parent,false);
        return  new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        holder.name.setText(ads.get(position).getTitle());
        holder.details.setText("Rs. " +ads.get(position).getPrice().toString()+ "/-");
//        Glide.with(context).load(ads.get(position).getPhoto1()).into(holder.thumbnail);

    }

    @Override
    public int getItemCount() {
        return ads.size();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        ImageView thumbnail;
        TextView name, details;
        public MyViewHolder(View itemView) {
            super(itemView);
//            thumbnail=(ImageView)itemView.findViewById(R.id.thumbnail);
            name=(TextView)itemView.findViewById(R.id.title);
            details=(TextView)itemView.findViewById(R.id.price);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            Toast.makeText(view.getContext(), "Clicked on Recycler View" , Toast.LENGTH_SHORT).show();
        }

    }
}
</code>```

This is my MainActivity

```<code>package com.example.dell.retroexample;

import android.content.res.Resources;
import android.graphics.Rect;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;

import com.example.dell.retroexample.apiHandlers.adapter.RecyclerAdapter;
import com.example.dell.retroexample.apiHandlers.model.Ad;
import com.example.dell.retroexample.apiHandlers.rest.ApiInterface;
import com.example.dell.retroexample.apiHandlers.rest.ApiClient;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getSimpleName();
    private RecyclerView recyclerView;
    private RecyclerView.LayoutManager layoutManager;
    private RecyclerAdapter adapter=null;
    private List<Ad> ads;
    private ApiInterface apiInterface;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView=(RecyclerView)findViewById(R.id.ads_recycler_view);
                // calculating the number of columns
        int columns=2;
        DisplayMetrics lDisplayMetrics = getResources().getDisplayMetrics();
        double widthPixels = lDisplayMetrics.widthPixels;
        Log.e("Width", String.valueOf(widthPixels));
        columns=(int)widthPixels/dpToPx(170);

        RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this,  columns);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        apiInterface=ApiClient.getClient().create(ApiInterface.class);

        Call <List<Ad>> call=apiInterface.getads();

        call.enqueue(new Callback<List<Ad>>() {
            @Override
            public void onResponse(Call<List<Ad>> call, Response<List<Ad>> response) {
                ads=response.body();
                adapter=new RecyclerAdapter(ads, MainActivity.this);
                recyclerView.setAdapter(adapter);
            }

            @Override
            public void onFailure(Call<List<Ad>> call, Throwable t) {

                Log.e(TAG, t.toString());
            }
        });

    }

    private int dpToPx(int dp) {
        Resources r = getResources();
        return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
    }

}
</code>```

答:
Your adapter class should be like below.

You have to remove onClickListener from ViewHolder class. and set click in onBindViewHolder Method.

```<code>public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder>{

    private List<Ad> ads;
    private Context context;

    public RecyclerAdapter(List<Ad> ads, Context context){
        this.ads=ads;
        this.context=context;

    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_item_ads, parent,false);
        return  new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        holder.name.setText(ads.get(position).getTitle());
        holder.details.setText("Rs. " +ads.get(position).getPrice().toString()+ "/-");
//        Glide.with(context).load(ads.get(position).getPhoto1()).into(holder.thumbnail);
        holder.linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /*Write your code here to send data to fragment*/
                Ad ad = ads.get(position);
            }
        });

    }

    @Override
    public int getItemCount() {
        return ads.size();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder{

        ImageView thumbnail;
        TextView name, details;
        LinearLayout linearLayout;
        public MyViewHolder(View itemView) {
            super(itemView);
//            thumbnail=(ImageView)itemView.findViewById(R.id.thumbnail);
            name=(TextView)itemView.findViewById(R.id.title);
            details=(TextView)itemView.findViewById(R.id.price);
            linearLayout=(TextView)itemView.findViewById(R.id.linearLayout); // its your main layout
        }

    }
}
</code>```

Body:
I need to set onClickListener on RecyclerView which gets the Json Id of an Item Clicked and redirects to the fragment which displays the details of the product based on that Json ID.  How Can I implement this in adapter? I am stuck here. I was able to set onClickListener but I couldn't get the Json ID.

This is my Adapter.

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.dell.retroexample.MainActivity;
import com.example.dell.retroexample.R;
import com.example.dell.retroexample.apiHandlers.model.Ad;

import java.util.List;

/**
 * Created by dell on 7/3/2017.
 */

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder>{

    private List<Ad> ads;
    private Context context;

    public RecyclerAdapter(List<Ad> ads, Context context){
        this.ads=ads;
        this.context=context;

    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_item_ads, parent,false);
        return  new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        holder.name.setText(ads.get(position).getTitle());
        holder.details.setText("Rs. " +ads.get(position).getPrice().toString()+ "/-");
//        Glide.with(context).load(ads.get(position).getPhoto1()).into(holder.thumbnail);

    }

    @Override
    public int getItemCount() {
        return ads.size();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        ImageView thumbnail;
        TextView name, details;
        public MyViewHolder(View itemView) {
            super(itemView);
//            thumbnail=(ImageView)itemView.findViewById(R.id.thumbnail);
            name=(TextView)itemView.findViewById(R.id.title);
            details=(TextView)itemView.findViewById(R.id.price);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            Toast.makeText(view.getContext(), "Clicked on Recycler View" , Toast.LENGTH_SHORT).show();
        }

    }
}

This is my MainActivity

package com.example.dell.retroexample;

import android.content.res.Resources;
import android.graphics.Rect;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;

import com.example.dell.retroexample.apiHandlers.adapter.RecyclerAdapter;
import com.example.dell.retroexample.apiHandlers.model.Ad;
import com.example.dell.retroexample.apiHandlers.rest.ApiInterface;
import com.example.dell.retroexample.apiHandlers.rest.ApiClient;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getSimpleName();
    private RecyclerView recyclerView;
    private RecyclerView.LayoutManager layoutManager;
    private RecyclerAdapter adapter=null;
    private List<Ad> ads;
    private ApiInterface apiInterface;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView=(RecyclerView)findViewById(R.id.ads_recycler_view);
                // calculating the number of columns
        int columns=2;
        DisplayMetrics lDisplayMetrics = getResources().getDisplayMetrics();
        double widthPixels = lDisplayMetrics.widthPixels;
        Log.e("Width", String.valueOf(widthPixels));
        columns=(int)widthPixels/dpToPx(170);

        RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this,  columns);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        apiInterface=ApiClient.getClient().create(ApiInterface.class);

        Call <List<Ad>> call=apiInterface.getads();

        call.enqueue(new Callback<List<Ad>>() {
            @Override
            public void onResponse(Call<List<Ad>> call, Response<List<Ad>> response) {
                ads=response.body();
                adapter=new RecyclerAdapter(ads, MainActivity.this);
                recyclerView.setAdapter(adapter);
            }

            @Override
            public void onFailure(Call<List<Ad>> call, Throwable t) {

                Log.e(TAG, t.toString());
            }
        });

    }

    private int dpToPx(int dp) {
        Resources r = getResources();
        return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
    }

}

Body:
Your adapter class should be like below.

You have to remove onClickListener from ViewHolder class. and set click in onBindViewHolder Method.

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder>{

    private List<Ad> ads;
    private Context context;

    public RecyclerAdapter(List<Ad> ads, Context context){
        this.ads=ads;
        this.context=context;

    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_item_ads, parent,false);
        return  new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        holder.name.setText(ads.get(position).getTitle());
        holder.details.setText("Rs. " +ads.get(position).getPrice().toString()+ "/-");
//        Glide.with(context).load(ads.get(position).getPhoto1()).into(holder.thumbnail);
        holder.linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /*Write your code here to send data to fragment*/
                Ad ad = ads.get(position);
            }
        });

    }

    @Override
    public int getItemCount() {
        return ads.size();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder{

        ImageView thumbnail;
        TextView name, details;
        LinearLayout linearLayout;
        public MyViewHolder(View itemView) {
            super(itemView);
//            thumbnail=(ImageView)itemView.findViewById(R.id.thumbnail);
            name=(TextView)itemView.findViewById(R.id.title);
            details=(TextView)itemView.findViewById(R.id.price);
            linearLayout=(TextView)itemView.findViewById(R.id.linearLayout); // its your main layout
        }

    }
}


问:
Is there any workaround for hg timing out on a push operation?
I'm trying to push to bitbucket, a changeset with several thousand files which were changed (I'm committing a huge library dependency). The commit on my local box worked just fine, but when I try to do the actual push, the operation times out (hg says "searching for changes" for a while, then the whole thing just collapses).

Obviously, I have absolutely no control over the server side.

Anything I can do in a scenario like this?

答: What does hg outgoing say? Also you could try to push partially hg push -r changeset_no, where changeset_no is any changeset from the middle of the all changesets need to be pushed.


问:
jquery:I want to make a particular table row readonly based on column td value. the td values have textboxes embedded into it using mvc
```<code>        var $row = $(this).closest("tr");      // Finds the closest row <tr>
        ($row).attr("readonly", true);
</code>```

I have to make table rows readonly based on td value or hidden field inside the table.kindly help

答:
Try the below one:</p>

```<code>$(function() {
  $('table tr').each(function() {
    $(this).find('td').each(function() {
        $(this).find('input,select,textarea').attr("readonly", true);
    });
  });
});
</code>```

Body:
        var $row = $(this).closest("tr");      // Finds the closest row

        ($row).attr("readonly", true);

I have to make table rows readonly based on td value or hidden field inside the table.kindly help

Body:
Try the below one:

$(function() {
  $('table tr').each(function() {
    $(this).find('td').each(function() {
        $(this).find('input,select,textarea').attr("readonly", true);
    });
  });
});