问:
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.

答:
The main problem, I believe, was that none of the SELECT elements had OPTION values. The call to session_start() should also be before any html output - so typically right at the very top of the script. Also, the call tha sets the session variables could set blank values as it was - a test to ensure the values are present before setting would be a good idea.

```<code><?php

    session_start();
    error_reporting(E_ALL);

    /* utility function to debug session and request data */
    function pre($data,$title){
        echo "<h1>".strtoupper($title)."</h1>```".print_r($data,true)."```";
    }
?>

<!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>
    <?php
        if( isset( $_SESSION['sesion_codigo'], $_SESSION['sesion_cedula'] ) ){
            echo '<h1>Debug session variables</h1>';
            pre($_SESSION,'session');
            pre($_POST,'post');

        }
    ?>

      <form method="post">
        <table>
             <tbody>
                <tr>
                   <td>Medicamento</td>
                   <td>
                      <select name="v_meds">
                         <option value=''>Seleccionar
                         <option value='Rojo'>Rojo
                         <option value='Verde'>Verde
                         <option value='Azul'>Azul
                         <option value='Amarillo'>Amarillo
                         <option value='Blanco'>Blanco
                         <option value='Negro'>Negro
                      </select>
                      <br>
                   </td>
                </tr>
                <tr>
                   <td>Via</td>
                   <td>
                      <select name="v_via">
                         <option value=''>Seleccionar
                         <option value='Oral'>Oral
                         <option value='Rectal'>Rectal
                         <option value='Nasal'>Nasal
                         <option value='Otica'>Otica
                         <option value='Oftalmica'>Oftalmica
                         <option value='Vaginal'>Vaginal
                         <option value='Topica'>Topica
                      </select>
                      <br>
                   </td>
                </tr>
                <tr>
                   <td>Frecuencia</td>
                   <td>
                      <select name="v_frec">
                         <option value=''>Seleccionar
                         <option value='6'>6
                         <option value='8'>8
                         <option value='12'>12
                         <option value='24'>24
                      </select>
                      <br>
                   </td>
                </tr>
                <tr>
                   <td>Duracion</td>
                   <td>
                      <select name="v_dur">
                         <option value=''>Seleccionar
                         <option value='5'>5
                         <option value='7'>7
                         <option value='15'>15
                         <option value='30'>30
                         <option value='PRN10'>PRN10
                         <option value='PRN20'>PRN20
                         <option value='PRN30'>PRN30
                      </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>
         </table>
      </form>

    <?php
        $codigo = !empty( $_REQUEST['v_codigo'] ) ? $_REQUEST['v_codigo'] : false;
        $cedula = !empty( $_REQUEST['v_cedula'] ) ? $_REQUEST['v_cedula'] : false;

        if( $codigo & $cedula ){

            $_SESSION['sesion_codigo'] = $codigo;
            $_SESSION['sesion_cedula'] = $cedula;

            $tabla = 'p'.$cedula1;

            printf( "Codigo: %s<br />Cedula: %s<br />", $codigo, $cedula );
        }

        if ( $_SERVER["REQUEST_METHOD"] == "POST" ) {

            $name1 = !empty( $_POST['v_meds'] ) ? $_POST['v_meds'] : false;
            $name2 = !empty( $_POST['v_via'] ) ? $_POST['v_via'] : false;
            $name3 = !empty( $_POST['v_frec'] ) ? $_POST['v_frec'] : false;
            $name4 = !empty( $_POST['v_dur'] ) ? $_POST['v_dur'] : false;

            if( $name1 && $name2 && $name3 && $name4 ){
                $message=$name1 . $name2 . $name3 . $name4;
            } else {
                $message="Receta contiene errores, favor llenar correctamente el formulario.<br/>";
            }

            echo $message;
        }

    ?>

   </body>
</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:
The main problem, I believe, was that none of the SELECT elements had OPTION values. The call to session_start() should also be before any html output - so typically right at the very top of the script. Also, the call tha sets the session variables could set blank values as it was - a test to ensure the values are present before setting would be a good idea.

<?php

    session_start();
    error_reporting(E_ALL);

    /* utility function to debug session and request data */
    function pre($data,$title){
        echo "<h1>".strtoupper($title)."</h1><pre>".print_r($data,true)."</pre>";
    }
?>

<!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>
    <?php
        if( isset( $_SESSION['sesion_codigo'], $_SESSION['sesion_cedula'] ) ){
            echo '<h1>Debug session variables</h1>';
            pre($_SESSION,'session');
            pre($_POST,'post');

        }
    ?>

      <form method="post">
        <table>
             <tbody>
                <tr>
                   <td>Medicamento</td>
                   <td>
                      <select name="v_meds">
                         <option value=''>Seleccionar
                         <option value='Rojo'>Rojo
                         <option value='Verde'>Verde
                         <option value='Azul'>Azul
                         <option value='Amarillo'>Amarillo
                         <option value='Blanco'>Blanco
                         <option value='Negro'>Negro
                      </select>
                      <br>
                   </td>
                </tr>
                <tr>
                   <td>Via</td>
                   <td>
                      <select name="v_via">
                         <option value=''>Seleccionar
                         <option value='Oral'>Oral
                         <option value='Rectal'>Rectal
                         <option value='Nasal'>Nasal
                         <option value='Otica'>Otica
                         <option value='Oftalmica'>Oftalmica
                         <option value='Vaginal'>Vaginal
                         <option value='Topica'>Topica
                      </select>
                      <br>
                   </td>
                </tr>
                <tr>
                   <td>Frecuencia</td>
                   <td>
                      <select name="v_frec">
                         <option value=''>Seleccionar
                         <option value='6'>6
                         <option value='8'>8
                         <option value='12'>12
                         <option value='24'>24
                      </select>
                      <br>
                   </td>
                </tr>
                <tr>
                   <td>Duracion</td>
                   <td>
                      <select name="v_dur">
                         <option value=''>Seleccionar
                         <option value='5'>5
                         <option value='7'>7
                         <option value='15'>15
                         <option value='30'>30
                         <option value='PRN10'>PRN10
                         <option value='PRN20'>PRN20
                         <option value='PRN30'>PRN30
                      </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">
                        <a href="view.php">Ver historial de recetas</a>
                    </td>
                </tr>
             </tbody>
         </table>
      </form>

    <?php
        $codigo = !empty( $_REQUEST['v_codigo'] ) ? $_REQUEST['v_codigo'] : false;
        $cedula = !empty( $_REQUEST['v_cedula'] ) ? $_REQUEST['v_cedula'] : false;

        if( $codigo & $cedula ){

            $_SESSION['sesion_codigo'] = $codigo;
            $_SESSION['sesion_cedula'] = $cedula;

            $tabla = 'p'.$cedula1;

            printf( "Codigo: %s<br />Cedula: %s<br />", $codigo, $cedula );
        }

        if ( $_SERVER["REQUEST_METHOD"] == "POST" ) {

            $name1 = !empty( $_POST['v_meds'] ) ? $_POST['v_meds'] : false;
            $name2 = !empty( $_POST['v_via'] ) ? $_POST['v_via'] : false;
            $name3 = !empty( $_POST['v_frec'] ) ? $_POST['v_frec'] : false;
            $name4 = !empty( $_POST['v_dur'] ) ? $_POST['v_dur'] : false;

            if( $name1 && $name2 && $name3 && $name4 ){
                $message=$name1 . $name2 . $name3 . $name4;
            } else {
                $message="Receta contiene errores, favor llenar correctamente el formulario.<br/>";
            }

            echo $message;
        }

    ?>

   </body>
</html>


来源: stackexchange

问:
Django Many to Many, ordering and serializing using REST
I was designing a system which allows users to select a number of objects (say 5) in a pre-configured ordered set of objects (count > 5). Basically, the user has to select top 5 objects in a set of 9. I have to save these entries and find out those objects which have the maximum votes (maximum selection) and a winner based on the most right entries.

My models:

```<code>class User(AbstractUser):
    '''Info about user '''

class Contest(models.Model):
    name = models.CharField(max_length=255)
    created = models.DateField(auto_now_add=True)

class ObjectsForContest(models.Model):
    name = models.CharField(max_length=255)
    contest = models.ManyToManyField('Contest', through='OrderedObjectsForContest')

class OrderedObjectsForContest(models.Model):
    choice = models.ForeignKey(ObjectsForContest)
    contest = models.ForeignKey(Contest, related_name='ordered_options')
    order = models.PositiveIntegerField()

    class Meta:
        ordering = ['order']

class UserEntriesForContest(models.Model):
    user = models.ForeignKey(User, related_name="entries_for_contest")
    contest = models.ForeignKey(Contest, related_name='participating_users')
    objects_selected = models.ManyToManyField(ObjectsForContest, through='OrderedChoicesByUser', null=True, blank=True)

    def __unicode__(self):
        return self.user.unique_id

class OrderedChoicesByUser(models.Model):
    choice = models.ForeignKey(ObjectsForContest)
    contest = models.ForeignKey(UserEntriesForContest)
    order = models.PositiveIntegerField()

    class Meta:
        ordering = ['order']
</code>```

My serializers are pretty straight forward.
Serializer:

```<code>class ContestObjectsSerializer(serializers.ModelSerializer):
    class Meta:
        model = ObjectsForContest
        exclude = ("contests", )

class ContestObjectsThroughSerializer(serializers.ModelSerializer):
    choice = ContestObjectsSerializer()

    class Meta:
        model = OrderedObjectsForContest
        exclude = ("id", )

class Contest(serializers.ModelSerializer):
    winner = SimpleUserProfileSerializer()  #this serializes the user and not included here.
    choices = ContestObjectsThroughSerializer(many=True)

    class Meta:
        model = Contest

class UserEntriesForContestSerializer(serializers.ModelSerializer):
    choices_made = ContestObjectsSerializer(many=True)

    class Meta:
        model = UserEntriesForContest
</code>```

How can I find the choice that has been selected by the maximum number of users according to their order?

Ex.
Objects according to contest: (Name, order)

```<code>(Apple, 1), (Orange, 2), (Grapes, 3), (Mango, 4), (Apricot, 5), (Cherry, 6), (Guava, 7), (Jackfruit, 8), (Lime, 9)
</code>```

Let us assume that there are 5 users whose choices are:

```<code>#User 1:
(Apple, 1), (Lime, 2), (Grapes, 3), (Mango, 4), (Apricot, 5)
#User 2:
(Apple, 1), (Orange, 2), (Lime, 3), (Mango, 4), (Apricot, 5)
#User 3:
(Apple, 1), (Orange, 2), (Grapes, 3), (Cherry, 4), (Apricot, 5)
#User 4:
(Apple, 1), (Orange, 2), (Lime, 3), (Cherry, 4), (Apricot, 5)
#User 5:
(Apple, 1), (Lime, 2), (Grapes, 3), (Cherry, 4), (Apricot, 5)
</code>```

The winning list should be:

```<code>(Apple, 1), (Orange, 2), (Grapes, 3), (Cherry, 3), (Apricot, 5)
</code>```

I need to know how can I get this list given my models.

答:
Many-to-Many Order can be done by SerializerMethodField in DRF

```<code>students_listss = serializers.SerializerMethodField('get_students_list')

