text:
Q: Running SQL script file through Java In order to execute a whole SQL script file[which includes create table statements and some rules defining create table]. I found this solution in order to achieve it --->"There is great way of executing SQL scripts from Java without reading them yourself as long as you don't mind having a runtime dependency on Ant. In my opinion such a dependency is very well justified in your case. Here is sample code, where SQLExec class lives in ant.jar:
private void executeSql(String sqlFilePath) {
    final class SqlExecuter extends SQLExec {
        public SqlExecuter() {
            Project project = new Project();
            project.init();
            setProject(project);
            setTaskType("sql");
            setTaskName("sql");
        }
    }

    SqlExecuter executer = new SqlExecuter();
    executer.setSrc(new File(sqlFilePath));
    executer.setDriver(args.getDriver());
    executer.setPassword(args.getPwd());
    executer.setUserid(args.getUser());
    executer.setUrl(args.getUrl());
    executer.execute();
}

I don't know whether it will work or not!!!
Can anybody give some hints to work on the above solution? I mean how to get the code work  and also let me know any other solution to execute SQL script files!!!
Thanks,
Mahesh

A: This is a code snippet I stole from the internet somewhere (I don't remember where) that I know works great:  it wont run the way that it is below.   It might give you enough clues to get yours working though, or you might find the source on Google somewhere:
private void runScriptOnce(Connection conn, Reader reader) throws IOException, SQLException {
    StringBuffer command = null;
    try {
        LineNumberReader lineReader = new LineNumberReader(reader);
        String line = null;
        while ((line = lineReader.readLine()) != null) {
            if (command == null) {
                command = new StringBuffer();
            }
            String trimmedLine = line.trim();
            if (trimmedLine.startsWith("--")) {
                println(trimmedLine);
            } else if (trimmedLine.length() < 1
                    || trimmedLine.startsWith("//")) {
                // Do nothing
            } else if (trimmedLine.length() < 1
                    || trimmedLine.startsWith("--")) {
                // Do nothing
            } else if (!fullLineDelimiter
                    && trimmedLine.endsWith(getDelimiter())
                    || fullLineDelimiter
                    && trimmedLine.equals(getDelimiter())) {
                command.append(line.substring(0, line
                        .lastIndexOf(getDelimiter())));
                command.append(" ");
                Statement statement = conn.createStatement();

                println(command);

                boolean hasResults = false;
                if (stopOnError) {
                    hasResults = statement.execute(command.toString());
                } else {
                    try {
                        statement.execute(command.toString());
                    } catch (SQLException e) {
                        e.fillInStackTrace();
                        printlnError("Error executing: " + command);
                        printlnError(e);
                    }
                }

                if (autoCommit && !conn.getAutoCommit()) {
                    conn.commit();
                }

                ResultSet rs = statement.getResultSet();
                if (hasResults && rs != null) {
                    ResultSetMetaData md = rs.getMetaData();
                    int cols = md.getColumnCount();
                    for (int i = 0; i < cols; i++) {
                        String name = md.getColumnLabel(i);
                        print(name + "\t");
                    }
                    println("");
                    while (rs.next()) {
                        for (int i = 0; i < cols; i++) {
                            String value = rs.getString(i);
                            print(value + "\t");
                        }
                        println("");
                    }
                }

                command = null;
                try {
                    statement.close();
                } catch (Exception e) {
                    // Ignore
                }
                Thread.yield();
            } else {
                command.append(line);
                command.append(" ");
            }
        }
        if (!autoCommit) {
            conn.commit();
        }
    } catch (SQLException e) {
        e.fillInStackTrace();
        printlnError("Error executing: " + command);
        printlnError(e);
        throw e;
    } catch (IOException e) {
        e.fillInStackTrace();
        printlnError("Error executing: " + command);
        printlnError(e);
        throw e;
    } finally {
        conn.rollback();
        flush();
    }
}

private String getDelimiter() {
    return delimiter;
}

private void print(Object o) {
    if (logWriter != null) {
        System.out.print(o);
    }
}

private void println(Object o) {
    if (logWriter != null) {
        logWriter.println(o);
    }
}

private void printlnError(Object o) {
    if (errorLogWriter != null) {
        errorLogWriter.println(o);
    }
}

private void flush() {
    if (logWriter != null) {
        logWriter.flush();
    }
    if (errorLogWriter != null) {
        errorLogWriter.flush();
    }
}


text:
Q: Finding a boundary in a density plot I am very new to machine learning so I am open to suggestions as well. I read something called minimax risk today and I was wondering if this is possible in my case.
I have two datasets and am interested in finding a line (or a boundary to be more precise) such that the area under the left curve to the right of the vertical line is equal to the area under the right curve to the left of the vertical line. Is there a way this can be done in R i.e., find out the exact location to draw the vertical line?
I put up some sample data here that can be used to plot the following graph: https://gist.github.com/Legend/2f299c3b9ba94b9328b2

A: Suppose you are using the density function to get the estimated kernel density for each response, then follow this link to get the estimated kernel CDF, then your question would become to find a value t, such that: 1 - cdf1(t) = cdf2(t), which can be solved by regular root find function:
x1 <- subset(data, Type == 'Curve 1')$Value
x2 <- subset(data, Type == 'Curve 2')$Value

pdf1 <- density(x1)
f1 <- approxfun(pdf1$x, pdf1$y, yleft = 0, yright = 0)
cdf1 <- function(z){
  integrate(f1, -Inf, z)$value
}

pdf2 <- density(x2)
f2 <- approxfun(pdf2$x, pdf2$y, yleft = 0, yright = 0)
cdf2 <- function(z){
  integrate(f2, -Inf, z)$value
}

Target <- function(t){
  1 - cdf1(t) - cdf2(t)
}

uniroot(Target, range(c(x1, x2)))$root

R > uniroot(Target, range(c(x1, x2)))$root
[1] 0.06501821

redpajama_set_name: RedPajamaStackExchange


text:
Q: No prompt to increase Web SQL limit in Android native browser? I need to save 11 MB of data offline using Web SQL. In iOS I am asked if I want to increase the quota, and everything is fine. But in Android's native browser (2.3-4.2) no such prompt is presented - it simply fails with QUOTA_ERR*.
I have spent many hours doing intensive search and have read absolutely everything related to this problem, but I'm still not completely certain whether I should receive a prompt or not and whether the limit can be pushed up by any means.
Any real info or help will be greatly appreciated.

* "there was not enough remaining storage space, or the storage quota was reached and the user declined to give more space to the database"

A: Have you give estimated database size during opening, like this?
var size = 11 * 1024 * 1024; // 11 MB
var db = openDatabase(db_name, '', description, size);

There will be an upper limit of database size. I am greatly appreciate if you found the upper limit on Android browser.
Thanks.

A: I have tried to research this all day to find out what the maximum sizes for Android and iPhone are. On the current Android 4.x phones the limit seems to be fixed at around 8MB, effectively limiting you to storing json-content of up to 4 million characters (each character is 2 bytes in utf-16).
No Android device I have tested will prompt you when you hit the limit, as opposed to iPhone, which will prompt you both at the time of database creation (with a size >= 5MB) and when you hit each of the limits (5, 10, 25 and 50 megabytes).
You can create several smaller databases, but it will not help you in increasing the total storage on Android which is still limited to 8MB. If you are running in a WebView, that is another story;
There you can store up to 50MB on Android, and the same on iPhone (in a UIWebView) - WITHOUT getting prompted.
PS. You might be able to cram the 11MB of data in 8MB if you compress the strings. Do expect approximately a tenfold decrease in read/write speeds. See http://labs.ft.com/2012/06/text-re-encoding-for-optimising-storage-capacity-in-the-browser/


text:
Q: DRY way to rename ModelSerializer fields without duplicating model/field definitions? Working with a legacy database with an awful schema and want to rename several ModelSerializer fields without having to redefine fields already defined on the model.
Here's an example model:

class LegacyItem(models.Model):
    # Note: ignore things that feel "wrong" here (just an example)
    legacyitem_id = models.IntegerField(primary_key=True)
    legacyitem_notes = models.CharField(max_length=4000, blank=True, null=True)
    directory_id = models.ForeignKey('Directory', models.DO_NOTHING)
    created_by_directory_id = models.ForeignKey('Directory', models.DO_NOTHING)
    created_date = models.DateField(auto_now_add=True)
    modified_by_directory_id = models.ForeignKey('Directory', models.DO_NOTHING)
    modified_date = models.DateField(auto_now=True)

Here's a working serializer:
class LegacyItemSerializer(serializers.ModelSerializer):
    class Meta:
        fields = '__all__'
        model = LegacyItem
        read_only_fields = [
            'created_date',
            'modified_date',
        ]

The goal is to bulk rename model fields for the API so we can abstract away the awful schema. Here's a working serializer showing the sort of renaming we want to do:
class LegacyItemSerializer(serializers.ModelSerializer):
    created_by = serializers.PrimaryKeyRelatedField(
        read_only=True,
        source='created_by_directory_id',
    )
    customer = serializers.PrimaryKeyRelatedField(
        queryset=Directory.objects.all(),
        source='directory_id',
    )
    id = serializers.PrimaryKeyRelatedField(
        read_only=True,
        source='legacyitem_id'
    )
    modified_by = serializers.PrimaryKeyRelatedField(
        read_only=True,
        source='modified_by_directory_id',
    )
    notes = serializers.DateField(source='legacyitem_notes')

    class Meta:
        fields = [
            'id',
            'customer',
            'notes',
            'created_by',
            'created_date',
            'modified_by',
            'modified_date',
        ]
        model = LegacyItem
        read_only_fields = [
            'created_date',
            'modified_date',
        ]

All we want to do is rename the fields. We don't want to change the validation and would rather keep most of that validation on the model and the model's fields and not also put it into the serializer. We will have to do this sort of thing for a lot of models and it's very tedious and bad practice (IMO) to be duplicating model validation on the serializer just to rename a field.
Is there a DRY way to do this? Maybe something we can put into LegacyItemSerializer.Meta or some method we can override? When working with Django forms, for example, you could do this easily by tweaking labels/widgets in the ModelForm.Meta. You would never have to redefine ModelForm fields/validation.
In a perfect world, maybe something like:
class LegacyItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = LegacyItem
        model_field_args = {
            'legacyitem_id': {'name': 'id'},
            'directory_id': {'name': 'customer'},
            'legacyitem_notes': {'name': 'notes'},
            'created_by_directory_id': {'name': 'created_by'},
            'modified_by_directory_id': {'name': 'modified_by'},
        }


text:
Q: How to set label after input field in React.js Formik (Input)? I would need to set the text of the Label, for the Formik Input Component, after the input field.
I am not sure how to target it and how to apply CSS.
So a code sample:
<div className="editable-job-title">
      {isEditing ? (
        <Formik
          validateOnMount={true}
          enableReinitialize
          initialValues={user}
          validationSchema={userNameValidationSchema}
          onSubmit={handleSubmit}>
          {(props) => (
            <Form>
                <Input
                name="job_title"
                type="text"
                label={t('userForm.job_title.label')}
              />
              <FormActions className="user-form-page__form-action">
                <RoundButton
                  type="button"
                  onClick={stopEditing}
                  className="button button--cancel">
                  <Icon icon={x} />
                </RoundButton>
            </Form>
          )}
        </Formik>

So basically, I would need the Job Title text to be below the field.
Or any other nice solution.

A: I guess you want to use <Field> element from formik.

If this is the case, check it out on https://codesandbox.io/s/formik-tests-onchange-mo4fi?file=/src/App.js
import { Field, Formik, Form } from "formik";
import { TextField } from "@material-ui/core";

<Formik
      initialValues={initialValues}
      onSubmit={() => alert("submitted!")}
    >
      <Form>
        <Field name="email">
          {(props) => (
            <>
              <TextField
                variant="outlined"
                placeholder={props.field.name}
                label={props.field.name}
                {...props.field}
              />
            </>
          )}
        </Field>
        ...


text:
Q: Excel VBA: Get the right date into a cell using DatePicker I have a UserForm with a DatePicker control in it.
It works fine, except when copying the selected date to the spreadsheet.
This is the code:
Range("A1").Value = UserForm1.DTPicker1.Value

Which returns:
00:00:00

In cell A1, no matter what date has been selected.

A: You cell formatting might be set to Time instead of Date.
Try changing that to see if it works.
Also, make formatting 'General' AFTER this step, to see if anything has been pasted in "A1".

A: You should need an intermediate variable to get it, like below:
t = Me.DTPicker1.Value
ws.Range("A1") = t

A: Make sure that the command to transfer the data is located in the same form or page of a multipage form as the DTPicker itself.
For some reason it wont work when the two are separated and will display a zero in the target cell. That zero is the "time" part of the date which has been switched off. Although the "Date" part refuses to transfer over, for some reason the time does, and so that zero time is read in the cell as time zero which is mid-day.
So in summary:
Keep the DTPicker and transfer control on the same page and that should solve the problem.
The code is pretty simple. It's
Sheet1.Range("AA9") = Me.DTPicker1.Value


text:
Q: GeoDataFrame - Unable to select range of linestrings df = sample['geometry']
line_gdf = gpd.GeoDataFrame(geometry=[df[2],  df[3], df[4], df[5], df[6], df[7], df[8], df[9]])

Above is the manual process of selecting Line Strings
In order to select from 2:180 I tried some code without luck
line_gdf = gpd.GeoDataFrame(geometry=[df[df.rows[2:4]])

it comes up with an error of'GeoSeries' object has no attribute 'rows'
I am bit confused how to solve it I would appriciate some guidance.

A: Assuming "sample" is a GeoDataFrame, then df in your example is a GeoSeries of geometries. As GeoSeries don't have rows, df.rows give you the error you report.
Its unclear to me exactly what you are trying to achieve, but I assume you have a dataframe  called sample, and you want to select rows 2 to 180. If so:
line_gdf = sample.iloc[2:180]

If you are trying to achieve something else, please clarify your inputs and desired outputs.


text:
Q: can't print in 22.04 I hope someone can help me fix this issue.
I'm using Ubuntu 22.04, I have been for about 2 months now with hardly any problems until Friday. In Libre Office Writer (the default version that installs with Ubuntu 22.04), my HP printer suddenly stopped working even though I haven't changed anything at all.
I haven't tried printing from other apps, should I? The LO Writer app shows my printer name. When I looked at my print queue, everything looked OK.
I did a little research & tried the following in terminal:
lpstat(1)

the result was:
bash: syntax error near unexpected token `1'

I've no idea what this means, I'm hoping someone can tell me or even if is my issue?
Anyone can help me.

A: sudo apt install hplip then
try visit http://localhost:631/admin and delete and re-add printer here.
Note, it works only in Firefox. Not Chrome or Vivaldi.


text:
Q: Actualizar datos de una tabla en un SP conforme éste busca datos de otras tablas. FOR...LOOP Tengo un SP que me selecciona desde dos tablas los flujos de una cuenta de cliente en un periodo dado. La tabla de Registro de Movimientos únicamente indica si es compra(cargo) o venta (abono) y el monto de éste; la otra tabla sólo dice cuál era el saldo al momento de abrir la cuenta i.e. Cliente y Saldo Inicial.
El procedimiento debe mostrar una tabla que resuma todos los movimientos entre dos fechas dadas pero a la vez, cada fila debe indicar en una columna cuál va siendo el saldo conforme van sucediendo los movimientos. ESTE es mi problema, ¿Cómo puedo hacer que por cada registro encontrado me genere ese saldo?
Suponiendo que el saldo inicial es cero, el SP que tengo toma el dato del saldo inicial y suma todos los movimientos hasta la fecha inicial del periodo a seleccionar, digamos que el acumulado hasta esa fecha sea 198, este valor debe sumarse al movimiento que inicia la tabla de resultados, la tabla que quiero se vería así:

Saldo inicial=0
Periodo De:2017-08-30, A: 2017-09-10
Saldo a la fecha inicial= $ 198

Fecha      | Operación | Importe | Saldo
2017-08-30 | Compra    | 100     | 98
2017-08-31 | Venta     | 10      | 108
2017-08-31 | Compra    | 100     | 8

Como ven, a veces hay más de un movimiento al día, por lo que necesito que se haga por movimiento (vale mencionar que la tabla de movimientos tiene un Primary Key para cada movimiento, no sé si esto ayude de algo). Este es mi código:
    PROCEDURE [dbo].[Movimientos_entre_fechas] @pmFechaDe date,@pmFechaA date,@pmCuenta nvarchar(20)
AS
SET NOCOUNT ON

Declare @varSaldo float=0,@pmInicial float=0,@SaldoXmovimiento float

--LEER DEL ESTADO INICIAL
SET @pmInicial=(SELECT Efectivo+Saldo  FROM EstadoInicial WHERE Cuenta=@pmCuenta) --Cash Disponible al Inicio de la cuenta
SET @varSaldo=(SELECT SUM(Importe) FROM Movimientos WHERE Cuenta=@pmCuenta and Fecha<=@pmFechaDe) --SUMA MOVIMIENTOS

SET @SaldoXmovimiento=@pmInicial+@varSaldo

SELECT Fecha,Operacion,Cantidad,Precio,ROUND(Precio*ABS(Cantidad),2) as [Importe Bruto],Comision,Impuesto,Importe as [Cargo/Abono],@SaldoXmovimiento + A.Importe as SALDO, A.Clave FROM Movimientos A
LEFT JOIN Productos B ON A.EmiID=B.EmiID
WHERE a.Fecha>=@pmFechaDe and a.Fecha<=@pmFechaA and A.Cuenta=@pmCuenta ORDER BY Fecha
SET NOCOUNT Off  --El Join es para identificar qué Producto es

A: Tu pregunta se reduce a un tema de Suma acumulada, si buscas en la red hay varios trucos para resolverlo. En lo posible evita la tentación de usar cursores y loops, suelen ser muy poco performantes y además implican una carga importante para el motor. En el siguiente ejemplo, conceptualmente lo que hacemos es crear una tabla temporal dónde volcaremos todas las operaciones con el orden adecuado (esto es fundamental) y que además tendrá un Id autonumérico. Luego la idea es hacer un JOIN a la misma tabla pero de los registros menores o iguales al actual de la tabla base, de esta forma sumamos (acumulamos) todos los importes hasta el registro listado. Este es un ejemplo reproducible como para que veas como funciona la idea:
En primer lugar creamos nuestras dos tablas de ejemplo que simularán las tuyas y las llenamos con algunos ejemplos (El Cliente 1 es exactamente tu ejemplo):
CREATE TABLE #SaldosIniciales (
    Cuenta  INT,
    Saldo       NUMERIC(15,2)
)

CREATE TABLE #Movimientos (
    Cuenta      VARCHAR(20),
    Fecha       DATETIME,
    Operacion   VARCHAR(15),
    Importe     NUMERIC(15,2)
)

INSERT INTO #SaldosIniciales (Cuenta, Saldo) VALUES ('1', 198)
INSERT INTO #Movimientos (Cuenta, Fecha, Operacion, Importe)
    VALUES  ('1', '20170830', 'Compra', 100),
        ('1', '20170831', 'Venta', 10),
        ('1', '20170831', 'Compra', 100),
        ('2', '20170830', 'Compra', 300),
        ('2', '20170830', 'Compra', 100),
        ('2', '20170831', 'Venta', 1000),
        ('2', '20170901', 'Compra', 100)

Ahora creamos nuestra tabla temporal de trabajo, notese el Id autonumérico:
CREATE TABLE #Saldos (
    Id          INT IDENTITY,
    Cuenta      VARCHAR(20),
    Fecha       DATETIME,
    Operacion   VARCHAR(15),
    Importe     NUMERIC(15,2)
)

Ahora llenamos nuestra tabla de trabajo con los datos reales, muy importante el orden ya que determinará el Id que tengan los registros. Hay un CASE en el ORDER simplemente para mantener el mismo orden del ejemplo, dónde la venta aparece antes de la compra en un mismo día, es un detalle que puedes obviar si no te interesa.
INSERT INTO #Saldos (Cuenta, Fecha, Operacion, Importe)
SELECT  M.Cuenta,
    M.Fecha,
    M.Operacion,
    M.Importe
    FROM #Movimientos M
    ORDER BY M.Cuenta,
        M.Fecha,
        CASE WHEN M.Operacion = 'Venta' THEN 0 ELSE 1 END

Y por último la consulta en sí, a la que le hemos agregado mediante un LEFT JOIN la tabla de saldos iniciales para que participe en la suma.
SELECT  T1.Cuenta,
    T1.Fecha,
    T1.Operacion,
    T1.Importe,
    ISNULL(SI.Saldo,0) + SUM(CASE WHEN T2.Operacion = 'Compra' THEN -1 ELSE 1 END * T2.Importe) AS Saldo
    FROM #Saldos t1
    INNER JOIN #Saldos T2
        ON  T1.id >= T2.id
        AND T1.Cuenta = T2.Cuenta
    LEFT JOIN #SaldosIniciales SI
        ON SI.Cuenta = T1.Cuenta
    GROUP BY T1.Id,
        T1.Cuenta,
        T1.Fecha,
        T1.Operacion,
        T1.Importe,
        SI.Saldo
    ORDER BY T1.Id

La salida obtenida:
+--------+--------------------------+-----------+----------+---------+
| Cuenta | Fecha                    | Operacion | Importe  | Saldo   |
+--------+--------------------------+-----------+----------+---------+
| 1      | 30/08/2017 12:00:00 a.m. | Compra    | 100,00   | 98,00   |
+--------+--------------------------+-----------+----------+---------+
| 1      | 31/08/2017 12:00:00 a.m. | Venta     | 10,00    | 108,00  |
+--------+--------------------------+-----------+----------+---------+
| 1      | 31/08/2017 12:00:00 a.m. | Compra    | 100,00   | 8,00    |
+--------+--------------------------+-----------+----------+---------+
| 2      | 30/08/2017 12:00:00 a.m. | Compra    | 300,00   | -300,00 |
+--------+--------------------------+-----------+----------+---------+
| 2      | 30/08/2017 12:00:00 a.m. | Compra    | 100,00   | -400,00 |
+--------+--------------------------+-----------+----------+---------+
| 2      | 31/08/2017 12:00:00 a.m. | Venta     | 1.000,00 | 600,00  |
+--------+--------------------------+-----------+----------+---------+
| 2      | 01/09/2017 12:00:00 a.m. | Compra    | 100,00   | 500,00  |
+--------+--------------------------+-----------+----------+---------+


text:
Q: How to render the entire URL for a link with Jinja (for use in an email) When creating a link in HTML on a website we typically just use the relative link, such as /my/link, and then the web browser fills in root when the page is loaded.  i.e. the browser converts that link into http://example.com/my/link.  This is great in general, but I'm using jinja2 to render an email body (using render_template), so the HTML content is never displayed under example.com, it's only displayed in the email application.  So is there a way for jinja2 to recognize the domain that the app is on and tell render_template to fill in the entire link?.

A: Set the _external flag to True to force a full URL to be generated:
url_for(endpoint, _external=True)

See the flask.url_for() documentation:

_external – if set to True, an absolute URL is generated. Server address can be changed via SERVER_NAME configuration variable which defaults to localhost.


text:
Q: JSON Path seems to be removing a comma I'm using JSON Path to extract a some data from a json object.
The object looks like this:
{
   "properties":
      {
         "random_field": "abc",
         "max value": "£35,900"
      }
}

My JSON path looks like this:
insert into display_paths (type,name,jsonpath) values ('type','Value (£)','$.properties.[''max value'']');

Annoyingly, this is returning the value without the ',', instead replacing it with a space:
Value (£): £35 900

Has anyone had a similar issue? Potentially it is a front end issue as opposed to a json path issue?

A: Note: Consider the risk of SQL injection when inserting unprepared data from external sources into an SQL statement like in your example. Read about prepared statements, using them can prevent this.

About the jsonpath issue, looks like a quoting issue with your code. Check this working example:
import json
from jsonpath import jsonpath

data = json.loads('''
{
   "properties":
      {
         "random_field": "abc",
         "max value": "£35,900"
      }
}
''')

query = "$.properties.['max value']"
# Note that this works too
query = "$.properties.[max value]"

print(data)
print(jsonpath(data, query))

Output:
{'properties': {'random_field': 'abc', 'max value': '£35,900'}}
['£35,900']

PS: pip install jsonpath must be run for this example to work.


text:
Q: how to send emails on local server I have Mamp Pro and have a PHP application that sends an email password to someone regestering in  a regester/login system.  I would like to test the email being sent on my local Mamp Pro server but cant figure out how to do it with gmail--it seems a lot of people have this problem with gmail.  Are there any suggestions how I can configure an email account to test this.
Has anyone had this problem also?
Thanks

A: use mail()
http://php.net/manual/en/function.mail.php


text:
Q: How to make a php SOAP call I am having trouble setting the body of a PHP SOAP call. I believe I am close just dont know how to get it in the correct format.
Here is what I have thus far in PHP
    $client = new SoapClient('http://url');
    $username='username';
    $password='password';

    $headers='
        '.$username.'
        '.$password.'
    ';

    $securityTags = new SoapVar($headers, XSD_ANYXML);

    $header=new SoapHeader("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Security",$securityTags,true);

    $client->__setSoapHeaders(array($header));

    //HOW DO I SET THE BODY????
    $params = array('deal'=>'PT10M', 'StoreIds'=>64);
    return $client->__soapCall("PullDeals", array('searchCriteria'=>$params));

Below is what the request should look like
<soapenv:Envelope xmlns:arr="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:deal="http://url.com" xmlns:ns="http://url" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Header>
      <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
         <wsse:UsernameToken wsu:Id="UsernameToken-145" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
            <wsse:Username>YOUR_USERNAME</wsse:Username>
            <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">YOUR_PASSWORD</wsse:Password>
            <wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">JQT6P7Zd3COZerXkREww2g==</wsse:Nonce>
            <wsu:Created>2013-11-19T22:18:54.122Z</wsu:Created>
         </wsse:UsernameToken>
      </wsse:Security>
   </soapenv:Header>
   <soapenv:Body>
      <ns:PullDeals>
         <ns:searchCriteria>
            <deal:MaxElapsedSinceUpdate>PT10M</deal:MaxElapsedSinceUpdate>
            <deal:StoreIds><arr:long>64</arr:long></deal:StoreIds>
         </ns:searchCriteria>
      </ns:PullDeals>
   </soapenv:Body>
</soapenv:Envelope>

A: To compare your request to the what the request should look like add 'trace' => true to your soap client.
$client = new SoapClient("my.wsdl", array('trace' => true));
and then use echo $client->__getLastRequest(); to spit out the XML.
I usually just view it on the page with chrome's Inspector to see it nicely indented.
You can reformat your call accordingly after you see how it is being formed.
Failing that you can hard code the XML.


text:
Q: How to see what command-line options handbrake sends to mencoder I want to see what command-line options handbrake is sending to mencoder. I looked at the Activity Window and it shows a lot of stuff but not what I'm looking for. How can I find it?

A: The reason I found this thread here is because, on
https://trac.handbrake.fr/wiki/CLIGuide
I noticed :
... under "Video Options"
-x, --encopts <string>  Specify advanced encoding options in the same
                        style as mencoder (all encoders except theora):
                        option1=value1:option2=value2

AND :
under "Picture Settings"
--crop: controls the cropping values. The cropping has to be in the form Top:Bottom:Left:Right, so to crop 60pixels from the top, 58 from the bottom, 2 from the left, and 6 from the right, use --crop 60:58:2:6

... do note that this is different from cropping in some other programs,
like MEncoder. If you don't enter this setting, HandBrake will
automatically detect how many pixels to crop to remove black borders.

A: Based on my experience with Handbrake on Windows and Linux: it does not use mencoder. Instead it offers its own command line interface: HandBrakeCLI.
On Windows one can click Show Queue>Queue>Generate Batch Script to export a script which contains all the command line parameters passed on to HandBrakeCLI. Although your reference to the "Activity Window" leads me to believe you're using Mac OS X, such an option may exist on the Mac version as well.


text:
Q: Facebook connect not redirecting properly all of sudden Did Facebook just randomly change their API over the last couple of days? I had my site working perfectly with the Facebook API and now all of a sudden it doesn't work at all. No, I haven't changed anything, it literally just decided yesterday to not redirect anymore...it seems to just try to connect a few times and then it displays this page:
"The page isn't redirecting properly
Firefox has detected that the server is redirecting the request for this address in a way that will never complete.
    *   This problem can sometimes be caused by disabling or refusing to accept
          cookies."
Anyway, here is some code to wrap your heads around :P (yes, I do actually have my real app id's and such in place)
This is the fbLogin_member.php file which is where you're directed after clicking on the Login link:
$app_id = "my id #";
$app_secret = "my secret id";
$my_url = "http://www.sitedomain.com/confirmlogin_fb_member.php";

if (empty($code)) {
    $dialog_url = "http://www.facebook.com/dialog/oauth?client_id=". $app_id ."&redirect_uri=". urlencode($my_url) ."&scope=email";
    echo "";
}

$code = $_REQUEST['code'];

Here is the confirmlogin_fb_member.php file:
//if user denies access to your website, take him to your manual login page
// if ($_GET['error']) {
    // header("Location: memberlogin.php");
    // exit;
// }

require_once('config/dbconfig.php');

$app_id = "my id #";
$app_secret = "my secret id";
$my_url = "http://www.sitedomain.com/confirmlogin_fb_member.php";

$code = $_GET['code'];

$token_url = "https://graph.facebook.com/oauth/access_token?client_id="
    . $app_id . "&redirect_uri=" . urlencode($my_url) . "&client_secret="
    . $app_secret . "&code=" . $code;

// request access token
//use curl and not file_get_contents()
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $token_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$access_token = curl_exec($ch);
curl_close($ch);

$graph_url = "https://graph.facebook.com/me?" . $access_token;

// request user data using the access token
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $graph_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$temp_user = curl_exec($ch);
curl_close($ch);

//decode the json array to get user data
$user = json_decode($temp_user);

//store user data
$u = $user->name;
$e = $user->email;
$fb_id = $user->id;
$username = $user->username;
$picture = 'https://graph.facebook.com/'. $fb_id .'/picture';

//check if user has already signed up before
$insert = true;
$result = mysql_query("SELECT * FROM members") or die(mysql_error());

while ($row = mysql_fetch_array($result)) {
    //if username already exists, do not insert
    if (($row['name'] == $u) && ($row['userType'] == "facebook_user")) {
        $insert = false;
    }
}

// Random Password Generator
$chars = "abcdefghijkmnopqrstuvwxyz023456789";
srand((double)microtime()*1000000);
$i = 0;
$pass = '' ;

while ($i <= 7) {
    $num = rand() % 33;
    $tmp = substr($chars, $num, 1);
    $pass = $pass . $tmp;
    $i++;
}
// end generator

// if new user, insert user details in your mysql table
if ($insert) {
    mysql_query("INSERT INTO members(name, fb_username, password, email, profile_pic, userType) VALUES('$u', '$username', '$pass' , '$e', '$picture', 'facebook_user')") or die(mysql_error());
}

//login user
if (!session_start()) session_start();
$_SESSION['in'] = true;
$_SESSION['userName'] = $u;
$_SESSION['userType'] = "facebook_user";
$_SESSION['userEmail'] = $e;

//take user to his/her homepage
header("Location: layout.php");

Lastly, here is the top of layout.php where the Facebook API session is called:
session_start();
require_once('config/dbconfig.php');
require_once('facebook/facebook.php');

if (isset($_REQUEST['logout'])) {
    unset($_SESSION['in']);
    unset($_SESSION['userName']);
    unset($_SESSION['userType']);
    unset($_SESSION['userEmail']);
    session_destroy();
    header("Location: layout.php");
}

$session = $_SESSION['in'];
if (!$session) {
    $login = 'Login with Facebook';

    $tooltipMsg = '
You must Log in to vote.
';
} else {
    $sessionUser = $_SESSION['userName'];
    $result = mysql_query("SELECT * FROM `members` WHERE name = '$sessionUser'") or die('Query failed: ' . mysql_error() . "
\n$sql");

    if ($result) {
        $sessionRow = mysql_fetch_array($result);
        $sessionUserid = $sessionRow['memberid'];
    }

    if ($sessionRow['userType'] == "facebook_user") {
        $facebook = new Facebook(array(
                                    'appId'  => 'my app id #',
                                    'secret' => 'my secret id',
                                    'cookie' => true
                                ));

        // $session = $facebook->getSession();
        $user = $facebook->getUser();

        $me = null;
        // Session based API call.
        if ($user) {
            try {
                $me = $facebook->api('/me');
            } catch (FacebookApiException $e) {
                // error_log($e);
            }
        }
    }

It just boggles my mind that it has worked fine for a couple weeks, and now when I come back home from being gone a day and a half it doesn't work. Any help would be appreciated, even if there is some other things wrong you see with my coding (this is my first attempt with the facebook api) :)

A: It sounds like you might have an infinite redirect problem?
You are checking to see if $code is set before assigning it, try flipping the order of these two statements:
$code = $_REQUEST['code'];
if (empty($code)) {
    $dialog_url = "http://www.facebook.com/dialog/oauth?client_id=". $app_id ."&redirect_uri=". urlencode($my_url) ."&scope=email";
    echo " top.location.href='". $dialog_url ."'";
  }

A: You might need to change $_REQUEST to $_GET in protected function getCode() in base_facebook.php
protected function getCode() {

if (isset($_GET['code'])) {
  if ($this->state !== null &&
      isset($_GET['state']) &&
      $this->state === $_GET['state']) {

    // CSRF state has done its job, so clear it
    $this->state = null;
    $this->clearPersistentData('state');
    return $_GET['code'];
  } else {
    self::errorLog('CSRF state token does not match one provided.');
    return false;
  }
}

return false;
  }


text:
Q: Intelligent Management of Large Session Values I have an application containing a 'wizard' like workflow, wherein users edit a large collection of objects and once complete they can choose to save or cancel their edits. Given the size of the objects, storing them client side and round tripping them is not feasible. Instead we use session state to store the objects, and use ajax methods to retrieve/edit them.
My problem is that, if the user chooses to navigate away from the current page without completing this workflow, then the object collection stays in the session until the session expires or the user begins the same workflow over again. Given that there may be many concurrent users and that the object collection can get fairly large (i.e. >2MB per user) I'm concerned that this will cause needless memory consumption and potential performance degradation.
Certainly there are other approaches available that do not use session (i.e. writing to temp tables), however, I was wondering if there is a way to intelligently detect when a user navigates away from a controller so that I may perform some sort of cleanup (delete the unnecessary session variables).

A: Detecting when a user leaves a page is tough.  While there are a few options out there, the most reliable is probably polling, which isn't perfect.  For example, if a user's connection flakes out for a few seconds, then you could wipe out their session.
You also can't just wipe out the wizard session objects if any page on the app outside of the wizard has activity by the user.  This solution fails if a user opens multiple tabs/windows.
If it's possible to put a timer on your wizard, then I'd set a manager in state to manage wizard object collections by user.  That manager would have the last activity date for every object, and you'd set up a sliding expiration to wipe out any session objects which haven't had activity in X minutes.
This solution would allow you to edit the length of your wizard timer to balance user needs with server resources.  If your session is consuming too much memory, then reduce the sliding expiration, or vice versa.


text:
Q: How to get URI from file with FileProvider How can I get URI from a file with a dynamic folder in the path?

java.lang.IllegalArgumentException: Failed to find configured root
  that contains
  /storage/emulated/0/AppName/155522864927/media/1555228649276.mp4

It works fine only if I set hardcoded path
<external-path name="/" path="AppName/155522864927/media/" />

A: The path cannot be random. You need to configure the path that you expose. For more info please have a look here.


text:
Q: cfthread object empty inside of a cfthread tag in Lucee 5.2 In Lucee v5.2.9.31, the following code throws an error inside of the checkTest thread when I request the status of the test_thread thread from the cfthread object. The error I get is key [test_thread] doesn't exist.
<cfthread action="run" name="test_thread">
    <cfloop index='i' from='1' to='50'>
        <cffile action="append" file="./test_thread.txt" addNewLine="yes" output="Index: #i#" />
        <cfset sleep(500) />
    </cfloop>
</cfthread>

<cfthread action="run" name="checkTest">
    <cfset test_thread_complete = false />
    <cfloop condition="test_thread_complete eq false">
        <cfset test_thread_status = cfthread['test_thread'].status />

        <cffile action="append" file="./checkTestThread.txt" addNewLine="yes" output="#test_thread_status#" />

        <cfif test_thread_status eq 'COMPLETED'>
            <cfset test_thread_complete = true />
        </cfif>
        <cfset sleep(1000) />
    </cfloop>
</cfthread>

<cfdump var="#cfthread#" />
<cfdump var="#cfthread['test_thread']#" />

However in an older version of Lucee (v4.5.5.015), the code works as expected and generated 2 files: test_thread.txt with the incrementing index, and checkTestThread.txt which contains the status of test_thread.
In both versions, the cfdumps return the cfthread object. The first dump contains both threads and the 2nd dump contains just the test_thread object as expected.
Is this a bug in Lucee 5 or was the code exploiting a bug in earlier versions of Lucee/Railo?

A: This was caused by an update that was made to Lucee.
According to Michael Offner (The maintainer of Lucee):

The reason is this no longer works in Lucee, because we added support
  of having threads inside threads, since then "cfthread" only shows the
  children of the current thread, in a tree (see key "childThreads"
  inside "cfthread"). We cannot show all threads on one level that would
  create a mess, because we would show the tree of threads at the same
  time.

Issue is fixed in v5.3.4.37, however the code will need to be updated as their solution adds a threadData function which returns the root cfthread object.
In my code changing the following: <cfset test_thread_status = cfthread['test_thread'].status /> to <cfset test_thread_status = threadData()['test_thread'].status /> fixes the error and properly returns the status of a sibling thread.
More Information:

*

*Git commit of the fix: https://github.com/lucee/Lucee/commit/576ff5f7e2556c1cc8298154d40006a158da9270

*Jira Issue: https://luceeserver.atlassian.net/browse/LDEV-2150


text:
Q: Mapping UUID in Spark Cassandra connector I have the following code to save RDD to cassandra:
 JavaRDD<UserByID> mapped = ......

CassandraJavaUtil.javaFunctions(mapped)
.writerBuilder("mykeyspace", "user_by_id", mapToRow(UserByID.class)).saveToCassandra();

And UserByID is a normal serializable POJO with the following variable with getters and setters
private UUID userid;

Cassandra table has exactly the same names of the class UserByID variables, and userid is of type uuid in Cassandra table, I am loading data successfully from the table using the same class mapping.
CassandraJavaRDD<UserByID> UserByIDRDD = javaFunctions(spark)
 .cassandraTable("mykeyspace", "user_by_id", mapRowTo(UserByID.class));

however, when I call saveToCassandra function above, I get the following exception:
org.apache.spark.SparkException: Job aborted due to stage failure: Task
0 in stage 227.0 failed 1 times, most recent failure: Lost task 0.0
in stage 227.0 (TID 12721, localhost, executor driver):
java.lang.IllegalArgumentException:
The value (4e22e71a-a387-4de8-baf1-0ef6e65fe33e) of the type
(java.util.UUID) cannot be converted to
struct<leastSignificantBits:bigint,mostSignificantBits:bigint>

To solve the problem I have registered UUID codec, but that didn't help, I am using spark-cassandra-connector_2.11 version 2.4.0 and the same version for spark-core_2.11 any suggestion?
my reference is here but it has no Java UUID example, your help is appreciated.

A: That's really strange error - this just works fine with connector 2.4.0 & Spark 2.2.1 with following example:
Table definition:
CREATE TABLE test.utest (
    id int PRIMARY KEY,
    u uuid
);

POJO class:
public class UUIDData {
    private UUID u;
    private int id;
    ...
    // getters/setters
};

Spark job:
public static void main(String[] args) {
    SparkSession spark = SparkSession
            .builder()
            .appName("UUIDTest")
            .getOrCreate();

    CassandraJavaRDD<UUIDData> uuids = javaFunctions(spark.sparkContext())
            .cassandraTable("test", "utest", mapRowTo(UUIDData.class));

    JavaRDD<UUIDData> uuids2 = uuids.map(x -> new UUIDData(x.getId() + 10, x.getU()));

    CassandraJavaUtil.javaFunctions(uuids2)
            .writerBuilder("test", "utest", mapToRow(UUIDData.class))
            .saveToCassandra();
}

I've noticed that in your code you're using functions mapRowTo and mapToRow without calling the .class on POJO - are you sure that your code compiled and you don't run any old version of the code?


text:
Q: How to create a registration form and save the data on sqlite? I am making an registration form in which i have two pages to complete the registration process.
page1 contains:
i have 8 textfield and one submit button in page 1...
when ever user enter the value in textfield and click the submit button all the enter value in textfield should get insert in my sqlite table and move to the next page with the same value in textfield .
page 2 contains
i have 8 textfield and two button:Edit, and continue in page 2...
this page should contains all the page1 textfield value in it,so that he can check the value enter by him are correct or not,and if not then he should be able to edit them and save them and proceed further.....
below is my page 1 code:
.h file
#import <UIKit/UIKit.h>
#import "/usr/include/sqlite3.h"
#import "Confirmation_form.h"

@interface Registration_Form :

UIViewController<UITextFieldDelegate> {
    Confirmation_form *con_form;

    sqlite3 *test1DB;

    IBOutlet UITextField *UserName;
    IBOutlet UITextField *Password;
    IBOutlet UITextField *ConfirmPassword;
    IBOutlet UITextField *Name;
    IBOutlet UITextField *Email;
    IBOutlet UITextField *ContactNO;
    IBOutlet UITextField *MobileNo;
    IBOutlet UITextField *Address;
    NSString *databasePath;

}
@property(nonatomic,retain)IBOutlet UITextField *UserName;

@property(nonatomic,retain)IBOutlet UITextField *Password;

@property(nonatomic,retain)IBOutlet UITextField *ConfirmPassword;

@property(nonatomic,retain)IBOutlet UITextField *Name;

@property(nonatomic,retain)IBOutlet UITextField *Email;

@property(nonatomic,retain)IBOutlet UITextField *ContactNO;

@property(nonatomic,retain)IBOutlet UITextField *MobileNo;

@property(nonatomic,retain)IBOutlet UITextField *Address;

-(IBAction) submit;

this is my .m file:
#import "Registration_Form.h"

@implementation Registration_Form
@synthesize UserName,Password,ConfirmPassword,Name,Email,ContactNO,MobileNo,Address;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {

    NSString *docsDir;

    NSArray *dirPaths;

    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    docsDir = [dirPaths objectAtIndex:0];

    databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent:@"test1.db"]];

    NSFileManager *filemgr = [NSFileManager defaultManager];

    if([filemgr fileExistsAtPath: databasePath ] == NO)
    {
        const char *dbpath = [databasePath UTF8String];

        if(sqlite3_open(dbpath, &test1DB) ==SQLITE_OK)
        {
            char *errMsg;

            const char *sql_stmt = "CREATE TABLE IF NOT EXISTS test (ID INTEGER PRIMARY KEY AUTOINCREMENT, USERNAME TEXT, PASSWORD TEXT, CONFIRMPASSWORD TEXT, NAME TEXT, EMAIL TEXT, CONTACTNO MUMBER, MOBILENO NUMBER,ADDRESS TEXT)";

            if(sqlite3_exec(test1DB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
            {
                //status.text = @"Failed to create table";
            }
            sqlite3_close(test1DB);
        }else {
            //status.text = @"Failed to open/create database";
        }

    }
    [filemgr release];
    [super viewDidLoad];
}

-(void)submit
{

sqlite3_stmt  *statement;

    const char *dbpath = [databasePath UTF8String];

    if (sqlite3_open(dbpath, &test1DB) == SQLITE_OK)
    {
        NSString *insertSQL = [NSString stringWithFormat:@"INSERT INTO test(UserName,

Password, ConfirmPassword, Name, Email, ContactNO, MobileNo, Address) VALUES (\"%@\", \"%@\",

\"%@\", \"%@\", \"%@\", \"%@\", \"%@\", \"%@\")",UserName.text, Password.text, ConfirmPassword.text,

Name.text, Email.text, ContactNO.text, MobileNo.text, Address.text];

        const char *insert_stmt = [insertSQL UTF8String];

        sqlite3_prepare_v2(test1DB, insert_stmt, -1, &statement, NULL);

        if(sqlite3_step(statement) == SQLITE_DONE)
        {
            //status.text = @"Contact added";
            UserName.text = @"";
            Password.text = @"";
            ConfirmPassword.text = @"";
            Name.text = @"";
            Email.text = @"";
            ContactNO.text = @"";
            MobileNo.text = @"";
            Address.text = @"";

        }else {
            //status.text = @"Failed to add Contact";
        }
        sqlite3_finalize(statement);
        sqlite3_close(test1DB);

    }

    con_form = [[Confirmation_form alloc] initWithNibName:@"Confirmation_form" bundle:[NSBundle

mainBundle]];

    [self.navigationController pushViewController:con_form animated:YES];

}

please help me out
thank's

A: First of all you have create NSString object and their property  in your 1stcontroller than after  store the text filed value in this NSString .eg.passstring = UserName.text;
Than after pass this string to the next 2ndcontroller .
By creating the the object of 1stcontroller.like this 1stcontroller *urobject = [[1stcontroller  alloc]init];
yourtextfiled = urobject.passstring;
i hope this will help you

A: Great tutorial on pure sqlite here.
But I would suggest just using properties unless that data is needed past the second form.
Also, if you are going to be doing a lot of db work I would suggest FMDatabase.


text:
Q: Self-referencing table entities not loaded in client I have a table Test with a foreign key to itself. In metadata class I have
[Include]
Test Test2 { get; set; }

In a service class:
 return this.ObjectContext.Test.Include("Test2")

I checked that data loaded correctly from database. But on a client side I see that no parent has been loaded.
I use a DomainDataSource to load data (Silverlight 4.0).
Someone else experienced this strange behavior?

A: Ok, my mistake. The answer is to use [Include] attribute as always, but make sure that all participating properties are public in your metadata class.


text:
Q: How to get double precision value in python equals to java Float.valueof() I am trying to migrate a java calculation to python, where I see the difference in the float value calculation results
for example: in Java
public class Main
{
    public static void main(String[] args) {
        long lg_val =  Long.parseLong("16191753860");
        float fg_val = Float.valueOf(lg_val);
        System.out.println(fg_val);
    }
}

result - 1.61917542E10 (prints the double value)
but in python float() method returns same value 16191753860.0
How to get the double-precision calculation in python to get the same results

A: The python float is a double precision floating point number. It is in fact your Java example that is using the single precision float, which is why it formats in scientific notation (as it has gone above integer precision).
If you want to print out the scientific notation of a float in python regardless of if it's crossed over the precision boundary, use the e format.
f'{lg_val:e}' -> '1.619175e+10'

Or to use a double precision number in Java instead, use
double fg_val = Double.valueOf(lg_val);

A: You can use numpy.float64(). In your example,
import numpy as np

np.float64(lg_val)


text:
Q: problems moving to API 31 in ionic cordova framework the problem is the following: I have my project in ionic cordova with API 30 and everything works perfectly, the problem happens when I want to go to API 31, what happens is that when going to API 31 only It works on Android 11 and its previous versions, but not on versions 12, 13 and it cannot be installed on the versions already mentioned
I tried to update ionic and all its dependencies to the latest version, hoping that would solve the problem

A: Do you have a specific error on some logging or something else to go off of?
I believe you have to switch from java-8 to at least java-11.
You also might have to update cordova-android, or at least read about the breaking changes in the update docs: https://cordova.apache.org/announcements/2022/07/12/cordova-android-release-11.0.0.html


text:
Q: Python multiprocessing map_async hangs I have some troubles [probably] with closing a pool of processes in my parser. When all tasks done, it hangs and do nothing, cpu usage is about 1%.
profiles_pool = multiprocessing.Pool(processes=4)
pages_pool = multiprocessing.Pool(processes=4)

m = multiprocessing.Manager()
pages = m.list(['URL'])
pages_done = m.list()

while True:
    # grab all links
    res = pages_pool.imap_unordered(deco_process_people, pages, chunksize=1)

    pages_done += pages
    pages = []

    for new_users,new_pages in res:
        users.update(new_users)
        profile_tasks = [ (new_users[i]['link'],i) for i in new_users ]
        # enqueue grabbed links for parsing
        profiles_pool.map_async(deco_process_profiles,
                                profile_tasks, chunksize=2,
                                callback=profile_update_callback)
        # i dont need a result of map_async actually
        # callback will apply parsed data to users dict
        # users dict is an instance of Manager.dict()

        for p in new_pages:
            if p not in pages_done and p not in pages:
                pages.append(p)

    # we need more than 900 pages to be parsed for bug occurrence
    #if len(pages) == 0:
    if len(pages_done) > 900:
        break

#
# closing other pools
#

# ---- the last printed string:
print 'Closing profiles pool',
sys.stdout.flush()
profiles_pool.close()
profiles_pool.join()
print 'closed'

I guess the problem is in wrong open tasks calculation in pool queue, but i'm not shure and cannot check this - idk how to get task queue length.
What can it be, and where to look first?

A: The most immediately-obvious problem is that pages_done is a synchronized Manager.list object (so each process can access it atomically), but while pages starts out as one such, it quickly becomes an ordinary un(multi)processed list:
pages_done += pages
pages = []

The second quoted line rebinds pages to a new, empty ordinary list.
Even if you deleted all the elements of pages on the second line (rather than doing a rebinding assignment), you could run into a race where (eg) pages had A, B, and C in it when you did the += on the first line, but had become A, B, C, and D by the second.
A quick fix would be to take items off pages one at a time and put them into pages_done one at a time (not very efficient).  Might be better to have these not be shared data structures at all though; it doesn't look like they need to be, in the quoted code (I'm assuming some unquoted code depends on it—since otherwise the rebinding of pages is a red herring anyway!).

A: I've found out the reason of a bug: "join method of multiprocessing Pool object hangs if iterable argument of pool.map is empty"
http://bugs.python.org/issue12157


text:
Q: Convert session value into Byte[] I store image into session in base64 format,
how can I convert it into byte[]
I want to do something like this:
Byte[] bytes =(Byte[]) Session["picimg"];

it's not working.
This is my code:
StreamReader reader = new StreamReader(Request.InputStream);
String Data = Server.UrlDecode(reader.ReadToEnd());
reader.Close();
 DateTime nm = DateTime.Now;
string date = nm.ToString("yyyymmddMMss");
        //used date for creating Unique image name

Session["capturedImageURL"] = Server.MapPath("Userimages/") + date + ".jpeg";

Session["Imagename"] = date + ".jpeg";
// We can use name of image where ever we required that why we are storing in Session

        drawimg(Data.Replace("imgBase64=data:image/png;base64,", String.Empty), Session["capturedImageURL"].ToString());

        // it is method
        // passing base64 string and string filename to Draw Image.
 Session["picimg"] = (Data.Replace("imgBase64=data:image/png;base64,", String.Empty));

        Byte[] bytes =(Byte[]) Session["picimg"];
        System.IO.File.WriteAllBytes(@"Userimages", bytes);

A: You need the Convert.FromBase64String method to decode the base64 string into a byte array.
byte[] Bytes = Convert.FromBase64String(DataInBase64);


text:
Q: Is the convex hull of a set bounded? Under what conditions it's bounded? Is the convex hull of a set bounded? Under what conditions it's bounded?

For a given set $X \subseteq \mathbb R^n$,the convex hull of $X$ denoted by $\text{CH}(X)$ is defined as $$\text{CH}(X):=\{\sum_{j=1}^{k}\lambda_j\mathbf{x}_j:\sum_{j=1}^{k}\lambda_j=1,\lambda_1,...,\lambda_k \ge 0\}$$
Where $\mathbf{x}_j$ are vectors in $X$ and $k \in \mathbb N^+$.
If the set $X$ is bounded itself by $M$, then it's convex hull is also bounded by $M$, But is that the only way that the convex hull of a set is bounded? In other words if the convex hull of a set is bounded, then what can be said about the set itself?
Moreover I know that there are sets whose convex hull is unbounded, but can someone give me an elementary example of such sets?

A: Yes, the convex hull of a set is bounded if and only if the set is bounded. If the set is bounded, say $\lVert x\rVert\le M$ for all $x\in X$, then $\left\lVert\sum_{k=1}^s \lambda_sx_s\right\rVert\le M\sum_{k=1}^s\lvert \lambda_s\rvert=M\sum_{k=1}^s \lambda_s=M$. If $X$ is unbounded, then $\operatorname{conv}(X)\supseteq X$ is too.


text:
Q: Printing a node's value only if information exists I'm looking to print out a customer's options only if they have a value in the node. I can access the information and print it out, however, because of the while loop it prints out the information under each account. Any help or hints would be appreciated, thanks.
Here is the code to access the xml:
XPathNodeIterator ItemOptionsIter;
String ItemsearchStringOptions = "Order/Items/Item/CustomerOptions";
ItemOptionsIter = nav.Select(ItemsearchStringOptions);

if (ItemIter.Current.SelectSingleNode("CustomerOptions") != null)
{
    while (ItemOptionsIter.MoveNext())
    {
        XPathNodeIterator ItemOptions = ItemOptionsIter.Current.SelectChildren(XPathNodeType.Element);
        if (ItemOptions.Current.HasChildren)
        {
            txtItemInfo.Text = txtItemInfo.Text + "Size: " + ItemOptions.Current.SelectSingleNode("Size") + Environment.NewLine;
            txtItemInfo.Text = txtItemInfo.Text + "Color: " + ItemOptions.Current.SelectSingleNode("Color") + Environment.NewLine;
            txtItemInfo.Text = txtItemInfo.Text + "-------------------------------------------------" + Environment.NewLine;
        }
    }
}

Here is the xml file:
<Item>
    <PartNo>JETSWEATER</PartNo>
    <Description>N.Y. Jets Sweatshirt</Description>
    <UnitPrice>10.50</UnitPrice>
    <Quantity>2</Quantity>
    <TotalCost>21.00</TotalCost>
    <CustomerOptions>
        <Size>M</Size>
        <Color>Green</Color>
    </CustomerOptions>
</Item>
<Item>
    <PartNo>JETSSWEATER</PartNo>
    <Description>N.Y. Jets Sweatshirt</Description>
    <UnitPrice>7.50</UnitPrice>
    <Quantity>3</Quantity>
    <TotalCost>22.50</TotalCost>
    <CustomerOptions>
        <Size>S</Size>
        <Color>White</Color>
    </CustomerOptions>
</Item>
<Item>
    <PartNo>JETSFLAG</PartNo>
    <Description>N.Y. Jets Flag for display</Description>
    <UnitPrice>5.00</UnitPrice>
    <Quantity>1</Quantity>
    <TotalCost>5.00</TotalCost>
    <CustomerOptions/>
</Item>

And finally here is a sample of my output:

Part Number: JETSWEATER
Description: N.Y. Jets Sweatshirt
UnitPrice: 10.50
Quantity: 2
TotalCost: 21.00
-------------------------------------------------
Size: M
Color: Green
-------------------------------------------------
Size: S
Color: White
-------------------------------------------------
Part Number: JETSSWEATER
Description: N.Y. Jets Sweatshirt
UnitPrice: 7.50
Quantity: 3
TotalCost: 22.50
-------------------------------------------------
Size: M
Color: Green
-------------------------------------------------
Size: S
Color: White
-------------------------------------------------
Part Number: JETSFLAG
Description: N.Y. Jets Flag for display
UnitPrice: 5.00
Quantity: 1
TotalCost: 5.00
-------------------------------------------------
Size: M
Color: Green
-------------------------------------------------
Size: S
Color: White
-------------------------------------------------

A: I'd say construct your main loop to iterate through the Item nodes and print out their values, and then in the place where you would print out the options, do this:
XPathNodeIterator options = item.SelectNodes("CustomerOptions/*[. != '']");
if(options.Count != 0)
{
  XPathNavigator size = item.SelectSingleNode("CustomerOptions/Size[. != '']");
  if(size != null)
  {
    txtItemInfo.Text = txtItemInfo.Text + "Size: " + size.Value + Environment.NewLine;
  }
  // Then do the same for color

  txtItemInfo.Text = txtItemInfo.Text + "-------------------------------------------------" + Environment.NewLine;
}


text:
Q: Kotlin Flow - Replacement for callbackFlow I am working on an Android project where MVVM is the architecture being used. There is a use case where a Flow in my Repository needs to be updated based on the results of a callback which is triggered when something in my Data Source changes. The most appropriate choice for this problem seems to be callbackFlow. However, it is still experimental. I am very tempted to use callbackFlow, however, I understand that any future changes might break some code and I don't want that to happen in a production app. Considering the above scenario, what should be a replacement for callbackFlow? Or should I consider going ahead with callbackFlow?

A: callbackFlow is runtime stable - it works just as it is supposed to and it exists exactly because it is exactly the right tool to use in many cases.

I understand that any future changes might break some code and I don't want that to happen in a production app"

The only change that would affect how it functions is when upgrading your version of coroutines. That has nothing to do with runtime stability.


text:
Q: Nginx won't start after server ip change I have a centos server with nginx running on it.
The server ip recently changed and nginx no longer starts up
it gives the following error message where 123.123.123.123. is the old ip address of the server
Starting nginx: nginx: [emerg] bind() to 123.123.123.123:80 failed (99: Cannot assign requested address)
Where is it reading the old IP address from?

A: Yes, paths to check seems to be:

/etc/nginx/conf.d/
/etc/nginx/sites-available/

Maybe the Nginx configuration files are also in different directory.
I had these in /home/admin/conf/web (VestaCP control panel?)
Then do "service nginx restart" command.


text:
Q: .width() function is not returning correct value I am trying to dynamically access the width of an element through jQuery using .width(). In developer tools I can see element's width as 37.333Px, where as .width() gives 38.33334Px.
Width in developer tools

Width from .width()

In this situation difference is of 1px, but sometimes it difference is in decimals. Why there is a such difference? Where am I going wrong? Is there any other to get exact width.

A: Use .width() only when DOM is ready to give you the exact value.
Since it takes time to adjust itself while parsing.
So You need to use $(document).ready(...  or $(window).load...

A: We can get width by few methods listed below,
width() - Sets or returns the width of an element
innerWidth() - Returns the width of an element (includes padding)
outerWidth() - Returns the width of an element (includes padding and border).
outerWidth(true) - Returns the width of an element (includes padding, border and margin).

A: The value reported by .width() is not guaranteed to be accurate when the element or its parent is hidden.
Also, dimensions may be incorrect when the page is zoomed by the user;
Note that .width() will always return the content width, regardless of the value of the CSS box-sizing property. As of jQuery 1.8, this may require retrieving the CSS width plus box-sizing property and then subtracting any potential border and padding on each element when the element has box-sizing: border-box. To avoid this penalty, use .css( "width" ) rather than .width().
Also you should be more specific when selecting the element. Going by XPath is never a good idea as the smallest change in the tree structure will break your code. Try to use an ID, Class, etc to make the selection

A: I have same question before and got answer this:
There are two actions taken by the browser:
Firstly: On the percentage itself - for example - Internet Explorer 7-11 will truncate any percentage to 2 decimal places, more modern browsers will round to a large number of decimal places.
Then the second action is on the resultant pixel value calculated using that percentage.
Example:

We have a container with a width of 1325px.
     Inside that we have a box with a width set to 50.5290112% in the CSS.
      This should give us a pixel width for the box of 669.5093984px by using the calculation (1325 / 100) x 50.5290112.
In Internet Explorer 8 the width of the box is actually 669px.
      What is happening in IE8 is that the browser is truncating the percentage to 50.52%.
      Which results in a pixel width of 669.39px by using the calculation (1325 / 100) x 50.52.
      The browser then rounds this down to the nearest integer, resulting in an actual width of 669px.

Reference Link

A: Why not use .getBoundingClientRect() ?
$('whatever')[0].getBoundingClientRect().width


text:
Q: TestCafe runs tests twice I am using TestCafe for some time now and never had a problem. A few days ago TestCafe started to run my tests twice, producing a lot of problems. I couldn't find the issue on https://github.com/DevExpress/testcafe/issues and wanted to ask if anyone else experienced these problems in the last time.
I am always starting the tests with: 'testcafe "chrome --start-fullscreen" tests/tests --speed 0.5 --skip-js-errors'.
Thank you so much and best regards from Germany
Stefan

A: I face this issue, whenever i am on same terminal with multiple interrupted run. Close your terminal


text:
Q: Tags [non-printable] and [non-printing-characters] Tags non-printable and non-printing-characters seem to be about the same thing.

A: Personally, I think this comes down to a popularity contest.  Here are some statistics:
More users elected to tag non-printable, that users are most likely to attempt that tag.  We get 14 vs 24.
On the contrary, a search for "non-printing character" has twice the results of "non-printable character".  1,007 and 2,640 respectively.
Google returns roughly the same number of results for the searches "non-printing" and "non-printable" (quotes included in search).
Based on the low number of questions with these tag, it's hard to say that's compelling evidence of future use.  The text-based search, however, indicates that "non-printing" is more common on Stackoverflow.


text:
Q: How can I change string to list in R? can someone help me ? I need to change string to list. Everything works fine when the inside of the parentheses is not in quotes. However, in my RShiny application, I am forced to use a string in parentheses. But the important thing is that it will not always be just YES and NO. There may be others depending on the dataset.
An example that works
vl = list(Yes = 2, No = 2)

#Output of str(vl):

List of 2
 $ Yes: num 2
 $ No : num 2

I need the same output for
vl = ...("Yes = 2, No = 2")

A: The eval/parse combination can be used to execute arbitrary strings as code, e.g.
v1 <- eval(parse(text=paste0("list(","Yes = 2, No = 2",")")))
v1
#$Yes
#[1] 2
#
#$No
#[1] 2

str(v1)
#List of 2
# $ Yes: num 2
# $ No : num 2


text:
Q: How Do I Determine the Security Account that IIS Uses to Run My Web Site? I'm using silverlight on IIS 7 and i created a folder "Logs" where i want to write (in a txt file) all the error that occured.
To solve the problem by now i've set the security rights of that folder to everyone, but i want to give the rights only to user(s) who will write into the log.
(That would be the user that is running IIS)
So my questions:
- How Do I Determine the Security Account that IIS Uses to Run My Web Site?
- Will that user be the same if i'm running my website under Windows Authentication? (now it's running under Anonymous authentication)

A: Go to advanced settings and look at the application pool being used by your web app. Then go into the application pools section of IIS admin and go to advanced settings of the relevant app pool. You should see the identity which is being used in there somewhere.


text:
Q: KeychainWrapper saving data and retrieving it in the same function isn't working So I have a custom function that makes a HTTP POST Request to my webserver to get some fields from my database and then returns it to my iOS App that will save that field value as a keychain item, using KeychainWrapper.
My iOS App is as simple as login screen that checks if user credentials are correct in the mySQL Database using HTTP POST again and if correct, brings me to a user page where it's supposed to display some information grabbed and displayed using KeychainWrapper.
Now the problem I'm facing is that whenever I press the login button on the login page and I land on the user page, all fields are displayed as null. But if I stop the build and re-build, it will load back to that page with the fields loaded this time.
As if when I get on the user page for the first time, the fields aren't saved in the keychain yet, but when I rebuild it, they are and they load from there.
I'll cut some parts out of my code to make it short and keep it relevant to this question. Here is my function that request the meta fields from the MYSQL Database :
func requestMetaField(metaField:String) -> String {

        let userEmail: String = KeychainWrapper.standard.string(forKey: "email")!;
        let userPassword: String = KeychainWrapper.standard.string(forKey: "password")!;
        let meta = metaField;

        // Send data to server side
        // Classic HTTP POST Request using JSONSerialization here.

                    if(resultValue=="Success") {

                        // Save downloaded data to keychain
                        self.saveDataToKeychain(value: metaValue, key: meta);
                    }

        // End of the HTTP POST Request and else statements.

        if let metaValue: String = KeychainWrapper.standard.string(forKey: meta) {
        return metaValue;
        } else {
            return "N/A";
        }

    }

Here is my saveDataToKeychain Function :
func saveDataToKeychain(value:String, key:String) -> Bool {
        let saveSuccessful: Bool = KeychainWrapper.standard.set(value, forKey: key);
        return saveSuccessful;
    }

Here is where I use the function on the user page to apply it to the labels :
override func viewDidLoad() {
        super.viewDidLoad()

        logoutButton.layer.cornerRadius = 6;

        let firstName = requestMetaField(metaField: "first_name");
        let lastName = requestMetaField(metaField: "last_name");
        userFullName.text = "\(firstName) \(lastName)";

        let userMinuteBalance = requestMetaField(metaField: "mycred_default_total");
        userBalance.text = "\(userMinuteBalance) min";
    }

And here is where I save the email & password in keychain when I use the login button :
if(resultValue=="Success") {

                        // Login is successful
                        UserDefaults.standard.set(true, forKey: "isUserLoggedIn");
                        UserDefaults.standard.synchronize();

                        // Save email & password in keychain
                        self.saveDataToKeychain(value: userEmail!, key: "email");
                        self.saveDataToKeychain(value: userPassword!, key: "password");

                        isUserLoggedIn = true;
}

Does anyone have an idea on how I could access the data immediately as I login ?
Also, I used the Keychain method because I've read that it's one of the safest of user information, but I'm open to other options if someone think there is an easier way to do this than using the keychain.
Thanks a lot for any help you can give !!

A: I think the problem is that you are treating requestMetaField as a synchronous function, when it is asynchronous. Your HTTP request will not finish until some time after requestMetaField returns.
Another approach would be to write a version of requestMetaField that takes a callback function that is called when the request completes. Then you can update your UI from the callback.
Here's what such a requestMetaField would look like:
func requestMetaField(metaField:String, callback: @escaping (String) -> Void) {

        let userEmail: String = KeychainWrapper.standard.string(forKey: "email")!;
        let userPassword: String = KeychainWrapper.standard.string(forKey: "password")!;
        let meta = metaField;

        // Send data to server side
        // Classic HTTP POST Request using JSONSerialization here.

                    if(resultValue=="Success") {

                        // Save downloaded data to keychain
                        self.saveDataToKeychain(value: metaValue, key: meta);

                        // call callback with value
                        callback(metaValue)
                    }

The code in viewDidLoad would look like:
    requestMetaField(metaField: "first_name") { firstName in
        requestMetaField(metaField: "last_name") { lastName in
            DispatchQueue.main.async {
                userFullName.text = "\(firstName) \(lastName)"
            }
        }
    }

    requestMetaField(metaField: "mycred_default_total") { userMinuteBalance in
        DispatchQueue.main.async {
            userBalance.text = "\(userMinuteBalance) min"
        }
    }


text:
Q: Scrape href/URL My code goes into a webpage which contains multiple entries, gets their URL and then puts them into a list.
Then it navigates through each list of URL 1 by 1, and then does a scape per presentation.
Right now I scrape each title of each presentation (you can see if you run the code), but within the title, there is another URL/href that I would want.
Is there a way to scrape this?
Thanks
from selenium import webdriver
import pandas as pd
from bs4 import BeautifulSoup
import requests
import time
val=[]
driver = webdriver.Chrome()
for x in range (1,3):
    driver.get(f'https://www.abstractsonline.com/pp8/#!/9325/sessions/@sessiontype=Advances%20in%20Diagnostics%20and%20Therapeutics/{x}')
    time.sleep(9)
    page_source = driver.page_source
    eachrow = ["https://www.abstractsonline.com/pp8/#!/9325/session/" + x.get_attribute('data-id') for x in driver.find_elements_by_xpath('//*[@id="results"]/li//h1[@class="name"]')]
    for row in eachrow:
        val.append(row)
        print(row)

for b in val:
    driver.get(b)
    time.sleep(3)
    page_source1=driver.page_source
    soup=BeautifulSoup(page_source1,'html.parser')
    productlist=soup.find_all('a',class_='title color-primary')
    for item in productlist:
        presentationTitle=item.text.strip()
        print(presentationTitle)

A: I think you want some wait conditions in there and then to extract the href attribute for each presentation within a page
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
base = 'https://www.abstractsonline.com/pp8/#!/9325/session/'

for x in range (1, 3):
    driver.get(f'https://www.abstractsonline.com/pp8/#!/9325/sessions/@sessiontype=Advances%20in%20Diagnostics%20and%20Therapeutics/{x}')
    links = [base + i.get_attribute('data-id') for i in WebDriverWait(driver,10).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "li .name")))]

    for link in links:
        driver.get(link)
        print(WebDriverWait(driver,10).until(EC.presence_of_element_located((By.ID, "spnSessionTitle"))).text)
        for presentation in driver.find_elements_by_css_selector('.title'):
            print(presentation.text.strip())
            print('https://www.abstractsonline.com/pp8' + presentation.get_attribute('href'))

A: links = driver.find_elements_by_partial_link_text('https://yourlinks.com/?action=')

for link in links:
    print(link.get_attribute("href"))


text:
Q: What is the use DOM in Salesforce where we can use that? I have understood the abbrevation of DOM,but i am not understanding what is use of that in salesforce. Is there any link between xml and DOM.

A: The DOM (DOM (Document Object Model) is just a model of the document. It could be a HTML/XHTML documents or XML document. The DOM only describes a structure of objects and it representation and accessibility.

*

*Document Object Model

*HTML DOM

*XML DOM

*Javascript DOM
In relation to Salesforce you have some ways where you can "use" DOM in Apex programming language and on the Visualforce pages.
In Apex the use of DOM is useful while creating or reading XML-documents. For that Apex language offers some classes:

*

*What is Apex?

*Document Class - to process XML content

*XmlNode Class - to work with a node in an XML document

Good XML and Apex examples could be found here: Reading and Writing XML Using the DOM
Other use case of the DOM in Salesforce is a Visualforce Page. It is like any other HTML page but processed all dynamic content on the server. When the page is loaded (rendered) completely - you can access page elements guided by DOM. For example manipulate the visibility, look & appearance with Javascript and CSS. For that you must have a strong understanding and knowledge of HTML, Javascript and CSS.
Some helpful topics:

*

*An Introduction to Visualforce

*Best Practices for Accessing Visualforce Component IDs

*Using $Component to Reference Components from JavaScript


text:
Q: what steps to take to get better performance I have a data frame like this :
dictt = {'country_cd': ['SE', 'IL', 'PL'],'timezone':['Euro/Stockho','Asia/Jerusalem','Euro/Warsaw'] , 'datetime':['8/10/2017 19:15', '8/10/2017 2:15', '8/10/2016 10:15'],
         'x':[1, 73, 248], 'y':[0, 48, 144], 'z':[0, 5,30], 'm':[0,6,40], 'response':['ok', 'cacel', 'suspend'] }
print(pd.DataFrame(dictt))

And I want to do multi-class classification over this(I have nearly 450000 observations).
The accuracy I got so far is around 56% which is not good, so I am asking if you guys have any idea what can I do to improve the performance:
so far I have done this:
1.country_cd have 85 unique nominal data, so I used dummy version of them (categorical to numeric)

*time zone I split the data (continent/country) the continent is separated from the country. like the previous feature I again got the dummy of that feature

*datetime I split the year and month, and created two different feature(I could not see any important correlation between month and response).
4.The other 4 features that I named x y z m I dont know what they are stands for(imagine you can not get the business behind them). in these 4 features, the sample presented in the dictt above is (min, mean, max) of each feature(just for getting an idea of how the distribution of the numbers is). for the numerical features, I applied standardization in sklearn.

*null value is available in the `country_sd only 100 rows which I filled them with Mod.

and I did labelencoding in the response feature having 4 different values(0,1,2,3).
I tried different approaches: MLP, LogisticRegression, Knearestneighbor ... but all the accuracy is around 55%.
I was wondering if someone has any idea I can apply and improve the model. (overal with all pd.dummied I did over the categorical features I came up with 220 features).

A: It seems that your data have panel form. There are two dimensions: Country and Time.
It has been my experience when running machine learning methods (like neural networks, random forests, boosted trees or SVM) on data with the time dimension that it helps to compress time into many summary features. Almost always. For example, you could calculate running minima, maxima, mean, volatility, strength of trend, strength of reversion and whatever else makes sense from the domain point of view. As much as I like random forests and such, they are not capable of figuring out such high-dimensional (spread in time) transformations on their own. Domain knowledge helps, typically.
You have much data. Sure, logistic regression can be tried. But I would not be surprised if a more complex and flexible machine learning method would work better in this situation. To avoid overfitting you can always employ something like cross-validaton and/or early stopping.
Hope I have partially answered your question. If I have misunderstood your problem, please let me know.


text:
Q: Cascade classifier can't be trained. Check the used training parameters I need to detect special image (something like symbol +) in scanned document. I'm going to train cascade using opencv_traincascade program (opencv 3.0)
This is my file structure:
C:\imgs\learn1
    Bad
       1.bmp
       ....
    Good
       1.bmp
       ....
    Bad.dat
    Good.dat

This my Bad.dat:
 Bad\1.bmp
 ...
 Bad\53.bmp
 Bad\img001.jpg
 ...
 Bad\img146.jpg

This is my Good.dat (every good file fully contains the special image and nothing more)
Good\1.bmp 1 0 0 60 59
...
Good\100.bmp 1 0 0 27 28

I've successfuly created vec file.
C:\opencv\build\x64\vc12\bin>opencv_createsamples.exe
-info C:\imgs\learn1\Good.dat
-vec samples.vec
-w 10 -h 10

Info file name: C:\imgs\learn1\Good.dat
Img file name: (NULL)
Vec file name: samples.vec
BG  file name: (NULL)
Num: 1000
BG color: 0
BG threshold: 80
Invert: FALSE
Max intensity deviation: 40
Max x angle: 1.1
Max y angle: 1.1
Max z angle: 0.5
Show samples: FALSE
Width: 10
Height: 10
Create training samples from images collection...
C:\imgs\learn1\Good.dat(101) : parse errorDone. Created 100 samples

This is call and result of opencv_traincascade
 C:\opencv\build\x64\vc12\bin>
-opencv_traincascade.exe
-data haarcascade
-vec C:\opencv\build\x64\vc12\bin\samples.vec
-bg C:\imgs\learn1\Bad.dat
-numStages 16
-minhiteate 0.99
-maxFalseAlarmRate 0.5
-numPos 80
-numNeg 199
-w 10
-h 10
-mode ALL
-precalcValBufSize 1024
-precalcIdxBufSize 1024

PARAMETERS:
cascadeDirName: haarcascade
vecFileName: C:\opencv\build\x64\vc12\bin\samples.vec
bgFileName: C:\imgs\learn1\Bad.dat
numPos: 80
numNeg: 199
numStages: 16
precalcValBufSize[Mb] : 1024
precalcIdxBufSize[Mb] : 1024
acceptanceRatioBreakValue : -1
stageType: BOOST
featureType: HAAR
sampleWidth: 10
sampleHeight: 10
boostType: GAB
minHitRate: 0.995
maxFalseAlarmRate: 0.5
weightTrimRate: 0.95
maxDepth: 1
maxWeakCount: 100
mode: ALL

===== TRAINING 0-stage =====
<BEGIN
POS count : consumed   80 : 80
Train dataset for temp stage can not be filled. Branch training terminated.
Cascade classifier can't be trained. Check the used training parameters.

As you can see, there is some error. Can you help me what is wrong exactly? "Check the used training parameters" is very general phrase.
(The folder C:\opencv\build\x64\vc12\bin\haarcascade exists)

A: I don't know what was wrong, but I've done it.
1)I've increased number of positive examples to 400
2)I've increased number of negative examples to 398
3)I found that if an image size 61 x 60, I shoud write in Good.dat
Good\1.bmp 1 0 0 60 59

(Image coordinates begin from 0 and end at width-1 and height-1 values)
4)I found  type error: minhiteate - > minHitRate
and nothing helps...
5)I try to train in openvc 2.4 and i've got my cascade.xml file
But now I can't use it because of other error, but it's offtopic. (now I,m googling)


