问:
Is it possible to flip between a large block of C++ macros?
Assume I have a bunch of macros defining some variables - they need to be defined two ways in different parts of the code (yes, it's a bad idea, but refactoring will take a good long ways).

Is it possible to get the below snippet to work, that is, to print out 4 then 1?

```<code>#include <iostream>
#define ENABLE
#ifdef ENABLE
#define B 4
#define C 5
//imagine a bunch more here
#else
#define B 1
#define C 2
//imagine a bunch more here
#endif

int main()
{
    std::cout << B << std::endl;
#pragma push_macro("ENABLE")
#undef ENABLE
    std::cout << B << std::endl;
#pragma pop_macro("ENABLE")

    return 0;
}
</code>```

It's certainly possible to achieve the same effect by defining B specifically, but if I have a large block of macros, that's not 100% practical:

```<code>#include <iostream>
#define B 4

int main()
{
#pragma push_macro("B")
#undef B
#define B 1
    std::cout << B << std::endl;
#pragma pop_macro("B")
    std::cout << B << std::endl;
    return 0;
}
</code>```

答:
You might be able to do it by repeatedly #includeing a header file:

Header:

```<code>// Note: no inclusion guards!
#undef B
#undef C
#ifdef ENABLE
#define B 4
#define C 5
//imagine a bunch more here
#else
#define B 1
#define C 2
//imagine a bunch more here
#endif
</code>```

Usage in a src file:

```<code>int main()
{
#define ENABLE
#include "header"
    std::cout << B << std::endl;
#undef ENABLE
#include "header"
    std::cout << B << std::endl;
    return 0;
}
</code>```

Body:
Assume I have a bunch of macros defining some variables - they need to be defined two ways in different parts of the code (yes, it's a bad idea, but refactoring will take a good long ways).

Is it possible to get the below snippet to work, that is, to print out 4 then 1?

#include <iostream>
#define ENABLE
#ifdef ENABLE
#define B 4
#define C 5
//imagine a bunch more here
#else
#define B 1
#define C 2
//imagine a bunch more here
#endif

int main()
{
    std::cout << B << std::endl;
#pragma push_macro("ENABLE")
#undef ENABLE
    std::cout << B << std::endl;
#pragma pop_macro("ENABLE")

    return 0;
}

It's certainly possible to achieve the same effect by defining B specifically, but if I have a large block of macros, that's not 100% practical:

#include <iostream>
#define B 4

int main()
{
#pragma push_macro("B")
#undef B
#define B 1
    std::cout << B << std::endl;
#pragma pop_macro("B")
    std::cout << B << std::endl;
    return 0;
}

Body:
You might be able to do it by repeatedly #includeing a header file:

Header:

// Note: no inclusion guards!
#undef B
#undef C
#ifdef ENABLE
#define B 4
#define C 5
//imagine a bunch more here
#else
#define B 1
#define C 2
//imagine a bunch more here
#endif

Usage in a src file:

int main()
{
#define ENABLE
#include "header"
    std::cout << B << std::endl;
#undef ENABLE
#include "header"
    std::cout << B << std::endl;
    return 0;
}


来源: stackexchange

问:
Update inventory stock csv file with python
I have a stock inventory file in csv format like this:

```<code>sku nome    prezzo  qty codice
1   uno       10    1   11111
2   due       10    1   22222
3   tre       10    1   33333
4   quattro   10    1   44444
5   cinque    10    1   55555
10  dieci     10    1   101010
</code>```

The only column that can be used as a key is 'sku'.
The file is update adding new sku,updating existings and deleting sku that are no more present in stock, like this:

```<code>sku nome    prezzo  qty codice
  1  uno        20    2  11111
  2  due        20    2  22222
  3  tre        20    2  33333
  5  cinque     20    2  55555
 10  dieci      20    2  101010
 11  undici     20    2  111111
</code>```

I'm new in python but with pandas module and 2 or 3 line of code I've make a outer merge :

```<code>import pandas as pd

    a = pd.read_csv("./old.csv")
    b = pd.read_csv("./new.csv")

    c = pd.merge(a, b, on = 'sku', how = 'outer', indicator = True)
    c.to_csv("./updated.csv", index=False)
</code>```

The result is right:

```<code>sku nome_x  prezzo_x    qty_x   codice _x   nome_y  prezzo_y    qty_y   codice _y   _merge
1   uno 10  1   11111   uno 20  2   11111   both
2   due 10  1   22222   due 20  2   22222   both
3   tre 10  1   33333   tre 20  2   33333   both
4   quattro 10  1   44444                   left_only
5   cinque  10  1   55555   cinque  20  2   55555   both
10  dieci   10  1   101010  dieci   20  2   101010  both
11                  undici  20  2   111111  right_only
</code>```

but isnt an useable csv...
I hope that I can have this:

```<code>sku nome    prezzo  qty codice
  1  uno        20  2   11111
  2  due        20  2   22222
  3  tre        20  2   33333
  4  quattro     0  0   44444
  5  cinque     20  2   55555
  10 dieci      20  2   101010
  11 undici     20  2   111111
</code>```

答:
IIUC:</p>

```<code>In [52]: r = b.set_index('sku') \
    ...:       .reindex(pd.Index(a['sku']).union(pd.Index(b['sku']))) \
    ...:       .combine_first(a.set_index('sku').assign(qty=0, prezzo=0)) \
    ...:       .reset_index()
    ...:

In [53]: r[['prezzo','qty','codice']] = r[['prezzo','qty','codice']].astype(int)

In [54]: r
Out[54]:
   sku     nome  prezzo  qty  codice
0    1      uno      20    2   11111
1    2      due      20    2   22222
2    3      tre      20    2   33333
3    4  quattro       0    0   44444
4    5   cinque      20    2   55555
5   10    dieci      20    2  101010
6   11   undici      20    2  111111
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a stock inventory file in csv format like this:

sku nome    prezzo  qty codice
1   uno       10    1   11111
2   due       10    1   22222
3   tre       10    1   33333
4   quattro   10    1   44444
5   cinque    10    1   55555
10  dieci     10    1   101010

The only column that can be used as a key is 'sku'.
The file is update adding new sku,updating existings and deleting sku that are no more present in stock, like this:

sku nome    prezzo  qty codice
  1  uno        20    2  11111
  2  due        20    2  22222
  3  tre        20    2  33333
  5  cinque     20    2  55555
 10  dieci      20    2  101010
 11  undici     20    2  111111

I'm new in python but with pandas module and 2 or 3 line of code I've make a outer merge :

import pandas as pd

    a = pd.read_csv("./old.csv")
    b = pd.read_csv("./new.csv")

    c = pd.merge(a, b, on = 'sku', how = 'outer', indicator = True)
    c.to_csv("./updated.csv", index=False)

The result is right:

sku nome_x  prezzo_x    qty_x   codice _x   nome_y  prezzo_y    qty_y   codice _y   _merge
1   uno 10  1   11111   uno 20  2   11111   both
2   due 10  1   22222   due 20  2   22222   both
3   tre 10  1   33333   tre 20  2   33333   both
4   quattro 10  1   44444                   left_only
5   cinque  10  1   55555   cinque  20  2   55555   both
10  dieci   10  1   101010  dieci   20  2   101010  both
11                  undici  20  2   111111  right_only

but isnt an useable csv...
I hope that I can have this:

sku nome    prezzo  qty codice
  1  uno        20  2   11111
  2  due        20  2   22222
  3  tre        20  2   33333
  4  quattro     0  0   44444
  5  cinque     20  2   55555
  10 dieci      20  2   101010
  11 undici     20  2   111111

Body:
IIUC:

In [52]: r = b.set_index('sku') \
    ...:       .reindex(pd.Index(a['sku']).union(pd.Index(b['sku']))) \
    ...:       .combine_first(a.set_index('sku').assign(qty=0, prezzo=0)) \
    ...:       .reset_index()
    ...:

In [53]: r[['prezzo','qty','codice']] = r[['prezzo','qty','codice']].astype(int)

In [54]: r
Out[54]:
   sku     nome  prezzo  qty  codice
0    1      uno      20    2   11111
1    2      due      20    2   22222
2    3      tre      20    2   33333
3    4  quattro       0    0   44444
4    5   cinque      20    2   55555
5   10    dieci      20    2  101010
6   11   undici      20    2  111111


问:
PyMySQL: Inserting data pepared statement
I am trying to insert data in the database using a prepared statement. All my columns in the database are VARCHAR, but PyMySQL gives the following error:

```<code>Not all arguments converted during string formatting
</code>```

All variables are parsed childnodes from a XML file. An example of a variable:

```<code>try:
    description1 = product.getElementsByTagName('description')[0]
    description = description1.childNodes[0].data
except IndexError:
    print('No description')
    description = 'None'
</code>```

When I insert the data without the prepared statement, It works fine. But I want to use prepared statements for the escape characters.

This is my prepared statement code:

```<code>        sql = """INSERT INTO Studystore(daisycon_unique_id, title, author, isbn, price, link, image_location, category, product_condition, description, in_stock, in_stock_amount, price_shipping, language, book_edition, number_of_pages, status, insert_date, update_date)
          VALUES ('%s')"""

        args = (str(daisycon_unique_id), str(title), str(author), str(isbn), str(price), str(link), str(image_location), str(category), str(product_condition), str(description), str(in_stock), str(in_stock_amount), str(price_shipping), str(language), str(book_edition), str(number_of_pages), str(status), str(insert_date), str(update_date),)

        try:

            # Execute the SQL command
            cursor.execute(sql, args)
            # Commit your changes in the database
            db.commit()

        except Exception as e:
            print(e)
)
</code>```

答:
I saw what was going wrong.
This is the working code:</p>

```<code># Prepare SQL query to INSERT a record into the database.
    sql = """INSERT INTO Studystore(daisycon_unique_id, title, author, isbn, price, link, image_location, category, product_condition, description, in_stock, in_stock_amount, price_shipping, language, book_edition, number_of_pages, status, insert_date, update_date)
      VALUES ("%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s")"""

    args = (daisycon_unique_id, title, author, isbn, price, link, image_location, category, product_condition, description, in_stock, in_stock_amount, price_shipping, language, book_edition, number_of_pages, status, insert_date, update_date,)

    try:

        # Execute the SQL command
        cursor.execute(sql, args)
        # Commit your changes in the database
        db.commit()

    except Exception as e:
        print(e)
</code>```

Body:
I am trying to insert data in the database using a prepared statement. All my columns in the database are VARCHAR, but PyMySQL gives the following error:

Not all arguments converted during string formatting

All variables are parsed childnodes from a XML file. An example of a variable:

try:
    description1 = product.getElementsByTagName('description')[0]
    description = description1.childNodes[0].data
except IndexError:
    print('No description')
    description = 'None'

When I insert the data without the prepared statement, It works fine. But I want to use prepared statements for the escape characters.

This is my prepared statement code:

        sql = """INSERT INTO Studystore(daisycon_unique_id, title, author, isbn, price, link, image_location, category, product_condition, description, in_stock, in_stock_amount, price_shipping, language, book_edition, number_of_pages, status, insert_date, update_date)
          VALUES ('%s')"""

        args = (str(daisycon_unique_id), str(title), str(author), str(isbn), str(price), str(link), str(image_location), str(category), str(product_condition), str(description), str(in_stock), str(in_stock_amount), str(price_shipping), str(language), str(book_edition), str(number_of_pages), str(status), str(insert_date), str(update_date),)

        try:

            # Execute the SQL command
            cursor.execute(sql, args)
            # Commit your changes in the database
            db.commit()

        except Exception as e:
            print(e)
)

Body:
I saw what was going wrong.
This is the working code:

# Prepare SQL query to INSERT a record into the database.
    sql = """INSERT INTO Studystore(daisycon_unique_id, title, author, isbn, price, link, image_location, category, product_condition, description, in_stock, in_stock_amount, price_shipping, language, book_edition, number_of_pages, status, insert_date, update_date)
      VALUES ("%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s", "%s")"""

    args = (daisycon_unique_id, title, author, isbn, price, link, image_location, category, product_condition, description, in_stock, in_stock_amount, price_shipping, language, book_edition, number_of_pages, status, insert_date, update_date,)

    try:

        # Execute the SQL command
        cursor.execute(sql, args)
        # Commit your changes in the database
        db.commit()

    except Exception as e:
        print(e)


问:
Spring CustomNumberEditor parses numbers that are not numbers
I'm using Spring CustomNumberEditor editor to bind my float values and I've experimented that if in the value is not a number sometimes it can parse the value and no error is returned.

number=10 ...... then the number is 10 and there's no errors

number=10a ......   then the number is 10 and there's no errors

number=10a25 ...... then the number is 10 and there's no errors

number=a ...... error because the number is not valid

So it seems that the editor parses the value until it can and omit the rest. Is there any way to configure this editor so the validation is strict (so numbers like 10a or 10a25 result in error) or do I have to build my custom implementation. I'm looking something like setting lenient to false in CustomDateEditor/DateFormat so dates cannot be parsed to the most probable one.

The way I register the editor is:

```<code>@InitBinder
public void initBinder(WebDataBinder binder){
    NumberFormat numberFormat = NumberFormat.getInstance();
    numberFormat.setGroupingUsed(false);
    binder.registerCustomEditor(Float.class, new CustomNumberEditor(Float.class, numberFormat, true));
}
</code>```

Thanks.

答:
Since it relies on the NumberFormat class, which stops parsing the input string at the first invalid character I think you'll have to extend the NumberFormat class.

First blush would be

```<code>public class StrictFloatNumberFormat extends NumberFormat {

  private void validate(in) throws ParseException{
     try {
       new Float(in);
     }
     catch (NumberFormatException nfe) {
       throw new ParseException(nfe.getMessage(), 0);
  }

  public Number parse(String in) throws ParseException {
    validate(in);
    super.parse(in);
  }
  ..... //any other methods
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm using Spring CustomNumberEditor editor to bind my float values and I've experimented that if in the value is not a number sometimes it can parse the value and no error is returned.

number=10 ...... then the number is 10 and there's no errors

number=10a ......   then the number is 10 and there's no errors

number=10a25 ...... then the number is 10 and there's no errors

number=a ...... error because the number is not valid

So it seems that the editor parses the value until it can and omit the rest. Is there any way to configure this editor so the validation is strict (so numbers like 10a or 10a25 result in error) or do I have to build my custom implementation. I'm looking something like setting lenient to false in CustomDateEditor/DateFormat so dates cannot be parsed to the most probable one.

The way I register the editor is:

@InitBinder
public void initBinder(WebDataBinder binder){
    NumberFormat numberFormat = NumberFormat.getInstance();
    numberFormat.setGroupingUsed(false);
    binder.registerCustomEditor(Float.class, new CustomNumberEditor(Float.class, numberFormat, true));
}

Thanks.

Body:
Since it relies on the NumberFormat class, which stops parsing the input string at the first invalid character I think you'll have to extend the NumberFormat class.

First blush would be

public class StrictFloatNumberFormat extends NumberFormat {

  private void validate(in) throws ParseException{
     try {
       new Float(in);
     }
     catch (NumberFormatException nfe) {
       throw new ParseException(nfe.getMessage(), 0);
  }

  public Number parse(String in) throws ParseException {
    validate(in);
    super.parse(in);
  }
  ..... //any other methods
}


问:
AngularJS Promise. undefined array that exists
So I'm doing some promise chain because I need some code run synchronous. It's everything fine until I have two nested forEach. After the first forEach I show the actual object that has the next array I want to iterate. Is there! But then I try to iterate that array and is undefined?

```<code>vm.enviarEmail = function() {
    var result = {};
    var def = $q.defer();
    def.promise
    .then(function(result){
        console.log("1");
        return estacion.leerEstacionesInforiego()
        .then(function(respuesta) {
            angular.forEach(respuesta, function(est) {
                est.latitud = $rootScope.dmsToddI(est.latitud);
                est.longitud = $rootScope.dmsToddI(est.longitud);
            });
            result.estaciones = respuesta;
            console.log("estaciones",result.estaciones);
            return result;
        }, function(respuesta) {
            console.log("ERROR: obtención de las estaciones no realizada");
        });
        return result;
    })
    .then(function(result) {
        console.log("2");
        return user.leerUsuarios()
        .then(function(respuesta) {
            result.users = respuesta;
            console.log("usuarios",result.users);
            return result;
        }, function(respuesta) {
            console.log("ERROR: obtención de usuarios no realizada.");
        });
        return result;
    })
    .then(function(result) {
        console.log("3");
        angular.forEach(result.users, function(user) {
            user.html = "<style>td {border:solid 1px;}</style><table><thead><tr><th>Parcela</th><th>Estación</th><th>Cultivo</th><th>Método de riego</th>"+
            "<th>Fecha siembra</th><th>Fecha último riego</th><th>Recomendación</th></tr></thead><tbody>";
            campo.leerParcelasPropietario(user.id)
            .then(function(respuesta) {
                user.parcelas = respuesta;
            }, function(respuesta) {
                console.log("ERROR: obtención de parcelas por usuario no realizada.");
            });
        });
        console.log("parcelas",result);
        return result;
    })
    .then(function(result) {
        console.log("4");
        angular.forEach(result.users, function(user) {
            console.log(user,user.parcelas);
            angular.forEach(user.parcelas, function(par) {
                console.log("parcela",par.nombre);
                var hoy = new Date();                           // Fecha actual

                // Obtener el cultivo de la parcela
                campo.leerCultivo(par.cultivo)
                .then(function(respuesta) {
                    par.cultivo = respuesta;
                    console.log(par);
                }, function(respuesta) {
                    console.log("ERROR: obtención del cultivo no realizada");
                });

                // Obtener el método de riego de la parcela
                campo.leerMetodoRiego(par.riego)
                .then(function(respuesta) {
                    par.riego = respuesta;
                }, function(respuesta) {
                    console.log("ERROR: obtención del método de riego no realizada");
                });

                // Calcular la estación cercana
                var distMin = 99999999;
                var x1 = new google.maps.LatLng(par.latitud,par.longitud);
                angular.forEach(result.estaciones, function(est) {
                    var x2 = new google.maps.LatLng(est.latitud,est.longitud);
                    var distancia = google.maps.geometry.spherical.computeDistanceBetween(x1, x2);
                    if (distancia < distMin) {
                        distMin = distancia;
                        par.estacion = est;
                    }
                });

                // Cálculo de días desde el último riego
                var fecha = new Date(Date.parse(par.consulta));
                par.diasR = (hoy - fecha)/(1000*60*60*24);  // En días y no milisegundos

                // Cálculo del estado del cultivo
                var fechaS = new Date(Date.parse(par.siembra));
                par.diasE = (hoy - fechaS)/(1000*60*60*24);

                if (par.diasE < 46)
                    par.estado = 'ini';
                else if (par.diasE < 76)
                    par.estado = 'des';
                else if (par.diasE < 96)
                    par.estado = 'med';
                else
                    par.estado = 'fin';
            });
        });
        return result;
    })
    .then(function(result) {
        console.log("5");
        angular.forEach(result.users, function(user) {
            console.log("para obtener datos",result.users);
            angular.forEach(user.parcelas, function(par) {
                estacion.obtenerDatosInforiego(Math.round(par.diasR),par.estacion.indicativo,par.estacion.provincia)
                .then(function(respuesta) {
                    par.datos = respuesta;
                }, function(respuesta) {
                    console.log("ERROR: obtención de los datos de Inforiego no realizada");
                });
            });
        });
        return result;
    })
    .then(function(result) {
        console.log("6");
        angular.forEach(result.users, function(user) {
            angular.forEach(user.parcelas, function(par) {
                par.datos_totales = {et0: 0, etc: 0, pe: 0};    // Los datos totales obtenidos de los cálculos
                angular.forEach(par.datos, function(diadatos) {
                    // Corrección de la temperatura media
                    diadatos.tempmedia = (diadatos.tempmax+diadatos.tempmin)/2;

                    // Cálculo de la presión atmosférica (kPa)
                    diadatos.presion = 101.3*Math.pow(((293-(0.0065*par.estacion.altitud))/293),5.26);

                    // Cálculo de la constante psicométrica (kPa/ºC)
                    diadatos.constante_psicometrica = diadatos.presion*0.000665;

                    // Cálculo de la presión de saturación de vapor a la temperatura del aire (max, med y min) (kPa)
                    var psvmax = 0.6108*Math.pow(2.7183,(17.27*diadatos.tempmax)/(diadatos.tempmax+237.3));
                    var psvmin = 0.6108*Math.pow(2.7183,(17.27*diadatos.tempmin)/(diadatos.tempmin+237.3));
                    var psvmed = (psvmax+psvmin)/2;

                    // Cálculo de la presión real de vapor (kPa)
                    diadatos.presion_real_vapor = (psvmed*diadatos.humedadmedia)/100;

                    // Cálculo de la pendiente de la curva de presión de vapor (kPa/ºC)
                    diadatos.pendiente_curva_presion = (4098*psvmed)/Math.pow((diadatos.tempmedia+237.3),2);

                    // Cálculo de la ET0
                    diadatos.et0 = ((0.408*diadatos.pendiente_curva_presion*diadatos.rn)
                            +(diadatos.constante_psicometrica*diadatos.velviento*900*(psvmed-diadatos.presion_real_vapor))/(273+diadatos.tempmedia))
                            /(diadatos.pendiente_curva_presion+(diadatos.constante_psicometrica*(1+0.34*diadatos.velviento)));

                    // Cálculo de la ETc
                    if (par.estado == 'ini') {
                        diadatos.etc = diadatos.et0*par.cultivo.coef_ini;
                        diadatos.kc = par.cultivo.coef_ini;
                    } else if (par.estado == 'des') {
                        diadatos.etc = diadatos.et0*par.cultivo.coef_des;
                        diadatos.kc = par.cultivo.coef_des;
                    } else if (par.estado == 'med') {
                        diadatos.etc = diadatos.et0*par.cultivo.coef_med;
                        diadatos.kc = par.cultivo.coef_med;
                    } else if (par.estado == 'fin') {
                        diadatos.etc = diadatos.et0*par.cultivo.coef_fin;
                        diadatos.kc = par.cultivo.coef_fin;
                    }

                    // Sumar para los totales
                    par.datos_totales.et0 = par.datos_totales.et0 + diadatos.et0;
                    par.datos_totales.etc = par.datos_totales.etc + diadatos.etc;
                    par.datos_totales.pe = par.datos_totales.pe + diadatos.pepmon;
                });
                par.datos_totales.rr = (par.datos_totales.etc-par.datos_totales.pe)/par.riego.coef_eficiencia;
                user.html = user.html + "<tr><td>" + par.nombre + "</td><td>" + par.estacion.nombre + "</td>"+
                "<td>" + par.cultivo.nombre + "</td><td>" + par.riego.nombre + "</td>"+
                "<td>" + $filter('date')(par.siembra, 'dd-MM-yyyy') + "</td>"+
                "<td>" + $filter('date')(par.consulta, 'dd-MM-yyyy') + "</td>"+
                "<td><b>" + Math.round(par.datos_totales.rr) + "</b> l/m<sup>2</sup></td></tr>";
            });
        });
        return result;
    })
    .then(function(result) {
        console.log("7");
        angular.forEach(result.users, function(user) {
            if (user.usuario != 'jlmm') {
                user.html = user.html + "</tbody></table><br><a href='http://localhost:8080/AgriWea/#!/'>AgriWea</a>";
                $http.post('http://localhost:8100/sendmail', {params: {
                      from: 'AgriWea <jmariscan@dominio.es>',
                      to: user.email,
                      subject: 'Recomendación diaria de riego',
                      html: user.html}})
                .then(function(respuesta) {
                    console.log("Email enviado correctamente",texto);
                }, function(respuesta) {
                    console.log("Email no enviado", respuesta);
                });
            }
        });
    })
    .catch(function (error) {
        console.log(error);
    });
    def.resolve(result);
</code>```

As you can see I have a console.log, this is what I get:

I was thinking that maybe the object was undefined because of asynchronous in Angular but in the same console.log I can see that the array exists but if I try to access it is undefined. Help!

SOLUTION

Using the code of @trincot, I reduced the number of then and I made all my code in just three. Thanks everyone!

答:
You state that you use a promise chain because you want to run code synchronously, but that is not possible. The parts of a promise chain are executed asynchronously. The last line in your function is executed before any of the then callbacks.

Also, you cannot expect the function call to return the email. Currently, your function is not returning anything, so when you call the function you'll get undefined.

But even if you would return something, it could never be the  result. At most you can return a promise.

You need to embrace the asynchronous behaviour, and keep working with that pattern. So don't expect to assign values synchronously. Instead, keep using then.

For instance, you could start with an immediately resolving promise that passes the empty result object down the chain:

```<code>vm.enviarEmail = function() {
  $q.when({}).then(function(result) {
      ...
      return result; // <-- don't forget to return the enriched value
    })
    .then(function(result) {
      ...
      return result;
    })
    .then(function(result) {
      ...
      return result;
    })
    .then(function(result) {
      angular.forEach(result.users, function(user) {
        console.log(user, user.parcelas);
        angular.forEach(user.parcelas, function(par) {
          ...
        });
      });
      return result; // <-- you need to return the promise
    });
};
</code>```

Then you use it as follows:

```<code>vm.enviarEmail().then(function (result)  {
     console.log(result); // keep with the async pattern
});
</code>```

Body:
So I'm doing some promise chain because I need some code run synchronous. It's everything fine until I have two nested forEach. After the first forEach I show the actual object that has the next array I want to iterate. Is there! But then I try to iterate that array and is undefined?

vm.enviarEmail = function() {
    var result = {};
    var def = $q.defer();
    def.promise
    .then(function(result){
        console.log("1");
        return estacion.leerEstacionesInforiego()
        .then(function(respuesta) {
            angular.forEach(respuesta, function(est) {
                est.latitud = $rootScope.dmsToddI(est.latitud);
                est.longitud = $rootScope.dmsToddI(est.longitud);
            });
            result.estaciones = respuesta;
            console.log("estaciones",result.estaciones);
            return result;
        }, function(respuesta) {
            console.log("ERROR: obtención de las estaciones no realizada");
        });
        return result;
    })
    .then(function(result) {
        console.log("2");
        return user.leerUsuarios()
        .then(function(respuesta) {
            result.users = respuesta;
            console.log("usuarios",result.users);
            return result;
        }, function(respuesta) {
            console.log("ERROR: obtención de usuarios no realizada.");
        });
        return result;
    })
    .then(function(result) {
        console.log("3");
        angular.forEach(result.users, function(user) {
            user.html = "

Parcela	Estación	Cultivo	Método de riego	"+
            "Fecha siembra	Fecha último riego	Recomendación

";
            campo.leerParcelasPropietario(user.id)
            .then(function(respuesta) {
                user.parcelas = respuesta;
            }, function(respuesta) {
                console.log("ERROR: obtención de parcelas por usuario no realizada.");
            });
        });
        console.log("parcelas",result);
        return result;
    })
    .then(function(result) {
        console.log("4");
        angular.forEach(result.users, function(user) {
            console.log(user,user.parcelas);
            angular.forEach(user.parcelas, function(par) {
                console.log("parcela",par.nombre);
                var hoy = new Date();                           // Fecha actual

                // Obtener el cultivo de la parcela
                campo.leerCultivo(par.cultivo)
                .then(function(respuesta) {
                    par.cultivo = respuesta;
                    console.log(par);
                }, function(respuesta) {
                    console.log("ERROR: obtención del cultivo no realizada");
                });

                // Obtener el método de riego de la parcela
                campo.leerMetodoRiego(par.riego)
                .then(function(respuesta) {
                    par.riego = respuesta;
                }, function(respuesta) {
                    console.log("ERROR: obtención del método de riego no realizada");
                });

                // Calcular la estación cercana
                var distMin = 99999999;
                var x1 = new google.maps.LatLng(par.latitud,par.longitud);
                angular.forEach(result.estaciones, function(est) {
                    var x2 = new google.maps.LatLng(est.latitud,est.longitud);
                    var distancia = google.maps.geometry.spherical.computeDistanceBetween(x1, x2);
                    if (distancia < distMin) {
                        distMin = distancia;
                        par.estacion = est;
                    }
                });

                // Cálculo de días desde el último riego
                var fecha = new Date(Date.parse(par.consulta));
                par.diasR = (hoy - fecha)/(1000*60*60*24);  // En días y no milisegundos

                // Cálculo del estado del cultivo
                var fechaS = new Date(Date.parse(par.siembra));
                par.diasE = (hoy - fechaS)/(1000*60*60*24);

                if (par.diasE < 46)
                    par.estado = 'ini';
                else if (par.diasE < 76)
                    par.estado = 'des';
                else if (par.diasE < 96)
                    par.estado = 'med';
                else
                    par.estado = 'fin';
            });
        });
        return result;
    })
    .then(function(result) {
        console.log("5");
        angular.forEach(result.users, function(user) {
            console.log("para obtener datos",result.users);
            angular.forEach(user.parcelas, function(par) {
                estacion.obtenerDatosInforiego(Math.round(par.diasR),par.estacion.indicativo,par.estacion.provincia)
                .then(function(respuesta) {
                    par.datos = respuesta;
                }, function(respuesta) {
                    console.log("ERROR: obtención de los datos de Inforiego no realizada");
                });
            });
        });
        return result;
    })
    .then(function(result) {
        console.log("6");
        angular.forEach(result.users, function(user) {
            angular.forEach(user.parcelas, function(par) {
                par.datos_totales = {et0: 0, etc: 0, pe: 0};    // Los datos totales obtenidos de los cálculos
                angular.forEach(par.datos, function(diadatos) {
                    // Corrección de la temperatura media
                    diadatos.tempmedia = (diadatos.tempmax+diadatos.tempmin)/2;

                    // Cálculo de la presión atmosférica (kPa)
                    diadatos.presion = 101.3*Math.pow(((293-(0.0065*par.estacion.altitud))/293),5.26);

                    // Cálculo de la constante psicométrica (kPa/ºC)
                    diadatos.constante_psicometrica = diadatos.presion*0.000665;

                    // Cálculo de la presión de saturación de vapor a la temperatura del aire (max, med y min) (kPa)
                    var psvmax = 0.6108*Math.pow(2.7183,(17.27*diadatos.tempmax)/(diadatos.tempmax+237.3));
                    var psvmin = 0.6108*Math.pow(2.7183,(17.27*diadatos.tempmin)/(diadatos.tempmin+237.3));
                    var psvmed = (psvmax+psvmin)/2;

                    // Cálculo de la presión real de vapor (kPa)
                    diadatos.presion_real_vapor = (psvmed*diadatos.humedadmedia)/100;

                    // Cálculo de la pendiente de la curva de presión de vapor (kPa/ºC)
                    diadatos.pendiente_curva_presion = (4098*psvmed)/Math.pow((diadatos.tempmedia+237.3),2);

                    // Cálculo de la ET0
                    diadatos.et0 = ((0.408*diadatos.pendiente_curva_presion*diadatos.rn)
                            +(diadatos.constante_psicometrica*diadatos.velviento*900*(psvmed-diadatos.presion_real_vapor))/(273+diadatos.tempmedia))
                            /(diadatos.pendiente_curva_presion+(diadatos.constante_psicometrica*(1+0.34*diadatos.velviento)));

                    // Cálculo de la ETc
                    if (par.estado == 'ini') {
                        diadatos.etc = diadatos.et0*par.cultivo.coef_ini;
                        diadatos.kc = par.cultivo.coef_ini;
                    } else if (par.estado == 'des') {
                        diadatos.etc = diadatos.et0*par.cultivo.coef_des;
                        diadatos.kc = par.cultivo.coef_des;
                    } else if (par.estado == 'med') {
                        diadatos.etc = diadatos.et0*par.cultivo.coef_med;
                        diadatos.kc = par.cultivo.coef_med;
                    } else if (par.estado == 'fin') {
                        diadatos.etc = diadatos.et0*par.cultivo.coef_fin;
                        diadatos.kc = par.cultivo.coef_fin;
                    }

                    // Sumar para los totales
                    par.datos_totales.et0 = par.datos_totales.et0 + diadatos.et0;
                    par.datos_totales.etc = par.datos_totales.etc + diadatos.etc;
                    par.datos_totales.pe = par.datos_totales.pe + diadatos.pepmon;
                });
                par.datos_totales.rr = (par.datos_totales.etc-par.datos_totales.pe)/par.riego.coef_eficiencia;
                user.html = user.html + "
" + par.nombre + "	" + par.estacion.nombre + "	"+
                "" + par.cultivo.nombre + "	" + par.riego.nombre + "	"+
                "" + $filter('date')(par.siembra, 'dd-MM-yyyy') + "	"+
                "" + $filter('date')(par.consulta, 'dd-MM-yyyy') + "	"+
                "" + Math.round(par.datos_totales.rr) + " l/m2
";
            });
        });
        return result;
    })
    .then(function(result) {
        console.log("7");
        angular.forEach(result.users, function(user) {
            if (user.usuario != 'jlmm') {
                user.html = user.html + "

AgriWea";
                $http.post('http://localhost:8100/sendmail', {params: {
                      from: 'AgriWea <jmariscan@dominio.es>',
                      to: user.email,
                      subject: 'Recomendación diaria de riego',
                      html: user.html}})
                .then(function(respuesta) {
                    console.log("Email enviado correctamente",texto);
                }, function(respuesta) {
                    console.log("Email no enviado", respuesta);
                });
            }
        });
    })
    .catch(function (error) {
        console.log(error);
    });
    def.resolve(result);

As you can see I have a console.log, this is what I get:

I was thinking that maybe the object was undefined because of asynchronous in Angular but in the same console.log I can see that the array exists but if I try to access it is undefined. Help!

SOLUTION

Using the code of @trincot, I reduced the number of then and I made all my code in just three. Thanks everyone!

Body:
You state that you use a promise chain because you want to run code synchronously, but that is not possible. The parts of a promise chain are executed asynchronously. The last line in your function is executed before any of the then callbacks.

Also, you cannot expect the function call to return the email. Currently, your function is not returning anything, so when you call the function you'll get undefined.

But even if you would return something, it could never be the  result. At most you can return a promise.

You need to embrace the asynchronous behaviour, and keep working with that pattern. So don't expect to assign values synchronously. Instead, keep using then.

For instance, you could start with an immediately resolving promise that passes the empty result object down the chain:

vm.enviarEmail = function() {
  $q.when({}).then(function(result) {
      ...
      return result; // <-- don't forget to return the enriched value
    })
    .then(function(result) {
      ...
      return result;
    })
    .then(function(result) {
      ...
      return result;
    })
    .then(function(result) {
      angular.forEach(result.users, function(user) {
        console.log(user, user.parcelas);
        angular.forEach(user.parcelas, function(par) {
          ...
        });
      });
      return result; // <-- you need to return the promise
    });
};

Then you use it as follows:

vm.enviarEmail().then(function (result)  {
     console.log(result); // keep with the async pattern
});


问:
Specify C++ compiler in waf
When building C++ code using the waf build system, can I choose a specific C++ compiler command?

While it is possible to run something like "CXX=g++-4.9 waf configure", or to get the same effect by setting os.environ['CXX'] in the wscript file, is there a 'proper' way of doing this?

i.e. What is the waf equivalent of setting the CXX variable in a Makefile.

答:
It's a little bit odd how little documentation I've found on this topic. I made do by setting the environment variable in the configure function, as you mention in your question.

Here's a small example for the curious:

import os

def options(opt):
    opt.load('wak.tools')
    opt.load('compiler_cxx')

def configure(conf):
    conf.load('wak.tools')

    conf.env.CXX = "g++-4.9" # default compiler

    if os.environ['CXX']: # Pull in the compiler
        conf.env.CXX = os.environ['CXX'] # override default

    # Additional setup of variables

    conf.load('compiler_cxx') # Will use the compiler from the environment path

def build(bld):
    bld.program(
        target='test',
        includes='include',
        source='src/main.cpp')
```

Title: Specify C++ compiler in waf

ContentLicense: CC BY-SA 4.0


问:
Iterate through a list, divide values, store in new list
In the code I have series of lists, each one containing the same number of entries. What I want to do now is iterate through the list and divide one list index by the other.

```<code>threads = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
dsk_indpt_PI = [99, 197, 295, 387, 391, 406, 407, 416, 424, 426, 425, 439]

avg_val = []
for x in threads:
    result = dsk_indpt_PI[x]/threads[x]
    avg_val.append(result[x])
</code>```

I am unsure if the above method works, previous methods I ran into the issue where it could not do division between type int and type list. Would the above example work better? If not, what should be changed to have it function as desired? Thank you.

答:
```<code>threads = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
dsk_indpt_PI = [99, 197, 295, 387, 391, 406, 407, 416, 424, 426, 425, 439]

avg_val = []
for x in range(len(threads)):
    result = dsk_indpt_PI[x]/threads[x]
    avg_val.append(result)

print(avg_val)
</code>```

Object is not iterable, and you cannot use result[x] as it is not a list and is being reset every time anyway.

Body:
In the code I have series of lists, each one containing the same number of entries. What I want to do now is iterate through the list and divide one list index by the other.

threads = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
dsk_indpt_PI = [99, 197, 295, 387, 391, 406, 407, 416, 424, 426, 425, 439]

avg_val = []
for x in threads:
    result = dsk_indpt_PI[x]/threads[x]
    avg_val.append(result[x])

I am unsure if the above method works, previous methods I ran into the issue where it could not do division between type int and type list. Would the above example work better? If not, what should be changed to have it function as desired? Thank you.

Body:
threads = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
dsk_indpt_PI = [99, 197, 295, 387, 391, 406, 407, 416, 424, 426, 425, 439]

avg_val = []
for x in range(len(threads)):
    result = dsk_indpt_PI[x]/threads[x]
    avg_val.append(result)

print(avg_val)

Object is not iterable, and you cannot use result[x] as it is not a list and is being reset every time anyway.


问:
Capture RWin +L or LWin+L with C#
So I'm trying to make an application in C# that executes some code before one locks his/her computer with Windows Key+L.

I don't have any experience with keyboard hooks whatsoever. I searched the web and found a nice implementation of a keyboard hook: Low-Level Keyboard Hook in C#

However, since the LWin and RWin key aren't modifier keys (as far as I understand), I cannot get the above mentioned example working for my case.

Does anyone have some sources and/or examples on how I can capture the LWin+L or RWin+L key combination?

I failed to find examples or information about how to prevent windows from locking itself with the Win+L key combination too. Is this even possible? If yes, how would I be able to achieve this?

Thanks in advance!

答:
Try this: http://inputsimulator.codeplex.com/

This sends Win32 SendInput methods to C#. This allows you to directly send the windows key. This will work:

InputSimulator.SimulateModifiedKeyStroke(VirtualKeyCode.LWIN, VirtualKeyCode.VK_L);

Title: Capture RWin +L or LWin+L with C#


问:
SQL Server - Get the Latest Date With Grouping
I am running a problem with SQL Server query that I couldn't figure out how to get it works correctly. I try to get the MAX date based on the Category grouped. I know it sounds confused, so let me explain what the result I want.

Let's say I have this table:

```<code>Table1
Category    Value   UpdatedDateTime
Cat1        5       2017-11-12 10:46
Cat1        2       2017-11-13 11:46
Cat1        4       2017-11-13 10:46
Cat2        5       2017-11-12 10:46
Cat2        7       2017-11-12 11:46
Cat2        3       2017-11-13 09:46
Cat3        1       2017-11-12 10:46
Cat3        2       2017-11-12 11:46
Cat3        7       2017-11-13 11:46
Cat3        8       2017-11-13 10:46
Cat3        3       2017-11-10 10:46
Cat4        4       2017-11-13 10:46
Cat4        4       2017-11-12 10:46
</code>```

I want the UpdatedDateTime in the result to pick the latest date by the Category grouping like this:

```<code>Category    Value   UpdatedDateTime
Cat1        5       2017-11-13 11:46
Cat1        2       2017-11-13 11:46
Cat1        4       2017-11-13 11:46
Cat2        5       2017-11-13 09:46
Cat2        7       2017-11-13 09:46
Cat2        3       2017-11-13 09:46
Cat3        1       2017-11-13 11:46
Cat3        2       2017-11-13 11:46
Cat3        7       2017-11-13 11:46
Cat3        8       2017-11-13 11:46
Cat3        3       2017-11-13 11:46
Cat4        4       2017-11-13 10:46
Cat4        4       2017-11-13 10:46
</code>```

I tried this query, but of course it doesn't work because I was looking for the Max(UpdatedDate) for the entire table, not by Category.  Then I got stuck.

```<code>With cte AS
(
    Select Category, Value, UpdatedDateTime FROM Table1
)
Select Category, Sum(Value)
, (Select Top 1 Max(UpdatedDateTime) FORM cte) AS UpdatedDateTime
FROM cte
Group By Category
</code>```

Please help, thanks in advance.

答:
```<code>SELECT t1.Category, t1.Value, t2.maxDate AS UpdatedDateTime
FROM Table1 AS t1
INNER JOIN (Select Category, Max(UpdatedDateTime) AS maxDate FROM Table1 Group By Category)
t2 ON t2.Category = t1.Category
</code>```

Body:
I am running a problem with SQL Server query that I couldn't figure out how to get it works correctly. I try to get the MAX date based on the Category grouped. I know it sounds confused, so let me explain what the result I want.

Let's say I have this table:

Table1
Category    Value   UpdatedDateTime
Cat1        5       2017-11-12 10:46
Cat1        2       2017-11-13 11:46
Cat1        4       2017-11-13 10:46
Cat2        5       2017-11-12 10:46
Cat2        7       2017-11-12 11:46
Cat2        3       2017-11-13 09:46
Cat3        1       2017-11-12 10:46
Cat3        2       2017-11-12 11:46
Cat3        7       2017-11-13 11:46
Cat3        8       2017-11-13 10:46
Cat3        3       2017-11-10 10:46
Cat4        4       2017-11-13 10:46
Cat4        4       2017-11-12 10:46

I want the UpdatedDateTime in the result to pick the latest date by the Category grouping like this:

Category    Value   UpdatedDateTime
Cat1        5       2017-11-13 11:46
Cat1        2       2017-11-13 11:46
Cat1        4       2017-11-13 11:46
Cat2        5       2017-11-13 09:46
Cat2        7       2017-11-13 09:46
Cat2        3       2017-11-13 09:46
Cat3        1       2017-11-13 11:46
Cat3        2       2017-11-13 11:46
Cat3        7       2017-11-13 11:46
Cat3        8       2017-11-13 11:46
Cat3        3       2017-11-13 11:46
Cat4        4       2017-11-13 10:46
Cat4        4       2017-11-13 10:46

I tried this query, but of course it doesn't work because I was looking for the Max(UpdatedDate) for the entire table, not by Category.  Then I got stuck.

With cte AS
(
    Select Category, Value, UpdatedDateTime FROM Table1
)
Select Category, Sum(Value)
, (Select Top 1 Max(UpdatedDateTime) FORM cte) AS UpdatedDateTime
FROM cte
Group By Category

Please help, thanks in advance.


问:
Tidying dataset by gathering multiple columns?
I want to tidy a dataset by manipulating the data this way:

```<code>age gender  education       previous_comp_exp   tutorial_time   qID.1    time_taken.1   qID.2    time_taken.2
18  Male    Undergraduate   casual gamer        62.17926        sor9     39.61206       sor8     19.4892
24  Male    Undergraduate   casual gamer        85.01288        sor9     50.92343       sor8     16.15616
</code>```

To become this:

```<code>age gender  education       previous_comp_exp   tutorial_time   qID      time_taken
18  Male    Undergraduate   casual gamer        62.17926        sor9     39.61206
18  Male    Undergraduate   casual gamer        62.17926        sor8     19.4892
24  Male    Undergraduate   casual gamer        85.01288        sor9     50.92343
24  Male    Undergraduate   casual gamer        85.01288        sor8     16.15616
</code>```

I've experimented with gather(), but I can only only get it working with one column and I keep getting this warning:

Warning message:attributes are not identical across measure variables;
  they will be dropped

Any ideas?

答:
With melt from data.table (see ?patterns):

```<code>library(data.table)

melt(setDT(df), measure = patterns("^qID", "^time_taken"),
     value.name = c("qID", "time_taken"))
</code>```

Result:

```<code>   age gender     education previous_comp_exp tutorial_time variable  qID time_taken
1:  18   Male Undergraduate      casual_gamer      62.17926        1 sor9   39.61206
2:  24   Male Undergraduate      casual_gamer      85.01288        1 sor9   50.92343
3:  18   Male Undergraduate      casual_gamer      62.17926        2 sor8   19.48920
4:  24   Male Undergraduate      casual_gamer      85.01288        2 sor8   16.15616
</code>```

or with tidyr:

```<code>library(dplyr)
library(tidyr)

df %>%
  gather(variable, value, qID.1:time_taken.2) %>%
  mutate(variable = sub("\\.\\d$", "", variable)) %>%
  group_by(variable) %>%
  mutate(ID = row_number()) %>%
  spread(variable, value, convert = TRUE) %>%
  select(-ID)
</code>```

Result:

```<code># A tibble: 4 x 7
    age gender     education previous_comp_exp tutorial_time   qID time_taken
  <int> <fctr>        <fctr>            <fctr>         <dbl> <chr>      <dbl>
1    18   Male Undergraduate      casual_gamer      62.17926  sor9   39.61206
2    18   Male Undergraduate      casual_gamer      62.17926  sor8   19.48920
3    24   Male Undergraduate      casual_gamer      85.01288  sor9   50.92343
4    24   Male Undergraduate      casual_gamer      85.01288  sor8   16.15616
</code>```

Note:

For the tidyr method, convert=TRUE is used to convert time_taken back to numeric, since it was coerced to character when gathered with the qID columns.

Data:

```<code>df = structure(list(age = c(18L, 24L), gender = structure(c(1L, 1L
), .Label = "Male", class = "factor"), education = structure(c(1L,
1L), .Label = "Undergraduate", class = "factor"), previous_comp_exp = structure(c(1L,
1L), .Label = "casual_gamer", class = "factor"), tutorial_time = c(62.17926,
85.01288), qID.1 = structure(c(1L, 1L), .Label = "sor9", class = "factor"),
    time_taken.1 = c(39.61206, 50.92343), qID.2 = structure(c(1L,
    1L), .Label = "sor8", class = "factor"), time_taken.2 = c(19.4892,
    16.15616)), .Names = c("age", "gender", "education", "previous_comp_exp",
"tutorial_time", "qID.1", "time_taken.1", "qID.2", "time_taken.2"
), class = "data.frame", row.names = c(NA, -2L))
</code>```

Body:
I want to tidy a dataset by manipulating the data this way:

age gender  education       previous_comp_exp   tutorial_time   qID.1    time_taken.1   qID.2    time_taken.2
18  Male    Undergraduate   casual gamer        62.17926        sor9     39.61206       sor8     19.4892
24  Male    Undergraduate   casual gamer        85.01288        sor9     50.92343       sor8     16.15616

To become this:

age gender  education       previous_comp_exp   tutorial_time   qID      time_taken
18  Male    Undergraduate   casual gamer        62.17926        sor9     39.61206
18  Male    Undergraduate   casual gamer        62.17926        sor8     19.4892
24  Male    Undergraduate   casual gamer        85.01288        sor9     50.92343
24  Male    Undergraduate   casual gamer        85.01288        sor8     16.15616

I've experimented with gather(), but I can only only get it working with one column and I keep getting this warning:

Warning message:attributes are not identical across measure variables;
  they will be dropped

Any ideas?

Body:
With melt from data.table (see ?patterns):

library(data.table)

melt(setDT(df), measure = patterns("^qID", "^time_taken"),
     value.name = c("qID", "time_taken"))

Result:

   age gender     education previous_comp_exp tutorial_time variable  qID time_taken
1:  18   Male Undergraduate      casual_gamer      62.17926        1 sor9   39.61206
2:  24   Male Undergraduate      casual_gamer      85.01288        1 sor9   50.92343
3:  18   Male Undergraduate      casual_gamer      62.17926        2 sor8   19.48920
4:  24   Male Undergraduate      casual_gamer      85.01288        2 sor8   16.15616

or with tidyr:

library(dplyr)
library(tidyr)

df %>%
  gather(variable, value, qID.1:time_taken.2) %>%
  mutate(variable = sub("\\.\\d$", "", variable)) %>%
  group_by(variable) %>%
  mutate(ID = row_number()) %>%
  spread(variable, value, convert = TRUE) %>%
  select(-ID)

Result:

# A tibble: 4 x 7
    age gender     education previous_comp_exp tutorial_time   qID time_taken
  <int> <fctr>        <fctr>            <fctr>         <dbl> <chr>      <dbl>
1    18   Male Undergraduate      casual_gamer      62.17926  sor9   39.61206
2    18   Male Undergraduate      casual_gamer      62.17926  sor8   19.48920
3    24   Male Undergraduate      casual_gamer      85.01288  sor9   50.92343
4    24   Male Undergraduate      casual_gamer      85.01288  sor8   16.15616

Note:

For the tidyr method, convert=TRUE is used to convert time_taken back to numeric, since it was coerced to character when gathered with the qID columns.

Data:

df = structure(list(age = c(18L, 24L), gender = structure(c(1L, 1L
), .Label = "Male", class = "factor"), education = structure(c(1L,
1L), .Label = "Undergraduate", class = "factor"), previous_comp_exp = structure(c(1L,
1L), .Label = "casual_gamer", class = "factor"), tutorial_time = c(62.17926,
85.01288), qID.1 = structure(c(1L, 1L), .Label = "sor9", class = "factor"),
    time_taken.1 = c(39.61206, 50.92343), qID.2 = structure(c(1L,
    1L), .Label = "sor8", class = "factor"), time_taken.2 = c(19.4892,
    16.15616)), .Names = c("age", "gender", "education", "previous_comp_exp",
"tutorial_time", "qID.1", "time_taken.1", "qID.2", "time_taken.2"
), class = "data.frame", row.names = c(NA, -2L))


问:
how to find linux process uptime in days
Can any one please let me know how can I find the uptime of a unix process in days?
I am able to get the date time of the process with below command

```<code>[zdkafadm@toplxkafp005 sa]$ ps -eo pid,lstart,cmd |grep server.properties | grep -v auto | awk 'NR==1;'|awk '{print $3" "$4" " $5" "$6}'
Oct 29 12:47:24 2017
</code>```

Somehow I need the output something like 15 days.

Thanks,
Chandan

答: The easiest (sticking within shell) is using the 'dateutils' package.  Otherwise perl has some fine date/time modules.</p>

Body:
Can any one please let me know how can I find the uptime of a unix process in days?
I am able to get the date time of the process with below command

[zdkafadm@toplxkafp005 sa]$ ps -eo pid,lstart,cmd |grep server.properties | grep -v auto | awk 'NR==1;'|awk '{print $3" "$4" " $5" "$6}'
Oct 29 12:47:24 2017

Somehow I need the output something like 15 days.

Thanks,
Chandan


问:
Not able to fire angular function (John Papa style)
Here's the form in html:

```<code><form ng-submit="vm.setTest(test)">
    <input type="text" ng-model="test" required />in USD
    <input type="submit" value="Submit">
</form>
</code>```

Here's the JavaScript:

```<code>var vm = this;
vm.setTest = setTest;
function setTest(test) {
    alert(test);
}
</code>```

Please note, that no $scope involved and should not be.

答:
you will have to declare setTest like this</p>

```<code>vm.setTest(test) {
    alert(test);
}
</code>```

Body:
Here's the form in html:

<form ng-submit="vm.setTest(test)">
    <input type="text" ng-model="test" required />in USD
    <input type="submit" value="Submit">
</form>

Here's the JavaScript:

var vm = this;
vm.setTest = setTest;
function setTest(test) {
    alert(test);
}

Please note, that no $scope involved and should not be.

Body:
you will have to declare setTest like this

vm.setTest(test) {
    alert(test);
}


问:
What order is null stored in a non clustered index
I have some columns in a non clustered index that have values of null in them, one of them for example is expiration date.  There are some values in the column that are null and some supplied.  The way the column is queried is that values that are null or greater than some expiration date are retrieved.  I am using this column in an index and it would be most efficient if I retrieve in descending order with null first.  So I guess I have a two part question:

In what order is null stored in a non-clustered index?  Is null first in an ASC index and last in a DESC index?  I had a co-worker who seemed to think null was stored first in both cases.  He also mentioned null was handled differently among version sql server versions.

Is there a way to force null first in a non clustered index?  This is kinda dependent on the answer to question one but lets say for arguments sake that indexing is handled like order by where null is first in ASC order.  Is there a way to create a non clustered index that stores values in descending order but with null first?

答:
This is painfully simple to test. Where is the row with NULL in the following queries?</p>

```<code>select *
from
(
    select SomeVal = 1 union all
    select 2 union all
    select null
) x
order by x.SomeVal desc

select *
from
(
    select SomeVal = 1 union all
    select 2 union all
    select null
) x
order by x.SomeVal
</code>```

Body:
This is painfully simple to test. Where is the row with NULL in the following queries?

select *
from
(
    select SomeVal = 1 union all
    select 2 union all
    select null
) x
order by x.SomeVal desc

select *
from
(
    select SomeVal = 1 union all
    select 2 union all
    select null
) x
order by x.SomeVal


问:
How to fit log(a-x) type functions with scipy. curve_fit?
I am trying to fit a function which looks like log(y)=a*log(b-x)+c, where a, b and c are the parameters that need to be fitted. The relevant bit of code is

```<code>import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit

def logfunc(T, a, b, c):
    v=(a*np.log(b-T))+c
    return v

popt, pcov=curve_fit(logfunc, T, np.log(Energy), check_finite=False, bounds=([0.1, 1.8, 0.1], [1.0, 2.6, 1.0]))

plt.plot(T, logfunc(T, *popt))
plt.show
</code>```

Where T and Energy is some data that was generated (I use it to plot other things so the data should be fine). T is between 0.3 and 3.2. I am pretty sure that the problem is the fact that there is a point where b=T because I keep getting the error ValueError: Residuals are not finite in the initial point. but I am not sure how to solve this.

答:
Residuals are not finite in the initial point

means the initial point is bad, where some logarithms are infinite or undefined.  You need a better initial point.

By the nature of the model, b has to be greater than any of the points in T. The bounds on b that you have at present do not guarantee that. Tighten them up.

When you do not provide p0 parameter, SciPy will take a guess within the provided bounds. So if the bounds guarantee finiteness, the error will not occur.
Still, it is generally better to prescribe p0 yourself, because you have better a priori understanding of the problem than SciPy does.

A working example with adjusted bounds:

```<code>popt, pcov=curve_fit(logfunc, np.linspace(0.3, 3.2, 6), [8, 7, 6, 5, 4, 3], bounds=([0.1, 3.2, 0.1], [1.0, 3.6, 1.0]))
</code>```

Body:
I am trying to fit a function which looks like log(y)=a*log(b-x)+c, where a, b and c are the parameters that need to be fitted. The relevant bit of code is

import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit

def logfunc(T, a, b, c):
    v=(a*np.log(b-T))+c
    return v

popt, pcov=curve_fit(logfunc, T, np.log(Energy), check_finite=False, bounds=([0.1, 1.8, 0.1], [1.0, 2.6, 1.0]))

plt.plot(T, logfunc(T, *popt))
plt.show

Where T and Energy is some data that was generated (I use it to plot other things so the data should be fine). T is between 0.3 and 3.2. I am pretty sure that the problem is the fact that there is a point where b=T because I keep getting the error ValueError: Residuals are not finite in the initial point. but I am not sure how to solve this.

Body:
Residuals are not finite in the initial point

means the initial point is bad, where some logarithms are infinite or undefined.  You need a better initial point.

By the nature of the model, b has to be greater than any of the points in T. The bounds on b that you have at present do not guarantee that. Tighten them up.

When you do not provide p0 parameter, SciPy will take a guess within the provided bounds. So if the bounds guarantee finiteness, the error will not occur.
Still, it is generally better to prescribe p0 yourself, because you have better a priori understanding of the problem than SciPy does.

A working example with adjusted bounds:

popt, pcov=curve_fit(logfunc, np.linspace(0.3, 3.2, 6), [8, 7, 6, 5, 4, 3], bounds=([0.1, 3.2, 0.1], [1.0, 3.6, 1.0]))


问:
Invalid Column Name when Create trigger using SQL server
I encountered several errors when I tried to create a simple trigger using SQL server. Tables are created using:

```<code>CREATE TABLE person
(
    person_id INT NOT NULL PRIMARY KEY,
    name VARCHAR NOT NULL,
    phone INT,
    birth_date DATE,
    address VARCHAR
);

CREATE TABLE volunteers
(
    person_id INT NOT NULL PRIMARY KEY,
    skill VARCHAR,
    FOREIGN KEY (person_id) REFERENCES person(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE physicians
(
    person_id INT NOT NULL PRIMARY KEY,
    speciality VARCHAR,
    phone_number INT,
    FOREIGN KEY (person_id) REFERENCES person(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE patients
(
    person_id INT NOT NULL PRIMARY KEY,
    contact_date DATE,
    physician_id INT,   -- TODO determine whether NULL able
                        -- TODO determine ON DELETE ACTION
    CHECK (person_id <> physician_id),
    FOREIGN KEY (person_id) REFERENCES person(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE,
    FOREIGN KEY (physician_id) REFERENCES physicians(person_id)
        ON DELETE NO ACTION
        ON UPDATE NO ACTION
);

CREATE TABLE outpatients
(
    person_id INT NOT NULL PRIMARY KEY,
    FOREIGN KEY (person_id) REFERENCES patients(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE visits
(
    person_id INT  NOT NULL,
    date DATE NOT NULL,
    comments VARCHAR,
    PRIMARY KEY (person_id, date),
    FOREIGN KEY (person_id) REFERENCES outpatients(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE employees
(
    person_id INT NOT NULL PRIMARY KEY,
    date_hire DATE,
    FOREIGN KEY (person_id) REFERENCES person(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE nurses
(
    person_id INT NOT NULL PRIMARY KEY,
    certificate VARCHAR,
    care_center_name VARCHAR,
    FOREIGN KEY (person_id) REFERENCES employees(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE,
    -- FOREIGN KEY (care_center_name) REFERENCES care_centers(name)
    --     ON DELETE CASCADE
    --     ON UPDATE CASCADE
);

CREATE TABLE care_centers
(
    name VARCHAR PRIMARY KEY NOT NULL,
    nurses_in_charge INT NOT NULL,
    location VARCHAR,
    type VARCHAR
    -- FOREIGN KEY (nurses_in_charge) REFERENCES registered_nurse(person_id)
);

CREATE TABLE registered_nurse
(
    person_id INT NOT NULL PRIMARY KEY,
    care_center_name VARCHAR,
    FOREIGN KEY (person_id) REFERENCES nurses(person_id),
        -- ON DELETE CASCADE
        -- ON UPDATE CASCADE,
    FOREIGN KEY (care_center_name) REFERENCES care_centers(name)
        -- ON DELETE CASCADE
        -- ON UPDATE CASCADE
);

ALTER TABLE nurses
    ADD constraint nurses__care_centers_FK
    FOREIGN KEY (care_center_name) REFERENCES care_centers(name)
        ON DELETE CASCADE
        ON UPDATE CASCADE;

ALTER TABLE care_centers
    ADD constraint care_centers__registered_nurse_FK
    FOREIGN KEY (nurses_in_charge) REFERENCES registered_nurse(person_id);

CREATE TABLE beds
(
    bed_number INT NOT NULL,
    room_number INT NOT NULL,
    care_center_name VARCHAR,
    PRIMARY KEY (bed_number,room_number),
    FOREIGN KEY (care_center_name) REFERENCES care_centers(name)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE residents
(
    person_id INT NOT NULL PRIMARY KEY,
    date_admitted DATE,
    bed_number INT,
    room_number INT,
    FOREIGN KEY (person_id) REFERENCES patients(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE,
    FOREIGN KEY (bed_number, room_number) REFERENCES beds(bed_number, room_number)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE staffs
(
    person_id INT NOT NULL PRIMARY KEY,
    job_class DATE,
    FOREIGN KEY (person_id) REFERENCES employees(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE technicians
(
    person_id INT NOT NULL PRIMARY KEY,
    skill VARCHAR,
    FOREIGN KEY (person_id) REFERENCES employees(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE laboratories
(
    name VARCHAR NOT NULL PRIMARY KEY,
    location VARCHAR
);

CREATE TABLE assignTechnicianToLab
(
    person_id INT NOT NULL,
    laboratories_name VARCHAR NOT NULL,
    PRIMARY KEY(person_id, laboratories_name),
    FOREIGN KEY (person_id) REFERENCES employees(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE,
    FOREIGN KEY (laboratories_name) REFERENCES laboratories(name)
        ON DELETE CASCADE
        ON UPDATE CASCADE
)
</code>```

And the trigger I am trying to create:

```<code>-- Trigger
/* if nurse has certificate "RN", add to registered_nurse */
CREATE TRIGGER registered_nurse_trigger
ON nurses
FOR INSERT, UPDATE
AS
BEGIN
    IF EXISTS (SELECT * FROM inserted where certificate = "RN")
    BEGIN
        INSERT INTO registered_nurse
        VALUES(inserted.person_id, nurses.care_center_name);
    END
END;
</code>```

And I keep getting errors saying that:

Msg 207, Level 16, State 1, Procedure registered_nurse_trigger, Line 6

  Invalid column name 'RN'.

Msg 4104, Level 16, State 1, Procedure registered_nurse_trigger, Line 8

  The multi-part identifier "inserted.person_id" could not be bound.

Msg 4104, Level 16, State 1, Procedure registered_nurse_trigger, Line 8

  The multi-part identifier "nurses.care_center_name" could not be bound.

I've been hanging over here for several hours and I really appreciate anyone can help me with it. Thank you very much!

答:
You are using double quote instead of single quotes in your Create Trigger statement try this and see if it works:</p>

```<code>-- Trigger
/* if nurse has certificate "RN", add to registered_nurse */
CREATE TRIGGER registered_nurse_trigger ON nurses
    FOR INSERT, UPDATE
AS
    BEGIN
        IF EXISTS (SELECT * FROM inserted where certificate = 'RN')
        BEGIN
            INSERT INTO registered_nurse
                SELECT person_id, care_center_name FROM Inserted;
        END
    END;
</code>```

Body:
I encountered several errors when I tried to create a simple trigger using SQL server. Tables are created using:

CREATE TABLE person
(
    person_id INT NOT NULL PRIMARY KEY,
    name VARCHAR NOT NULL,
    phone INT,
    birth_date DATE,
    address VARCHAR
);

CREATE TABLE volunteers
(
    person_id INT NOT NULL PRIMARY KEY,
    skill VARCHAR,
    FOREIGN KEY (person_id) REFERENCES person(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE physicians
(
    person_id INT NOT NULL PRIMARY KEY,
    speciality VARCHAR,
    phone_number INT,
    FOREIGN KEY (person_id) REFERENCES person(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE patients
(
    person_id INT NOT NULL PRIMARY KEY,
    contact_date DATE,
    physician_id INT,   -- TODO determine whether NULL able
                        -- TODO determine ON DELETE ACTION
    CHECK (person_id <> physician_id),
    FOREIGN KEY (person_id) REFERENCES person(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE,
    FOREIGN KEY (physician_id) REFERENCES physicians(person_id)
        ON DELETE NO ACTION
        ON UPDATE NO ACTION
);

CREATE TABLE outpatients
(
    person_id INT NOT NULL PRIMARY KEY,
    FOREIGN KEY (person_id) REFERENCES patients(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE visits
(
    person_id INT  NOT NULL,
    date DATE NOT NULL,
    comments VARCHAR,
    PRIMARY KEY (person_id, date),
    FOREIGN KEY (person_id) REFERENCES outpatients(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE employees
(
    person_id INT NOT NULL PRIMARY KEY,
    date_hire DATE,
    FOREIGN KEY (person_id) REFERENCES person(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE nurses
(
    person_id INT NOT NULL PRIMARY KEY,
    certificate VARCHAR,
    care_center_name VARCHAR,
    FOREIGN KEY (person_id) REFERENCES employees(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE,
    -- FOREIGN KEY (care_center_name) REFERENCES care_centers(name)
    --     ON DELETE CASCADE
    --     ON UPDATE CASCADE
);

CREATE TABLE care_centers
(
    name VARCHAR PRIMARY KEY NOT NULL,
    nurses_in_charge INT NOT NULL,
    location VARCHAR,
    type VARCHAR
    -- FOREIGN KEY (nurses_in_charge) REFERENCES registered_nurse(person_id)
);

CREATE TABLE registered_nurse
(
    person_id INT NOT NULL PRIMARY KEY,
    care_center_name VARCHAR,
    FOREIGN KEY (person_id) REFERENCES nurses(person_id),
        -- ON DELETE CASCADE
        -- ON UPDATE CASCADE,
    FOREIGN KEY (care_center_name) REFERENCES care_centers(name)
        -- ON DELETE CASCADE
        -- ON UPDATE CASCADE
);

ALTER TABLE nurses
    ADD constraint nurses__care_centers_FK
    FOREIGN KEY (care_center_name) REFERENCES care_centers(name)
        ON DELETE CASCADE
        ON UPDATE CASCADE;

ALTER TABLE care_centers
    ADD constraint care_centers__registered_nurse_FK
    FOREIGN KEY (nurses_in_charge) REFERENCES registered_nurse(person_id);

CREATE TABLE beds
(
    bed_number INT NOT NULL,
    room_number INT NOT NULL,
    care_center_name VARCHAR,
    PRIMARY KEY (bed_number,room_number),
    FOREIGN KEY (care_center_name) REFERENCES care_centers(name)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE residents
(
    person_id INT NOT NULL PRIMARY KEY,
    date_admitted DATE,
    bed_number INT,
    room_number INT,
    FOREIGN KEY (person_id) REFERENCES patients(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE,
    FOREIGN KEY (bed_number, room_number) REFERENCES beds(bed_number, room_number)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE staffs
(
    person_id INT NOT NULL PRIMARY KEY,
    job_class DATE,
    FOREIGN KEY (person_id) REFERENCES employees(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE technicians
(
    person_id INT NOT NULL PRIMARY KEY,
    skill VARCHAR,
    FOREIGN KEY (person_id) REFERENCES employees(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
);

CREATE TABLE laboratories
(
    name VARCHAR NOT NULL PRIMARY KEY,
    location VARCHAR
);

CREATE TABLE assignTechnicianToLab
(
    person_id INT NOT NULL,
    laboratories_name VARCHAR NOT NULL,
    PRIMARY KEY(person_id, laboratories_name),
    FOREIGN KEY (person_id) REFERENCES employees(person_id)
        ON DELETE CASCADE
        ON UPDATE CASCADE,
    FOREIGN KEY (laboratories_name) REFERENCES laboratories(name)
        ON DELETE CASCADE
        ON UPDATE CASCADE
)

And the trigger I am trying to create:

-- Trigger
/* if nurse has certificate "RN", add to registered_nurse */
CREATE TRIGGER registered_nurse_trigger
ON nurses
FOR INSERT, UPDATE
AS
BEGIN
    IF EXISTS (SELECT * FROM inserted where certificate = "RN")
    BEGIN
        INSERT INTO registered_nurse
        VALUES(inserted.person_id, nurses.care_center_name);
    END
END;

And I keep getting errors saying that:

Msg 207, Level 16, State 1, Procedure registered_nurse_trigger, Line 6

  Invalid column name 'RN'.

Msg 4104, Level 16, State 1, Procedure registered_nurse_trigger, Line 8

  The multi-part identifier "inserted.person_id" could not be bound.

Msg 4104, Level 16, State 1, Procedure registered_nurse_trigger, Line 8

  The multi-part identifier "nurses.care_center_name" could not be bound.

I've been hanging over here for several hours and I really appreciate anyone can help me with it. Thank you very much!

Body:
You are using double quote instead of single quotes in your Create Trigger statement try this and see if it works:

-- Trigger
/* if nurse has certificate "RN", add to registered_nurse */
CREATE TRIGGER registered_nurse_trigger ON nurses
    FOR INSERT, UPDATE
AS
    BEGIN
        IF EXISTS (SELECT * FROM inserted where certificate = 'RN')
        BEGIN
            INSERT INTO registered_nurse
                SELECT person_id, care_center_name FROM Inserted;
        END
    END;


问:
Wordpress plugin data disappearing
I'm working on a simple plug that lets me save pairs of values with a post; there's a bit of JS to add or delete pairings. Everything works just fine, but randomly data will disappear. I'm not sure if it's a problem with autosaving or what, but I'd thought I'd accounted for that.

Any ideas why my data is saving, but disappearing randomly?

```<code><?php

function esys_menus() {
    if (function_exists('add_meta_box')) {
        add_meta_box('esys_box','Energy System Details','esys_meta','energy-systems');
    }
}

function esys_meta() {
    global $wpdb, $post_ID;
    $files = esys_get_files($post_ID);
    ?>

    <table>
        <thead>
            <tr>
                <th width="50%">BPM</th>
                <th width="50%">Duration</th>
            </tr>
        </thead>
        <tbody>
        <?php
$i = 0;
if ($files && $post_ID) {
foreach ((array)$files as $file) { ?>
            <tr id="esys-<?php echo $i; ?>">
                <td><input type="text" name="esys[<?php echo $i; ?>][bpm]" value="<?php echo $file['bpm']; ?>" /></td>
                <td><input type="text" name="esys[<?php echo $i; ?>][duration]" value="<?php echo $file['duration']; ?>" /></td>
                <td><a href="#" class="button" onclick="esys_remove(<?php echo $i; ?>); return false;">X</a></td>
            </tr>
<?php $i++;
}; }; ?>
            <tr id="esys-<?php echo $i; ?>">
                <td><input type="text" name="esys[<?php echo $i; ?>][bpm]" /></td>
                <td><input type="text" name="esys[<?php echo $i; ?>][duration]" /></td>
                <td><a href="#" class="button" onclick="esys_remove(<?php echo $i; ?>); return false;">X</a></td>
            </tr>
        </tbody>
    </table>
    <p align="right" style="padding:10px 0 5px; margin:0;"><a href="#" class="button" id="add-esys-file">Add</a></p>
    <?php

}

function esys_get_files($ID) {
    $data = unserialize(get_option("esys-files"));
    return ($ID) ? $data[$ID] : $data;
}

function esys_delete() {
    delete_option('esys-files');
}

function esys_submit($post_ID) {
  global $wpdb;
    if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) {
        return $post_id;
    }
    $data = esys_get_files($post_ID);
    foreach((array)$_POST['esys'] as $file) {
        $t[] = $file;
        $data[$post_ID] = $t;
    }
    esys_update_files($data);
}

function esys_update_files($data) {
    update_option('esys-files', serialize($data));
}

function esys_admin_head() {
    echo '<link type="text/css" rel="stylesheet" media="all" href="'.plugins_url('energy-systems-module/admin.css').'" />'."\n";
    echo '<script type="text/javascript" src="'.plugins_url('energy-systems-module/esys.js').'"></script>'."\n";
}

add_action('admin_head', 'esys_admin_head');
add_action('admin_menu', 'esys_menus');
add_action('save_post', 'esys_submit');
?>
</code>```

答:
The problem was storing data as "options." There is only one options table, and as it turns out, it was getting erased when trying to attach data to more than one post.

Post meta data is the way to go.

Title: Wordpress plugin data disappearing

Body:
I'm working on a simple plug that lets me save pairs of values with a post; there's a bit of JS to add or delete pairings. Everything works just fine, but randomly data will disappear. I'm not sure if it's a problem with autosaving or what, but I'd thought I'd accounted for that.

Any ideas why my data is saving, but disappearing randomly?

<?php

function esys_menus() {
    if (function_exists('add_meta_box')) {
        add_meta_box('esys_box','Energy System Details','esys_meta','energy-systems');
    }
}

function esys_meta() {
    global $wpdb, $post_ID;
    $files = esys_get_files($post_ID);
    ?>

                BPM
                Duration

        <?php
$i = 0;
if ($files && $post_ID) {
foreach ((array)$files as $file) { ?>
            <tr id="esys-<?php echo $i; ?>">
                <input type="text" name="esys[<?php echo $i; ?>][bpm]" value="<?php echo $file['bpm']; ?>" />
                <input type="text" name="esys[<?php echo $i; ?>][duration]" value="<?php echo $file['duration']; ?>" />
                <a href="#" class="button" onclick="esys_remove(<?php echo $i; ?>); return false;">X

<?php $i++;
}; }; ?>
            <tr id="esys-<?php echo $i; ?>">
                <input type="text" name="esys[<?php echo $i; ?>][bpm]" />
                <input type="text" name="esys[<?php echo $i; ?>][duration]" />
                <a href="#" class="button" onclick="esys_remove(<?php echo $i; ?>); return false;">X

Add

    <?php

}

function esys_get_files($ID) {
    $data = unserialize(get_option("esys-files"));
    return ($ID) ? $data[$ID] : $data;
}

function esys_delete() {
    delete_option('esys-files');
}

function esys_submit($post_ID) {
  global $wpdb;
    if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) {
        return $post_id;
    }
    $data = esys_get_files($post_ID);
    foreach((array)$_POST['esys'] as $file) {
        $t[] = $file;
        $data[$post_ID] = $t;
    }
    esys_update_files($data);
}

function esys_update_files($data) {
    update_option('esys-files', serialize($data));
}

function esys_admin_head() {
    echo '<link type="text/css" rel="stylesheet" media="all" href="'.plugins_url('energy-systems-module/admin.css').'" />'."\n";
    echo ''."\n";
}

add_action('admin_head', 'esys_admin_head');
add_action('admin_menu', 'esys_menus');
add_action('save_post', 'esys_submit');
?>


问:
How to install bcmath on a debian:jessie php5.6?
I am running a linux instance on a docker container. It is a debian:jessie with a php 5.6.

I want to install bcmath module, but I have no success.

Does someone know how o do that?

```<code>root@1419c032c35f:/etc/php5/fpm# apt install php5.6-bcmath
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package php5.6-bcmath
E: Couldn't find any package by regex 'php5.6-bcmath'
</code>```

答:
Simply create a Dockerfile that will build from the image you want (the one linked above) and add the line </p>

```<code>RUN docker-php-ext-install bcmath
</code>```

Body:
I am running a linux instance on a docker container. It is a debian:jessie with a php 5.6.

I want to install bcmath module, but I have no success.

Does someone know how o do that?

root@1419c032c35f:/etc/php5/fpm# apt install php5.6-bcmath
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package php5.6-bcmath
E: Couldn't find any package by regex 'php5.6-bcmath'

Body:
Simply create a Dockerfile that will build from the image you want (the one linked above) and add the line

RUN docker-php-ext-install bcmath


问:
template literals is not working in react
I have my code as below. template literals not creating multiline string in span tag, where as it is creating multiline in console.</p>

```<code>import React, {Component} from 'react';

import ReactDOM from 'react-dom';

class MyApp extends Component {

    render() {

        console.log(`string text line 1
        string text line 2`);

        let test = `dfas dss
        sdassas`;

        return (
            <span>{test}</span>
        )
    }
}

ReactDOM.render(
    <MyApp />,
    document.getElementById('app')
  );
</code>```

答:
HTML collapses whitespace into a single space. See Why does HTML require that multiple spaces show up as a single space in the browser?

The easiest solution would be to tell that span that it should not collapse whitespace.

The following snippet shows you that this is not related to React, and how to display newlines in HTML

Using white-space: pre

    Hello this

    has new lines

Collapsing white space

    Hello this

    has new lines

```

Body:
I have my code as below. template literals not creating multiline string in span tag, where as it is creating multiline in console.

import React, {Component} from 'react';

import ReactDOM from 'react-dom';

class MyApp extends Component {

    render() {

        console.log(`string text line 1
        string text line 2`);

        let test = `dfas dss
        sdassas`;

        return (
            {test}
        )
    }
}

ReactDOM.render(
    <MyApp />,
    document.getElementById('app')
  );

Body:
HTML collapses whitespace into a single space. See Why does HTML require that multiple spaces show up as a single space in the browser?

The easiest solution would be to tell that span that it should not collapse whitespace.

The following snippet shows you that this is not related to React, and how to display newlines in HTML

<h2>Using white-space: pre</h2>
<span style="white-space: pre">

    Hello this

    has new lines
</span>

<h2>Collapsing white space</h2>
<span>

    Hello this

    has new lines

</span>


问:
I have seperate node REST api and separate Angular 4 interface. Can I pass data from this Angular 4 to Separate REST api?
I have a Separate NodeJS RESTful api and Separate angular 4 interface. Can I pass data that are submitted from the interface to RESTful api by giving path?</p>

答:
You tried call make an service  like as :</p>

```<code>import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Rx';

@Injectable()
export class YourService {
  constructor(private http:Http) { }
  // Uses http.get() to communicate with NodeJs
  getSomeThing() {
    return this.http.get('yourAPIUrl').map((res:Response) => res.json());
  }
}
</code>```

Body:
You tried call make an service  like as :

import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Rx';

@Injectable()
export class YourService {
  constructor(private http:Http) { }
  // Uses http.get() to communicate with NodeJs
  getSomeThing() {
    return this.http.get('yourAPIUrl').map((res:Response) => res.json());
  }
}


问:
How do I get the size of a directory in C?
Is there a POSIX function that will give me the size of a directory (including all sub-folders), roughly equivalent to "du -s somepath"?

答:
```<code>$ man nftw
</code>```

NAME

ftw, nftw - file tree walk

DESCRIPTION

ftw() walks through the directory tree
  that is located under the directory
  dirpath, and calls fn() once for  each
  entry  in  the  tree.   By default,
  directories  are  handled before the
  files and subdirectories they contain
  (pre-order traversal).

CONFORMING TO

POSIX.1-2001, SVr4, SUSv1.

Simple example

```<code>#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>

static unsigned int total = 0;

int sum(const char *fpath, const struct stat *sb, int typeflag) {
    total += sb->st_size;
    return 0;
}

int main(int argc, char **argv) {
    if (!argv[1] || access(argv[1], R_OK)) {
        return 1;
    }
    if (ftw(argv[1], &sum, 1)) {
        perror("ftw");
        return 2;
    }
    printf("%s: %u\n", argv[1], total);
    return 0;
}
</code>```

OwnerDisplayName: therefromhere

LastEditorDisplayName: therefromhere

Body:
$ man nftw

NAME

ftw, nftw - file tree walk

DESCRIPTION

ftw() walks through the directory tree
  that is located under the directory
  dirpath, and calls fn() once for  each
  entry  in  the  tree.   By default,
  directories  are  handled before the
  files and subdirectories they contain
  (pre-order traversal).

CONFORMING TO

POSIX.1-2001, SVr4, SUSv1.

Simple example

#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>

static unsigned int total = 0;

int sum(const char *fpath, const struct stat *sb, int typeflag) {
    total += sb->st_size;
    return 0;
}

int main(int argc, char **argv) {
    if (!argv[1] || access(argv[1], R_OK)) {
        return 1;
    }
    if (ftw(argv[1], &sum, 1)) {
        perror("ftw");
        return 2;
    }
    printf("%s: %u\n", argv[1], total);
    return 0;
}

OwnerDisplayName: Checkers

LastEditorDisplayName: Checkers


答:
In base R you can use the powerful reshape to transform your data from wide to long format in one-line statement:

```<code>   reshape(dx,direction="long",
        varying=list(grep("qID",colnames(dx)),
                     grep("time_taken",colnames(dx))),
        v.names=c("qID","time_taken"))

     age gender     education previous_comp_exp tutorial_time time  qID time_taken id
1.1  18   Male Undergraduate      casual_gamer      62.17926    1 sor9   39.61206  1
2.1  24   Male Undergraduate      casual_gamer      85.01288    1 sor9   50.92343  2
1.2  18   Male Undergraduate      casual_gamer      62.17926    2 sor8   19.48920  1
2.2  24   Male Undergraduate      casual_gamer      85.01288    2 sor8   16.15616  2
</code>```

Title: Tidying dataset by gathering multiple columns?

Body:
I want to tidy a dataset by manipulating the data this way:

age gender  education       previous_comp_exp   tutorial_time   qID.1    time_taken.1   qID.2    time_taken.2
18  Male    Undergraduate   casual gamer        62.17926        sor9     39.61206       sor8     19.4892
24  Male    Undergraduate   casual gamer        85.01288        sor9     50.92343       sor8     16.15616

To become this:

age gender  education       previous_comp_exp   tutorial_time   qID      time_taken
18  Male    Undergraduate   casual gamer        62.17926        sor9     39.61206
18  Male    Undergraduate   casual gamer        62.17926        sor8     19.4892
24  Male    Undergraduate   casual gamer        85.01288        sor9     50.92343
24  Male    Undergraduate   casual gamer        85.01288        sor8     16.15616

I've experimented with gather(), but I can only only get it working with one column and I keep getting this warning:

Warning message:attributes are not identical across measure variables;
  they will be dropped

Any ideas?

Body:
In base R you can use the powerful reshape to transform your data from wide to long format in one-line statement:

   reshape(dx,direction="long",
        varying=list(grep("qID",colnames(dx)),
                     grep("time_taken",colnames(dx))),
        v.names=c("qID","time_taken"))

     age gender     education previous_comp_exp tutorial_time time  qID time_taken id
1.1  18   Male Undergraduate      casual_gamer      62.17926    1 sor9   39.61206  1
2.1  24   Male Undergraduate      casual_gamer      85.01288    1 sor9   50.92343  2
1.2  18   Male Undergraduate      casual_gamer      62.17926    2 sor8   19.48920  1
2.2  24   Male Undergraduate      casual_gamer      85.01288    2 sor8   16.15616  2


问:
C# - How to combine SharePoint Lists in C#
I am trying to combine two SharePoint lists into one so I can return items from two separate lists as one entity.

I have multiple Objects but I haven't found a good way to combine them no matter which ones I use.

Is there a simple way to combine the following?

```<code>SPList pubList = web.Lists["public"];
SPList secureList = web.Lists["secure"];
</code>```

or

```<code>SPListItemCollection pubFiles = retrieveDocs(web, meta, pubList);
SPListItemCollection secureFiles = retrieveDocs(web, meta, secureList);
</code>```

or convert these DataTables to SPListItemCollections

```<code>DataTable pubTable = pubFiles.GetDataTable();
DataTable secureTable = secureFiles.GetDataTable();

pubTable.Merge(secureTable);
</code>```

答:
This post answered my question.

In Summary

```<code>using System.Linq;

Then

List<SPListItem> allItems = new List<SPListItem>();
allItems.AddRange(list.GetItems(spQuery).Cast<SPListItem>().ToList());
allItems.AddRange(list2.GetItems(spQuery).Cast<SPListItem>().ToList());

//Do something to the "allItems"
</code>```

Body:
I am trying to combine two SharePoint lists into one so I can return items from two separate lists as one entity.

I have multiple Objects but I haven't found a good way to combine them no matter which ones I use.

Is there a simple way to combine the following?

SPList pubList = web.Lists["public"];
SPList secureList = web.Lists["secure"];

or

SPListItemCollection pubFiles = retrieveDocs(web, meta, pubList);
SPListItemCollection secureFiles = retrieveDocs(web, meta, secureList);

or convert these DataTables to SPListItemCollections

DataTable pubTable = pubFiles.GetDataTable();
DataTable secureTable = secureFiles.GetDataTable();

pubTable.Merge(secureTable);

Body:
This post answered my question.

In Summary

using System.Linq;

Then

List<SPListItem> allItems = new List<SPListItem>();
allItems.AddRange(list.GetItems(spQuery).Cast<SPListItem>().ToList());
allItems.AddRange(list2.GetItems(spQuery).Cast<SPListItem>().ToList());

//Do something to the "allItems"


问:
IntelliJ IDEA .iml file adding wrong scope to dependency
I have a scala file located at src/main/scala/my.cool.package.name/MyTestClass that has an import for scala.reflect.runtime.universe._. Maven resolves this dependency fine, and the code compiles. The import is heavily used throughout the code, so I know the dependency actually exists and Maven is using it.

The project-name.iml file that IDEA generates has the reference to scala-reflect, but it's putting it in the TEST scope:

```<code><orderEntry type="library" scope="TEST" name="Maven: org.scala-lang:scala-reflect:2.11.8" level="project" />
</code>```

Because it's in TEST, and the source file isn't, the source file generates tons of warnings & errors in IDEA. If I manually remove scope="TEST" from that line, IDEA resolves the dependency perfectly fine. The problem is that this file is auto-generated, so this change gets removed pretty often.

So, what is causing scala-reflect to be brought in as TEST? I'm not explicitly referencing reflect anywhere in my pom.xml file, so if it's come from Maven, I'm not sure how. Is there a way to force that line to be generated the way I want?

答:
Try to add

```<code><dependency>
  <groupId>org.scala-lang</groupId>
  <artifactId>scala-reflect</artifactId>
  <version>2.12.4<!--your version of Scala--></version>
  <scope>compile<!--runtime--></scope>
</dependency>
</code>```

to pom.xml.

Body:
I have a scala file located at src/main/scala/my.cool.package.name/MyTestClass that has an import for scala.reflect.runtime.universe._. Maven resolves this dependency fine, and the code compiles. The import is heavily used throughout the code, so I know the dependency actually exists and Maven is using it.

The project-name.iml file that IDEA generates has the reference to scala-reflect, but it's putting it in the TEST scope:

<orderEntry type="library" scope="TEST" name="Maven: org.scala-lang:scala-reflect:2.11.8" level="project" />

Because it's in TEST, and the source file isn't, the source file generates tons of warnings & errors in IDEA. If I manually remove scope="TEST" from that line, IDEA resolves the dependency perfectly fine. The problem is that this file is auto-generated, so this change gets removed pretty often.

So, what is causing scala-reflect to be brought in as TEST? I'm not explicitly referencing reflect anywhere in my pom.xml file, so if it's come from Maven, I'm not sure how. Is there a way to force that line to be generated the way I want?

Body:
Try to add

<dependency>
  <groupId>org.scala-lang</groupId>
  <artifactId>scala-reflect</artifactId>
  <version>2.12.4<!--your version of Scala--></version>
  <scope>compile<!--runtime--></scope>
</dependency>

to pom.xml.


问:
unexpected Identifier return for no forseeable reason
I'm not sure whats going on here I keep getting an unexpected identifier return on my first line of code but I can't tell whats going on is there something wrong with my code or is it my compiler?

```<code>private static final float IDEAL_FRAME_RATE = 100;

KeyInput currentKeyInput;
GameSystem system;
PFont smallFont, largeFont;
boolean paused;

void setup() {
  size(1360, 640, P2D);
  frameRate(IDEAL_FRAME_RATE);

  // Prepare font
  final String fontFilePath = "Lato-Regular.ttf";
  smallFont = createFont(fontFilePath, 20f, true);
  largeFont = createFont(fontFilePath, 96f, true);
  textFont(largeFont, 96f);
  textAlign(CENTER, CENTER);

  rectMode(CENTER);
  ellipseMode(CENTER);

  currentKeyInput = new KeyInput();

  newGame(true, true);  // demo play (computer vs computer), shows         instruction window
}

void draw() {
  if(keyIsDown(72))
    println("H");
  background(255f);
  background(random(255), random(255), random(255));
  system.run();
}

void newGame(boolean demo, boolean instruction) {
  system = new GameSystem(demo, instruction);
}

void mousePressed() {
  system.showsInstructionWindow = !system.showsInstructionWindow;
}
</code>```

There are six other classes that go with this one if there is nothing wrong with this one could it be due to another lass? If I need to link then I will gladly cause I'm stuck and really want to get this done

答:
Since you've now mentioned that this is in Processing, see
https://en.wikipedia.org/wiki/Processing_(programming_language)
where it mentions that "static" is not allowed (you have it at IDEAL_FRAME_RATE at the 1st line, which would explain the error message you were getting)

Every Processing sketch is actually a subclass of the PApplet[3] Java class (formerly a subclass of Java's built-in Applet) which implements most of the Processing language's features.

When programming in Processing, all additional classes defined will be treated as inner classes when the code is translated into pure Java before compiling. This means that the use of static variables and methods in classes is prohibited unless Processing is explicitly told to code in pure Java mode.

Processing also allows for users to create their own classes within the PApplet sketch. This allows for complex data types that can include any number of arguments and avoids the limitations of solely using standard data types such as: int (integer), char (character), float (real number), and color (RGB, ARGB, hex).

Body:
I'm not sure whats going on here I keep getting an unexpected identifier return on my first line of code but I can't tell whats going on is there something wrong with my code or is it my compiler?

private static final float IDEAL_FRAME_RATE = 100;

KeyInput currentKeyInput;
GameSystem system;
PFont smallFont, largeFont;
boolean paused;

void setup() {
  size(1360, 640, P2D);
  frameRate(IDEAL_FRAME_RATE);

  // Prepare font
  final String fontFilePath = "Lato-Regular.ttf";
  smallFont = createFont(fontFilePath, 20f, true);
  largeFont = createFont(fontFilePath, 96f, true);
  textFont(largeFont, 96f);
  textAlign(CENTER, CENTER);

  rectMode(CENTER);
  ellipseMode(CENTER);

  currentKeyInput = new KeyInput();

  newGame(true, true);  // demo play (computer vs computer), shows         instruction window
}

void draw() {
  if(keyIsDown(72))
    println("H");
  background(255f);
  background(random(255), random(255), random(255));
  system.run();
}

void newGame(boolean demo, boolean instruction) {
  system = new GameSystem(demo, instruction);
}

void mousePressed() {
  system.showsInstructionWindow = !system.showsInstructionWindow;
}

There are six other classes that go with this one if there is nothing wrong with this one could it be due to another lass? If I need to link then I will gladly cause I'm stuck and really want to get this done


问:
How to convert a list of characters to ASCII in python?
Hi i’m sort of new to Python and i’m trying to convert a string of characters to ASCII in Python but I don’t know how to do that

So the relevant parts of my code are probably this

```<code>string = input(“Enter a line of text: “)
l = list(string)
return(l)
</code>```

So it puts the input in a list because then it’s separate characters instead of a whole string of them but then I don’t know how to convert it to ASCII. I know I have to use ord() but I don’t understand how to do that when it’s more than one character because I don’t know what the input will be so I can’t just do like ord(A).

How can I do it?

答:
If you are using python 2, strings are encoded as ascii by default. If you are using python 3, you can convert a string to ascii using the built-in string method encode:

```<code>ascii = string.encode('ascii')
</code>```

If you want this to be represented as a list, you might try encoding each separately, as the default iterated representation for ascii characters are integers. (try [x for x in b'binary string!'])

```<code>ascii_chars = [char.encode('ascii') for char in string]
</code>```

Body:
Hi i’m sort of new to Python and i’m trying to convert a string of characters to ASCII in Python but I don’t know how to do that

So the relevant parts of my code are probably this

string = input(“Enter a line of text: “)
l = list(string)
return(l)

So it puts the input in a list because then it’s separate characters instead of a whole string of them but then I don’t know how to convert it to ASCII. I know I have to use ord() but I don’t understand how to do that when it’s more than one character because I don’t know what the input will be so I can’t just do like ord(A).

How can I do it?

Body:
If you are using python 2, strings are encoded as ascii by default. If you are using python 3, you can convert a string to ascii using the built-in string method encode:

ascii = string.encode('ascii')

If you want this to be represented as a list, you might try encoding each separately, as the default iterated representation for ascii characters are integers. (try [x for x in b'binary string!'])

ascii_chars = [char.encode('ascii') for char in string]