def get_students_list(self, instance):
    return Student.objects\
        .filter()\
        .order_by('name')\
        .values_list('name', flat=True)
</code>```

you can apply order condition as usual in order_by()

ContentLicense: CC BY-SA 3.0

Body:
I was designing a system which allows users to select a number of objects (say 5) in a pre-configured ordered set of objects (count > 5). Basically, the user has to select top 5 objects in a set of 9. I have to save these entries and find out those objects which have the maximum votes (maximum selection) and a winner based on the most right entries.

My models:

class User(AbstractUser):
    '''Info about user '''

class Contest(models.Model):
    name = models.CharField(max_length=255)
    created = models.DateField(auto_now_add=True)

class ObjectsForContest(models.Model):
    name = models.CharField(max_length=255)
    contest = models.ManyToManyField('Contest', through='OrderedObjectsForContest')

class OrderedObjectsForContest(models.Model):
    choice = models.ForeignKey(ObjectsForContest)
    contest = models.ForeignKey(Contest, related_name='ordered_options')
    order = models.PositiveIntegerField()

    class Meta:
        ordering = ['order']

class UserEntriesForContest(models.Model):
    user = models.ForeignKey(User, related_name="entries_for_contest")
    contest = models.ForeignKey(Contest, related_name='participating_users')
    objects_selected = models.ManyToManyField(ObjectsForContest, through='OrderedChoicesByUser', null=True, blank=True)

    def __unicode__(self):
        return self.user.unique_id

class OrderedChoicesByUser(models.Model):
    choice = models.ForeignKey(ObjectsForContest)
    contest = models.ForeignKey(UserEntriesForContest)
    order = models.PositiveIntegerField()

    class Meta:
        ordering = ['order']

My serializers are pretty straight forward.
Serializer:

class ContestObjectsSerializer(serializers.ModelSerializer):
    class Meta:
        model = ObjectsForContest
        exclude = ("contests", )

class ContestObjectsThroughSerializer(serializers.ModelSerializer):
    choice = ContestObjectsSerializer()

    class Meta:
        model = OrderedObjectsForContest
        exclude = ("id", )

class Contest(serializers.ModelSerializer):
    winner = SimpleUserProfileSerializer()  #this serializes the user and not included here.
    choices = ContestObjectsThroughSerializer(many=True)

    class Meta:
        model = Contest

class UserEntriesForContestSerializer(serializers.ModelSerializer):
    choices_made = ContestObjectsSerializer(many=True)

    class Meta:
        model = UserEntriesForContest

How can I find the choice that has been selected by the maximum number of users according to their order?

Ex.
Objects according to contest: (Name, order)

(Apple, 1), (Orange, 2), (Grapes, 3), (Mango, 4), (Apricot, 5), (Cherry, 6), (Guava, 7), (Jackfruit, 8), (Lime, 9)

Let us assume that there are 5 users whose choices are:

#User 1:
(Apple, 1), (Lime, 2), (Grapes, 3), (Mango, 4), (Apricot, 5)
#User 2:
(Apple, 1), (Orange, 2), (Lime, 3), (Mango, 4), (Apricot, 5)
#User 3:
(Apple, 1), (Orange, 2), (Grapes, 3), (Cherry, 4), (Apricot, 5)
#User 4:
(Apple, 1), (Orange, 2), (Lime, 3), (Cherry, 4), (Apricot, 5)
#User 5:
(Apple, 1), (Lime, 2), (Grapes, 3), (Cherry, 4), (Apricot, 5)

The winning list should be:

(Apple, 1), (Orange, 2), (Grapes, 3), (Cherry, 3), (Apricot, 5)

I need to know how can I get this list given my models.

Body:
Many-to-Many Order can be done by SerializerMethodField in DRF

students_listss = serializers.SerializerMethodField('get_students_list')

def get_students_list(self, instance):
    return Student.objects\
        .filter()\
        .order_by('name')\
        .values_list('name', flat=True)

you can apply order condition as usual in order_by()


问:
Unable to import yaml (pyyaml) on travis-ci using python 3.6
I'm trying to test a python project which utilizes the yaml package (pyyaml) using travis-ci.

```<code>sudo: required
python: "3.6"
before_install:
  - sudo apt-get install -y python3-pip
  - sudo pip3 install pyyaml
script:
  - ./setup.py test
</code>```

However travis keeps giving me:

```<code>ModuleNotFoundError: No module named 'yaml'
</code>```

I've tried using plain pip to install pyyaml, as well as the ubuntu package python3-yaml with no luck. I can get it to work on a local VM with ubuntu, just not in travis-ci.

答:
The "ModuleNotFoundError" indicates that it is indeed Python 3.6 that generates the error Python <= 3.5 would give a module error. I would tend to use /path/to/python setup.py test, but it already looks like you have the right Python there.

That leaves that pip3 might not install where you think it installs, so you should at least do:

```<code>- sudo /path/to/python36 -m pip install pyyaml
</code>```

to make sure you get the pip3 that you are expecting, and that you are not using some default system Python 3.5 or earlier.

You could also consider installing virtualenv with a known path, and install pyyaml in there and then run your setup.py with a full path of the python from there.

Body:
I'm trying to test a python project which utilizes the yaml package (pyyaml) using travis-ci.

sudo: required
python: "3.6"
before_install:
  - sudo apt-get install -y python3-pip
  - sudo pip3 install pyyaml
script:
  - ./setup.py test

However travis keeps giving me:

ModuleNotFoundError: No module named 'yaml'

I've tried using plain pip to install pyyaml, as well as the ubuntu package python3-yaml with no luck. I can get it to work on a local VM with ubuntu, just not in travis-ci.

Body:
The "ModuleNotFoundError" indicates that it is indeed Python 3.6 that generates the error Python <= 3.5 would give a module error. I would tend to use /path/to/python setup.py test, but it already looks like you have the right Python there.

That leaves that pip3 might not install where you think it installs, so you should at least do:

- sudo /path/to/python36 -m pip install pyyaml

to make sure you get the pip3 that you are expecting, and that you are not using some default system Python 3.5 or earlier.

You could also consider installing virtualenv with a known path, and install pyyaml in there and then run your setup.py with a full path of the python from there.


问:
How to parse date string to Date?
How do I parse the date string below into a Date object?

```<code>String target = "Thu Sep 28 20:29:30 JST 2000";
DateFormat df = new SimpleDateFormat("E MM dd kk:mm:ss z yyyy");
Date result =  df.parse(target);
</code>```

Throws exception...

```<code>java.text.ParseException: Unparseable date: "Thu Sep 28 20:29:30 JST 2000"
        at java.text.DateFormat.parse(DateFormat.java:337)
</code>```

答:
The pattern is wrong. You have a 3-letter day abbreviation, so it must be EEE. You have a 3-letter month abbreviation, so it must be MMM. As those day and month abbreviations are locale sensitive, you'd like to explicitly specify the SimpleDateFormat locale to English as well, otherwise it will use the platform default locale which may not be English per se.

```<code>public static void main(String[] args) throws Exception {
    String target = "Thu Sep 28 20:29:30 JST 2000";
    DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy", Locale.ENGLISH);
    Date result =  df.parse(target);
    System.out.println(result);
}
</code>```

This prints here

```Thu Sep 28 07:29:30 BOT 2000```

which is correct as per my timezone.

I would also reconsider if you wouldn't rather like to use HH instead of kk. Read the javadoc for details about valid patterns.

Title: How to parse date string to Date?

Body:
How do I parse the date string below into a Date object?

String target = "Thu Sep 28 20:29:30 JST 2000";
DateFormat df = new SimpleDateFormat("E MM dd kk:mm:ss z yyyy");
Date result =  df.parse(target);

Throws exception...

java.text.ParseException: Unparseable date: "Thu Sep 28 20:29:30 JST 2000"
        at java.text.DateFormat.parse(DateFormat.java:337)

Body:
The pattern is wrong. You have a 3-letter day abbreviation, so it must be EEE. You have a 3-letter month abbreviation, so it must be MMM. As those day and month abbreviations are locale sensitive, you'd like to explicitly specify the SimpleDateFormat locale to English as well, otherwise it will use the platform default locale which may not be English per se.

public static void main(String[] args) throws Exception {
    String target = "Thu Sep 28 20:29:30 JST 2000";
    DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy", Locale.ENGLISH);
    Date result =  df.parse(target);
    System.out.println(result);
}

This prints here

Thu Sep 28 07:29:30 BOT 2000

which is correct as per my timezone.

I would also reconsider if you wouldn't rather like to use HH instead of kk. Read the javadoc for details about valid patterns.


问:
a laravel5 delete , how to pass 2 parameters to DELETE operation
my first idea is to send two parameters to DELETE operation!

```<code><form action="{{ url('admin/sco/'.$sco->sno,$sco->cno) }}" method="POST" style="display: inline;">
    {{ method_field('DELETE') }}
    {{ csrf_field() }}
    <button type="submit" class="btn btn-danger">删除</button>
</form>
</code>```

then,it is the destroy function!

```<code>public function destroy($sno, $cno)
{
    $query = DB::table('scos')->where('sno', $sno)->where('cno', $cno);
    $query->delete();

    return redirect()->back()->withInput()->withErrors('删除成功!');
}
</code>```

but i get the result with  NotFoundHttpException

i think where problem exists is i have not passed the parameters correctly. how can i do it?
addtional information:
'sno' means student number,
'cno' means class number,
i have to delete a specific record with the two numbers.

答:
Try this solution:

In routes:

```<code>Route::post('/admin/sco/{sno}/{cno}', 'Your_controller@your_action')->name('sco.delete');
</code>```

In views:

```<code><form action="{{ route('sno.delete', ['sno' => $sco->sno, 'cno' => $sco->cno]) }}" method="POST" style="display: inline;">
</code>```

Hope it help you :)

Body:
my first idea is to send two parameters to DELETE operation!

<form action="{{ url('admin/sco/'.$sco->sno,$sco->cno) }}" method="POST" style="display: inline;">
    {{ method_field('DELETE') }}
    {{ csrf_field() }}
    <button type="submit" class="btn btn-danger">删除</button>
</form>

then,it is the destroy function!

public function destroy($sno, $cno)
{
    $query = DB::table('scos')->where('sno', $sno)->where('cno', $cno);
    $query->delete();

    return redirect()->back()->withInput()->withErrors('删除成功!');
}

but i get the result with  NotFoundHttpException

i think where problem exists is i have not passed the parameters correctly. how can i do it?
addtional information:
'sno' means student number,
'cno' means class number,
i have to delete a specific record with the two numbers.

Body:
Try this solution:

In routes:

Route::post('/admin/sco/{sno}/{cno}', 'Your_controller@your_action')->name('sco.delete');

In views:

<form action="{{ route('sno.delete', ['sno' => $sco->sno, 'cno' => $sco->cno]) }}" method="POST" style="display: inline;">

Hope it help you :)


问:
Forecast in R - auto.arima with external regressors
Further to this discussion regarding fitting arima model using external regressors.

From Auto.arima to forecast in R

I was able to forecast perfectly for next 5 months given that I had future values for the predictors explaining my response variable (churn_rate).

```<code>arima_model_churn_rate <- auto.arima(tsm_churn_rate, stepwise = FALSE,
                                 approximation = FALSE,
                                 xreg = xreg_in_out_p_month_1)

