问:
Image Rows in Constraint Layout
Using constraints in a ConstraintLayout, I have created a layout as following:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardCornerRadius="2dp"
    app:cardElevation="4dp"
    app:cardUseCompatPadding="true">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="4dp"
        >

        <ImageView
            android:id="@+id/post_photo"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="4dp"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            android:adjustViewBounds="true"
            android:scaleType="fitCenter"
            app:srcCompat="@drawable/ic_photo"
            />

        <ImageButton
            android:id="@+id/create_button"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="4dp"
            app:layout_constraintTop_toBottomOf="@+id/post_photo"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toLeftOf="@+id/share_button"
            app:srcCompat="@drawable/ic_action_share"
            android:scaleType="fitCenter"
            />

        <ImageButton
            android:id="@+id/share_button"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="4dp"
            app:layout_constraintTop_toBottomOf="@+id/post_photo"
            app:layout_constraintLeft_toRightOf="@+id/create_button"
            app:layout_constraintRight_toRightOf="parent"
            app:srcCompat="@drawable/ic_action_share"
            android:scaleType="fitCenter"
            />

    </android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>
</code>```

My problem is that lower ImageButtons are not shown whenever height of image in ImageView is more than its width. If we hardcode a height (some kind of sufficient) on ConstraintLayout then buttons can get some height depending on the height of ImageView. I believe that the problem is when View Bounds are adjusted for ImageView. How can I overcome this situation?

答:
If you want to prevent this situation, you need to define percent or (dp) value.

1 - You can use maxWidth / maxHeight on ConstraintLayout like

```<code> <ImageView
        ...
        android:maxHeight="192dp"
        />
</code>```

2 - Also you can use Guideline like

```<code><Guideline
       id="guideLineMaxHeightOfImage"
       guideLinePercent="0.4"
       orientation="horizontal"
       >
</code>```

ImageView

```<code><ImageView
        ...
        app:layout_constraintTop_toTopOf="@+id/guideLineMaxHeightOfImage"
        />
</code>```

Title: Image Rows in Constraint Layout

Body:
Using constraints in a ConstraintLayout, I have created a layout as following:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardCornerRadius="2dp"
    app:cardElevation="4dp"
    app:cardUseCompatPadding="true">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="4dp"
        >

        <ImageView
            android:id="@+id/post_photo"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="4dp"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            android:adjustViewBounds="true"
            android:scaleType="fitCenter"
            app:srcCompat="@drawable/ic_photo"
            />

        <ImageButton
            android:id="@+id/create_button"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="4dp"
            app:layout_constraintTop_toBottomOf="@+id/post_photo"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toLeftOf="@+id/share_button"
            app:srcCompat="@drawable/ic_action_share"
            android:scaleType="fitCenter"
            />

        <ImageButton
            android:id="@+id/share_button"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="4dp"
            app:layout_constraintTop_toBottomOf="@+id/post_photo"
            app:layout_constraintLeft_toRightOf="@+id/create_button"
            app:layout_constraintRight_toRightOf="parent"
            app:srcCompat="@drawable/ic_action_share"
            android:scaleType="fitCenter"
            />

    </android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>

My problem is that lower ImageButtons are not shown whenever height of image in ImageView is more than its width. If we hardcode a height (some kind of sufficient) on ConstraintLayout then buttons can get some height depending on the height of ImageView. I believe that the problem is when View Bounds are adjusted for ImageView. How can I overcome this situation?

Body:
If you want to prevent this situation, you need to define percent or (dp) value.

1 - You can use maxWidth / maxHeight on ConstraintLayout like

 <ImageView
        ...
        android:maxHeight="192dp"
        />

2 - Also you can use Guideline like

<Guideline
       id="guideLineMaxHeightOfImage"
       guideLinePercent="0.4"
       orientation="horizontal"
       >

ImageView

<ImageView
        ...
        app:layout_constraintTop_toTopOf="@+id/guideLineMaxHeightOfImage"
        />


来源: stackexchange

问:
What is wrong in this mysql function ?
when i run this function

```<code>CREATE PROCEDURE alege()
    BEGIN
        declare v_prenumeNou VARCHAR(15);
        declare v_numeRandom INTEGER(10);
        declare v_prenumeRandom INTEGER(10);
        declare v_idCutremurRandom INTEGER(10);

        set v_numeRandom = 1 + CEIL ( RAND() * 50 );
        set v_prenumeRandom = 1 + CEIL ( RAND() * 50 );
        set v_idCutremurRandom = 1 + CEIL ( RAND() * 50 );

        select prenume into v_prenumeNou from (SELECT prenume, rownum as v_rn from voluntari) where v_rn=v_prenumeRandom;
        select nume into v_numeNou from (SELECT nume, rownum as v_rn from voluntari) where v_rn=v_numeRandom;

        v_idPersoanaNou := v_idPersoanaNou + 1;

        INSERT INTO voluntari (IDCUTREMUR, IDPERSOANA, NUME, PRENUME)
        VALUES (CONCAT('C',IFNULL(v_idCutremurRandom, '')), CONCAT('V',IFNULL(v_idPersoanaNou, '')) , v_numeNou, v_prenumeNou);
END;
</code>```

i have this error

[Err] 1248 - Every derived table must have its own alias

how can i solve this ?

答:
You must add an alias to each subquery in your select into statements:

```<code>select prenume
into v_prenumeNou
from (SELECT prenume, rownum as v_rn
      from voluntari) t1  <-----------
where v_rn=v_prenumeRandom;

select nume
into v_numeNou
from (SELECT nume, rownum as v_rn
      from voluntari) t1 <------------
where v_rn=v_numeRandom;
</code>```

ContentLicense: CC BY-SA 3.0

Title: What is wrong in this mysql function ?

Body:
when i run this function

CREATE PROCEDURE alege()
    BEGIN
        declare v_prenumeNou VARCHAR(15);
        declare v_numeRandom INTEGER(10);
        declare v_prenumeRandom INTEGER(10);
        declare v_idCutremurRandom INTEGER(10);

        set v_numeRandom = 1 + CEIL ( RAND() * 50 );
        set v_prenumeRandom = 1 + CEIL ( RAND() * 50 );
        set v_idCutremurRandom = 1 + CEIL ( RAND() * 50 );

        select prenume into v_prenumeNou from (SELECT prenume, rownum as v_rn from voluntari) where v_rn=v_prenumeRandom;
        select nume into v_numeNou from (SELECT nume, rownum as v_rn from voluntari) where v_rn=v_numeRandom;

        v_idPersoanaNou := v_idPersoanaNou + 1;

        INSERT INTO voluntari (IDCUTREMUR, IDPERSOANA, NUME, PRENUME)
        VALUES (CONCAT('C',IFNULL(v_idCutremurRandom, '')), CONCAT('V',IFNULL(v_idPersoanaNou, '')) , v_numeNou, v_prenumeNou);
END;

i have this error

[Err] 1248 - Every derived table must have its own alias

how can i solve this ?

Body:
You must add an alias to each subquery in your select into statements:

select prenume
into v_prenumeNou
from (SELECT prenume, rownum as v_rn
      from voluntari) t1  <-----------
where v_rn=v_prenumeRandom;

select nume
into v_numeNou
from (SELECT nume, rownum as v_rn
      from voluntari) t1 <------------
where v_rn=v_numeRandom;


问:
How do I center the div vertically?

Possible Duplicate:

  What's The Best Way of Centering a Div Vertically with CSS

```<code>.title_text_only{
position:absolute;
width:100%;
display:none;
z-index:9;
top:50%;
bottom:50%;
text-align:center;
color:#fff;
font-size:18px;
text-shadow: 1px 1px 1px #666;
}
</code>```

Right now, it doesn't seem to work. top 50% doesn't center it vertically. It's a little to the bottom.  It's as if the top border is 50%.

答: How to vertically center a div for all browsers?</p>

ContentLicense: CC BY-SA 2.5

Title: How do I center the div vertically?

Body:
Possible Duplicate:

  What's The Best Way of Centering a Div Vertically with CSS

.title_text_only{
position:absolute;
width:100%;
display:none;
z-index:9;
top:50%;
bottom:50%;
text-align:center;
color:#fff;
font-size:18px;
text-shadow: 1px 1px 1px #666;
}

Right now, it doesn't seem to work. top 50% doesn't center it vertically. It's a little to the bottom.  It's as if the top border is 50%.


问:
How do I get the URL of the active Google Chrome tab in Windows?
How can my Python script get the URL of the currently active Google Chrome tab in Windows? This has to be done without interrupting the user, so sending key strokes to copy/paste is not an option.</p>

答:
Christian's answer did not work for me as internal structure of Chrome changed entirely and you can't really access elements of Chrome window using win32gui anymore.

The only possible way I managed to find was through UI Automation API, which has this python wrapper with some examples of usage

Run this and switch to Chrome window you want to grab address from:

```<code>from time import sleep
import uiautomation as automation

if __name__ == '__main__':
    sleep(3)
    control = automation.GetFocusedControl()
    controlList = []
    while control:
        controlList.insert(0, control)
        control = control.GetParentControl()
    if len(controlList) == 1:
        control = controlList[0]
    else:
        control = controlList[1]
    address_control = automation.FindControl(control, lambda c, d: isinstance(c, automation.EditControl) and "Address and search bar" in c.Name)
    print address_control.CurrentValue()
</code>```

Body:
Christian's answer did not work for me as internal structure of Chrome changed entirely and you can't really access elements of Chrome window using win32gui anymore.

The only possible way I managed to find was through UI Automation API, which has this python wrapper with some examples of usage

Run this and switch to Chrome window you want to grab address from:

from time import sleep
import uiautomation as automation

if __name__ == '__main__':
    sleep(3)
    control = automation.GetFocusedControl()
    controlList = []
    while control:
        controlList.insert(0, control)
        control = control.GetParentControl()
    if len(controlList) == 1:
        control = controlList[0]
    else:
        control = controlList[1]
    address_control = automation.FindControl(control, lambda c, d: isinstance(c, automation.EditControl) and "Address and search bar" in c.Name)
    print address_control.CurrentValue()


问:
Symfony Twig, undefined index for persistent collection
```<code>{{ dump(memory.memoryImages) }}
</code>```

gives me:

But

```<code>{{ dump(memory.memoryImages.getValues) }}
</code>```

or

```<code>{{ dump(memory.memoryImages.first) }}
</code>```

or

```<code>{% for memoryImage in memory.memoryImages %}
     ...
{% endfor %}
</code>```

all give me:

An exception has been thrown during the rendering of a template
  ("Notice: Undefined index: Memory").

How can I get the memoryImage from memoryImages? Did I might got wrongly configured doctrine mappings?

Entity Memory has a oneToMany relation:

```<code>oneToMany:
    memoryImages:
        targetEntity: MemoryImage
        mappedBy: Memory
        cascade: ["persist", "remove"]
</code>```

and MemoryImages Entity has a ManyToOne relation:

```<code>manyToOne:
    memory:
        targetEntity: Memory
        inversedBy: memorieImages
        joinColumn:
            name: memory_id
            referencedColumnName: id