text:
Q: jQuery group elements by name with count I have a large list of names from a database that I want to filter and give a count for a specific name value - in this case 'Anonymous'.
For example:

Johnny Ace

Mary Adams

Bob Allen

Anonymous

Anonymous

Anonymous

Anonymous

Anonymous

David Brown

Sue Smith

John Williams

I want the result to be:

Johnny Ace

Mary Adams

Bob Allen

Anonymous (5)

David Brown

Sue Smith

John Williams

What's the best way to do this?

A: Something like this using :contains() to get the length and remove all but the first one, and then set the text
var count=$('ul li:contains("Anonymous")').length;
$('ul li:contains("Anonymous")').not(':first').remove().end().text("Anonymous("+count+")");

DEMO

A: Loops might be easy as well, works for all elements:
http://jsfiddle.net/N6wSf/16/
var categories = {},
    category;
$('ul li').each(function(i, el){
    category = $(el).text();
    if (categories.hasOwnProperty(category)) {
        categories[category] += 1;
    } else {
        categories[category] = 1;
    }
});

$('ul').empty();
// print results
for(var key in categories){
    $('ul').append('
' + key + ' (' + categories[key] + ')
');
}


text:
Q: Question on definition derivation for concave functions I was looking into how the following definition was arrived at of concave functions (and related convex functions). I found the following derivation/justification and had an issue with one of the steps. I think it is ok, but wanted someone to weigh in on the issue. Thanks in advance!
Concave function definition:
$$
f((1−λ)a + λb)  ≥  (1 − λ)f(a) + λf(b)
$$
The author goes on to state the following:
Denote the height of the line segment from (a, f(a)) to (b, f(b)) at the point x by $h_{ab}(x)$. Then according to the definition, the function f is concave if and only if for every pair of numbers a and b with $x_1$ ≤ a ≤ $x_2$ and $x_1$ ≤ b ≤ $x_2$ we have:
$$
f(x) \ge h_{a,b}(x) \; for \; all \; x \; with \; a ≤ x ≤ b
$$
Now, every point x with a ≤ x ≤ b may be written as x = (1 − λ)a + λb, where λ is a real number from 0 to 1.

The fact that $h_{a,b}$ is linear means that
  $h_{a,b}$((1 − λ)a + λb) =     (1 − λ)$h_{a,b}$(a) + λ$h_{a,b}$(b)

Further, we have $h_{a,b}(a)$ = f(a) and $h_{a,b}$(b) = f(b) (the line segment coincides with the function at its endpoints), so
$h_{a,b}$((1 − λ)a + λb)    =  (1 − λ)$f(a)$ + λ$f(b)$.
On the part in yellow, where the author uses the fact that $h_{a,b}$ is linear. I agree the function is linear in the fact that the highest degree of the function would be 1 (since it is a line), but stating it as a linear transformation and using properties of a linear transformation isn't as clear. I believe it is a linear transformation if either the line intercepts the y-axis at 0 OR we shift the coordinate system to force the line to intercept the y-axis at 0. Is this a correct explanation?
If the y-intercept was 8, we could re-write all of our coordinates using the equation (0,8) -> (0,0). So we subtract 8 to all coordinates in our space to shift the origin to ensure our line has no y-intercept and is thus a linear transformation.
Thanks!

A: The definition of a concave function requires an inequality to hold for all applicable $x$, $a$, and $b$. While you could define a shifted version of $f$ such that some particular $h_{a,b}$ passes through the origin, you can't make every $h_{a,b}$ pass through the origin simultaneously. So that's probably not worth doing.
The good news is, you don't need to!
Although $h_{a,b}$ is not a linear transformation, it is an affine transformation. Affine transformations are characterized by preserving affine combinations, which are linear combinations whose weights sum to $1$. In particular, $(1 − \lambda)a + \lambda b$ is an affine combination of $a$ and $b$. So the fact that $h_{a,b}$ is an affine transformation really does justify that $h_{a,b}((1 − \lambda)a + \lambda b) = (1 − \lambda)h_{a,b}(a) + \lambda h_{a,b}(b)$. No shifting or playing with coordinates is necessary to make this work.


text:
Q: awatch does not stop on specified address I understand that the awatch command in GDB breaks when expresssion is read/written. However, why is it that when I set awatch command to an address of my structure pointer, it only stopped once. Below is a screenshot of my GDB and a code snippet. Please advice. Thank you.

Testing.c
College_Record *college = NULL;
college = malloc(sizeof(College_Record));
printf("college %p\n", college);
free(college);
printf("college %p\n", college);
college = NULL;
printf("college %p\n", college);

printf("***************************\n");
printf("\tDONE OKAY\n");
printf("***************************\n");

return 0;

Testing.h
  typedef struct {
    int college_id;
    char school[20];
} College_Record;

A: Here's a sample program:
struct college {
    int x;
    int y;
};

struct college college_glob;

struct college *college;

void
setwatch(void)
{

    college = &college_glob;
}

void
brkgdb(void)
{
}

int
main(void)
{

    setwatch();
    brkgdb();

    return college_glob.x;
}

Here's the gdb session:
> gdb /tmp/watch
GNU gdb (GDB) Fedora 7.9.1-19.fc22
Copyright (C) 2015 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-redhat-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from /tmp/watch...done.
(gdb) b brkgdb
Breakpoint 1 at 0x40050c: file /tmp/watch.c, line 20.
(gdb) run
Starting program: /tmp/watch

Breakpoint 1, brkgdb () at /tmp/watch.c:20
20  }
(gdb) awatch *college
Hardware access (read/write) watchpoint 2: *college
(gdb) c
Continuing.
Hardware access (read/write) watchpoint 2: *college