number_of_future_month <- 5
forecast_churn_rate <- forecast (arima_model_churn_rate,
                             xreg = xreg_fut_in_out_p_month_churn_rate,
                             h = number_of_future_month)
plot(forecast_churn_rate)
</code>```

My question is as I need to predict in future I can not wait for the predictors to be measured to make prediction for future months ?

If I have to wait till end of month then I can do simple calculation to see what is churn rate ?

My goal is predict for next 3 months in that case what I should I do get future values for my predictors?

I am kind of confused with this whole scenario as discussed in the blog. For arima model with external regressor we need future values. Its perfectly worked for example case where I just trained my model on 2 years data and I used next 5 months measurements for predictors as future value.

But what If I want to predict for future 3/6/ or even year and If I have to wait for future values then I am already in that time point. Then prediction does not make any sense.

Can someone explain this whole concept to me please. Sorry if I could not explain this whole scenario really well. I tried my level best to get around though.

Thanks in advance !!

答:
If you don't have values for your future predictors, then you need to either forecast them first, or use a different model.

You could try a model without those predictors, or you could include lagged values of the predictors where the lag is at least as long as the forecast horizon.

Body:
Further to this discussion regarding fitting arima model using external regressors.

From Auto.arima to forecast in R

I was able to forecast perfectly for next 5 months given that I had future values for the predictors explaining my response variable (churn_rate).

arima_model_churn_rate <- auto.arima(tsm_churn_rate, stepwise = FALSE,
                                 approximation = FALSE,
                                 xreg = xreg_in_out_p_month_1)

number_of_future_month <- 5
forecast_churn_rate <- forecast (arima_model_churn_rate,
                             xreg = xreg_fut_in_out_p_month_churn_rate,
                             h = number_of_future_month)
plot(forecast_churn_rate)

My question is as I need to predict in future I can not wait for the predictors to be measured to make prediction for future months ?

If I have to wait till end of month then I can do simple calculation to see what is churn rate ?

My goal is predict for next 3 months in that case what I should I do get future values for my predictors?

I am kind of confused with this whole scenario as discussed in the blog. For arima model with external regressor we need future values. Its perfectly worked for example case where I just trained my model on 2 years data and I used next 5 months measurements for predictors as future value.

But what If I want to predict for future 3/6/ or even year and If I have to wait for future values then I am already in that time point. Then prediction does not make any sense.

Can someone explain this whole concept to me please. Sorry if I could not explain this whole scenario really well. I tried my level best to get around though.

Thanks in advance !!


问:
how to save android application's global data to SavedSate
we all know how to save an Activity's state to SavedState via  onSaveInstanceState before it is killed.  but when the application has some global data will be used by all the activities. so I do not have a good method to save the global data. when the application be killed on the backgound.</p>

答: You can consider storing the data in the shared preferences. This data will persist across the activites. check this using shared preferences.</p>

ContentLicense: CC BY-SA 2.5


问:
How to sum specific column when key matches in PIG
I have sample data as below:

```<code>(id,code,key,value)
1,A,p,10
2,B,q,20
3,B,p,30
3,B,q,20
3,C,t,60
3,C,q,20
</code>```

After storing it into PIG, i need output like below:

```<code>O/P:

(A,{(p,10)})

(B,{(q,40),(p,30)})

(C,{(t,60)},(q,20))
</code>```

We can drop id, and need output that adds the sum of all value that match with the key for specific code. in the above example we can see for code B- q,20 is twice, hence added and became q,40.

Below is my code but not able to get the exact output:

```<code>Lo = load 'pivot.txt' using PigStorage (',') as (id:chararray, code:chararray, key:chararray, value:int);
Aa = group L by (code);
Bb = foreach Aa {AUX = foreach Lo generate $0,$2,$3;generate group, AUX;}`

dump Bb:
(A,{(1,p,10)})
(B,{(3,q,20),(3,p,30),(2,q,20)})
(C,{(3,t,60),(3,q,20)})
</code>```

I am not able to proceed further, help is much appreciated.

Thanks,
Rohith

答:
Pig Script :

```<code>input_data = LOAD 'input.csv' USING PigStorage(',') AS (id:int,code:chararray,key:chararray,value:int);
req_stats = FOREACH(GROUP input_data BY (code,key)) GENERATE FLATTEN(group) AS (code,key), SUM(input_data.value) AS value;
req_stats_fmt = FOREACH(GROUP req_stats BY code) GENERATE group AS code, req_stats.(key,value);
DUMP req_stats_fmt;
</code>```

Input :

```<code>1,A,p,10
2,B,q,20
3,B,p,30
3,B,q,20
3,C,t,60
3,C,q,20
</code>```

Output : DUMP req_stats_fmt

```<code>(A,{(p,10)})
(B,{(q,40),(p,30)})
(C,{(t,60),(q,20)})
</code>```

Body:
I have sample data as below:

(id,code,key,value)
1,A,p,10
2,B,q,20
3,B,p,30
3,B,q,20
3,C,t,60
3,C,q,20

After storing it into PIG, i need output like below:

O/P:

(A,{(p,10)})

(B,{(q,40),(p,30)})

(C,{(t,60)},(q,20))

We can drop id, and need output that adds the sum of all value that match with the key for specific code. in the above example we can see for code B- q,20 is twice, hence added and became q,40.

Below is my code but not able to get the exact output:

Lo = load 'pivot.txt' using PigStorage (',') as (id:chararray, code:chararray, key:chararray, value:int);
Aa = group L by (code);
Bb = foreach Aa {AUX = foreach Lo generate $0,$2,$3;generate group, AUX;}`

dump Bb:
(A,{(1,p,10)})
(B,{(3,q,20),(3,p,30),(2,q,20)})
(C,{(3,t,60),(3,q,20)})

I am not able to proceed further, help is much appreciated.

Thanks,
Rohith

Body:
Pig Script :

input_data = LOAD 'input.csv' USING PigStorage(',') AS (id:int,code:chararray,key:chararray,value:int);
req_stats = FOREACH(GROUP input_data BY (code,key)) GENERATE FLATTEN(group) AS (code,key), SUM(input_data.value) AS value;
req_stats_fmt = FOREACH(GROUP req_stats BY code) GENERATE group AS code, req_stats.(key,value);
DUMP req_stats_fmt;

Input :

1,A,p,10
2,B,q,20
3,B,p,30
3,B,q,20
3,C,t,60
3,C,q,20

Output : DUMP req_stats_fmt

(A,{(p,10)})
(B,{(q,40),(p,30)})
(C,{(t,60),(q,20)})


问:
Can an iPhone 7 or later using iOS 11+ act as an NFC tag?
I understand that an iPhone 7 or later will be able to read certain NFC tags under certain conditions however will an iPhone also be able to act as an NFC tag or "display"/share any sort of unique NDEF data that can be read by other devices with NFC reading capabilities?</p>

答: Not at this time.  Using CoreNFC in iOS 11 an iPhone 7(+) can read NDEF data from NFC tags but not act as a tag.</p>


问:
Any way to share data between Polymer components?
Currently I have two Polymer components that share a great amount of data. You can see here:

```<code><polymer-component1
      series="{{series}}"
      stackhelper={{stackhelper}}
      stack={{stack}}
      controls={{controls}}
      camera={{camera}}
      threed={{threed}}
      scene={{scene}}
      renderer={{renderer}}>
</polymer-component1>
<polymer-component2
      stackhelper=[[stackhelper]]
      stack={{stack}}
      controls={{controls}}
      camera={{camera}}
      threed={{threed}}
      scene={{scene}}
      renderer={{renderer}}
      guiobjects={{guiobjects}}>
</polymer-component2>
</code>```

This is working fine right now but whats the best practice about sharing data? Any way to share all the properties between two components?

答:
It's recommended to share data through data binding, just as what you're doing. You can share any property, not just strings and numbers. e.g. assuming you have an object

JS

```<code>data = {
    series: "",
    stackhelper: "",
    stack: "",
    controls: "",
    camera: "",
    threed: "",
    scene: "",
    renderer: "",
}
</code>```

Your code can be rewritten like this.

HTML

```<code><polymer-component1 data="{{data}}"></polymer-component1>
<polymer-component2 data="{{data}}"></polymer-component2>
</code>```

Body:
Currently I have two Polymer components that share a great amount of data. You can see here:

<polymer-component1
      series="{{series}}"
      stackhelper={{stackhelper}}
      stack={{stack}}
      controls={{controls}}
      camera={{camera}}
      threed={{threed}}
      scene={{scene}}
      renderer={{renderer}}>
</polymer-component1>
<polymer-component2
      stackhelper=[[stackhelper]]
      stack={{stack}}
      controls={{controls}}
      camera={{camera}}
      threed={{threed}}
      scene={{scene}}
      renderer={{renderer}}
      guiobjects={{guiobjects}}>
</polymer-component2>

This is working fine right now but whats the best practice about sharing data? Any way to share all the properties between two components?

Body:
It's recommended to share data through data binding, just as what you're doing. You can share any property, not just strings and numbers. e.g. assuming you have an object

JS

data = {
    series: "",
    stackhelper: "",
    stack: "",
    controls: "",
    camera: "",
    threed: "",
    scene: "",
    renderer: "",
}

Your code can be rewritten like this.

HTML

<polymer-component1 data="{{data}}"></polymer-component1>
<polymer-component2 data="{{data}}"></polymer-component2>


问:
how to fix LookupError: base64 in python3 while running String decode() Method
I am running below program in python3, but getting an error

```<code>Str = "this is string example....wow!!!";
Str = Str.encode('base64','strict');
print ("Encoded String: " + Str)
print ("Decoded String: " + Str.decode('base64','strict'))
</code>```

and getting Error is:-

```<code>File "learn.py", line 646, in <module>
    Str = Str.encode('base64','strict');