</code>```

答:
Are you sure you are not calling Memory instead of your memory (maybe even somewhere higher up) cause the error message should reflect that with its proper case (note the capital letter).

As for accessing values a loop etc like you are showing should just be fine so another reason why I doubt its these little things, but in fact the most tiniest of things.

Body:
{{ dump(memory.memoryImages) }}

gives me:

But

{{ dump(memory.memoryImages.getValues) }}

or

{{ dump(memory.memoryImages.first) }}

or

{% for memoryImage in memory.memoryImages %}
     ...
{% endfor %}

all give me:

An exception has been thrown during the rendering of a template
  ("Notice: Undefined index: Memory").

How can I get the memoryImage from memoryImages? Did I might got wrongly configured doctrine mappings?

Entity Memory has a oneToMany relation:

oneToMany:
    memoryImages:
        targetEntity: MemoryImage
        mappedBy: Memory
        cascade: ["persist", "remove"]

and MemoryImages Entity has a ManyToOne relation:

manyToOne:
    memory:
        targetEntity: Memory
        inversedBy: memorieImages
        joinColumn:
            name: memory_id
            referencedColumnName: id


问:
AWGN channel outputs real numbers instead of complex
I get this error when I run my code in Matlab. But I can run example "Transmit a shortened RS-encoded, 256-QAM-modulated symbol stream through an AWGN channel" at link https://www.mathworks.com/help/comm/ref/comm.rsencoder-class.html with no problem.

When I check values in variable chnData in my code, I see real numbers. When I check values in variable chan in the example code, I see complex numbers. What's wrong with my code?

PS: I am working on R2012b and Communication Toolbox version is 5.3.

Error message:

```<code>Error using comm.RectangularQAMDemodulator/step
Complexity mismatch with input 1; expected complex, got real.
Error in project (line 41)
            demData = step(qamDemodulator, chnData);
</code>```

My code:

```<code>close all;
clear all;
clc;
enableRS = 1;
M = 16; % M-QAM
N = 15; % Reed-Solomon Coding : codelength
K = 11; % Reed-Solomon Coding : wordlength
EbNo = [-5:5]; % AWGN Channel : bit-to-noise energy
bps = log2(M); % AWGN Channel : bits per symbol
rsEncoder = comm.RSEncoder('CodewordLength', N, ...
                           'MessageLength',  K);
rsDecoder = comm.RSDecoder('CodewordLength', N, ...
                           'MessageLength',  K);
qamModulator = comm.RectangularQAMModulator('ModulationOrder', M, ...
                                            'NormalizationMethod', 'Average power');
qamDemodulator = comm.RectangularQAMDemodulator('ModulationOrder', M, ...
                                                'NormalizationMethod', 'Average power');
awgnChannel = comm.AWGNChannel('EbNo', EbNo, ...
                               'BitsPerSymbol', bps);
errorRate = comm.ErrorRate;
[H W] = size(EbNo);
errors = zeros(1,W);
for e = 1:W
    error = zeros(1,3);
    awgnChannel.EbNo = EbNo(e);
    if enableRS == 1
        while error(2) < 100 && error(3) < 1e7
             txData = randi([0 1], K, bps);
            encData = step(rsEncoder, bi2de(txData));
            modData = step(qamModulator, encData);
            chnData = step(awgnChannel, encData);
            demData = step(qamDemodulator, chnData);
            decData = step(rsDecoder, de2bi(demData));
             rxData = decData;
               error = step(errorRate, bi2de(txData), bi2de(rxData));
        end
    end
    errors(e) = error(1);
end
if enableRS == 1
    semilogy(EbNo, errors);
    grid;
    xlabel('Eb/No (db)');
    ylabel('Bit Error Rate');
    hold;
    uncoded = berawgn(EbNo, 'qam', M);
    semilogy(EbNo, uncoded);
end
</code>```

答:
Found the mistake! It is fixed now.</p>

```<code>modData = step(qamModulator, encData);
chnData = step(awgnChannel, encData); // Should have been modData
</code>```

Body:
I get this error when I run my code in Matlab. But I can run example "Transmit a shortened RS-encoded, 256-QAM-modulated symbol stream through an AWGN channel" at link https://www.mathworks.com/help/comm/ref/comm.rsencoder-class.html with no problem.

When I check values in variable chnData in my code, I see real numbers. When I check values in variable chan in the example code, I see complex numbers. What's wrong with my code?

PS: I am working on R2012b and Communication Toolbox version is 5.3.

Error message:

Error using comm.RectangularQAMDemodulator/step
Complexity mismatch with input 1; expected complex, got real.
Error in project (line 41)
            demData = step(qamDemodulator, chnData);

My code:

close all;
clear all;
clc;
enableRS = 1;
M = 16; % M-QAM
N = 15; % Reed-Solomon Coding : codelength
K = 11; % Reed-Solomon Coding : wordlength
EbNo = [-5:5]; % AWGN Channel : bit-to-noise energy
bps = log2(M); % AWGN Channel : bits per symbol
rsEncoder = comm.RSEncoder('CodewordLength', N, ...
                           'MessageLength',  K);
rsDecoder = comm.RSDecoder('CodewordLength', N, ...
                           'MessageLength',  K);
qamModulator = comm.RectangularQAMModulator('ModulationOrder', M, ...
                                            'NormalizationMethod', 'Average power');
qamDemodulator = comm.RectangularQAMDemodulator('ModulationOrder', M, ...
                                                'NormalizationMethod', 'Average power');
awgnChannel = comm.AWGNChannel('EbNo', EbNo, ...
                               'BitsPerSymbol', bps);
errorRate = comm.ErrorRate;
[H W] = size(EbNo);
errors = zeros(1,W);
for e = 1:W
    error = zeros(1,3);
    awgnChannel.EbNo = EbNo(e);
    if enableRS == 1
        while error(2) < 100 && error(3) < 1e7
             txData = randi([0 1], K, bps);
            encData = step(rsEncoder, bi2de(txData));
            modData = step(qamModulator, encData);
            chnData = step(awgnChannel, encData);
            demData = step(qamDemodulator, chnData);
            decData = step(rsDecoder, de2bi(demData));
             rxData = decData;
               error = step(errorRate, bi2de(txData), bi2de(rxData));
        end
    end
    errors(e) = error(1);
end
if enableRS == 1
    semilogy(EbNo, errors);
    grid;
    xlabel('Eb/No (db)');
    ylabel('Bit Error Rate');
    hold;
    uncoded = berawgn(EbNo, 'qam', M);
    semilogy(EbNo, uncoded);
end

Body:
Found the mistake! It is fixed now.

modData = step(qamModulator, encData);
chnData = step(awgnChannel, encData); // Should have been modData


问:
How do i select multiple rows which match the value of an item in an array?
I have written a php script that returns an arbitrary number of specific ids (which are in the format of numbers) in an array. I would like to make a new query that selects each row from a table that belongs to each id. I know i can do 1 query to get one row with the matching id. But i would like to do this all in one query. Here is my code:</p>

```<code>$id = array(1,4,7,3,11,120); // The array containing the ids