Value = {x = 0, y = 0}
Hardware access (read/write) watchpoint 2: *college

Value = {x = 0, y = 0}
main () at /tmp/watch.c:30
30  }
(gdb) list
25
26      setwatch();
27      brkgdb();
28
29      return college_glob.x;
30  }
(gdb) q
A debugging session is active.

    Inferior 1 [process 15761] will be killed.

Quit anyway? (y or n) y


text:
Q: How to get 2 sidebars onto one page? For my website, I want to use 2 navigation bars; a horizontal one at the very top, and the other one under the first, a vertical one this time, and on the left of my text content so that the text wraps around it. How would I achieve this?
When I copy and paste CSS codes from websites such as w3schools.com, both codes will stuff up. Right now, it's either one navigation bar or two very strange-looking ones.
The second sidebar should look similar to the hyperlinked one on Wikipedia.
Here's the code. Sorry if it's too long.

ul {
width: 100%;
position: fixed;
border: none;
font-size: 20;
font-family: "candara",cambria, sans-serif;
list-style-type: none;
margin-top: -10px;
margin-left: -8px;
margin-right: -8px;
padding: 1px;
overflow: hidden;
background-color: #333;
}

li {
text-align: centre;
border-bottom: none;
}

li:last-child {
border-bottom: none;
}