LookupError: 'base64' is not a text encoding; use codecs.encode() to handle arbitrary codecs
</code>```

答:
Encode and Decode base64 (using more than required variable so that everyone can keep track of operations).

```<code>import base64
print("base64 Encoded/Decoded string \n")
str="this is a test string "
s1=str.encode('ascii')  # it will result like: b'this is a test string'
s2=base64.b64encode(s1);   #storing value before printing
print("encoded : ",s2)
print("decoded : ",base64.b64decode(s2)) #direct conversion
</code>```

Body:
I am running below program in python3, but getting an error

Str = "this is string example....wow!!!";
Str = Str.encode('base64','strict');
print ("Encoded String: " + Str)
print ("Decoded String: " + Str.decode('base64','strict'))

and getting Error is:-

File "learn.py", line 646, in <module>
    Str = Str.encode('base64','strict');
LookupError: 'base64' is not a text encoding; use codecs.encode() to handle arbitrary codecs

Body:
Encode and Decode base64 (using more than required variable so that everyone can keep track of operations).

import base64
print("base64 Encoded/Decoded string \n")
str="this is a test string "
s1=str.encode('ascii')  # it will result like: b'this is a test string'
s2=base64.b64encode(s1);   #storing value before printing
print("encoded : ",s2)
print("decoded : ",base64.b64decode(s2)) #direct conversion


问:
UILongPressGestureRecognizer over UITextField in swift
Is there away to use a UILongPressGestureRecognizer over a UITextField without triggering field edit while still being able to edit the textfield on a regular tap?

I have tried adding a long press gesture recognizer to the UITextField but the long press seems to only work a fraction of the time.

```<code>init(frame: CGRect, userCompany: WLUserCompany) {
    super.init(frame: frame)

    var textField: UITextField?

    var longPress = UILongPressGestureRecognizer(target: self, action: #selector(self.longPress(gesture:)))
    textField?.addGestureRecognizer(longPress)

    self.addSubview(textField!)
}

@objc func longPress(gesture: UILongPressGestureRecognizer) {
    if gesture.state == UIGestureRecognizerState.began {
        print("Long Press")
    }
}
</code>```

答:
After looking at similar SO here and here, and experimenting myself, I don't think this is possible -- at least the way you describe your intent.

I was able to add a background view with gesture control, but the gesture conflicts with the user interaction on the text field. Wouldn't a button to the side of the textfield create a better user experience?

FWIW, here is the code to add a background UIView using a double tap. a long press gesture had the same result

```<code> @IBOutlet weak var backgroundView: UIView!
    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.myTextFieldTapped))
        tapGesture.numberOfTapsRequired = 2
        backgroundView.addGestureRecognizer(tapGesture)
    }

    @objc func myTextFieldTapped() {
        print("Double tapped on textField")
    }
</code>```

Here is an image of the storyboard:

Body:
Is there away to use a UILongPressGestureRecognizer over a UITextField without triggering field edit while still being able to edit the textfield on a regular tap?

I have tried adding a long press gesture recognizer to the UITextField but the long press seems to only work a fraction of the time.

init(frame: CGRect, userCompany: WLUserCompany) {
    super.init(frame: frame)

    var textField: UITextField?

    var longPress = UILongPressGestureRecognizer(target: self, action: #selector(self.longPress(gesture:)))
    textField?.addGestureRecognizer(longPress)

    self.addSubview(textField!)
}

@objc func longPress(gesture: UILongPressGestureRecognizer) {
    if gesture.state == UIGestureRecognizerState.began {
        print("Long Press")
    }
}

Body:
After looking at similar SO here and here, and experimenting myself, I don't think this is possible -- at least the way you describe your intent.

I was able to add a background view with gesture control, but the gesture conflicts with the user interaction on the text field. Wouldn't a button to the side of the textfield create a better user experience?

FWIW, here is the code to add a background UIView using a double tap. a long press gesture had the same result

 @IBOutlet weak var backgroundView: UIView!
    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.myTextFieldTapped))
        tapGesture.numberOfTapsRequired = 2
        backgroundView.addGestureRecognizer(tapGesture)
    }

    @objc func myTextFieldTapped() {
        print("Double tapped on textField")
    }

Here is an image of the storyboard:


问:
File Upload using AJAX in Struts2 without page refresh
I want to upload file using Struts2, but without refreshing page.

How can I use AJAX for this solution.

```<code>$.ajax({
url:"strutsaction",
type : 'POST',
async: false,

});
</code>```

What should I write for data and contentType in ajax request ?

jsp code:

```<code><s:form action="strutsaction" method="post" enctype="multipart/form-data">

        <s:file name="imgFileUpload" label="Choose file to upload" accept="image/*"></s:file>
        <s:submit value="Upload" align="center"></s:submit>
    </s:form>
</code>```

答:
Hi the below code is working for me. I hope it will help you.

JSP Code:

```<code><div id="uploadImg">
     <s:form id="uploadImgForm" action="strutsaction" method="post" enctype="multipart/form-data">
            <s:file name="imgFileUpload" label="Choose file to upload" accept="image/*"></s:file>
            <s:submit value="Upload" align="center" id="uploadImgSubmitBtn"></s:submit>
     </s:form>
<div>
</code>```

JQuery:

```<code>$("#uploadImgSubmitBtn").click(function(e){

    // Get form
    var form = $('#uploadImgForm')[0];

    // Create an FormData object
    var data = new FormData(form);

    $.ajax({
        type: "POST",
        enctype: 'multipart/form-data',
        url: "strutsaction.action",
        data : data,
        cache: false,
        processData: false,
        contentType: false,
        success: function(data){
            $('#uploadImg').html(data);
        }
    });
});
</code>```

Body:
I want to upload file using Struts2, but without refreshing page.

How can I use AJAX for this solution.

$.ajax({
url:"strutsaction",
type : 'POST',
async: false,

});

What should I write for data and contentType in ajax request ?

jsp code:

<s:form action="strutsaction" method="post" enctype="multipart/form-data">

        <s:file name="imgFileUpload" label="Choose file to upload" accept="image/*"></s:file>
        <s:submit value="Upload" align="center"></s:submit>
    </s:form>

Body:
Hi the below code is working for me. I hope it will help you.

JSP Code:

<div id="uploadImg">
     <s:form id="uploadImgForm" action="strutsaction" method="post" enctype="multipart/form-data">
            <s:file name="imgFileUpload" label="Choose file to upload" accept="image/*"></s:file>
            <s:submit value="Upload" align="center" id="uploadImgSubmitBtn"></s:submit>
     </s:form>
<div>

JQuery:

$("#uploadImgSubmitBtn").click(function(e){

    // Get form
    var form = $('#uploadImgForm')[0];

    // Create an FormData object
    var data = new FormData(form);

    $.ajax({
        type: "POST",
        enctype: 'multipart/form-data',
        url: "strutsaction.action",
        data : data,
        cache: false,
        processData: false,
        contentType: false,
        success: function(data){
            $('#uploadImg').html(data);
        }
    });
});


问:
How to rotate 4 (or more) images, fading between each one?
I have 4 images, which I want to fade between each other in a loop. I have something like the following:

```<code><img src="/images/image-1.jpg" id="featureImg1" />
<img src="/images/image-2.jpg" id="featureImg2" style="display:none;" />
<img src="/images/image-3.jpg" id="featureImg3" style="display:none;" />
<img src="/images/image-4.jpg" id="featureImg4" style="display:none;" />
</code>```

I am up for revisions to the HTML, although I cannot use absolute positioning in this case. I am using jQuery else where on the site, so it's available. I also need to deal with an image not being loaded right away as the images are larger.

答:
You can use a div and an img, like so:

```<code><div id="featureImgContainer">
    <img src="/images/image-1.jpg" id="featureImg" />
</div>
</code>```

In your Javascript do something like this (pseudo-jQuery):

```<code>function rotateImage(newImage) {
    var oldImage = $("#featureImg").image();

    $("#featureImgContainer").css({backgroundImage: "url('" + oldImage + "')"}); // TODO Escape URL

    $("#featureImg").image(newImage).opacity(0).fadeIn();
}
</code>```

Basically, we make the div's background the "old" image, and the img the new one.  We set the img to 0 opacity, and fade it in, so it appears as if the old image is fading into the new one.  After the fade in, the div isn't shown any more.

Take care to set up the CSS appropriately to set the width/height of the div and the background position where appropriate.

OwnerDisplayName: Darryl Hein

Body:
I have 4 images, which I want to fade between each other in a loop. I have something like the following:

I am up for revisions to the HTML, although I cannot use absolute positioning in this case. I am using jQuery else where on the site, so it's available. I also need to deal with an image not being loaded right away as the images are larger.

Body:
You can use a div and an img, like so:

<div id="featureImgContainer">
    <img src="/images/image-1.jpg" id="featureImg" />
</div>

In your Javascript do something like this (pseudo-jQuery):

function rotateImage(newImage) {
    var oldImage = $("#featureImg").image();

    $("#featureImgContainer").css({backgroundImage: "url('" + oldImage + "')"}); // TODO Escape URL

    $("#featureImg").image(newImage).opacity(0).fadeIn();
}

Basically, we make the div's background the "old" image, and the img the new one.  We set the img to 0 opacity, and fade it in, so it appears as if the old image is fading into the new one.  After the fade in, the div isn't shown any more.

Take care to set up the CSS appropriately to set the width/height of the div and the background position where appropriate.

OwnerDisplayName: strager


问:
Raw XML Push from input stream captures only the first line of XML
I'm trying to read XML that is being pushed to my java app. I originally had this in my glassfish server working. The working code in glassfish is as follows:

```<code>public class XMLPush implements Serializable
{
public void processXML()
{
    StringBuilder sb = new StringBuilder();
    BufferedReader br = null;
    try
    {
        br = ((HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest()).getReader ();
        String s = null;
        while((s = br.readLine ()) != null)
        {
            sb.append ( s );
        }
          //other code to process xml
        ...........
.............................

    }catch(Exception ex)
    {
        XMLCreator.exceptionOutput ( "processXML","Exception",ex);
    }
....
.....
}//processXML
}//class
</code>```

It works perfect, but my client is unable to have glassfish on their server. I tried grabbing the raw xml from php, but I couldn't get it to work. I decided to open up a socket and listen for the xml push manually. Here is my code for receiving the push:

```<code>public class ListenerService extends Thread
{
private BufferedReader reader = null;
private String line;
public ListenerService ( Socket connection  )thows Exception
{
        this.reader = new BufferedReader ( new InputStreamReader ( connection.getInputStream () ) );
        this.line = null;

}//ListenerService
@Override
public void run ()
{
    try
    {
        while ( (this.line = this.reader.readLine ()) != null)
        {
            System.out.println ( this.line );
                 ........

        }//while
    }      System.out.println ( ex.toString () );
        }
    } catch ( Exception ex )
    {
        ...
    }//catch
}//run
</code>```

I haven't done much socket programing, but from what I read for the past week is that passing the xml into a string is bad. What am I doing wrong and why is it that in glassfish server it works, and when I just open a socket myself it doesn't?

this is all that I receive from the push:

```<code>PUT /?XML_EXPORT_REASON=ResponseLoop&TIMESTAMP=1292559547 HTTP/1.1
Host: ************************
Accept: */*
Content-Length: 470346
Expect: 100-continue

<?xml version="1.0" encoding="UTF-8" ?>
</code>```

Where did the xml go? Is it because I am placing it in a string? I just need to grab the xml and save it into a file and then process it. Everything else works, but this.Any help would be greatly appreciated.

答:
I think the key here is this line in your push request:

```<code>100-continue
</code>```

From the HTTP/1.1 specifications:

The purpose of the 100 (Continue) status (see section 10.1.1) is to allow a client that is sending a request message with a request body to determine if the origin server is willing to accept the request (based on the request headers) before the client sends the request body. In some cases, it might either be inappropriate or highly inefficient for the client to send the body if the server will reject the message without looking at the body.

When you go through GlassFish (or some other technology which implements the HTTP standards), that middleware will handle all the negotiations to ensure that by the time the request gets to your code, you have everything you're able to accept. Because you're reading direct from the Socket in your example though, you have nothing between you and the client handling the HTTP negotiations, so you only get the first little bit and a '100-continue' waiting for the go-ahead.

Body:
I'm trying to read XML that is being pushed to my java app. I originally had this in my glassfish server working. The working code in glassfish is as follows:

public class XMLPush implements Serializable
{
public void processXML()
{
    StringBuilder sb = new StringBuilder();
    BufferedReader br = null;
    try
    {
        br = ((HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest()).getReader ();
        String s = null;
        while((s = br.readLine ()) != null)
        {
            sb.append ( s );
        }
          //other code to process xml
        ...........
.............................

    }catch(Exception ex)
    {
        XMLCreator.exceptionOutput ( "processXML","Exception",ex);
    }
....
.....
}//processXML
}//class

It works perfect, but my client is unable to have glassfish on their server. I tried grabbing the raw xml from php, but I couldn't get it to work. I decided to open up a socket and listen for the xml push manually. Here is my code for receiving the push:

public class ListenerService extends Thread
{
private BufferedReader reader = null;
private String line;
public ListenerService ( Socket connection  )thows Exception
{
        this.reader = new BufferedReader ( new InputStreamReader ( connection.getInputStream () ) );
        this.line = null;

}//ListenerService
@Override
public void run ()
{
    try
    {
        while ( (this.line = this.reader.readLine ()) != null)
        {
            System.out.println ( this.line );
                 ........

        }//while
    }      System.out.println ( ex.toString () );
        }
    } catch ( Exception ex )
    {
        ...
    }//catch
}//run

I haven't done much socket programing, but from what I read for the past week is that passing the xml into a string is bad. What am I doing wrong and why is it that in glassfish server it works, and when I just open a socket myself it doesn't?

this is all that I receive from the push:

PUT /?XML_EXPORT_REASON=ResponseLoop&TIMESTAMP=1292559547 HTTP/1.1
Host: ************************
Accept: */*
Content-Length: 470346
Expect: 100-continue