$query = mysql_query("SELECT *
                        FROM posts
                       WHERE id = '$id[0]'");
// I would like to Do this for each id in the array and return it as one group of rows.`
</code>```

答:
What you want is SQL's IN clause.

```<code>SELECT * FROM posts WHERE id IN (1, 4, 7, 11, 120)
</code>```

In PHP, you'll probably want something like:

```<code>$query = mysql_query(sprintf("SELECT * FROM posts WHERE id IN (%s)", implode(',', $id)));
</code>```

Obviously, that's assuming you know you have integer values for $id, and that the values for $id didn't come from the user (that is, they should be sanitized). To be safe, you really ought to do something like:

```<code>$ids = implode(',', array_map('mysql_real_escape_string', $id));
$query = mysql_query("SELECT * FROM posts WHERE id IN ($ids)");
</code>```

And if $id is dynamically generated, don't forget to put something in that IN clause, because SELECT * FROM foo WHERE bar IN () will give you an error. I generally make sure to set my IN-clause variables to 0, since IN (0) is good, and primary keys are pretty much never 0.

Body:
I have written a php script that returns an arbitrary number of specific ids (which are in the format of numbers) in an array. I would like to make a new query that selects each row from a table that belongs to each id. I know i can do 1 query to get one row with the matching id. But i would like to do this all in one query. Here is my code:

$id = array(1,4,7,3,11,120); // The array containing the ids

$query = mysql_query("SELECT *
                        FROM posts
                       WHERE id = '$id[0]'");
// I would like to Do this for each id in the array and return it as one group of rows.`

Body:
What you want is SQL's IN clause.

SELECT * FROM posts WHERE id IN (1, 4, 7, 11, 120)

In PHP, you'll probably want something like:

$query = mysql_query(sprintf("SELECT * FROM posts WHERE id IN (%s)", implode(',', $id)));

Obviously, that's assuming you know you have integer values for $id, and that the values for $id didn't come from the user (that is, they should be sanitized). To be safe, you really ought to do something like:

$ids = implode(',', array_map('mysql_real_escape_string', $id));
$query = mysql_query("SELECT * FROM posts WHERE id IN ($ids)");

And if $id is dynamically generated, don't forget to put something in that IN clause, because SELECT * FROM foo WHERE bar IN () will give you an error. I generally make sure to set my IN-clause variables to 0, since IN (0) is good, and primary keys are pretty much never 0.


问:
Host Key Verification Failed with sshpass rsync
On my linux server I run the command:

```<code>sshpass -p 'password' rsync -avz /source/folder/ root@192.168.x.x:/dest/folder
</code>```

When I run the command without sshpass it will provide me with prompts for authenticity of host and the password.

I need some equivalent to "-o StrictHostKeyChecking=no" (which I use for ssh) that will allow me to run this with no prompts or errors.

Everything I saw from googling was about ssh throwing the error not rsync.

答:
If you want to connect to new server, which public key is not yet in your ~/.ssh/knonwn_hosts, you should not skip this only security check, but rather store the server host key in the known_hosts manually, verify that it is correct and then make the automatic check working.

Simplest way to get the known hosts populated with the server host key is using

```<code>ssh-keyscan server-ip >> ~/.ssh/known_hosts
</code>```

After that, you should not need to use the StrictHostKeyChecking=no workaround.

Body:
On my linux server I run the command:

sshpass -p 'password' rsync -avz /source/folder/ root@192.168.x.x:/dest/folder

When I run the command without sshpass it will provide me with prompts for authenticity of host and the password.

I need some equivalent to "-o StrictHostKeyChecking=no" (which I use for ssh) that will allow me to run this with no prompts or errors.

Everything I saw from googling was about ssh throwing the error not rsync.

Body:
If you want to connect to new server, which public key is not yet in your ~/.ssh/knonwn_hosts, you should not skip this only security check, but rather store the server host key in the known_hosts manually, verify that it is correct and then make the automatic check working.

Simplest way to get the known hosts populated with the server host key is using

ssh-keyscan server-ip >> ~/.ssh/known_hosts

After that, you should not need to use the StrictHostKeyChecking=no workaround.


答:
Try with this, just changed the alias of the from clauses (every deribed table must have an alias):</p>

```<code>CREATE PROCEDURE alege()
    BEGIN
        declare v_prenumeNou VARCHAR(15);
        declare v_numeRandom INTEGER(10);
        declare v_prenumeRandom INTEGER(10);
        declare v_idCutremurRandom INTEGER(10);

        set v_numeRandom = 1 + CEIL ( RAND() * 50 );
        set v_prenumeRandom = 1 + CEIL ( RAND() * 50 );
        set v_idCutremurRandom = 1 + CEIL ( RAND() * 50 );

        select prenume into v_prenumeNou from (SELECT prenume, rownum as v_rn from voluntari) AS A where v_rn=v_prenumeRandom;
        select nume into v_numeNou from (SELECT nume, rownum as v_rn from voluntari) AS B where v_rn=v_numeRandom;

        v_idPersoanaNou := v_idPersoanaNou + 1;

        INSERT INTO voluntari (IDCUTREMUR, IDPERSOANA, NUME, PRENUME)
        VALUES (CONCAT('C',IFNULL(v_idCutremurRandom, '')), CONCAT('V',IFNULL(v_idPersoanaNou, '')) , v_numeNou, v_prenumeNou);
END;
</code>```

Title: What is wrong in this mysql function ?

Body:
Try with this, just changed the alias of the from clauses (every deribed table must have an alias):

CREATE PROCEDURE alege()
    BEGIN
        declare v_prenumeNou VARCHAR(15);
        declare v_numeRandom INTEGER(10);
        declare v_prenumeRandom INTEGER(10);
        declare v_idCutremurRandom INTEGER(10);

        set v_numeRandom = 1 + CEIL ( RAND() * 50 );
        set v_prenumeRandom = 1 + CEIL ( RAND() * 50 );
        set v_idCutremurRandom = 1 + CEIL ( RAND() * 50 );

        select prenume into v_prenumeNou from (SELECT prenume, rownum as v_rn from voluntari) AS A where v_rn=v_prenumeRandom;
        select nume into v_numeNou from (SELECT nume, rownum as v_rn from voluntari) AS B where v_rn=v_numeRandom;

        v_idPersoanaNou := v_idPersoanaNou + 1;

        INSERT INTO voluntari (IDCUTREMUR, IDPERSOANA, NUME, PRENUME)
        VALUES (CONCAT('C',IFNULL(v_idCutremurRandom, '')), CONCAT('V',IFNULL(v_idPersoanaNou, '')) , v_numeNou, v_prenumeNou);
END;


问:
Javascript display name of div
I have a container with divs inside, using Javascript I am trying to open an alert box for each item found displaying the 'name' of the div...

items = document.getElementsByClassName("single_item");

for (i = 0; i < items.length; i++) {
    alert("This is an item - the name is...")
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
    <div name="item1" class="single_item">
        Item 1
    </div>
    <div name="item2" class="single_item">
        Item 2
    </div>
    <div name="item3" class="single_item">
        Item 3
    </div>
    <div name="item4" class="single_item">
        Item 4
    </div>
</div></code>```

I am stuck trying to access the name value, anyone have an example I can look at?

答:
If by name you mean the text inside the div, then this is accessible via textContent property</p>

```<code>alert("This is an item - the name is "+items[i].textContent);
</code>```

Title: Javascript display name of div

Body:
I have a container with divs inside, using Javascript I am trying to open an alert box for each item found displaying the 'name' of the div...

items = document.getElementsByClassName("single_item");

for (i = 0; i < items.length; i++) {
    alert("This is an item - the name is...")
}

        Item 1

        Item 2

        Item 3

        Item 4

I am stuck trying to access the name value, anyone have an example I can look at?

Body:
If by name you mean the text inside the div, then this is accessible via textContent property

alert("This is an item - the name is "+items[i].textContent);


问:
Best Practices to Build an Admin Approval System
there should be a sub system of admin panel which different users can manage their products but every change should be approved by administrator before going affecting the main Product table.
there is three main table:

Product : store products that have final approved and are used in entire system

Changes_versions : a table with One To Many Relation with Product Table that indicates each change version is committed by who , when ,and is approved/rejected by admin or still is in Pending state .table structure is as following :

```<code>CREATE TABLE `changes_versions` (
  `xid` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `xcreated_date` datetime DEFAULT NULL,
  `xupdated_date` timestamp NULL DEFAULT NULL,
  `xversion` int(11) DEFAULT NULL,
  `xobject_id` int(11) DEFAULT NULL,
  `xobject_type` varchar(255) DEFAULT NULL,
  `xstate` enum('PENDING','ACCEPTED','REJECTED') DEFAULT 'PENDING',
  PRIMARY KEY (`xid`)
) ENGINE=InnoDB AUTO_INCREMENT=165 DEFAULT CHARSET=utf8
</code>```

Changes :  a table that have One To Many relation with Changes_versions table that keep every column change record of the main Table (here i mean product table) and by approving a change_version record by admin its related changes records will be placed in main table column. table structure is as following :

```<code>CREATE TABLE `changes` (
  `xid` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `xcreated_date` datetime DEFAULT NULL,
  `xcreated_by` varchar(255) DEFAULT NULL,
  `xupdated_date` timestamp NULL DEFAULT NULL,
  `xupdated_by` varchar(255) DEFAULT NULL,
  `xversion_id` int(11) DEFAULT NULL,
  `xcolumn_name` varchar(255) DEFAULT NULL,
  `xcolumn_value` varchar(255) DEFAULT NULL,
  `xstate` enum('PENDING','ACCEPTED','REJECTED') DEFAULT 'PENDING',
  `xadmin_review` text,
  PRIMARY KEY (`xid`)
) ENGINE=InnoDB AUTO_INCREMENT=764 DEFAULT CHARSET=utf8
</code>```

with this system and table schema i handled to work with record changes, user fetch list of records ,if user have any Pending state change_version, system will pull its related changes records and place them in the right column in the fetched product row(temporary just for displaying) , so even if user has any pending state changes he/she can see its changes in his/hes panel(not main system, only his/her panel).

the problem is for INSERTING new records, i can create a change_version record and save all user data to changes table pointing to new change_vesrion record but change_vesrsion record is not connected to any product record because there was no record.

notice that based on system complexity and current stability i do not want to add any column to product table to indicate that this is a temp record.

so i want a strategy to handle issues like when i paginate products in user panel and filling them with last PENDING changes, there is not product record for inserted record to fill with changes so user cant see his/her previous inserted product.

I should also notice that some what this tables structure may seems complex for this question.this structure is complex because changes_vesrsion and chaneges tables save and present historical and admin approval process for many tables with different structures.

答:
A solution to this is create all tables as discribed and when user create a product into changes_version table there should be a mysql event that check regularly each record in product table and match it with changes_version table. If any changes or new insertion found inside changed_version table, the product table should be inserted/updated accordingly.

Revised Solution:

You can achieve it by inserting user record into product table from changes_version when user logged in and delete it on logout. This works for those products who are not yet moved into product table and you can check it via query.

If you have front-end source then you can show changes_version record to user only and moved it via trigger to product table when it gets approved.

Body:
there should be a sub system of admin panel which different users can manage their products but every change should be approved by administrator before going affecting the main Product table.
there is three main table:

Product : store products that have final approved and are used in entire system

Changes_versions : a table with One To Many Relation with Product Table that indicates each change version is committed by who , when ,and is approved/rejected by admin or still is in Pending state .table structure is as following :

CREATE TABLE `changes_versions` (
  `xid` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `xcreated_date` datetime DEFAULT NULL,
  `xupdated_date` timestamp NULL DEFAULT NULL,
  `xversion` int(11) DEFAULT NULL,
  `xobject_id` int(11) DEFAULT NULL,
  `xobject_type` varchar(255) DEFAULT NULL,
  `xstate` enum('PENDING','ACCEPTED','REJECTED') DEFAULT 'PENDING',
  PRIMARY KEY (`xid`)
) ENGINE=InnoDB AUTO_INCREMENT=165 DEFAULT CHARSET=utf8

Changes :  a table that have One To Many relation with Changes_versions table that keep every column change record of the main Table (here i mean product table) and by approving a change_version record by admin its related changes records will be placed in main table column. table structure is as following :

CREATE TABLE `changes` (
  `xid` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `xcreated_date` datetime DEFAULT NULL,
  `xcreated_by` varchar(255) DEFAULT NULL,
  `xupdated_date` timestamp NULL DEFAULT NULL,
  `xupdated_by` varchar(255) DEFAULT NULL,
  `xversion_id` int(11) DEFAULT NULL,
  `xcolumn_name` varchar(255) DEFAULT NULL,
  `xcolumn_value` varchar(255) DEFAULT NULL,
  `xstate` enum('PENDING','ACCEPTED','REJECTED') DEFAULT 'PENDING',
  `xadmin_review` text,
  PRIMARY KEY (`xid`)
) ENGINE=InnoDB AUTO_INCREMENT=764 DEFAULT CHARSET=utf8

with this system and table schema i handled to work with record changes, user fetch list of records ,if user have any Pending state change_version, system will pull its related changes records and place them in the right column in the fetched product row(temporary just for displaying) , so even if user has any pending state changes he/she can see its changes in his/hes panel(not main system, only his/her panel).

the problem is for INSERTING new records, i can create a change_version record and save all user data to changes table pointing to new change_vesrion record but change_vesrsion record is not connected to any product record because there was no record.

notice that based on system complexity and current stability i do not want to add any column to product table to indicate that this is a temp record.

so i want a strategy to handle issues like when i paginate products in user panel and filling them with last PENDING changes, there is not product record for inserted record to fill with changes so user cant see his/her previous inserted product.

I should also notice that some what this tables structure may seems complex for this question.this structure is complex because changes_vesrsion and chaneges tables save and present historical and admin approval process for many tables with different structures.


问:
getline in C++ - Help needed
I am using getline to read up to end of newline but c++ getline gets me stuff till space,

I have txt file data as

address(tab char)1420 Happy Lane

When I do

getline(reader, ss, '\t') I get address in ss string.
when I do getline(reader, ss, '\n') I just get 1420.

I want full "1420 Happy Lane", How to get it ?

Thanks.

```<code>#include <fstream>
#include <string>
#include <iostream>
#include <vector>
#include <sstream>

using namespace std;
int main( int argc, char *argv[] )
{
        if( argc < 2 )
        {
                cout << "Missing filename as first argument" << "\n";
                exit(2);
        }

        vector<string> myvector;
        string ss;
        int i=0, j=0;

        ifstream reader(argv[1]);

        if (! reader )
        {
                cout << "Error opening input file : " << " " << argv[1] << '\n';
                return -1;
        }

        while( !reader.eof())
        {
                 if ((i+1) % 2 == 0 )
                        getline(reader, ss, '\n');
                 else
                         getline(reader, ss, '\t');
                if (ss[0] == '#')
                {
                        //Skip
                        getline(reader,ss, '\n');i=0;
                        continue;
                }

                i++;
                myvector.push_back(ss);
        }

        reader.close();

        vector<string>::iterator it;
        stringstream stream;
        int vecloc=1;
        string tag;
        string sData;

        cout << "myvector contains: \n";

        for ( it=myvector.begin() ; it < myvector.end(); it++ )
        {
                switch (vecloc)
                {
                case 1: stream << *it;  stream >> tag; vecloc++;break;
                case 2:
                                stream << *it;  stream >> sData;
                                // Do job
                                cout << tag << "   " << sData << "\n";
                                // Reset.
                                vecloc=1;       break;
                default :       break;
                }
                // Clear String stream
        stream.str(""); stream.clear();
        }

        return(0);
}
</code>```

output

/home/sr/utl

cat abc.txt

hey     c++ making me nuts.

/home/sr/utl

a.out abc.txt

myvector contains:

hey   c++

答:
Paste the actual code from your editor and double check that there isn't a newline (or maybe other unexpected non-printing characters) in your data file.

This works as expected here:

```<code>#include <iostream>
#include <sstream>

using namespace std;

int main()
{
    stringstream reader("address\t1420 Happy Lane\n");

    string ss;

    getline(reader, ss, '\t');
    cout << "1: " << ss << endl;

    getline(reader, ss, '\n');
    cout << "2: " << ss << endl;
}
</code>```

Output:

```<code>1: address
2: 1420 Happy Lane
</code>```

Title: getline in C++ - Help needed

Body:
I am using getline to read up to end of newline but c++ getline gets me stuff till space,

I have txt file data as

address(tab char)1420 Happy Lane

When I do

getline(reader, ss, '\t') I get address in ss string.
when I do getline(reader, ss, '\n') I just get 1420.

I want full "1420 Happy Lane", How to get it ?

Thanks.

#include <fstream>
#include <string>
#include <iostream>
#include <vector>
#include <sstream>

using namespace std;
int main( int argc, char *argv[] )
{
        if( argc < 2 )
        {
                cout << "Missing filename as first argument" << "\n";
                exit(2);
        }

        vector<string> myvector;
        string ss;
        int i=0, j=0;

        ifstream reader(argv[1]);

        if (! reader )
        {
                cout << "Error opening input file : " << " " << argv[1] << '\n';
                return -1;
        }

        while( !reader.eof())
        {
                 if ((i+1) % 2 == 0 )
                        getline(reader, ss, '\n');
                 else
                         getline(reader, ss, '\t');
                if (ss[0] == '#')
                {
                        //Skip
                        getline(reader,ss, '\n');i=0;
                        continue;
                }

                i++;
                myvector.push_back(ss);
        }

        reader.close();

        vector<string>::iterator it;
        stringstream stream;
        int vecloc=1;
        string tag;
        string sData;

        cout << "myvector contains: \n";

        for ( it=myvector.begin() ; it < myvector.end(); it++ )
        {
                switch (vecloc)
                {
                case 1: stream << *it;  stream >> tag; vecloc++;break;
                case 2:
                                stream << *it;  stream >> sData;
                                // Do job
                                cout << tag << "   " << sData << "\n";
                                // Reset.
                                vecloc=1;       break;
                default :       break;
                }
                // Clear String stream
        stream.str(""); stream.clear();
        }

        return(0);
}

output

/home/sr/utl

cat abc.txt

hey     c++ making me nuts.

/home/sr/utl

a.out abc.txt

myvector contains:

hey   c++

Body:
Paste the actual code from your editor and double check that there isn't a newline (or maybe other unexpected non-printing characters) in your data file.

This works as expected here:

#include <iostream>
#include <sstream>

using namespace std;

int main()
{
    stringstream reader("address\t1420 Happy Lane\n");

    string ss;

    getline(reader, ss, '\t');
    cout << "1: " << ss << endl;

    getline(reader, ss, '\n');
    cout << "2: " << ss << endl;
}

Output:

1: address
2: 1420 Happy Lane


答:
You can use .getAttribute() to do this. Also, have a habit of using var keyword for your variables, or further, when your code gets bigger, you might end up having a lot of global variables.

Also, you are using name attribute, which is used for form elements like input, so if you want to use it for your div, you can use custom attributes like data-name and accordingly edit your JS getAttribute value

var items = document.getElementsByClassName("single_item");

for (i = 0; i < items.length; i++) {
    //using getAttribute to fetch the name attribute value
    alert("This is an item - the name is..." + items[i].getAttribute("name"));
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
    <div name="item1" class="single_item">
        Item 1
    </div>
    <div name="item2" class="single_item">
        Item 2
    </div>
    <div name="item3" class="single_item">
        Item 3
    </div>
    <div name="item4" class="single_item">
        Item 4
    </div>
</div></code>```

Also, am just curious to know why you are using alert() which is quite annoying and not recommended. If you are trying to debug and want to output some results, you can always use console.log() which will print the results in your console, and unlike alert(), it won't stop executing your JS either.

Title: Javascript display name of div

Body:
You can use .getAttribute() to do this. Also, have a habit of using var keyword for your variables, or further, when your code gets bigger, you might end up having a lot of global variables.

Also, you are using name attribute, which is used for form elements like input, so if you want to use it for your div, you can use custom attributes like data-name and accordingly edit your JS getAttribute value

var items = document.getElementsByClassName("single_item");

for (i = 0; i < items.length; i++) {
    //using getAttribute to fetch the name attribute value
    alert("This is an item - the name is..." + items[i].getAttribute("name"));
}

<div class="container">
    <div name="item1" class="single_item">
        Item 1
    </div>
    <div name="item2" class="single_item">
        Item 2
    </div>
    <div name="item3" class="single_item">
        Item 3
    </div>
    <div name="item4" class="single_item">
        Item 4
    </div>
</div>

Also, am just curious to know why you are using alert() which is quite annoying and not recommended. If you are trying to debug and want to output some results, you can always use console.log() which will print the results in your console, and unlike alert(), it won't stop executing your JS either.


答:
items = document.getElementsByClassName("single_item");

for (i = 0; i < items.length; i++) {
    alert("This is an item - the name = " + items[i].getAttribute("name"))
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
    <div name="item1" class="single_item">
        Item 1
    </div>
    <div name="item2" class="single_item">
        Item 2
    </div>
    <div name="item3" class="single_item">
        Item 3
    </div>
    <div name="item4" class="single_item">
        Item 4
    </div>
</div></code>```

Title: Javascript display name of div

Body:
items = document.getElementsByClassName("single_item");

for (i = 0; i < items.length; i++) {
    alert("This is an item - the name = " + items[i].getAttribute("name"))
}

<div class="container">
    <div name="item1" class="single_item">
        Item 1
    </div>
    <div name="item2" class="single_item">
        Item 2
    </div>
    <div name="item3" class="single_item">
        Item 3
    </div>
    <div name="item4" class="single_item">
        Item 4
    </div>
</div>


问:
Inverting Matrix transformations on an image
I'm hoping to work out how to improve image quality by doing a Matrix transformation on an image which essentially 'undoes' the softening/motion blur of an image.

If I was to apply transform A to a sharp image, what transform B would get me back to the original image if A is the following:

```<code>0 1 0
0 1 0
0 1 0
</code>```

答:
The only way to achieve such goal, would be depending on the transform.

Imagine a case a very basic(and perhaps stupid) blurring function. It applies to image and converts all pixels 127, 128, 129 from values in range of [0-255]. To inverse this filter we have to be able to map values back. However, we just lost the information. Example is both pixel values 1 and 5 converted to 127. Now, with no information of their previous values, when we read the value of converted pixel 127, should we convert it to 1 or 5? We don't know.

Now, keeping in the mind some transforms are one way ticket. There are better scenarios. For example, linear transforms such as rotation of an image can be completely reversed by basically transforming image with the inverse or rotation matrix.

A^(-1)=A^(T)

where A is rotation matrix.

So basically, transform is inversed when:

AIA^(T)

where I is image and A is rotation matrix.

Therefore, there are two things you need to have to be able to reverse the transform an image. Your transform must be mathematically reversable. And then you need to apply tranform which is mathematically inverse of your transform function.

There are of course, ways you can try to sharpen an image without exactly transforming back, if they are ok for you here are some these techniques for dealing with blur images;

High pass filtering, simple but a classic: http://northstar-www.dartmouth.edu/doc/idl/html_6.2/Sharpening_an_Image.html

Deconvolution: https://en.wikipedia.org/wiki/Deconvolution

Variational methods(Methods based on calculus of variations ) : http://www.math.ucla.edu/~bertozzi/papers/moellerpaper.pdf

More can be found in literature.

Body:
I'm hoping to work out how to improve image quality by doing a Matrix transformation on an image which essentially 'undoes' the softening/motion blur of an image.

If I was to apply transform A to a sharp image, what transform B would get me back to the original image if A is the following:

0 1 0
0 1 0
0 1 0


问:
Add object to list in local storage
I'm trying to add object first to myMovieto localstorage. But myMovie is always empty when check localstorage.

```<code>var myMovie= [];
    localStorage.setItem('myMovie', JSON.stringify(myMovie));
    var output = JSON.parse(localStorage.getItem('myMovie'));
    var first= {id:"tt3783958", title:"La La Land", year:"2016", type:"Comedy, Drama, Music"}
        myMovie.push(first);
</code>```

I can't figure out what I'm I doing it wrong here.

答:
Well, it looks like you are writing your object in the storage before actually adding the first item to it.

Try to add the content in the list at first or save it again after each updates.

```<code>var myMovie= [];
var first= {id:"tt3783958", title:"La La Land", year:"2016",
            type:"Comedy, Drama, Music"};
myMovie.push(first);

localStorage.setItem('myMovie', JSON.stringify(myMovie));
var output = JSON.parse(localStorage.getItem('myMovie'));
</code>```

Title: Add object to list in local storage

Body:
I'm trying to add object first to myMovieto localstorage. But myMovie is always empty when check localstorage.

var myMovie= [];
    localStorage.setItem('myMovie', JSON.stringify(myMovie));
    var output = JSON.parse(localStorage.getItem('myMovie'));
    var first= {id:"tt3783958", title:"La La Land", year:"2016", type:"Comedy, Drama, Music"}
        myMovie.push(first);

I can't figure out what I'm I doing it wrong here.

Body:
Well, it looks like you are writing your object in the storage before actually adding the first item to it.

Try to add the content in the list at first or save it again after each updates.

var myMovie= [];
var first= {id:"tt3783958", title:"La La Land", year:"2016",
            type:"Comedy, Drama, Music"};
myMovie.push(first);

localStorage.setItem('myMovie', JSON.stringify(myMovie));
var output = JSON.parse(localStorage.getItem('myMovie'));


问:
How do I define a parser function for variables?
I need help creating a parser for ternary expressions. I'm given this grammar for ternary expressions.

```<code>tExp :: tOpd ( '<=>' tExp | '==>' tExp| e )
tOpd :: tTerm ( '|||' tOpd | e )
tTerm :: tFact ( '&&&' tTerm | e)
tFact :: '~' tPrim | tPrim
primary :: tVar | tLit | '('tExp')'
tVar :: lowercase (Alphanumeric)*
tLit :: T | F | M
</code>```

I also have defined the data type Ternary and expression tree here.

```<code>data Ternary = T | F | M
    deriving (Eq,  Show, Ord)

   data TExpTree = L Ternary              -- Ternary literal (i.e. T, F or M)
                  | V String               -- Variable
                  | N TExpTree             -- Prefix not
                  | A TExpTree TExpTree    -- And node
                  | O TExpTree TExpTree    -- Or node
                  | E TExpTree TExpTree    -- Equivalence node
                  | I TExpTree TExpTree    -- Implication node
        deriving (Show, Eq)
</code>```

I know that first I need to create functions for each rule.

```<code>tExp:: Parser TExpTree
tExp = do o <- tOpd
          (do symbol "<=>"
              e <- tExp
              return (e<=>o)
           +++ do synbol "==>"
              e <- tExp
              return (e==>o)
           +++ return o)

tOpd :: Parser TExpTree
tOpd = do t <- tTerm
          (do symbol "|||"
              e <- tOpd
              return (t|||e)
           +++ return t)

tTerm :: Parser TExpTree
tTerm = do f <- tFact
          (do symbol "&&&"
              e <- tTerm
              return (f+e)
           +++ return f)

tFact:: Parser TExpTree
tFact = do m <- tPrim
           return m
        +++
           (do symbol "~"
              m <- tExp
              return (~m))
</code>```

So far, I have these, but I don't know how to go about creating them for primary, tLit, and tVar.

Can someone help me figure out just tLit, so I can try doing the rest myself? I'm not sure how to go about this.

I have this test function for tLit to confirm that it works as well.

```<code>testtLit :: Bool
testtLit = lt == (L T) && lf == (L F) && lm == (L M)
       where Just (lt, _) = parse tLit " T "
             Just (lf, _) = parse tLit " F "
             Just (lm, _) = parse tLit " M "
</code>```

答:
You are implementing a parser and an evaluator in a single function. Because of that, you never use TExpTree. If you want to build a parser, change the type of your parser functions to Parser TExpTree. Then, let tExp return (I e o) instead of (e==>o), and so on.

The implementation of the tLit function depends on the tools your parser offers. It could look like this (untested):

```<code>tLit :: Parser TExpTree
tLit = (symbol "T" >> return (L T))
   <|> (symbol "F" >> return (L F))
   <|> (symbol "M" >> return (L M))
</code>```

Body:
I need help creating a parser for ternary expressions. I'm given this grammar for ternary expressions.

tExp :: tOpd ( '<=>' tExp | '==>' tExp| e )
tOpd :: tTerm ( '|||' tOpd | e )
tTerm :: tFact ( '&&&' tTerm | e)
tFact :: '~' tPrim | tPrim
primary :: tVar | tLit | '('tExp')'
tVar :: lowercase (Alphanumeric)*
tLit :: T | F | M

I also have defined the data type Ternary and expression tree here.

data Ternary = T | F | M
    deriving (Eq,  Show, Ord)

   data TExpTree = L Ternary              -- Ternary literal (i.e. T, F or M)
                  | V String               -- Variable
                  | N TExpTree             -- Prefix not
                  | A TExpTree TExpTree    -- And node
                  | O TExpTree TExpTree    -- Or node
                  | E TExpTree TExpTree    -- Equivalence node
                  | I TExpTree TExpTree    -- Implication node
        deriving (Show, Eq)

I know that first I need to create functions for each rule.

tExp:: Parser TExpTree
tExp = do o <- tOpd
          (do symbol "<=>"
              e <- tExp
              return (e<=>o)
           +++ do synbol "==>"
              e <- tExp
              return (e==>o)
           +++ return o)

tOpd :: Parser TExpTree
tOpd = do t <- tTerm
          (do symbol "|||"
              e <- tOpd
              return (t|||e)
           +++ return t)

tTerm :: Parser TExpTree
tTerm = do f <- tFact
          (do symbol "&&&"
              e <- tTerm
              return (f+e)
           +++ return f)

tFact:: Parser TExpTree
tFact = do m <- tPrim
           return m
        +++
           (do symbol "~"
              m <- tExp
              return (~m))

So far, I have these, but I don't know how to go about creating them for primary, tLit, and tVar.

Can someone help me figure out just tLit, so I can try doing the rest myself? I'm not sure how to go about this.

I have this test function for tLit to confirm that it works as well.

testtLit :: Bool
testtLit = lt == (L T) && lf == (L F) && lm == (L M)
       where Just (lt, _) = parse tLit " T "
             Just (lf, _) = parse tLit " F "
             Just (lm, _) = parse tLit " M "

Body:
You are implementing a parser and an evaluator in a single function. Because of that, you never use TExpTree. If you want to build a parser, change the type of your parser functions to Parser TExpTree. Then, let tExp return (I e o) instead of (e==>o), and so on.

The implementation of the tLit function depends on the tools your parser offers. It could look like this (untested):

tLit :: Parser TExpTree
tLit = (symbol "T" >> return (L T))
   <|> (symbol "F" >> return (L F))
   <|> (symbol "M" >> return (L M))


答:
top: 50%; does exactly what you suspect: it places the top edge at 50% height. You can offset this effect by also applying a negative vertical margin equal to half of the height of the element. For example, if the element was 100px high, you would add this property:

```<code>margin-top: -50px;
</code>```

Title: How do I center the div vertically?

Body:
Possible Duplicate:

  What's The Best Way of Centering a Div Vertically with CSS

.title_text_only{
position:absolute;
width:100%;
display:none;
z-index:9;
top:50%;
bottom:50%;
text-align:center;
color:#fff;
font-size:18px;
text-shadow: 1px 1px 1px #666;
}

Right now, it doesn't seem to work. top 50% doesn't center it vertically. It's a little to the bottom.  It's as if the top border is 50%.

Body:
top: 50%; does exactly what you suspect: it places the top edge at 50% height. You can offset this effect by also applying a negative vertical margin equal to half of the height of the element. For example, if the element was 100px high, you would add this property:

margin-top: -50px;


答:
do it like this, with getAttribute

items = document.getElementsByClassName("single_item");

for (i = 0; i < items.length; i++) {
    alert("This is an item - the name is " + items[i].getAttribute("name"));
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
    <div name="item1" class="single_item">
        Item 1
    </div>
    <div name="item2" class="single_item">
        Item 2
    </div>
    <div name="item3" class="single_item">
        Item 3
    </div>
    <div name="item4" class="single_item">
        Item 4
    </div>
</div></code>```

Title: Javascript display name of div

Body:
do it like this, with getAttribute

items = document.getElementsByClassName("single_item");

for (i = 0; i < items.length; i++) {
    alert("This is an item - the name is " + items[i].getAttribute("name"));
}

<div class="container">
    <div name="item1" class="single_item">
        Item 1
    </div>
    <div name="item2" class="single_item">
        Item 2
    </div>
    <div name="item3" class="single_item">
        Item 3
    </div>
    <div name="item4" class="single_item">
        Item 4
    </div>
</div>


问:
How do i get "sed" to delete everything else but email address.
how do i get "sed" to delete everything else but email address. </p>

```<code>db dump: someusername ::: kRW...0fPc ::: $2a$10$...aucvkDt86 ::: joesmith@gmail.com
</code>```

答:
With sed:

```<code>$ echo "db dump: someusername ::: kRW...0fPc ::: $2a$10$...aucvkDt86 ::: joesmith@gmail.com"|sed 's/.*::: //' joesmith@gmail.com
</code>```

With awk:

```<code>$ echo "db dump: someusername ::: kRW...0fPc ::: $2a$10$...aucvkDt86 ::: joesmith@gmail.com"|awk '{print $NF}'
</code>```

EDIT: Given the new info in your comment - it's quite hard to do what you ask without any regularity. Check the Syntax section here:

http://en.wikipedia.org/wiki/Email_address

Standard says that e.g. 1$%3{C}@example.com is a valid email address (believe it or not). You can even quote it (the example given in the article is John Doe@example.com). So, by following the standard it's almost impossible to recognize the valid e-mail.

If you restrict your search, you can e.g. extract the lines containing @ by first doing:

```<code>cat your-file.txt|grep @
</code>```

then do some of the above. You can even do something like this:

```<code>$ echo "garbage John.Doe123@example.com garbage"|sed 's/[^@]* \([a-zA-Z0-9.]*@[^ ]*\).*/\1/'
John.Doe123@example.com
</code>```

Note that the above works under the following assumptions:

There's a space before an email address

There are no spaces in an email address itself

There is one email address in the line (it will actually get only the first one, so it can work with more then one)

The local-part (all before @) contains only letters (lower- or upper-case), digits and a dot

Expand the character set ([a-zA-Z0-9.]) as you wish to make it less restrictive - e.g. you can do [a-zA-Z0-9.-_] to include - and _.

Body:
how do i get "sed" to delete everything else but email address.

db dump: someusername ::: kRW...0fPc ::: $2a$10$...aucvkDt86 ::: joesmith@gmail.com

Body:
With sed:

$ echo "db dump: someusername ::: kRW...0fPc ::: $2a$10$...aucvkDt86 ::: joesmith@gmail.com"|sed 's/.*::: //' joesmith@gmail.com

With awk:

$ echo "db dump: someusername ::: kRW...0fPc ::: $2a$10$...aucvkDt86 ::: joesmith@gmail.com"|awk '{print $NF}'

EDIT: Given the new info in your comment - it's quite hard to do what you ask without any regularity. Check the Syntax section here:

http://en.wikipedia.org/wiki/Email_address

Standard says that e.g. 1$%3{C}@example.com is a valid email address (believe it or not). You can even quote it (the example given in the article is John Doe@example.com). So, by following the standard it's almost impossible to recognize the valid e-mail.

If you restrict your search, you can e.g. extract the lines containing @ by first doing:

cat your-file.txt|grep @

then do some of the above. You can even do something like this:

$ echo "garbage John.Doe123@example.com garbage"|sed 's/[^@]* \([a-zA-Z0-9.]*@[^ ]*\).*/\1/'
John.Doe123@example.com

Note that the above works under the following assumptions:

There's a space before an email address

There are no spaces in an email address itself

There is one email address in the line (it will actually get only the first one, so it can work with more then one)

The local-part (all before @) contains only letters (lower- or upper-case), digits and a dot

Expand the character set ([a-zA-Z0-9.]) as you wish to make it less restrictive - e.g. you can do [a-zA-Z0-9.-_] to include - and _.


问:
ffmpeg through python subprocess fails to find camera
Weird problem here, i use this command to capture my webcam through ffmpeg (through cmd on windows):

```<code>ffmpeg -y -t 300 -rtbufsize 1024M -f dshow -i video="Lenovo EasyCamera" -c:v libx264 -preset veryslow -crf 25 Desktop.mkv
</code>```

and everything works fine. But when i try the very same command through python as a subprocess it fails. Here's the python code:

```<code>from subprocess import Popen
cmd = ['ffmpeg', '-y', '-t', '300', '-rtbufsize', '1024M', '-f', 'dshow', '-i', 'video="Lenovo EasyCamera"', '-c:v', 'libx264', '-preset', 'veryslow', '-crf', '25', 'Desktop.mkv']
p = Popen(cmd)
</code>```

Outputs the following error and freezes:

```<code>[dshow @ 00000000023a2cc0] Could not find video device with name ["Lenovo EasyCamera"] among source devices of type video.
video="Lenovo EasyCamera": I/O error
</code>```

Can anyone figure this out and tell me what i'm doing wrong? Or is it some known bug in python or the subprocess module (using python 3.6.1, but not attached to the specific version if it will help me solve this problem)?

Thanks in advance!

P.S. This question is a follow up to this one, if that's relevant: How to grab laptop webcam video with ffmpeg in windows

答:
The problem is that, in the commandline, video="Lenovo EasyCamera" uses the quotes to make sure the space doesn't make it another argument.

You can see this with a test python file:

```<code>import sys
print(sys.argv[1:])
</code>```

```<code>> python print_argv.py video="Lenovo EasyCamera"
['video=Lenovo EasyCamera']
> python print_argv.py "video=Lenovo EasyCamera"
['video=Lenovo EasyCamera']
> python
>>> from subprocess import Popen
>>> cmd = ['python', 'print_argv.py', 'video="Lenovo EasyCamera"']
>>> p = Popen(cmd)
['video="Lenovo EasyCamera"']
</code>```

ffmpeg thinks you're looking for a device called "Lenovo EasyCamera" instead of Lenovo EasyCamera

So, you need to change your command so that it is not in quotes, as Popen will not split it on spaces.

```<code>from subprocess import Popen
cmd = [..., '-i', 'video=Lenovo EasyCamera', ...]
p = Popen(cmd)
</code>```

Body:
Weird problem here, i use this command to capture my webcam through ffmpeg (through cmd on windows):

ffmpeg -y -t 300 -rtbufsize 1024M -f dshow -i video="Lenovo EasyCamera" -c:v libx264 -preset veryslow -crf 25 Desktop.mkv

and everything works fine. But when i try the very same command through python as a subprocess it fails. Here's the python code:

from subprocess import Popen
cmd = ['ffmpeg', '-y', '-t', '300', '-rtbufsize', '1024M', '-f', 'dshow', '-i', 'video="Lenovo EasyCamera"', '-c:v', 'libx264', '-preset', 'veryslow', '-crf', '25', 'Desktop.mkv']
p = Popen(cmd)

Outputs the following error and freezes:

[dshow @ 00000000023a2cc0] Could not find video device with name ["Lenovo EasyCamera"] among source devices of type video.
video="Lenovo EasyCamera": I/O error

Can anyone figure this out and tell me what i'm doing wrong? Or is it some known bug in python or the subprocess module (using python 3.6.1, but not attached to the specific version if it will help me solve this problem)?

Thanks in advance!

P.S. This question is a follow up to this one, if that's relevant: How to grab laptop webcam video with ffmpeg in windows

Body:
The problem is that, in the commandline, video="Lenovo EasyCamera" uses the quotes to make sure the space doesn't make it another argument.

You can see this with a test python file:

import sys
print(sys.argv[1:])

> python print_argv.py video="Lenovo EasyCamera"
['video=Lenovo EasyCamera']
> python print_argv.py "video=Lenovo EasyCamera"
['video=Lenovo EasyCamera']
> python
>>> from subprocess import Popen
>>> cmd = ['python', 'print_argv.py', 'video="Lenovo EasyCamera"']
>>> p = Popen(cmd)
['video="Lenovo EasyCamera"']

ffmpeg thinks you're looking for a device called "Lenovo EasyCamera" instead of Lenovo EasyCamera

So, you need to change your command so that it is not in quotes, as Popen will not split it on spaces.

from subprocess import Popen
cmd = [..., '-i', 'video=Lenovo EasyCamera', ...]
p = Popen(cmd)


问:
How to disable ssh-agent forwarding
ssh-agent forwarding can be accomplished with ssh -A ....

Most references I have found state that the local machine must configure ~/.ssh/config to enable AgentForwarding with the following code:

```<code>Host <trusted_ip>
  ForwardAgent yes

Host *
  ForwardAgent no
</code>```

However, with this configuration, I am still able to see my local machines keys when tunneling into a remote machine, with ssh -A user@remote_not_trusted_ip, and running ssh-add -l.

From the configuration presented above, I would expect that the ssh-agent forwarding would fail and the keys of the local machine would not be listed by ssh-add -l.

Why is the machine @remote_not_trusted_ip able to access the ssh-agent forwarded keys even though the ~/.ssh/config file states the following?

```<code>Host *
  ForwardAgent no
</code>```

How can i prevent ssh-agent from forwarding keys to machines not explicitly defined in the ~/.ssh/config?

答:
How can i prevent ssh-agent from forwarding keys to machines not explicitly defined in the ~/.ssh/config?

It is the default behavior. If you do not allow it in ~/.ssh/config it will not be forwarded. But the command-line arguments have higher priority so it overwrites what is defined in the configuration,as explained in the manual page for ssh_config:

ssh(1) obtains configuration data from the following sources in the following order:

command-line options

user's configuration file (~/.ssh/config)

system-wide configuration file (/etc/ssh/ssh_config)

So as already said, you just need to provide correct arguments to ssh.

So back to the questions:

Why is the machine @remote_not_trusted_ip able to access the ssh-agent forwarded keys even though the ~/.ssh/config file states the following?

```<code>Host *
  ForwardAgent no
</code>```

Because the command-line argument -A has higher priority than the configuration files.

How can I prevent ssh-agent from forwarding keys to machines not explicitly defined in the ~/.ssh/config?

Do not use -A command-line option if you do not want forward your ssh-agent. Use -a command-line option instead.

Title: How to disable ssh-agent forwarding

Body:
ssh-agent forwarding can be accomplished with ssh -A ....

Most references I have found state that the local machine must configure ~/.ssh/config to enable AgentForwarding with the following code:

Host <trusted_ip>
  ForwardAgent yes

Host *
  ForwardAgent no

However, with this configuration, I am still able to see my local machines keys when tunneling into a remote machine, with ssh -A user@remote_not_trusted_ip, and running ssh-add -l.

From the configuration presented above, I would expect that the ssh-agent forwarding would fail and the keys of the local machine would not be listed by ssh-add -l.

Why is the machine @remote_not_trusted_ip able to access the ssh-agent forwarded keys even though the ~/.ssh/config file states the following?

Host *
  ForwardAgent no

How can i prevent ssh-agent from forwarding keys to machines not explicitly defined in the ~/.ssh/config?

Body:
How can i prevent ssh-agent from forwarding keys to machines not explicitly defined in the ~/.ssh/config?

It is the default behavior. If you do not allow it in ~/.ssh/config it will not be forwarded. But the command-line arguments have higher priority so it overwrites what is defined in the configuration,as explained in the manual page for ssh_config:

ssh(1) obtains configuration data from the following sources in the following order:

command-line options

user's configuration file (~/.ssh/config)

system-wide configuration file (/etc/ssh/ssh_config)

So as already said, you just need to provide correct arguments to ssh.

So back to the questions:

Why is the machine @remote_not_trusted_ip able to access the ssh-agent forwarded keys even though the ~/.ssh/config file states the following?

Host *
  ForwardAgent no

Because the command-line argument -A has higher priority than the configuration files.

How can I prevent ssh-agent from forwarding keys to machines not explicitly defined in the ~/.ssh/config?

Do not use -A command-line option if you do not want forward your ssh-agent. Use -a command-line option instead.


问:
Change the result language of Google's PlaceAutoComplete widget
I'm using PlaceAutoComplete widget (full screen mode) by following the instruction in this link PlaceAutoComplete widget. Everything went fine, I got autocomplete result appeared when I typed any valid place/city name. The autocomplete result showed in English, like "North Java, East Java, ect."

My question is, how can I get the autocomplete result in other language? Say I want it in French or Bahasa instead of English.

答: Doesn't this simply depend on the user's system language?</p>


问:
Test Coverage .NetCore
I was looking for a TestCoverage for .netCore Xunit.

I found OpenCover, but i have no sucess to execute the command to run it:

```<code>C:\Users\andre.silva\AppData\Local\Apps\OpenCover\OpenCover.Console.exe -target:"C:\Users\andre.silva\.dnx\runtimes\dnx-clr-win-x86.1.0.0-rc1-update1\bin\dnx.exe" -targetargs:"--lib dotnet test" -output:coverage.xml -register:user -filter:"+[*]* -[xunit*]*"
</code>```

Error: Unable to resolve project

Does Anybody know if OpenCover can runwith .NETCore projects?

Tks guys

答: With the current released version you will need to use full pdbs for it to work.</p>

Title: Test Coverage .NetCore

Body:
I was looking for a TestCoverage for .netCore Xunit.

I found OpenCover, but i have no sucess to execute the command to run it:

C:\Users\andre.silva\AppData\Local\Apps\OpenCover\OpenCover.Console.exe -target:"C:\Users\andre.silva\.dnx\runtimes\dnx-clr-win-x86.1.0.0-rc1-update1\bin\dnx.exe" -targetargs:"--lib dotnet test" -output:coverage.xml -register:user -filter:"+[*]* -[xunit*]*"

Error: Unable to resolve project

Does Anybody know if OpenCover can runwith .NETCore projects?

Tks guys


问:
Difference between Strings added directly and with references
I came across a question asking the output of the below:

```<code>    String s1 = "String 1";
    String s2 = "String 2";

    String s3 = s1 + s2;
    String s4 = "String 1" + "String 2";

    System.out.println(s3==s4);
</code>```

Output - false

Now, since the strings are not created using new operator, so the objects are created in the string pool, so as per my understanding s1 + s2 and "String 1" + "String 2" should be equal, and s3==s4 should be true.

But it is not happening in real. Can any one please explain this?

答:
This line compare memory addresses of two strings. Because of both are separate objects and output will be false.

```<code>s3==s4
</code>```

You need to compare using equals()

```<code>System.out.println(s3.equals(s4));
</code>```

equals() is compare value of object not address.

Body:
I came across a question asking the output of the below:

    String s1 = "String 1";
    String s2 = "String 2";

    String s3 = s1 + s2;
    String s4 = "String 1" + "String 2";

    System.out.println(s3==s4);

Output - false

Now, since the strings are not created using new operator, so the objects are created in the string pool, so as per my understanding s1 + s2 and "String 1" + "String 2" should be equal, and s3==s4 should be true.

But it is not happening in real. Can any one please explain this?

Body:
This line compare memory addresses of two strings. Because of both are separate objects and output will be false.

s3==s4

You need to compare using equals()

System.out.println(s3.equals(s4));

equals() is compare value of object not address.


问:
SQL Insert Code Not Working
I am trying to execute the following SQL code on SQL Server, but 0 rows are affected.

```<code>INSERT INTO IV10201 (ITEMNMBR, TRXLOCTN, QTYTYPE, DOCDATE, RCTSEQNM, ORIGINDOCTYPE, ORIGINDOCID, LNSEQNBR, CMPNTSEQ, QTYSOLD, UNITCOST, IVIVINDX, IVIVOFIX, SRCRCTSEQNM, TRXREFERENCE, PCHSRCTY)
    SELECT
        ITEMNMBR, TRXLOCTN, QTYTYPE, DOCDATE, 218,
        ORIGINDOCTYPE, ORIGINDOCID, LNSEQNBR, CMPNTSEQ, 15.500000,
        UNITCOST, IVIVINDX, IVIVOFIX, 0, TRXREFERENCE, PCHSRCTY
    FROM
        IV10201
    WHERE
        itemNmbr = 'N-LB-00039-0015-0004'
        AND trxLoctn = 'KATAMYA'
        AND qtyType = 1
        AND docDate = '2016-02-08 00:00:00'
        AND rctseqnm = 157
        AND srcrctseqnm = 64
</code>```

I am not getting any error messages, just that 0 rows were affected. Any idea what is the problem with my code?

Thank you!

答: Well, your select query does not return anything, that's your problem most likely. Try running your query without insert and see what results you get.</p>

Title: SQL Insert Code Not Working

Body:
I am trying to execute the following SQL code on SQL Server, but 0 rows are affected.

INSERT INTO IV10201 (ITEMNMBR, TRXLOCTN, QTYTYPE, DOCDATE, RCTSEQNM, ORIGINDOCTYPE, ORIGINDOCID, LNSEQNBR, CMPNTSEQ, QTYSOLD, UNITCOST, IVIVINDX, IVIVOFIX, SRCRCTSEQNM, TRXREFERENCE, PCHSRCTY)
    SELECT
        ITEMNMBR, TRXLOCTN, QTYTYPE, DOCDATE, 218,
        ORIGINDOCTYPE, ORIGINDOCID, LNSEQNBR, CMPNTSEQ, 15.500000,
        UNITCOST, IVIVINDX, IVIVOFIX, 0, TRXREFERENCE, PCHSRCTY
    FROM
        IV10201
    WHERE
        itemNmbr = 'N-LB-00039-0015-0004'
        AND trxLoctn = 'KATAMYA'
        AND qtyType = 1
        AND docDate = '2016-02-08 00:00:00'
        AND rctseqnm = 157
        AND srcrctseqnm = 64

I am not getting any error messages, just that 0 rows were affected. Any idea what is the problem with my code?

Thank you!


问:
Getting memory leaks from Appcelerator Alloy app
I have an Alloy app. It has got 7 windows and opens at same time. When user close a opened window $.removeListener(); $.destroy(); codes runs at window close event. But I am getting memory leaks on Android device. %90 windows has got ListView, every window has got max 2 Listview. What is the right approach for multiple windows?

答:
First of all, why you would want to open 7 windows at same time when user can only see max 1 window at a time.

It's dead simple, open only that window which user should see first, & create a link-flow to other window in previous window.

Can you think of any app on Play Store which does so, if you have, then please send me its link, I would really love to review it?

But if you mean to say that user will see all windows at same time in a scrolling behaviour or like paging, then go to Ti.UI.TabGroup

ContentLicense: CC BY-SA 4.0


问:
How to add post query parameter string with double quote in url in retrofit?
I am accessing an api .which looks like

http://XXX.XX.XXX.XXX/api/Gallery/getgallerylist?userid="17" .

I have tried the following annotation.

```<code> @POST("Gallery/getgallerylist")
    Call<GalleryImagesResponse> getGalleryImages(@Query("userid") String userid);
</code>```

But the url it requests is http://XXX.XX.XXX.XXX/api/Gallery/getgallerylist?userid=17

So that how can I add double quote to userid's value like userid="17".

答:
you should try this before hitting url

```<code>URLDecoder.decode(url,UTF8);
</code>```

Body:
I am accessing an api .which looks like

http://XXX.XX.XXX.XXX/api/Gallery/getgallerylist?userid="17" .

I have tried the following annotation.

 @POST("Gallery/getgallerylist")
    Call<GalleryImagesResponse> getGalleryImages(@Query("userid") String userid);

But the url it requests is http://XXX.XX.XXX.XXX/api/Gallery/getgallerylist?userid=17

So that how can I add double quote to userid's value like userid="17".

Body:
you should try this before hitting url

URLDecoder.decode(url,UTF8);


答:
Best would be a function, that not only changes the array but also stores it in localStorage:

    var myMovie=[] //JSON.parse(localStorage.getItem('myMovie')||"[]");

    function push(el){
    myMovie.push(el);
    //localStorage.setItem('myMovie', JSON.stringify(myMovie));
    }

    function remove(title){
     var i=myMovie.findIndex(movie=>movie.title===title);
     if(i!==-1){
       myMovie.splice(i,1);
       //localStorage.setItem('myMovie', JSON.stringify(myMovie));
     }
    }

    push({id:"tt3783958", title:"La La Land", year:"2016", type:"Comedy, Drama, Music"});
    console.log(myMovie);
    remove("La La Land");
    console.log(myMovie);```

To make a running stackSnippet, i had to remove the localStorage functionality, it is commented out.

Title: Add object to list in local storage

Body:
I'm trying to add object first to myMovieto localstorage. But myMovie is always empty when check localstorage.

var myMovie= [];
    localStorage.setItem('myMovie', JSON.stringify(myMovie));
    var output = JSON.parse(localStorage.getItem('myMovie'));
    var first= {id:"tt3783958", title:"La La Land", year:"2016", type:"Comedy, Drama, Music"}
        myMovie.push(first);

I can't figure out what I'm I doing it wrong here.

Body:
Best would be a function, that not only changes the array but also stores it in localStorage:

    var myMovie=[] //JSON.parse(localStorage.getItem('myMovie')||"[]");

    function push(el){
    myMovie.push(el);
    //localStorage.setItem('myMovie', JSON.stringify(myMovie));
    }

    function remove(title){
     var i=myMovie.findIndex(movie=>movie.title===title);
     if(i!==-1){
       myMovie.splice(i,1);
       //localStorage.setItem('myMovie', JSON.stringify(myMovie));
     }
    }

    push({id:"tt3783958", title:"La La Land", year:"2016", type:"Comedy, Drama, Music"});
    console.log(myMovie);
    remove("La La Land");
    console.log(myMovie);

To make a running stackSnippet, i had to remove the localStorage functionality, it is commented out.


问:
How to have Chrome show true image size?
I can't seem to have Chrome browser show the true image size via
and also by drawImage via canvas context. Explorer shows both of these
correctly.

In Chrome, the image shown is not by the dimensions of the original image
but a scaled down one. The browser when rendered from a Web server seems to
have something to do with it.  Curiously enough, when open the browser on
the html file locally:

E.g. file:///C:/xampp/htdocs/Website_TEST_active/test1.html, the image dimensions are correct.

Attached is a stripped down HTML and Javascript code. Appreciate any insights.

Thanks
Sean

```<code><!DOCTYPE html>
    <html>
        <body>
            <p>Image to use:</p>
            <img id="scream" onload="loadImage()" src="pics/cover.jpg" alt="Test">
            <p>Canvas:</p>
            <canvas id="myCanvas" width="854" height="480" style="border:1px solid #d3d3d3;">
                Your browser does not support the HTML5 canvas tag.
            </canvas>
        <script>
            window.onload = function() {
                // Not used
            }
            /*
            * Upon image load, draw image on canvas
            */
            function loadImage(){
                var c = document.getElementById("myCanvas");
                var ctx = c.getContext("2d");
                var img = document.getElementById("scream");
                ctx.drawImage(img, 0,0, img.naturalWidth, img.naturalHeight);
                console.log("Original Image W=" + img.naturalWidth +
                            " H=" + img.naturalHeight);
            }
        </script>
    </body>
</html>
</code>```

答:
I found something that might be right for what you're asking.

Here's the link- https://superuser.com/a/364875

Open Developer tools (Ctrl+Shift+I or use the Settings Icon at the
  top-right of your browser window => Tools => Developer tools) and on
  the relevant page, switch to the Network tab and reload the page.

  In the Size column you'll see the size of everything loaded
  (Documents, Stylesheets, Images, Scripts, ...). You can enable a
  filter to help you find out what you need - at the bottom-center of
  Developer tools frame.

Body:
I can't seem to have Chrome browser show the true image size via
and also by drawImage via canvas context. Explorer shows both of these
correctly.

In Chrome, the image shown is not by the dimensions of the original image
but a scaled down one. The browser when rendered from a Web server seems to
have something to do with it.  Curiously enough, when open the browser on
the html file locally:

E.g. file:///C:/xampp/htdocs/Website_TEST_active/test1.html, the image dimensions are correct.

Attached is a stripped down HTML and Javascript code. Appreciate any insights.

Thanks
Sean

<!DOCTYPE html>

Image to use:

Canvas:

            <canvas id="myCanvas" width="854" height="480" style="border:1px solid #d3d3d3;">
                Your browser does not support the HTML5 canvas tag.
            </canvas>


问:
Refresh Token for Google Api Php Client
I am using the Google API Client to access Google Analytics. I want to access the data in offline mode, so I need a refresh token. How do I get a refresh_token?</p>

答:
For PHP SDK of Google Client v2:

```<code>php composer.phar require google/apiclient:^2.0
</code>```

You can try the PHP code to refresh accessToken as following:

```<code><?php

require_once __DIR__ . '/vendor/autoload.php';

define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
define('SCOPES', implode(' ', array(
  Google_Service_Analytics::ANALYTICS_READONLY)
));

$client = new Google_Client();
$client->setApplicationName('YOUR APPLICATION NAME');
$client->setScopes(SCOPES);
$client->setAuthConfig(CLIENT_SECRET_PATH);
$client->setAccessType('offline');

// Input AccessToken from such as session or database
$accessToken = json_decode('YOUR CURRENT ACEESS TOKEN');

$client->setAccessToken($accessToken);

// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    // Get RefreshToken as json which can be reused
    $refreshToken = json_encode($client->getAccessToken());
}
</code>```

Offline access issue

In addition, if you want to keep the existing behavior in your server-side applications, you need to set approval_prompt to force, otherwise you may get NULL returned from getRefreshToken(), which Google document doesn't mention:

```<code>$client->setApprovalPrompt('force');
</code>```

Referring Upcoming changes to OAuth 2.0 endpoint

Title: Refresh Token for Google Api Php Client

Body:
For PHP SDK of Google Client v2:

php composer.phar require google/apiclient:^2.0

You can try the PHP code to refresh accessToken as following:

<?php

require_once __DIR__ . '/vendor/autoload.php';

define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
define('SCOPES', implode(' ', array(
  Google_Service_Analytics::ANALYTICS_READONLY)
));

$client = new Google_Client();
$client->setApplicationName('YOUR APPLICATION NAME');
$client->setScopes(SCOPES);
$client->setAuthConfig(CLIENT_SECRET_PATH);
$client->setAccessType('offline');

// Input AccessToken from such as session or database
$accessToken = json_decode('YOUR CURRENT ACEESS TOKEN');

$client->setAccessToken($accessToken);

// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    // Get RefreshToken as json which can be reused
    $refreshToken = json_encode($client->getAccessToken());
}

Offline access issue

In addition, if you want to keep the existing behavior in your server-side applications, you need to set approval_prompt to force, otherwise you may get NULL returned from getRefreshToken(), which Google document doesn't mention:

$client->setApprovalPrompt('force');

Referring Upcoming changes to OAuth 2.0 endpoint


问:
React Native: How to disable PanResponder temporarily?
Below is the snippet for creating an instance of the panResponder:

```<code>  constructor( props ) {
    super( props );

    this.position = new Animated.ValueXY();

    this.panResponder = PanResponder.create( {
      onStartShouldSetPanResponder: ( ) => true,
      onPanResponderMove: ( event, gesture ) => {
        this.position.setValue( { x: 0, y: gesture.dy } );
      },
      onPanResponderRelease: ( event, gesture ) => {
        if ( gesture.dy > SWIPE_THRESHOLD ) {
          this.forceSwipe( 'up' );
        } else if ( gesture.dy < -SWIPE_THRESHOLD ) {
          this.forceSwipe( 'down' );
        } else {
          this.resetPosition();
        }
      },
      onMoveShouldSetPanResponderCapture: ( evt, gestureState ) =>
      gestureState.dx !== 0 && gestureState.dy !== 0,
    } );
  }

  getCardStyle() {
    return {
      ...this.position.getLayout(),
    };
  }
</code>```

Below is the code snippet of my Component:

```<code><Animated.View
   key={ item.id }
   style={ [ this.getCardStyle(), styles.cardStyle ] }
   { ...this.panResponder.panHandlers }
>
  <Card
    shouldPanRespond={ this.shouldPanRespond }
     item={ item }
  />
</Animated.View>
</code>```

Code snippet for card component:

```<code>  <TouchableOpacity
    activeOpacity={ 1 }
    style={ cardStyle }
    onPress={ this.onPress }
  >
    <ScrollView contentContainerStyle={ cardStyle }>
      <Image
        resizeMode="cover"
        style={ imageStyle }
        source={ { uri: img_url } }
      />

      <View style={ titleWrapStyle }>
        <Text style={ textStyle }>{ title }</Text>
      </View>
    </ScrollView>
  </TouchableOpacity>
</code>```

I am building cards that are absolutely positioned one behind another. These cards can then be swiped up or down using the panResponder. But, on tapping the screen I am supposed to show a detail page on the same screen.

Now, I can detect the tap, but whenever the user taps/clicks, I want to disable the panResponder so that the card cannot be swiped and the user can scroll through the content. Once, the user scrolls to the end, I want to re-enable swiping i.e I want to enable panning.

I know that onStartShouldSetResponder: () => false disables panResponder but how do we disable it after an instance is created. I couldn't find much about it else where.

答:
For someone who will be looking how to temporarily disable PanResponder, below is my solution.

Like @RaHuL - House Javascript noticed, the other answer doesn't really solve the problem because setting onStartShouldSetResponder to value corresponding to some state value which might change from true to false won't affect PanResponder (at least it seems so) if it was created with true.

I solved similar problem by changing onPanResponderMove function. I have a value inside state: panResponderEnabled and my function looks like this:

```<code> onPanResponderMove: ( event, gesture ) => {
    if(this.state.panResponderEnabled){
       this.position.setValue( { x: 0, y: gesture.dy } );
    }
}
</code>```

When I don't want to read changes from PanRespoder I just set panResponderEnabled to false.

Body:
Below is the snippet for creating an instance of the panResponder:

  constructor( props ) {
    super( props );

    this.position = new Animated.ValueXY();

    this.panResponder = PanResponder.create( {
      onStartShouldSetPanResponder: ( ) => true,
      onPanResponderMove: ( event, gesture ) => {
        this.position.setValue( { x: 0, y: gesture.dy } );
      },
      onPanResponderRelease: ( event, gesture ) => {
        if ( gesture.dy > SWIPE_THRESHOLD ) {
          this.forceSwipe( 'up' );
        } else if ( gesture.dy < -SWIPE_THRESHOLD ) {
          this.forceSwipe( 'down' );
        } else {
          this.resetPosition();
        }
      },
      onMoveShouldSetPanResponderCapture: ( evt, gestureState ) =>
      gestureState.dx !== 0 && gestureState.dy !== 0,
    } );
  }

  getCardStyle() {
    return {
      ...this.position.getLayout(),
    };
  }

Below is the code snippet of my Component:

<Animated.View
   key={ item.id }
   style={ [ this.getCardStyle(), styles.cardStyle ] }
   { ...this.panResponder.panHandlers }
>
  <Card
    shouldPanRespond={ this.shouldPanRespond }
     item={ item }
  />
</Animated.View>

Code snippet for card component:

  <TouchableOpacity
    activeOpacity={ 1 }
    style={ cardStyle }
    onPress={ this.onPress }
  >
    <ScrollView contentContainerStyle={ cardStyle }>
      <Image
        resizeMode="cover"
        style={ imageStyle }
        source={ { uri: img_url } }
      />

      <View style={ titleWrapStyle }>
        <Text style={ textStyle }>{ title }</Text>
      </View>
    </ScrollView>
  </TouchableOpacity>

I am building cards that are absolutely positioned one behind another. These cards can then be swiped up or down using the panResponder. But, on tapping the screen I am supposed to show a detail page on the same screen.

Now, I can detect the tap, but whenever the user taps/clicks, I want to disable the panResponder so that the card cannot be swiped and the user can scroll through the content. Once, the user scrolls to the end, I want to re-enable swiping i.e I want to enable panning.

I know that onStartShouldSetResponder: () => false disables panResponder but how do we disable it after an instance is created. I couldn't find much about it else where.

Body:
For someone who will be looking how to temporarily disable PanResponder, below is my solution.

Like @RaHuL - House Javascript noticed, the other answer doesn't really solve the problem because setting onStartShouldSetResponder to value corresponding to some state value which might change from true to false won't affect PanResponder (at least it seems so) if it was created with true.

I solved similar problem by changing onPanResponderMove function. I have a value inside state: panResponderEnabled and my function looks like this:

 onPanResponderMove: ( event, gesture ) => {
    if(this.state.panResponderEnabled){
       this.position.setValue( { x: 0, y: gesture.dy } );
    }
}

When I don't want to read changes from PanRespoder I just set panResponderEnabled to false.


问:
Xcode 7.3.1 - SVN : Couldn't communicate with a helper application
Using Xcode 7.3.1, I get the following error when trying to commit any changes to my project which is under SVN source control

"The working copy "ProjectName" failed to commit files.
Couldn't communicate with a helper application"

My guess would be it's failing to locate / execute the "svn" binary under the hood, but it does seem strange that other SVN actions in Xcode work fine (Source Control -> History... happily shows all previous commits etc, which would suggest it is able to communicate with the SVN server just fine)

There are other similar problems to this on the site, but all are either related to Git projects or are unanswered

答:
We got this problem when adding a new localization. We are using xCode 8.2.1

We found that the graphics files with a @ character in them caused the problem. SVN doesn't like @. When you do an SVN operation on a file with a @ in its name you have to add another @ at the end of the command. Seemingly xCode is not taking this into consideration when interacting with SVN.

The workaround for this is to temporarily move  your .svn file from your project directory, do the work in xCode, then move your .svn file back and manually update SVN using the non-xCode interface of your choice.


问:
Error: could not find function "%>%"
I'm running an example in R, going through the steps and everything is working so far except for this code produces an error:

```<code> words <- dtm %>%
 as.matrix %>%
 colnames %>%
 (function(x) x[nchar(x) < 20])
</code>```

Error: could not find function "%>%"

I don't understand what the benefit of using this special operator
%>% is, and any feedback would be great.

答:
On Windows: if you use %>% inside a %dopar% loop, you have to add a reference to load package dplyr (or magrittr, which dplyr loads).

Example:

```<code>plots <- foreach(myInput=iterators::iter(plotCount), .packages=c("RODBC", "dplyr")) %dopar%
{
    return(getPlot(myInput))
}
</code>```

If you omit the .packages command, and use %do% instead to make it all run in a single process, then works fine. The reason is that it all runs in one process, so it doesn't need to specifically load new packages.

Title: Error: could not find function "%>%"

Body:
I'm running an example in R, going through the steps and everything is working so far except for this code produces an error:

 words <- dtm %>%
 as.matrix %>%
 colnames %>%
 (function(x) x[nchar(x) < 20])

Error: could not find function "%>%"

I don't understand what the benefit of using this special operator
%>% is, and any feedback would be great.

Body:
On Windows: if you use %>% inside a %dopar% loop, you have to add a reference to load package dplyr (or magrittr, which dplyr loads).

Example:

plots <- foreach(myInput=iterators::iter(plotCount), .packages=c("RODBC", "dplyr")) %dopar%
{
    return(getPlot(myInput))
}

If you omit the .packages command, and use %do% instead to make it all run in a single process, then works fine. The reason is that it all runs in one process, so it doesn't need to specifically load new packages.


问:
Match multiple patterns in Logstash?
I have two types of error messages in the below format:

```<code>[2017-05-25 01:00:00,647][ERROR][marvel.agent.exporter.local] local exporter [default_local] - failed to delete indices
RemoteTransportException[[data-0][10.0.0.8:9300][indices:admin/delete]]; nested: IndexNotFoundException[no such index];

[2017-05-18 00:00:06,339][DEBUG][action.admin.indices.create] [data-2] [data-may-2017,data-apr-2017,data-mar-2017] failed to create
[data-may-2017,data-apr-2017,data-mar-2017]
</code>```

My logstash configuration is like this:

```<code>input {
      file {
            path => "D:\logstash\logstash-2.4.0\bin\logs.txt"
            start_position => "beginning"
        codec => multiline {
            pattern => "^\[%{TIMESTAMP_ISO8601:TIMESTAMP}\]"
            negate => true
            what => "previous"
        }
  }

}
filter {
   grok {
        match => [ "message", "(?m)^\[%{TIMESTAMP_ISO8601:TIMESTAMP}\]\[%{LOGLEVEL:LEVEL}%{SPACE}\]\[%{DATA:ERRORTYPE}\]%{SPACE}\[%{DATA:SERVERNAME}\]%{SPACE}(?<ERRORMESSAGE>(.|\r|\n)*)", "message",  "(?m)^\[%{TIMESTAMP_ISO8601:TIMESTAMP}\]\[%{LOGLEVEL:LEVEL}%{SPACE}\]\[%{DATA:ERRORTYPE}%{SPACE}\]%{SPACE}(?<ERRORMESSAGE>(.|\r|\n)*)"]
   }

}
output {

  stdout { codec => rubydebug }
}
</code>```

For Both the logs it is taking only the first grok pattern. Why it is not taking the second one?

答:
Your question was:

Why it is not taking the second one?

Answer is here:

```<code>filter {
   grok {
        match => [ "message", "(?m)^\[%{TIMESTAMP_ISO8601:TIMESTAMP}\]\[%{LOGLEVEL:LEVEL}%{SPACE}\]\[%{DATA:ERRORTYPE}\]%{SPACE}\[%{DATA:SERVERNAME}\]%{SPACE}(?<ERRORMESSAGE>(.|\r|\n)*)", "message",  "(?m)^\[%{TIMESTAMP_ISO8601:TIMESTAMP}\]\[%{LOGLEVEL:LEVEL}%{SPACE}\]\[%{DATA:ERRORTYPE}%{SPACE}\]%{SPACE}(?<ERRORMESSAGE>(.|\r|\n)*)"]
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------^
   }

}
</code>```

You don't have to specify source multiple times, just once.

What you did now was:

```<code>["message", "pattern", "message", "pattern"]
</code>```

While in reality it has to be:

```<code>["message", "pattern", "pattern", ..., "pattern"]
</code>```

Title: Match multiple patterns in Logstash?

Body:
I have two types of error messages in the below format:

[2017-05-25 01:00:00,647][ERROR][marvel.agent.exporter.local] local exporter [default_local] - failed to delete indices
RemoteTransportException[[data-0][10.0.0.8:9300][indices:admin/delete]]; nested: IndexNotFoundException[no such index];

[2017-05-18 00:00:06,339][DEBUG][action.admin.indices.create] [data-2] [data-may-2017,data-apr-2017,data-mar-2017] failed to create
[data-may-2017,data-apr-2017,data-mar-2017]

My logstash configuration is like this:

input {
      file {
            path => "D:\logstash\logstash-2.4.0\bin\logs.txt"
            start_position => "beginning"
        codec => multiline {
            pattern => "^\[%{TIMESTAMP_ISO8601:TIMESTAMP}\]"
            negate => true
            what => "previous"
        }
  }

}
filter {
   grok {
        match => [ "message", "(?m)^\[%{TIMESTAMP_ISO8601:TIMESTAMP}\]\[%{LOGLEVEL:LEVEL}%{SPACE}\]\[%{DATA:ERRORTYPE}\]%{SPACE}\[%{DATA:SERVERNAME}\]%{SPACE}(?<ERRORMESSAGE>(.|\r|\n)*)", "message",  "(?m)^\[%{TIMESTAMP_ISO8601:TIMESTAMP}\]\[%{LOGLEVEL:LEVEL}%{SPACE}\]\[%{DATA:ERRORTYPE}%{SPACE}\]%{SPACE}(?<ERRORMESSAGE>(.|\r|\n)*)"]
   }

}
output {

  stdout { codec => rubydebug }
}

For Both the logs it is taking only the first grok pattern. Why it is not taking the second one?

Body:
Your question was:

Why it is not taking the second one?

Answer is here:

filter {
   grok {
        match => [ "message", "(?m)^\[%{TIMESTAMP_ISO8601:TIMESTAMP}\]\[%{LOGLEVEL:LEVEL}%{SPACE}\]\[%{DATA:ERRORTYPE}\]%{SPACE}\[%{DATA:SERVERNAME}\]%{SPACE}(?<ERRORMESSAGE>(.|\r|\n)*)", "message",  "(?m)^\[%{TIMESTAMP_ISO8601:TIMESTAMP}\]\[%{LOGLEVEL:LEVEL}%{SPACE}\]\[%{DATA:ERRORTYPE}%{SPACE}\]%{SPACE}(?<ERRORMESSAGE>(.|\r|\n)*)"]
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------^
   }

}

You don't have to specify source multiple times, just once.

What you did now was:

["message", "pattern", "message", "pattern"]

While in reality it has to be:

["message", "pattern", "pattern", ..., "pattern"]