li {
float: left;
}

li a, .dropbtn {
display: inline-block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}

li a:hover, .dropdown:hover .dropbtn {
color: black;
background-color: #F5F5F5;
}

li.dropdown {
display: inline-block;
}

.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}

.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
text-align: left;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {
display: block;
}

.active {
background-color: #4682B4;
}

li a:hover:not(.active) {
background-color: #555;
color: white;
}

div.one {
background-color:white;
border-style: solid;
border-color:#F5F5F5;
border-width: 1px;
margin-left: 20px;
margin-right: 20px;
padding-left: 30px;
padding-right: 30px
}

<title>Introduction to Goldfish</title>
<link rel="icon" href="Images/Goldfish.ico" type="image/x-icon"/>
<link rel="shortcut icon" href="Goldfish.ico" type="image/x-icon"/>

Home

Enter

  Link 1
  Link 2
  Link 3

Dropdown

  Link 1
  Link 2
  Link 3

<img src="Assignment/Aquarium.jpg"

Your First         Goldfish

Congratulations on your first goldfish! Oh dear, I sound like a     grandmother congratulating her daughter on her first child, don't I? Anyway,     keeping goldfish as pets is a rewarding, calming and educational experience of     people of all ages.

Millions of fish are bought each year and it's easy to see why.