<?xml version="1.0" encoding="UTF-8" ?>

Where did the xml go? Is it because I am placing it in a string? I just need to grab the xml and save it into a file and then process it. Everything else works, but this.Any help would be greatly appreciated.

Body:
I think the key here is this line in your push request:

100-continue

From the HTTP/1.1 specifications:

The purpose of the 100 (Continue) status (see section 10.1.1) is to allow a client that is sending a request message with a request body to determine if the origin server is willing to accept the request (based on the request headers) before the client sends the request body. In some cases, it might either be inappropriate or highly inefficient for the client to send the body if the server will reject the message without looking at the body.

When you go through GlassFish (or some other technology which implements the HTTP standards), that middleware will handle all the negotiations to ensure that by the time the request gets to your code, you have everything you're able to accept. Because you're reading direct from the Socket in your example though, you have nothing between you and the client handling the HTTP negotiations, so you only get the first little bit and a '100-continue' waiting for the go-ahead.


问:
Rendering vanishing text in pygame
I'm making a small game using pygame. When the game starts I want to display "start" and vanish it after a few seconds. How to do that?</p>

答:
First you need a timer variable (there are other questions about timers, so I won't explain them here). I'm just counting the frames in the following example.

To remove the text abruptly you can just keep blitting it until the time is up.

```<code>if timer > 0:
    screen.blit(txt_surf, (position))
</code>```

The slowly disappearing text can be achieved by filling the text surface with white and the current alpha value (which is reduced each frame) and by passing the pg.BLEND_RGBA_MULT special flag. That will affect only the alpha channel of the surface.

```<code>txt_surf.fill((255, 255, 255, alpha), special_flags=pg.BLEND_RGBA_MULT)
</code>```

Also, use a copy of the original text surface, otherwise it would subsequently reduce the alpha of the previously modified surface and the text would disappear too quickly.

```<code>import pygame as pg

def main():
    pg.init()
    clock = pg.time.Clock()
    screen = pg.display.set_mode((640, 480))
    font = pg.font.Font(None, 64)
    orig_surf = font.render('Enter your text', True, pg.Color('royalblue'))
    txt_surf = orig_surf.copy()
    alpha = 255  # The current alpha value of the surface.
    timer = 20  # To get a 20 frame delay.

    while True:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                return

        if timer > 0:
            timer -= 1
        else:
            if alpha > 0:
                # Reduce alpha each frame, but make sure it doesn't get below 0.
                alpha = max(0, alpha-4)
                # Create a copy so that the original surface doesn't get modified.
                txt_surf = orig_surf.copy()
                txt_surf.fill((255, 255, 255, alpha), special_flags=pg.BLEND_RGBA_MULT)

        screen.fill((30, 30, 30))
        screen.blit(txt_surf, (30, 60))
        pg.display.flip()
        clock.tick(30)

if __name__ == '__main__':
    main()
    pg.quit()
</code>```

Title: Rendering vanishing text in pygame

Body:
First you need a timer variable (there are other questions about timers, so I won't explain them here). I'm just counting the frames in the following example.

To remove the text abruptly you can just keep blitting it until the time is up.

if timer > 0:
    screen.blit(txt_surf, (position))

The slowly disappearing text can be achieved by filling the text surface with white and the current alpha value (which is reduced each frame) and by passing the pg.BLEND_RGBA_MULT special flag. That will affect only the alpha channel of the surface.

txt_surf.fill((255, 255, 255, alpha), special_flags=pg.BLEND_RGBA_MULT)

Also, use a copy of the original text surface, otherwise it would subsequently reduce the alpha of the previously modified surface and the text would disappear too quickly.

import pygame as pg

def main():
    pg.init()
    clock = pg.time.Clock()
    screen = pg.display.set_mode((640, 480))
    font = pg.font.Font(None, 64)
    orig_surf = font.render('Enter your text', True, pg.Color('royalblue'))
    txt_surf = orig_surf.copy()
    alpha = 255  # The current alpha value of the surface.
    timer = 20  # To get a 20 frame delay.

    while True:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                return

        if timer > 0:
            timer -= 1
        else:
            if alpha > 0:
                # Reduce alpha each frame, but make sure it doesn't get below 0.
                alpha = max(0, alpha-4)
                # Create a copy so that the original surface doesn't get modified.
                txt_surf = orig_surf.copy()
                txt_surf.fill((255, 255, 255, alpha), special_flags=pg.BLEND_RGBA_MULT)

        screen.fill((30, 30, 30))
        screen.blit(txt_surf, (30, 60))
        pg.display.flip()
        clock.tick(30)

if __name__ == '__main__':
    main()
    pg.quit()

ContentLicense: CC BY-SA 4.0


问:
How to create summed variables using object values from List of objects in Scala?
I have an class

```<code>class Test(val first: Int, val second: Int, val third: Int)
</code>```

Class Test may have other attributes than first, second, and third.

And I have a list:

```<code>val list: List[Test] = List(new Test(0,1,2), new Test(1,14,2), new Test(7,15,2))
</code>```

How would I use foldLeft here to add together all first`s, second's, third's together to end up with variables:

allFirsts = 8

allSeconds = 30

allThirds = 6

I already have something like this worked out:

```<code>val (totalFirsts, totalSeconds, totalThirds) = list.foldLeft(0, 0, 0){ (sum, l) => (sum._1 + l.first , sum._2 + l.second, sum._3 + l.third) }
</code>```

It seems to work fine, but I don't like the readability of _1, _2, and _3.  Maybe I can use case here to decompose values but I am just not sure how to make it all work together.

答:
I would not use it but it works

```<code>  case class Test3(a1: Int, a2: Int, a3: Int)
  case class Test4(a1: Int, a2: Int, a3: Int, a4: Int)

  import scala.reflect._
  def doMagic[T <: Product : ClassTag](data: List[T]): T ={
    val params: Seq[Object] = data.map(_.productIterator.toList.map(_.asInstanceOf[Int]))
      .reduce((buffer, next) => buffer.zip(next).map { case (i, j) => i + j }).map(_.asInstanceOf[Object])
    classTag[T].runtimeClass.getConstructors()(0).newInstance(params:_*).asInstanceOf[T]
  }
  doMagic(List(Test3(1,2,3), Test3(2,3,4), Test3(10,20,30))) // Test3(13,25,37)
  doMagic(List(Test4(1,2,3,5), Test4(2,3,4,0), Test4(10,20,30,100))) // Test4(13,25,37,105)
</code>```

Do not forget to use reduceOption instead of reduce to handle empty lists. Here is used reduce to simplify code

Body:
I have an class

class Test(val first: Int, val second: Int, val third: Int)

Class Test may have other attributes than first, second, and third.

And I have a list:

val list: List[Test] = List(new Test(0,1,2), new Test(1,14,2), new Test(7,15,2))

How would I use foldLeft here to add together all first`s, second's, third's together to end up with variables:

allFirsts = 8

allSeconds = 30

allThirds = 6

I already have something like this worked out:

val (totalFirsts, totalSeconds, totalThirds) = list.foldLeft(0, 0, 0){ (sum, l) => (sum._1 + l.first , sum._2 + l.second, sum._3 + l.third) }

It seems to work fine, but I don't like the readability of _1, _2, and _3.  Maybe I can use case here to decompose values but I am just not sure how to make it all work together.

Body:
I would not use it but it works

  case class Test3(a1: Int, a2: Int, a3: Int)
  case class Test4(a1: Int, a2: Int, a3: Int, a4: Int)

  import scala.reflect._
  def doMagic[T <: Product : ClassTag](data: List[T]): T ={
    val params: Seq[Object] = data.map(_.productIterator.toList.map(_.asInstanceOf[Int]))
      .reduce((buffer, next) => buffer.zip(next).map { case (i, j) => i + j }).map(_.asInstanceOf[Object])
    classTag[T].runtimeClass.getConstructors()(0).newInstance(params:_*).asInstanceOf[T]
  }
  doMagic(List(Test3(1,2,3), Test3(2,3,4), Test3(10,20,30))) // Test3(13,25,37)
  doMagic(List(Test4(1,2,3,5), Test4(2,3,4,0), Test4(10,20,30,100))) // Test4(13,25,37,105)

Do not forget to use reduceOption instead of reduce to handle empty lists. Here is used reduce to simplify code


问:
ANGULAR JS ng-if
I am trying to learning angular JS and I am an absolute beginner.I tried using ng-if directives to print 'Mr or Mrs or Ms' according to the their gender and relationship  status.When I bind the married model within the div tag it is giving out the correct value .But the binding after that prints true every time. Are there any other ways to check conditions ?
Moreover I tried checking conditions with the controller , why doesn't that work? Please help!</p>

```<code><body ng-app="myApp" ng-controller="myFirstController" ng- init="first='';last='';gender='Male';married='true'">
    <input type="text" data-ng-model="first">
    <input type="text" data-ng-model="last">

    <label for="gender">GENDER </label>
    <input type="radio" name="gender" data-ng-model="gender" value="Male" /> MALE
    <input type="radio" name="gender" data-ng-model="gender" value="Female" /> FEMALE
    <br>
    <br>

    <div ng-if="gender==='Female'">
        <input type="radio" name="married" data-ng-model="married" value="true" /> MARRIED
        <input type="radio" name="married" data-ng-model="married" value="false" /> UNMARRIED
        <br>
        <br> {{married}}

    </div>
    <span ng-if="gender==='Male'">MR.</span>
    <span ng-if="gender!=='Male'">
    <span ng-if="married=='true'">MRS.</span>
    <span ng-if="married=='false'">MS.</span> </span>{{first }} {{last}} {{married}}
    <div ng-app="" ng-init="myCol='lightblue'">
</code>```

答:
The problem is that your checks are on strings like MRS. but the ng-model for input checkbox binds it to boolean true or false. So change your code in such a way that wherever there is check with true or false, it should be boolean value instead of string 'true' or 'false'

This

```<code><span ng-if="married=='true'">MRS.</span>
<span ng-if="married=='false'">MRS.</span>
</code>```

Should be

```<code><span ng-if="married">MRS.</span>
<span ng-if="!married">MRS.</span>
</code>```

Title: ANGULAR JS ng-if

Body:
I am trying to learning angular JS and I am an absolute beginner.I tried using ng-if directives to print 'Mr or Mrs or Ms' according to the their gender and relationship  status.When I bind the married model within the div tag it is giving out the correct value .But the binding after that prints true every time. Are there any other ways to check conditions ?
Moreover I tried checking conditions with the controller , why doesn't that work? Please help!

    <input type="text" data-ng-model="first">
    <input type="text" data-ng-model="last">

    GENDER
    <input type="radio" name="gender" data-ng-model="gender" value="Male" /> MALE
    <input type="radio" name="gender" data-ng-model="gender" value="Female" /> FEMALE

        <input type="radio" name="married" data-ng-model="married" value="true" /> MARRIED
        <input type="radio" name="married" data-ng-model="married" value="false" /> UNMARRIED

 {{married}}

    MR.

    MRS.
    MS. {{first }} {{last}} {{married}}

Body:
The problem is that your checks are on strings like <span ng-if="married=='true'">MRS.</span> but the ng-model for input checkbox binds it to boolean true or false. So change your code in such a way that wherever there is check with true or false, it should be boolean value instead of string 'true' or 'false'

This

<span ng-if="married=='true'">MRS.</span>
<span ng-if="married=='false'">MRS.</span>

Should be

<span ng-if="married">MRS.</span>
<span ng-if="!married">MRS.</span>


问:
Polymer2.0- Trying to download DIV content of custom element
I am trying to download div content of custom element using document.getElementById of the div and trying to implement download option from the JS FIddle - http://jsfiddle.net/evx9stLb/

From console, I am getting below error

pen.js:6 Uncaught TypeError: Cannot read property 'innerHTML' of null
    at download (pen.js:6)
    at HTMLButtonElement.onclick (index.html:15)

HTML:

```<code><head>
  <base href="https://polygit.org/polymer+v2.0.0/shadycss+webcomponents+1.0.0/components/">
  <link rel="import" href="polymer/polymer.html">
  <link rel="import" href="iron-collapse/iron-collapse.html">
</head>
<body>

  <x-foo></x-foo>

<button onClick="download()">Download</button>
  <dom-module id="x-foo">
    <template>

      <button on-click="toggle">toggle collapse</button>
      <div id="content">
<iron-collapse id="collapse">
  <div>Content goes here...</div>
</iron-collapse>
      </div>
    </template>
  </dom-module>
</body>
</code>```

JS:

```<code>function download(){
    var a = document.body.appendChild(
        document.createElement("a")
    );
    a.download = "export.html";
    a.href = "data:text/html," + document.getElementById("content").innerHTML;
    a.click();
}

    class XFoo extends Polymer.Element {
      static get is() { return 'x-foo'; }

      static get properties() {
        return {};

      }
         toggle() {
    this.$.collapse.toggle();
  }

    }
    customElements.define(XFoo.is, XFoo);
</code>```

Code which I am below - https://codepen.io/nagasai/pen/ZyRKxj

答:
a document query (on light dom) won't pierce the shadowDom. To do that you have to specifically select the element and query it's shadowRoot.

it would look something like this

```<code>a.href = "data:text/html," + document.getElementsByTagName('x-foo')[0].shadowRoot.querySelector('#content').innerHTML;
</code>```

BUT only do this if you can't modify the element itself. It's not nice to stir around in someone else's shadowRoot.

As shown by Frank R. its far better to modify the element itself and provide a download functionality.

You can trigger this easily from an external element with something like

```<code>document.getElementsByTagName('x-foo')[0].download();
</code>```

Body:
I am trying to download div content of custom element using document.getElementById of the div and trying to implement download option from the JS FIddle - http://jsfiddle.net/evx9stLb/

From console, I am getting below error

pen.js:6 Uncaught TypeError: Cannot read property 'innerHTML' of null
    at download (pen.js:6)
    at HTMLButtonElement.onclick (index.html:15)

HTML:

  <base href="https://polygit.org/polymer+v2.0.0/shadycss+webcomponents+1.0.0/components/">
  <link rel="import" href="polymer/polymer.html">
  <link rel="import" href="iron-collapse/iron-collapse.html">

  <x-foo></x-foo>

<button onClick="download()">Download</button>
  <dom-module id="x-foo">
    <template>

      <button on-click="toggle">toggle collapse</button>

<iron-collapse id="collapse">

Content goes here...

</iron-collapse>

    </template>
  </dom-module>

JS:

function download(){
    var a = document.body.appendChild(
        document.createElement("a")
    );
    a.download = "export.html";
    a.href = "data:text/html," + document.getElementById("content").innerHTML;
    a.click();
}

    class XFoo extends Polymer.Element {
      static get is() { return 'x-foo'; }

      static get properties() {
        return {};

      }
         toggle() {
    this.$.collapse.toggle();
  }

    }
    customElements.define(XFoo.is, XFoo);

Code which I am below - https://codepen.io/nagasai/pen/ZyRKxj

Body:
a document query (on light dom) won't pierce the shadowDom. To do that you have to specifically select the element and query it's shadowRoot.

it would look something like this

a.href = "data:text/html," + document.getElementsByTagName('x-foo')[0].shadowRoot.querySelector('#content').innerHTML;

BUT only do this if you can't modify the element itself. It's not nice to stir around in someone else's shadowRoot.

As shown by Frank R. its far better to modify the element itself and provide a download functionality.

You can trigger this easily from an external element with something like

document.getElementsByTagName('x-foo')[0].download();


问:
Invalid header field value in Go ONLY on kubernetes/CoreOS
I have a Go program that uses aws-sdk-go to talk to dynamodb. Dependencies are vendored. Go version 1.7.1. aws-sdk-go version 1.6.24. The program works as expected in all the following environments:

dev box from shell (Arch Linux)

docker container running on my dev box (Docker 1.13.1)

Ec2 instance from shell (Ubuntu 16.04)

When I run the docker container on kubernetes (same one I tested on my dev box),  I get the following error:

```

2017/03/02 22:30:13 DEBUG ERROR: Request dynamodb/GetItem:
---[ REQUEST DUMP ERROR ]-----------------------------
net/http: invalid header field value "AWS4-HMAC-SHA256 Credential=hidden\n/20170302/us-east-1/dynamodb/aws4_request, SignedHeaders=accept-encoding;content-length;content-type;host;x-amz-date;x-amz-target, Signature=483f56dd0b17d8945d3c2f2044b7f97e531190602f132a4d5f828264b3a2cff2" for key Authorization
-----------------------------------------------------

2017/03/02 22:30:13 DEBUG: Response dynamodb/GetItem Details:
---[ RESPONSE ]--------------------------------------
HTTP/0.0 000 status code 0
Content-Length: 0

```

Based on:

https://golang.org/src/net/http/transport.go

https://godoc.org/golang.org/x/net/lex/httplex#ValidHeaderFieldValue

It looks like the problem is with the header value validation, yet I am at a loss to understand why it works everywhere except on my k8s cluster. The cluster is composed of Ec2 instances running the latest CoreOS stable ami (CoreOS stable 1235.8.0)

The docker image that works on my dev machine is scratch based. To troubleshoot I created an image based on Ubuntu latest with a separate go program that just does a simple get item from dynamodb. When this image is run on my k8s cluster and the program run from an interactive shell, I get the same errors. I have confirmed I can ping the dynamodb endpoints from this env.

I am having a hard time troubleshooting this issue: am I missing something stupid here? Can someone point me in the right direction or have an idea of what is going on?

答:
remember the "-n" when you do this:
echo -n key | base64</p>

Body:
I have a Go program that uses aws-sdk-go to talk to dynamodb. Dependencies are vendored. Go version 1.7.1. aws-sdk-go version 1.6.24. The program works as expected in all the following environments:

dev box from shell (Arch Linux)

docker container running on my dev box (Docker 1.13.1)

Ec2 instance from shell (Ubuntu 16.04)

When I run the docker container on kubernetes (same one I tested on my dev box),  I get the following error:

2017/03/02 22:30:13 DEBUG ERROR: Request dynamodb/GetItem:
---[ REQUEST DUMP ERROR ]-----------------------------
net/http: invalid header field value "AWS4-HMAC-SHA256 Credential=hidden\n/20170302/us-east-1/dynamodb/aws4_request, SignedHeaders=accept-encoding;content-length;content-type;host;x-amz-date;x-amz-target, Signature=483f56dd0b17d8945d3c2f2044b7f97e531190602f132a4d5f828264b3a2cff2" for key Authorization
-----------------------------------------------------

2017/03/02 22:30:13 DEBUG: Response dynamodb/GetItem Details:
---[ RESPONSE ]--------------------------------------
HTTP/0.0 000 status code 0
Content-Length: 0

Based on:

https://golang.org/src/net/http/transport.go

https://godoc.org/golang.org/x/net/lex/httplex#ValidHeaderFieldValue

It looks like the problem is with the header value validation, yet I am at a loss to understand why it works everywhere except on my k8s cluster. The cluster is composed of Ec2 instances running the latest CoreOS stable ami (CoreOS stable 1235.8.0)

The docker image that works on my dev machine is scratch based. To troubleshoot I created an image based on Ubuntu latest with a separate go program that just does a simple get item from dynamodb. When this image is run on my k8s cluster and the program run from an interactive shell, I get the same errors. I have confirmed I can ping the dynamodb endpoints from this env.

I am having a hard time troubleshooting this issue: am I missing something stupid here? Can someone point me in the right direction or have an idea of what is going on?


问:
An app which has complete control of the device
I would like to create an app which is preinstalled on a device and has complete control of it (no way to exit it), this is for devices handed out for a specific purpose. It will have some pages/navigation as well as the ability to run certain whitelisted apps.

Is there anything out there helping with this, or would this kind of an app have to be a custom build of Android? Thanks.

答: There are apps that donot do exactly what you want but achieve something similar to that. App Lock is one such app. It blocks the specific app view from the user until he enters the pin. The user will have to set Device administrator properties for such an app usually but if you are planning it as preinstalled then that can also be handled.</p>


问:
Could not load file or assembly 'System.IdentityModel.Tokens.Jwt after deploying on Azure
my web app is working fine on localhost, but when I publish it on Azure, I get the following error:

Could not load file or assembly 'System.IdentityModel.Tokens.Jwt' or
  one of its dependencies. The located assembly's manifest definition
  does not match the assembly reference. (Exception from HRESULT:
  0x80131040)

On a localhost is working fine.

I am using 4.5 framework, and it is definned in web.config file too. I tried to reinstall it in nuget manager but I get

Package 'System.IdentityModel.Tokens.Jwt.4.0.2.206221351' already exists in
  project 'project1'

I also can't find this assembly in references folder.
This is the first time I have expirienced this type of a problem.

What do you recommend me to do?

Regards,
Sandi

答: I had to roll back the dot net framework to 4.5.1</p>


问:
Convert MSSQL table to MySQL table
How to convert the below table into MySQL?

```<code>CREATE TABLE cmps(
`Id` varchar(5) NOT NULL,
`Estck` int NOT NULL,
`Qstck` int NOT NULL,
`Sstck` int NOT NULL,
`Rstck` int NOT NULL,
`Bstck` int NOT NULL,
`Shstck` int NOT NULL,
`Avlstck`  AS ([Sstck]-(([Rstck]+[Bstck]);+`Shstck`)),
 CONSTRAINT `PK_cmps` PRIMARY KEY CLUSTERED
(
`Id` ASC
)
</code>```

I have an issue with the below line.

```<code>   `Avlstck`  AS ([Sstck]-(([Rstck]+[Bstck]);+`Shstck`)),
</code>```

答:
By looking at Mysql documentation for computed columns, looks like you need to mention datatype for Avlstck. Also you need to remove those square brackets and semicolon

```<code>`Avlstck` int  AS (`Sstck`-((`Rstck`+`Bstck`) +`Shstck`))
</code>```

Title: Convert MSSQL table to MySQL table

Body:
How to convert the below table into MySQL?

CREATE TABLE cmps(
`Id` varchar(5) NOT NULL,
`Estck` int NOT NULL,
`Qstck` int NOT NULL,
`Sstck` int NOT NULL,
`Rstck` int NOT NULL,
`Bstck` int NOT NULL,
`Shstck` int NOT NULL,
`Avlstck`  AS ([Sstck]-(([Rstck]+[Bstck]);+`Shstck`)),
 CONSTRAINT `PK_cmps` PRIMARY KEY CLUSTERED
(
`Id` ASC
)

I have an issue with the below line.

   `Avlstck`  AS ([Sstck]-(([Rstck]+[Bstck]);+`Shstck`)),

Body:
By looking at Mysql documentation for computed columns, looks like you need to mention datatype for Avlstck. Also you need to remove those square brackets and semicolon

`Avlstck` int  AS (`Sstck`-((`Rstck`+`Bstck`) +`Shstck`))


问:
FizzBuzz returning empty array
I'm not quite sure why this is returning an empty array, does anyone have any clues or hints? Any help is appreciated.

function fizzBuzz() {
  var array = [];
  for (var i = 1; i <= 100; i++) {
    if (i % 3 === 0) {
      array.push("Fizz");
    } else if (i % 5 === 0) {
      array.push("Buzz");
    } else if (i % 3 === 0 && i % 5 === 0) {
      array.push("FizzBuzz");
    }
    return array;
  }
}
fizzBuzz();```

答:
You return from inside the loop after the first iteration.</p>

```<code>function fizzBuzz() {
  var array = [];
  for (var i = 1; i <= 100; i++) {
    if (i % 3 === 0) {
      array.push("Fizz");
    } else if (i % 5 === 0) {
      array.push("Buzz");
    } else if (i % 3 === 0 && i % 5 === 0) {
      array.push("FizzBuzz");
    }
  }
  return array; // <- !
}
fizzBuzz();
</code>```

Title: FizzBuzz returning empty array

Body:
You return from inside the loop after the first iteration.

function fizzBuzz() {
  var array = [];
  for (var i = 1; i <= 100; i++) {
    if (i % 3 === 0) {
      array.push("Fizz");
    } else if (i % 5 === 0) {
      array.push("Buzz");
    } else if (i % 3 === 0 && i % 5 === 0) {
      array.push("FizzBuzz");
    }
  }
  return array; // <- !
}
fizzBuzz();


问:
Server won't start on using authlogic-oauth2
I have included oauth2 and authlogic-oauth2 in the gemfile as I want to use them and am trying to start the server. It doesn't start and gives me the error:

```<code>/Library/Ruby/Gems/1.8/gems/railties-3.0.3/lib/rails.rb:44:in `configuration': undefined method `config' for nil:NilClass (NoMethodError)
        from /Library/Ruby/Gems/1.8/gems/authlogic_oauth2-1.1.2/lib/authlogic_oauth2.rb:14
        from /Library/Ruby/Gems/1.8/gems/bundler-1.0.7/lib/bundler/runtime.rb:64:in `require'
        from /Library/Ruby/Gems/1.8/gems/bundler-1.0.7/lib/bundler/runtime.rb:64:in `require'
        from /Library/Ruby/Gems/1.8/gems/bundler-1.0.7/lib/bundler/runtime.rb:62:in `each'
        from /Library/Ruby/Gems/1.8/gems/bundler-1.0.7/lib/bundler/runtime.rb:62:in `require'
        from /Library/Ruby/Gems/1.8/gems/bundler-1.0.7/lib/bundler/runtime.rb:51:in `each'
        from /Library/Ruby/Gems/1.8/gems/bundler-1.0.7/lib/bundler/runtime.rb:51:in `require'
        from /Library/Ruby/Gems/1.8/gems/bundler-1.0.7/lib/bundler.rb:112:in `require'
        from /Users/arkidmitra/Documents/qorm_bzar/buyzaar/config/application.rb:7
        from /Library/Ruby/Gems/1.8/gems/railties-3.0.3/lib/rails/commands.rb:28:in `require'
        from /Library/Ruby/Gems/1.8/gems/railties-3.0.3/lib/rails/commands.rb:28
        from /Library/Ruby/Gems/1.8/gems/railties-3.0.3/lib/rails/commands.rb:27:in `tap'
        from /Library/Ruby/Gems/1.8/gems/railties-3.0.3/lib/rails/commands.rb:27
        from script/rails:6:in `require'
        from script/rails:6
</code>```

I am using Rails 3.0.3 and Ruby 1.8.7. Also the sever seems to be starting fine till I add

```<code>gem "authlogic-oauth2"
</code>```

to the Gemfile.

答:
The authlogic-oauth2 is no more taken care by Andrew. For the updated gem try https://github.com/robdimarco/authlogic_oauth2

```<code>Here the authlogic_oauth2.rb had been changed.
require File.dirname(__FILE__) + "/authlogic_oauth2/version"
require File.dirname(__FILE__) + "/authlogic_oauth2/oauth2_process"
require File.dirname(__FILE__) + "/authlogic_oauth2/acts_as_authentic"
require File.dirname(__FILE__) + "/authlogic_oauth2/session"
require File.dirname(__FILE__) + "/authlogic_oauth2/helper"
require File.dirname(__FILE__) + "/oauth2_callback_filter"

ActiveRecord::Base.send(:include, AuthlogicOauth2::ActsAsAuthentic)
Authlogic::Session::Base.send(:include, AuthlogicOauth2::Session)
ActionController::Base.helper AuthlogicOauth2::Helper

# Throw callback rack app into the middleware stack
if defined?(ActionController::Metal)
  module AuthlogicOAuth2
    class Railtie < Rails::Railtie
      initializer :load_oauth2_callback_filter do |app|
        app.config.middleware.use(Oauth2CallbackFilter) # Rails >= 3.0
      end
    end
  end
else
  ActionController::Dispatcher.middleware.use(Oauth2CallbackFilter) # Rails < 3.0
end
</code>```

Hope this solves the problem for you.

Body:
I have included oauth2 and authlogic-oauth2 in the gemfile as I want to use them and am trying to start the server. It doesn't start and gives me the error:

/Library/Ruby/Gems/1.8/gems/railties-3.0.3/lib/rails.rb:44:in `configuration': undefined method `config' for nil:NilClass (NoMethodError)
        from /Library/Ruby/Gems/1.8/gems/authlogic_oauth2-1.1.2/lib/authlogic_oauth2.rb:14
        from /Library/Ruby/Gems/1.8/gems/bundler-1.0.7/lib/bundler/runtime.rb:64:in `require'
        from /Library/Ruby/Gems/1.8/gems/bundler-1.0.7/lib/bundler/runtime.rb:64:in `require'
        from /Library/Ruby/Gems/1.8/gems/bundler-1.0.7/lib/bundler/runtime.rb:62:in `each'
        from /Library/Ruby/Gems/1.8/gems/bundler-1.0.7/lib/bundler/runtime.rb:62:in `require'
        from /Library/Ruby/Gems/1.8/gems/bundler-1.0.7/lib/bundler/runtime.rb:51:in `each'
        from /Library/Ruby/Gems/1.8/gems/bundler-1.0.7/lib/bundler/runtime.rb:51:in `require'
        from /Library/Ruby/Gems/1.8/gems/bundler-1.0.7/lib/bundler.rb:112:in `require'
        from /Users/arkidmitra/Documents/qorm_bzar/buyzaar/config/application.rb:7
        from /Library/Ruby/Gems/1.8/gems/railties-3.0.3/lib/rails/commands.rb:28:in `require'
        from /Library/Ruby/Gems/1.8/gems/railties-3.0.3/lib/rails/commands.rb:28
        from /Library/Ruby/Gems/1.8/gems/railties-3.0.3/lib/rails/commands.rb:27:in `tap'
        from /Library/Ruby/Gems/1.8/gems/railties-3.0.3/lib/rails/commands.rb:27
        from script/rails:6:in `require'
        from script/rails:6

I am using Rails 3.0.3 and Ruby 1.8.7. Also the sever seems to be starting fine till I add

gem "authlogic-oauth2"

to the Gemfile.

Body:
The authlogic-oauth2 is no more taken care by Andrew. For the updated gem try https://github.com/robdimarco/authlogic_oauth2

Here the authlogic_oauth2.rb had been changed.
require File.dirname(__FILE__) + "/authlogic_oauth2/version"
require File.dirname(__FILE__) + "/authlogic_oauth2/oauth2_process"
require File.dirname(__FILE__) + "/authlogic_oauth2/acts_as_authentic"
require File.dirname(__FILE__) + "/authlogic_oauth2/session"
require File.dirname(__FILE__) + "/authlogic_oauth2/helper"
require File.dirname(__FILE__) + "/oauth2_callback_filter"

ActiveRecord::Base.send(:include, AuthlogicOauth2::ActsAsAuthentic)
Authlogic::Session::Base.send(:include, AuthlogicOauth2::Session)
ActionController::Base.helper AuthlogicOauth2::Helper

# Throw callback rack app into the middleware stack
if defined?(ActionController::Metal)
  module AuthlogicOAuth2
    class Railtie < Rails::Railtie
      initializer :load_oauth2_callback_filter do |app|
        app.config.middleware.use(Oauth2CallbackFilter) # Rails >= 3.0
      end
    end
  end
else
  ActionController::Dispatcher.middleware.use(Oauth2CallbackFilter) # Rails < 3.0
end

Hope this solves the problem for you.


问:
VBA copy active cell data to all active sheet error
I have 3 sheets and 1 master sheets.
I want to copy cell data in master to rest of the sheets.
It always thrw "Runtime error 1004. can anyone help?

Private Sub Worksheet_Change(ByVal Target As Range)
 Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets("Master")
    Dim columnName As String
    columnName = Split(ActiveCell.Address, "$")(1)
    Sheets.FillAcrossSheets ws.Range(columnName & ActiveCell.Row), xlFillWithAll
End Sub

答:
All sheets should be assigned to array and the range to fill must be from a sheet within the array. Try this</p>

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    Dim ws As Worksheet
    Dim shtArray As Variant
    shtArray = Array("Master", "Sheet1", "Sheet2", "Sheet3")
    Set ws = ThisWorkbook.Sheets("Master")
    Sheets(shtArray).FillAcrossSheets Target

    'Dim columnName As String
    'columnName = Split(ActiveCell.Address, "$")(1)
    'Sheets(shtArray).FillAcrossSheets ws.Range(columnName & ActiveCell.Row), xlFillWithAll
End Sub
</code>```

Body:
All sheets should be assigned to array and the range to fill must be from a sheet within the array. Try this

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim ws As Worksheet
    Dim shtArray As Variant
    shtArray = Array("Master", "Sheet1", "Sheet2", "Sheet3")
    Set ws = ThisWorkbook.Sheets("Master")
    Sheets(shtArray).FillAcrossSheets Target

    'Dim columnName As String
    'columnName = Split(ActiveCell.Address, "$")(1)
    'Sheets(shtArray).FillAcrossSheets ws.Range(columnName & ActiveCell.Row), xlFillWithAll
End Sub


问:
MYSQL Stored Procedure only updates on record
MYSQL Stored Procedure only updates one record when it should update all the ids in the WHERE id IN clause. When I run the SELECT and UPDATE outside of the stored procedure it works fine. Any suggestions?

```<code>DELIMITER $$
CREATE PROCEDURE update_ids(IN source int(10),IN target int(10))
BEGIN
    DECLARE idList varchar(5000) DEFAULT NULL;
    SET idList = (SELECT GROUP_CONCAT(id SEPARATOR ', ') FROM myTable ii WHERE ii.generic_id = source);
    UPDATE myTable i SET i.generic_id = target WHERE i.id IN (idList);

END$$
DELIMITER ;
</code>```

Then I call it by -->

```<code>CALL update_generic_ids(63, 1258);
</code>```

Update : 1 row effected.

Thanks in advance,

答:
once try below chunk of code, hope it will solve your problems!
If any question reach me!

DELIMITER $$
CREATE PROCEDURE update_ids(IN source int(10),IN target int(10))
BEGIN
    DECLARE idList varchar(5000) DEFAULT NULL;
    --SET idList = (SELECT GROUP_CONCAT(id SEPARATOR ', ') FROM myTable ii WHERE ii.generic_id = source);
    UPDATE myTable i SET i.generic_id = target WHERE i.id IN (
        SELECT  id FROM myTable ii WHERE ii.generic_id = source
    );

END$$
DELIMITER ;

Body:
MYSQL Stored Procedure only updates one record when it should update all the ids in the WHERE id IN clause. When I run the SELECT and UPDATE outside of the stored procedure it works fine. Any suggestions?

DELIMITER $$
CREATE PROCEDURE update_ids(IN source int(10),IN target int(10))
BEGIN
    DECLARE idList varchar(5000) DEFAULT NULL;
    SET idList = (SELECT GROUP_CONCAT(id SEPARATOR ', ') FROM myTable ii WHERE ii.generic_id = source);
    UPDATE myTable i SET i.generic_id = target WHERE i.id IN (idList);

END$$
DELIMITER ;

Then I call it by -->

CALL update_generic_ids(63, 1258);

Update : 1 row effected.

Thanks in advance,


问:
How to convert an NSString into an NSNumber
How can I convert a NSString containing a number of any primitive data type (e.g. int, float, char, unsigned int, etc.)? The problem is, I don't know which number type the string will contain at runtime.

I have an idea how to do it, but I'm not sure if this works with any type, also unsigned and floating point values:

```<code>long long scannedNumber;
NSScanner *scanner = [NSScanner scannerWithString:aString];
[scanner scanLongLong:&scannedNumber];
NSNumber *number = [NSNumber numberWithLongLong: scannedNumber];
</code>```

Thanks for the help.

答:
you can also do like this code 8.3.3 ios 10.3 support</p>

```<code>[NSNumber numberWithInt:[@"put your string here" intValue]]
</code>```

Body:
How can I convert a NSString containing a number of any primitive data type (e.g. int, float, char, unsigned int, etc.)? The problem is, I don't know which number type the string will contain at runtime.

I have an idea how to do it, but I'm not sure if this works with any type, also unsigned and floating point values:

long long scannedNumber;
NSScanner *scanner = [NSScanner scannerWithString:aString];
[scanner scanLongLong:&scannedNumber];
NSNumber *number = [NSNumber numberWithLongLong: scannedNumber];

Thanks for the help.

Body:
you can also do like this code 8.3.3 ios 10.3 support

[NSNumber numberWithInt:[@"put your string here" intValue]]


问:
select and calculate numdays from two tables in oracle
I m doing a leave calculation. I have Leave requested table and Employee Table.

Their relationship is Employee can request many Leaves. i.e

Leave request table has Employee_Serail_ID as one to many. I have done the following query to select all leave request and calculkate the number of days.

```<code>    SELECT (LR.DATE_TO - LR.DATE_FROM) as NumDays ,
    LR.EMPLOYEE_SERIAL_ID, LR.ID as LEAVE_REQUEST_ID
    FROM TBL_LEAVE_REQUEST LR ;

NUMDAYS EMPLOYEE_SERIAL_ID LEAVE_REQUEST_ID
     3 EMP_286  LEAVE_35
     2 EMP_243  LEAVE_36
     2 EMP_284  LEAVE_37
     3 EMP_243  LEAVE_38
    32 EMP_243  LEAVE_39
     0 EMP_303  LEAVE_40
     1 EMP_241  LEAVE_41
</code>```

But , i figured out that all employee who have not requested leave will not be selected using this query.

I want to modify this query that - if the employee has rquested a leave it will show the numdays , and if it has not this query should return Numdays 0 for all employees.

Numdays

答:
You'll need to left join your leave request table to your actual employee table. This will give you an employee record, even if they don't have a leave request.

Since you haven't posted your schema, and you haven't specified what database you're actually using, I can't write much of the query for you. Your logic will look something like this:

```<code>SELECT
    T.EMPLOYEE_ID
    , ISNULL((LR.DATE_TO - LR.DATE_FROM), 0) as NumDays
    , LR.EMPLOYEE_SERIAL_ID
    , LR.ID as LEAVE_REQUEST_ID
FROM
    TBL_EMPLOYEE T
    LEFT JOIN TBL_LEAVE_REQUEST LR
        on T.EMPLOYEE_ID = LR.EMPLOYEE_ID
;
</code>```

The ISNULL function is used by MSSQL Server. Other databases require different functions.

If you're using Oracle, replace ISNULL( with NVL(.

If you're using PostgreSQL or MySQL, you'll want the command COALESCE(.

A note in ISNULL() and NVL() vs COALESCE(). As @Ronnis pointed out, any ANSI compliant database should support the COALESCE() function.

Looking into the documentation a little further, you may get better query performance using COALESCE() than  NVL() or ISNULL(). The former will short circuit its evaluation, whereas the other two will not.

Body:
I m doing a leave calculation. I have Leave requested table and Employee Table.

Their relationship is Employee can request many Leaves. i.e

Leave request table has Employee_Serail_ID as one to many. I have done the following query to select all leave request and calculkate the number of days.

    SELECT (LR.DATE_TO - LR.DATE_FROM) as NumDays ,
    LR.EMPLOYEE_SERIAL_ID, LR.ID as LEAVE_REQUEST_ID
    FROM TBL_LEAVE_REQUEST LR ;

NUMDAYS EMPLOYEE_SERIAL_ID LEAVE_REQUEST_ID
     3 EMP_286  LEAVE_35
     2 EMP_243  LEAVE_36
     2 EMP_284  LEAVE_37
     3 EMP_243  LEAVE_38
    32 EMP_243  LEAVE_39
     0 EMP_303  LEAVE_40
     1 EMP_241  LEAVE_41

But , i figured out that all employee who have not requested leave will not be selected using this query.

I want to modify this query that - if the employee has rquested a leave it will show the numdays , and if it has not this query should return Numdays 0 for all employees.

Numdays

Body:
You'll need to left join your leave request table to your actual employee table. This will give you an employee record, even if they don't have a leave request.

Since you haven't posted your schema, and you haven't specified what database you're actually using, I can't write much of the query for you. Your logic will look something like this:

SELECT
    T.EMPLOYEE_ID
    , ISNULL((LR.DATE_TO - LR.DATE_FROM), 0) as NumDays
    , LR.EMPLOYEE_SERIAL_ID
    , LR.ID as LEAVE_REQUEST_ID
FROM
    TBL_EMPLOYEE T
    LEFT JOIN TBL_LEAVE_REQUEST LR
        on T.EMPLOYEE_ID = LR.EMPLOYEE_ID
;

The ISNULL function is used by MSSQL Server. Other databases require different functions.

If you're using Oracle, replace ISNULL( with NVL(.

If you're using PostgreSQL or MySQL, you'll want the command COALESCE(.

A note in ISNULL() and NVL() vs COALESCE(). As @Ronnis pointed out, any ANSI compliant database should support the COALESCE() function.

Looking into the documentation a little further, you may get better query performance using COALESCE() than  NVL() or ISNULL(). The former will short circuit its evaluation, whereas the other two will not.