Goldfish are delightful creatures to watch, bumping against each other to chase after another morsel of food, following you as you walk around, and zooming around the tank.
Additionally, there are so many varieties to choose from, all in different shapes, sizes and colours.

Hopefully that got your attention. Now, let me tell you more about these delightful goldies you've bought. Let's just say that it requires more work than just dropping a few flakes into their small glass bowl and changing their tank water once every few months.

</style>

A: i think you need add

 in your dropdown:
In your html :

Link 1

Link 2

Link 3

Execute in code snippet:

ul {
width: 100%;
position: fixed;
border: none;
font-size: 20;
font-family: "candara",cambria, sans-serif;
list-style-type: none;
margin-top: -10px;
margin-left: -8px;
margin-right: -8px;
padding: 1px;
overflow: hidden;
background-color: #333;
}

li {
text-align: centre;
border-bottom: none;
}

li:last-child {
border-bottom: none;
}

li {
float: left;
}

li a, .dropbtn {
display: inline-block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}

li a:hover, .dropdown:hover .dropbtn {
color: black;
background-color: #F5F5F5;
}

li.dropdown {
display: inline-block;
}

.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}

.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
text-align: left;
}

.dropdown-content a:hover {background-color: #f1f1f1}

.dropdown:hover .dropdown-content {
display: block;
}

.active {
background-color: #4682B4;
}

li a:hover:not(.active) {
background-color: #555;
color: white;
}

div.one {
background-color:white;
border-style: solid;
border-color:#F5F5F5;
border-width: 1px;
margin-left: 20px;
margin-right: 20px;
padding-left: 30px;
padding-right: 30px
}

Home

   Enter

Link 1

Link 2

Link 3

   Dropdown

Link 1

 Link 2

Link 3

Your First         Goldfish

Congratulations on your first goldfish! Oh dear, I sound like a     grandmother congratulating her daughter on her first child, don't I? Anyway,     keeping goldfish as pets is a rewarding, calming and educational experience of     people of all ages.

Millions of fish are bought each year and it's easy to see why.

Goldfish are delightful creatures to watch, bumping against each other to chase after another morsel of food, following you as you walk around, and zooming around the tank.
Additionally, there are so many varieties to choose from, all in different shapes, sizes and colours.

Hopefully that got your attention. Now, let me tell you more about these delightful goldies you've bought. Let's just say that it requires more work than just dropping a few flakes into their small glass bowl and changing their tank water once every few months.

hopefully this as you wish


text:
Q: Dynamically render and remove HTML knockoutjs So I'm having an odd issue. I am iterating with a ko foreach:,  I have 2 "if" statements.
ifnot: row.disabled
 //this html
if: row.disabled
 //that html

all rows start disabled on page load. my page is formatted something like this
**Enabled**

//empty

**Disabled**

thing1

thing 2

thing 3

this is fine. It works as expected... Except for one little thing. the ifNot has a div that I need for another plugin. This is causing an unexpected side-effect. "Html to display when row is enabled" is still there, just missing some child elements.

    html to display when row is enabled

The side-effect is that when I getElementById, then querySelectorAll(html to display...) it's getting all rows, when, for this use case, the rows can't be there if they are disabled.
I need to dynamically render, or remove this html from my page when the state of the row changes. I'm trying something like this, and I've seen the template: binding, but I can't figure out how to use it.
Please, if you can laymans the template binding for a novice, or figure out how to bind what I have, or modify what I have below to add and remove html from the dom dynamically, that'd be wonderful.
P.S.No jQuery
self.template = ko.observable();

    self.toggleTemplate = function (row) {
        var template = ko.observable();
        if (!row.disabled) {
            self.template(enabledRowTemplate);
        }
        else {
            self.template(null);
        }
    };

A: Simple example of the template binding, hope this helps

and in JS
self.template = ko.computedObservable(function(){
   return self.enabled ? 'enabledRowTemplate' : 'disabledRowTemplate' // or {name: templateName, data: templateData} instead of template name string
});