问:
how to send by ajax a pdf file autogenerated
I generated a pdf object with jsPDF. I want to send mail with PDF attached by AJAX, but I can't send the file correctly. I try to convert in Blob object to send and later in PHP I try to decode to base64 for can be sent by mail, but when I receive mail I receive blob file without extension.

1.- I create PDF object:

```<code>var pdf = new jsPDF(); // new pdf object
pdf.text("Table title", 14, 16); // text line
var elem = $(".tableSample")[0]; // node -> html to pdf
var res = pdf.autoTableHtmlToJson(elem); // lib to transform htmlTables to pdf
pdf.autoTable(res.columns, res.data, {startY: 20}); // lib to transform htmlTables to pdf

var outputBase64 = pdf.output('datauristring');
var blob = new Blob([outputBase64], { type: "application/pdf"});
</code>```

2.- I Call to my function Ajax:

```<code>ajaxAdjunto({
    controler : "ctInformes2.php",
    method : "enviarInforme",
    attached : blob,
    paramValid : {
        mailText : "This is the mail body",
        mailAsunto : "Este es el asunto",
        mailDest : "mailTo@mailTo.com"
    },
    callbackSucces : function (backParam) { },
    callbackError : function (err) {  }
});
</code>```

3.- My function Ajax is prepared for send with attachments with FormData object:

```<code>function ajaxAdjunto(objParam){
url = "./controller/"+objParam.controler+"?metodo="+objParam.method;
param = new FormData();
//Add to FormData mail text
for (var item in objParam.paramValid){
    if (item == ""){
        param.append(item , "null");
    }else{
        param.append(item , objParam.paramValid[item ]);
    }
}
//Add to FormData file
param.append("adjunto", objParam.attached);
//Call Ajax
$.ajax({
    data: param,
    type: "POST",
    url: url,
    cache: false,
    contentType: false,
    processData: false,
    success: function (backParam) {
        objParam.callbackSucces(backParam, objParam);
        },
    error: function (xhr){
        if ( objParam.callbackError ){
            objParam.callbackError(xhr);
        }else{
            alerta(xhr.statusText);
            console.log(xhr);
        }
    }
});
}
</code>```

PHP CODE - ( I remove other $body content and mail headers for this sample )

```<code>// var_dump -> $_FILES['attached']
array (size=5)
    'name' => string 'blob' (length=4)
    'type' => string 'application/pdf' (length=15)
    'tmp_name' => string 'C:\Windows\Temp\php9593.tmp' (length=27)
    'error' => int 0
    'size' => int 6328

// PHP CODE
if ( count($_FILES) > 0 ){
    $nameFile = $_FILES['attached ']['name'];
    $sizeFile = $_FILES['attached ']['size'];
    $typeFile = $_FILES['attached ']['type'];
    $tempFile = $_FILES["attached "]["tmp_name"];

    $body .= "--=C=T=E=C=\r\n"; // delimiter
    $body .= "Content-Type: application/octet-stream; ";
    $body .= "name=" . $nameFile . "\r\n";
    $body .= "Content-Transfer-Encoding: base64\r\n";
    $body .= "Content-Disposition: attachment; ";
    $body .= "filename=" . $nameFile . "\r\n";
    $body .= "\r\n"; // empty line

    $fp = fopen($tempFile, "rb");
    $file = fread($fp, $sizeFile);
    $file = chunk_split(base64_encode($file));

    $body .= "$file\r\n";
    $body .= "\r\n"; // empty line
}
    $body .= "--=C=T=E=C=--\r\n"; // delimiter end mail

//Send mail
if(mail($mailTo, $subject, $body, $header)){
    echo "mail was sent";
}else{
    echo "error when try send mail";
}
</code>```

答:
The solution is in point 1:

1º - Add this function

```<code>function dataURItoBlob(dataURI) {
    // convert base64/URLEncoded data component to raw binary data held in a string
    var byteString;
    if (dataURI.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(dataURI.split(',')[1]);
    else
        byteString = unescape(dataURI.split(',')[1]);

    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    // write the bytes of the string to a typed array
    var ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    return new Blob([ia], {type:mimeString});
}
</code>```

2º - In point 1 when i create pfd I change this:

```<code>var outputBase64 = pdf.output('datauristring');
var blob = new Blob([outputBase64], { type: "application/pdf"});
</code>```

for this:

```<code>var outputBase64 = pdf.output('datauristring');
var preBlob = dataURItoBlob(outputBase64 );
var file = new File([preBlob], "namefile.pdf", {type: 'application/pdf'});
</code>```

3º - ENJOY!

Body:
I generated a pdf object with jsPDF. I want to send mail with PDF attached by AJAX, but I can't send the file correctly. I try to convert in Blob object to send and later in PHP I try to decode to base64 for can be sent by mail, but when I receive mail I receive blob file without extension.

1.- I create PDF object:

var pdf = new jsPDF(); // new pdf object
pdf.text("Table title", 14, 16); // text line
var elem = $(".tableSample")[0]; // node -> html to pdf
var res = pdf.autoTableHtmlToJson(elem); // lib to transform htmlTables to pdf
pdf.autoTable(res.columns, res.data, {startY: 20}); // lib to transform htmlTables to pdf

var outputBase64 = pdf.output('datauristring');
var blob = new Blob([outputBase64], { type: "application/pdf"});

2.- I Call to my function Ajax:

ajaxAdjunto({
    controler : "ctInformes2.php",
    method : "enviarInforme",
    attached : blob,
    paramValid : {
        mailText : "This is the mail body",
        mailAsunto : "Este es el asunto",
        mailDest : "mailTo@mailTo.com"
    },
    callbackSucces : function (backParam) { },
    callbackError : function (err) {  }
});

3.- My function Ajax is prepared for send with attachments with FormData object:

function ajaxAdjunto(objParam){
url = "./controller/"+objParam.controler+"?metodo="+objParam.method;
param = new FormData();
//Add to FormData mail text
for (var item in objParam.paramValid){
    if (item == ""){
        param.append(item , "null");
    }else{
        param.append(item , objParam.paramValid[item ]);
    }
}
//Add to FormData file
param.append("adjunto", objParam.attached);
//Call Ajax
$.ajax({
    data: param,
    type: "POST",
    url: url,
    cache: false,
    contentType: false,
    processData: false,
    success: function (backParam) {
        objParam.callbackSucces(backParam, objParam);
        },
    error: function (xhr){
        if ( objParam.callbackError ){
            objParam.callbackError(xhr);
        }else{
            alerta(xhr.statusText);
            console.log(xhr);
        }
    }
});
}

PHP CODE - ( I remove other $body content and mail headers for this sample )

// var_dump -> $_FILES['attached']
array (size=5)
    'name' => string 'blob' (length=4)
    'type' => string 'application/pdf' (length=15)
    'tmp_name' => string 'C:\Windows\Temp\php9593.tmp' (length=27)
    'error' => int 0
    'size' => int 6328

// PHP CODE
if ( count($_FILES) > 0 ){
    $nameFile = $_FILES['attached ']['name'];
    $sizeFile = $_FILES['attached ']['size'];
    $typeFile = $_FILES['attached ']['type'];
    $tempFile = $_FILES["attached "]["tmp_name"];

    $body .= "--=C=T=E=C=\r\n"; // delimiter
    $body .= "Content-Type: application/octet-stream; ";
    $body .= "name=" . $nameFile . "\r\n";
    $body .= "Content-Transfer-Encoding: base64\r\n";
    $body .= "Content-Disposition: attachment; ";
    $body .= "filename=" . $nameFile . "\r\n";
    $body .= "\r\n"; // empty line

    $fp = fopen($tempFile, "rb");
    $file = fread($fp, $sizeFile);
    $file = chunk_split(base64_encode($file));

    $body .= "$file\r\n";
    $body .= "\r\n"; // empty line
}
    $body .= "--=C=T=E=C=--\r\n"; // delimiter end mail

//Send mail
if(mail($mailTo, $subject, $body, $header)){
    echo "mail was sent";
}else{
    echo "error when try send mail";
}

Body:
The solution is in point 1:

1º - Add this function

function dataURItoBlob(dataURI) {
    // convert base64/URLEncoded data component to raw binary data held in a string
    var byteString;
    if (dataURI.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(dataURI.split(',')[1]);
    else
        byteString = unescape(dataURI.split(',')[1]);

    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    // write the bytes of the string to a typed array
    var ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    return new Blob([ia], {type:mimeString});
}

2º - In point 1 when i create pfd I change this:

var outputBase64 = pdf.output('datauristring');
var blob = new Blob([outputBase64], { type: "application/pdf"});

for this:

var outputBase64 = pdf.output('datauristring');
var preBlob = dataURItoBlob(outputBase64 );
var file = new File([preBlob], "namefile.pdf", {type: 'application/pdf'});

3º - ENJOY!


来源: stackexchange

问:
Unexpected error while executing
I searched for this question already but there were no answers that worked for me. Every time I debug my app it gives me this error.

```<code>Unexpected error while executing: am start -n "com.example.maomei.passusersystem/com.example.maomei.passusersystem.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -D
Error while Launching activity
</code>```

Here is my MainActivity code:

```<code>public class MainActivity extends AppCompatActivity {

    TextView textView1;
    Button button1;

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

        TextView textView1 = (TextView) findViewById(R.id.textView1);
        Button button1 = (Button) findViewById(R.id.button1);

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()){
                    case R.id.button1:

                        Intent myIntent = new Intent(MainActivity.this, Main2Activity.class);
                        MainActivity.this.startActivity(myIntent);

                    }

            }

        });
    }
}
</code>```

and my Manifest code:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.maomei.passusersystem">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name="com.example.maomei.passusersystem.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Main2Activity"
            android:label="@string/title_activity_main2"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".Main4Activity"
            android:label="@string/title_activity_main4"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".Main5Activity"
            android:label="@string/title_activity_main5"
            android:theme="@style/AppTheme.NoActionBar">

        </activity>
    </application>
</manifest>
</code>```

答:
Mira, I just created a new android app using empty activity template, added 1 more activity for checking and below are files that have same code as yours but doesn't have any error.

Only difference is my manifest file has manifest tag which is not present in yours.

Delete the project, recreate the project and copy paste your code safely to the newly generated project.

Manifest file

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.maomei.passusersystem">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

MainActivity class

```<code>package com.example.maomei.passusersystem;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    TextView textView1;
    Button button1;

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

        TextView textView1 = (TextView) findViewById(R.id.textView1);
        Button button1 = (Button) findViewById(R.id.button1);

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()){
                    case R.id.button1:

                        Intent myIntent = new Intent(MainActivity.this, Main2Activity.class);
                        MainActivity.this.startActivity(myIntent);

                }

            }

        });
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Unexpected error while executing

Body:
I searched for this question already but there were no answers that worked for me. Every time I debug my app it gives me this error.

Unexpected error while executing: am start -n "com.example.maomei.passusersystem/com.example.maomei.passusersystem.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -D
Error while Launching activity

Here is my MainActivity code:

public class MainActivity extends AppCompatActivity {

    TextView textView1;
    Button button1;

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

        TextView textView1 = (TextView) findViewById(R.id.textView1);
        Button button1 = (Button) findViewById(R.id.button1);

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()){
                    case R.id.button1:

                        Intent myIntent = new Intent(MainActivity.this, Main2Activity.class);
                        MainActivity.this.startActivity(myIntent);

                    }

            }

        });
    }
}

and my Manifest code:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.maomei.passusersystem">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name="com.example.maomei.passusersystem.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Main2Activity"
            android:label="@string/title_activity_main2"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".Main4Activity"
            android:label="@string/title_activity_main4"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".Main5Activity"
            android:label="@string/title_activity_main5"
            android:theme="@style/AppTheme.NoActionBar">

        </activity>
    </application>
</manifest>

Body:
Mira, I just created a new android app using empty activity template, added 1 more activity for checking and below are files that have same code as yours but doesn't have any error.

Only difference is my manifest file has manifest tag which is not present in yours.

Delete the project, recreate the project and copy paste your code safely to the newly generated project.

Manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.maomei.passusersystem">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

MainActivity class

package com.example.maomei.passusersystem;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    TextView textView1;
    Button button1;

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

        TextView textView1 = (TextView) findViewById(R.id.textView1);
        Button button1 = (Button) findViewById(R.id.button1);

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()){
                    case R.id.button1:

                        Intent myIntent = new Intent(MainActivity.this, Main2Activity.class);
                        MainActivity.this.startActivity(myIntent);

                }

            }

        });
    }
}


问:
Haskell function definition not working as expected
I am new to functional programming and Haskell. Trying to learn it. Not sure what is wrong with the following definition:

Function definition in test.h

```<code>drop5 [a]  = drop 5 [a]
</code>```

Trying to use this function I get Program error

```<code>$:load test.h
$drop5 [2,3,4,5,6,7,8]
Program error: pattern match failure: drop5 [2,3,4,5,6,7,8]
$:t drop5
drop5 :: [a] -> [a]
</code>```

When I change the definition to following it works; meaning it takes a list and drops first 5 elements of the list

```<code>drop5 ns = drop 5 ns
</code>```

And in this case when print type I see:

```<code>$:t drop5
drop5 :: [a] -> [a]
</code>```

I am not sure why is the first definition different than second? And what does the error "Program error: pattern match failure means"?

答:
In the first definition, [a] is a pattern that only matches a list of exactly one element, and that element becomes known as a in the right part of the rule.

Thus, you define the function as only accepting singleton lists.

Moreover, dropping 5 elements from a list that only has one obviously results in an empty list (as does dropping of any positive number of elements).

Body:
I am new to functional programming and Haskell. Trying to learn it. Not sure what is wrong with the following definition:

Function definition in test.h

drop5 [a]  = drop 5 [a]

Trying to use this function I get Program error

$:load test.h
$drop5 [2,3,4,5,6,7,8]
Program error: pattern match failure: drop5 [2,3,4,5,6,7,8]
$:t drop5
drop5 :: [a] -> [a]

When I change the definition to following it works; meaning it takes a list and drops first 5 elements of the list

drop5 ns = drop 5 ns

And in this case when print type I see:

$:t drop5
drop5 :: [a] -> [a]

I am not sure why is the first definition different than second? And what does the error "Program error: pattern match failure means"?


问:
Create a background color on a breaking inline element
In a website I'm coding, the designer wishes to have ragged-right text with a background color (over a photo). The design prescribes some padding on both the left and the right side and also a well balanced background: all background "blocks" have the same height and stack tightly on top of each other. The following image shows an example.

Searching for solutions for this, it turned out that this design has two distinct challenges:

Make sure that any left and right padding are applied to all lines; and

Make sure that the vertical spacing is perfect.

Challenge 1 can be solved using some css-tricks on multi-line-padded-text. This has also been discussed here on SO on several Q&A's: span background-color & padding problems, CSS create padding before line-break, to link some.

Challenge 2 is a bit trickier and is also related to the box-shadow-solution for the left and right padding on all lines.

First on this last point: even after carefully setting top and bottom padding to the text, I notice subtle errors (in Firefox, which is definitely one of the targeted browsers):

These subtle lines may also occur between (some of) the lines upon zooming. This would be indicative of a non-exact line-height (thus padding). However, setting the vertical padding too much (to be on the safe side) also has problems:

I used a semi-transparent background (and box-shadow) here to highlight the issues. First, the solution will not work for cases where transparency is needed. And second: the background "blocks" are not anymore of equal height (e.g. the gap between lines 2 and 4 is much narrower than line 4).

It turns out that there exists an inherent problem with setting the right padding: it cannot be predicted exactly how high the actual line-height is (i.e. not without digging very deep into the internals of the font metrics). Especially in cases where the font used is not predictable (which is common on the web).

So the question is, how to add a background-color to a flowing piece of text, having it properly left and right padded, and having the lines to stack exactly on top of each other?

Some caveats:

Setting display: inline-block is a no-no: it will create a rectangular background.

The afore-mentioned solutions work "a bit", which is not enough. They have their issues, as illustrated.

Obviously, I am looking for a css-only solution, NOT javascript.

Of course, the text used is server-generated and can change.

I have found one solution which works for me: using a background image of the right color, which can be scaled to exactly one line-height. I will submit this self-answer. Although I do like the hack, I am still open for other suggestions.

答:
    Lorem ipsum dolor sit amet ...
    Sed ultrices, leo eu porta mattis ...

```

<pre class="lang-css prettyprint-override"><code>p {
    width: 30em; /* as needed */
    font-size: 12px;
    line-height: 2;
}
span {
    padding: 0.6em 0.5em;
    background-image: url(data:image/gif;base64,R0lGODdhAQABAIABAFVVVf///ywAAAAAAQABAAACAkQBADs=);
    -webkit-box-decoration-break: clone;
    -ms-box-decoration-break: clone;
    -o-box-decoration-break: clone;
    box-decoration-break: clone;
    background-repeat: repeat-x;
    background-size: 1px 2em ;
    background-position: center;
}
</code>```

Notice that I did not specify a font-family: font metrics are now not an issue anymore. Also, any font-size can be used. It is important to match the line-height to the settings for the span (see below), but this is also 'free'. It's even possible to use line heights lower than normal, although ascenders and descenders may of course extend from the background in that case.

The actual trick is specifying a background image and setting its height exactly equal to the line height (2em in this example). For this, I use a single-pixel gif image that I crafted in the Gimp. The string in the data-uri is just the base-64 encoded content of the gif file (of 35 bytes). This gif is then expanded to the desired height using background-size and setting background-repeat: repeat-x makes sure that the width is set properly. Not setting vertical repeating allows us to set an imprecise amount of vertical padding (see below). background-position: center takes care of properly aligning the text to the background vertically.

The vertical padding is another part of the trick: set it high enough so that the padding (both top and bottom) plus the line-box height exceed the line height. 0.5em should have been enough, but I'm using 0.6em here to be on the safe side (and it distinguishes nicely from the 0.5em horizontal value). Since there is no background-color, everything outside the background-image is transparent! (if the span inherits some background-color, just override it to be transparent)

The horizontal padding (0.5em here), together with the box-decoration-break: clone setting (also with prefixes, although I do not know which are actually needed) takes care of the left and right padding, also setting it equal for all lines.

For semi-transparent backgrounds, a dito png-image will work instead of the gif. I chose a gif here because of the file size. The image can also be loaded separately, but using the data-uri saves a http-request (which would be way more than the current 70 bytes and take a long time).

Body:
<p>
    <span>Lorem ipsum dolor sit amet ...</span>
    <span>Sed ultrices, leo eu porta mattis ...</span>
</p>

p {
    width: 30em; /* as needed */
    font-size: 12px;
    line-height: 2;
}
span {
    padding: 0.6em 0.5em;
    background-image: url(data:image/gif;base64,R0lGODdhAQABAIABAFVVVf///ywAAAAAAQABAAACAkQBADs=);
    -webkit-box-decoration-break: clone;
    -ms-box-decoration-break: clone;
    -o-box-decoration-break: clone;
    box-decoration-break: clone;
    background-repeat: repeat-x;
    background-size: 1px 2em ;
    background-position: center;
}

Notice that I did not specify a font-family: font metrics are now not an issue anymore. Also, any font-size can be used. It is important to match the line-height to the settings for the span (see below), but this is also 'free'. It's even possible to use line heights lower than normal, although ascenders and descenders may of course extend from the background in that case.

The actual trick is specifying a background image and setting its height exactly equal to the line height (2em in this example). For this, I use a single-pixel gif image that I crafted in the Gimp. The string in the data-uri is just the base-64 encoded content of the gif file (of 35 bytes). This gif is then expanded to the desired height using background-size and setting background-repeat: repeat-x makes sure that the width is set properly. Not setting vertical repeating allows us to set an imprecise amount of vertical padding (see below). background-position: center takes care of properly aligning the text to the background vertically.

The vertical padding is another part of the trick: set it high enough so that the padding (both top and bottom) plus the line-box height exceed the line height. 0.5em should have been enough, but I'm using 0.6em here to be on the safe side (and it distinguishes nicely from the 0.5em horizontal value). Since there is no background-color, everything outside the background-image is transparent! (if the span inherits some background-color, just override it to be transparent)

The horizontal padding (0.5em here), together with the box-decoration-break: clone setting (also with prefixes, although I do not know which are actually needed) takes care of the left and right padding, also setting it equal for all lines.

For semi-transparent backgrounds, a dito png-image will work instead of the gif. I chose a gif here because of the file size. The image can also be loaded separately, but using the data-uri saves a http-request (which would be way more than the current 70 bytes and take a long time).


问:
populating values of a dictionary with lists in python csv package
I have a CSV file of sat scores per state. The file has one state's data(state_name, rate, math, verbal) per one row of the CSV. I have created a dictionary with key values of state, rate, math, verbal with the code below:

```<code>with open('../sat_scores.csv', mode='r') as f:
    sat = {}
    reader = csv.reader(f)
    for row in reader:
        for item in row:
            sat[item]=[]
        break
</code>```

now I to fill the columns with the remaining CSV. The dictionary format for data will be the column names as the key, and the data under each column as the values. I also need to make string numeric columns Rate, Math, and Verbal into floats. I have gotten this far:

```<code>    for row in reader:
        for item, key in (row, sat.keys()):
            if key == 'State':
                sat[key].append(item)
                print(sat)
            else:
                new_item = float(item)
                sat[key].append(new_item)
                print(sat)
</code>```

I cannot figure out how to loop through both the keys of sat dictionary and the items in row simultaneously. Help, please?

答:
You need to keep the order of the header fields:

```<code>reader = csv.reader(f)
header = next(reader)
for row in reader:
    for name, value in zip(header, row):
        print(name, value)
</code>```

You don't really need to do that yourself though, you can use csv.DictReader to get a dictionary per row, with keys taken from the first line:

```<code>reader = csv.DictReader(f)
for row in reader:
    print(row)
</code>```

Body:
I have a CSV file of sat scores per state. The file has one state's data(state_name, rate, math, verbal) per one row of the CSV. I have created a dictionary with key values of state, rate, math, verbal with the code below:

with open('../sat_scores.csv', mode='r') as f:
    sat = {}
    reader = csv.reader(f)
    for row in reader:
        for item in row:
            sat[item]=[]
        break

now I to fill the columns with the remaining CSV. The dictionary format for data will be the column names as the key, and the data under each column as the values. I also need to make string numeric columns Rate, Math, and Verbal into floats. I have gotten this far:

    for row in reader:
        for item, key in (row, sat.keys()):
            if key == 'State':
                sat[key].append(item)
                print(sat)
            else:
                new_item = float(item)
                sat[key].append(new_item)
                print(sat)

I cannot figure out how to loop through both the keys of sat dictionary and the items in row simultaneously. Help, please?

Body:
You need to keep the order of the header fields:

reader = csv.reader(f)
header = next(reader)
for row in reader:
    for name, value in zip(header, row):
        print(name, value)

You don't really need to do that yourself though, you can use csv.DictReader to get a dictionary per row, with keys taken from the first line:

reader = csv.DictReader(f)
for row in reader:
    print(row)


问:
Nullify QString data bytes
I use QStrings to store passwords. If to be more precise, I use QStrings to fetch passwords from GUI.
The point is that after password usage/appliance I need to nullify (zero) internal QStrings data bytes with password to eliminate it from memory entirely.

Here are my investigations:

After QString destruction it's data remains in memory nonzeroed;

When I attempt to modify QString to fulfill it with zeroes it triggers copy-on-write idiom and allocates new memory for a modified variant of data. Old data remains untouched. Same happens even if I use QString::data() method. Not really sure why - probably because it returns not raw char * but QChar *;

QString::clear(), = "" does actually the same COW as described above.

Q: How can I implement proper QString cleanup to prevent passwords leaks?

答:
You have to be aware of all the temporary copies that may be done. If you want to avoid this you must manually erase memory before deallocating each temporal copy. Unfortunately that cannot be done with the standard QString since the implementation is closed.

You can, however, specialise std::basic_string using a custom allocator, which, before deleting can clean up the memory block (see below for an example). You can use this new secure string to manipulate your password instead of a plain char array, if you find it more convenient. I'm not sure is std::basic_string can be specialised with QChar, but if not you can use any of the Unicode characters from C++11 (char16_t, char32_t...) instead if you need other than ANSI support.

Regarding the user interface, I think an option you have is to create your own text input widget, reimplementing the keyPressEvent / keyReleaseEvent to store the typed password into either the secure string or a char array. Also reimplement the paintEvent to display only stars, dots, or whatever other masking character you want. Once the password has been used just clear the array or empty the secure string.

Update: example of secure string

```<code>namespace secure {
  template<class T>
  class allocator : public std::allocator<T> {
  public:
    typedef typename std::allocator<T>::pointer pointer;
    typedef typename std::allocator<T>::size_type size_type;

    template<class U>
    struct rebind {
      typedef allocator<U> other;
    };
    allocator() throw() :
      std::allocator<T>() {}
    allocator(const allocator& other) throw() :
      std::allocator<T>(other) {}
    template <class U>
    allocator(const allocator<U>& other) throw() :
      std::allocator<T>(other) {}

    void deallocate(pointer p, size_type num) {
      memset(p, 0, num); // can be replaced by SecureZeroMemory(p, num) on Windows
      std::allocator<T>::deallocate(p, num);
    }
  };

  class string : public std::basic_string<char, std::char_traits<char>, allocator<char>> {
  public:
    string() :
      basic_string() {}

    string(const string& str) :
      basic_string(str.data(), str.length()) {}

    template<class _Elem, class _Traits, class _Ax>
    string(const std::basic_string<_Elem, _Traits, _Ax>& str) :
      basic_string(str.begin(), str.end()) {}

    string(const char* chars) :
      basic_string(chars) {}

    string(const char* chars, size_type sz) :
      basic_string(chars, sz) {}

    template<class _It>
    string(_It a, _It b) :
      basic_string(a, b) {}
  };
}
</code>```

Title: Nullify QString data bytes

Body:
You have to be aware of all the temporary copies that may be done. If you want to avoid this you must manually erase memory before deallocating each temporal copy. Unfortunately that cannot be done with the standard QString since the implementation is closed.

You can, however, specialise std::basic_string using a custom allocator, which, before deleting can clean up the memory block (see below for an example). You can use this new secure string to manipulate your password instead of a plain char array, if you find it more convenient. I'm not sure is std::basic_string can be specialised with QChar, but if not you can use any of the Unicode characters from C++11 (char16_t, char32_t...) instead if you need other than ANSI support.

Regarding the user interface, I think an option you have is to create your own text input widget, reimplementing the keyPressEvent / keyReleaseEvent to store the typed password into either the secure string or a char array. Also reimplement the paintEvent to display only stars, dots, or whatever other masking character you want. Once the password has been used just clear the array or empty the secure string.

Update: example of secure string

namespace secure {
  template<class T>
  class allocator : public std::allocator<T> {
  public:
    typedef typename std::allocator<T>::pointer pointer;
    typedef typename std::allocator<T>::size_type size_type;

    template<class U>
    struct rebind {
      typedef allocator<U> other;
    };
    allocator() throw() :
      std::allocator<T>() {}
    allocator(const allocator& other) throw() :
      std::allocator<T>(other) {}
    template <class U>
    allocator(const allocator<U>& other) throw() :
      std::allocator<T>(other) {}

    void deallocate(pointer p, size_type num) {
      memset(p, 0, num); // can be replaced by SecureZeroMemory(p, num) on Windows
      std::allocator<T>::deallocate(p, num);
    }
  };

  class string : public std::basic_string<char, std::char_traits<char>, allocator<char>> {
  public:
    string() :
      basic_string() {}

    string(const string& str) :
      basic_string(str.data(), str.length()) {}

    template<class _Elem, class _Traits, class _Ax>
    string(const std::basic_string<_Elem, _Traits, _Ax>& str) :
      basic_string(str.begin(), str.end()) {}

    string(const char* chars) :
      basic_string(chars) {}

    string(const char* chars, size_type sz) :
      basic_string(chars, sz) {}

    template<class _It>
    string(_It a, _It b) :
      basic_string(a, b) {}
  };
}


问:
Microchip Harmony timing issues on PIC32MZ
I am using MPLABX + Harmony framework to write code for a PIC32MZ1024EFK064.

My goal is, to trigger the ISR every microsecond.
In order to test this, I toggle a LED after 1000000 cycles of the ISR:

```<code>uint32_t xxx = 0;

void __ISR(_TIMER_2_VECTOR, ipl1AUTO) IntHandlerDrvTmrInstance0(void)
{

    xxx++;

    if(xxx > 1000000){

        xxx = 0;
        blink();

    }

    PLIB_INT_SourceFlagClear(INT_ID_0,INT_SOURCE_TIMER_2);

}
</code>```

Timer2 runs at 80MHz with a prescaler of 1 with a timer period of 80.

At my first attempt, the LED toggled every 4 seconds (ISR = every 4us).

I figured out that I can reach 2 seconds by changing the Postscaler of PBCLK7 from 2 to 1. (now the CPU-core runs at 160MHz instead of 80MHz).

But even when I change the timer period to 1, I only get my LED toggled every 2 seconds.

Any idea how to speed things up further here?

UPDATE:

The subroutine blink() was too slow.
By manipulating the Register directly, it works at 1us

```<code>void __ISR(_TIMER_2_VECTOR, ipl1AUTO) IntHandlerDrvTmrInstance0(void)
{
    LATBINV = 1<<8;
    PLIB_INT_SourceFlagClear(INT_ID_0,INT_SOURCE_TIMER_2);
}
</code>```

答:
I am not very familiar with that specific microcontroller but have worked a lot with Microchip PICs, so here are some points you might want to look at:

1- First make sure your clocks (CPU and PBCLK) really run at the speed you think they run. You can usually output some of your internal clocks on an external pin (usually REFCLKO on PIC32s). That way you can measure them with an oscilloscope and make sure they are correctly configured.

2- Make sure you minimize the internal execution time of your interrupt. Check if PLIB_INT_SourceFlagClear() is a macro-like function or an actual function call. If this is a function call, you might want to work at the register level to avoid this overhead.

3- Enable compiler optimization. By the way, it is also a good practice when working with a global variable from within an interrupt to declare it as volatile (or declare it static inside your interrupt handler function).

4- Unless it is explicitely documented by Microchip, verify if you should clear your interrupt at the beginning of your interrupt handler instead of the end. What might happen in your case, especially if you set its period to a very short period of time, is that your timer expires again while you are still inside your interrupt handler but BEFORE you clear its flag. That would result in an extra delay before your interrupt fires again. What you want is to clear the flag as soon as possible so if the timer expires again, it sets the flag which will result in your interrupt handler to fire again as soon as it completes its execution. Of course that would not give any time for your background application to execute though...

5- I am also assuming that your timer is correctly configured, that is it reloads its internal count to 0 when the period expires, but take a look to make sure it is the case.

Franck

Body:
I am using MPLABX + Harmony framework to write code for a PIC32MZ1024EFK064.

My goal is, to trigger the ISR every microsecond.
In order to test this, I toggle a LED after 1000000 cycles of the ISR:

uint32_t xxx = 0;

void __ISR(_TIMER_2_VECTOR, ipl1AUTO) IntHandlerDrvTmrInstance0(void)
{

    xxx++;

    if(xxx > 1000000){

        xxx = 0;
        blink();

    }

    PLIB_INT_SourceFlagClear(INT_ID_0,INT_SOURCE_TIMER_2);

}

Timer2 runs at 80MHz with a prescaler of 1 with a timer period of 80.

At my first attempt, the LED toggled every 4 seconds (ISR = every 4us).

I figured out that I can reach 2 seconds by changing the Postscaler of PBCLK7 from 2 to 1. (now the CPU-core runs at 160MHz instead of 80MHz).

But even when I change the timer period to 1, I only get my LED toggled every 2 seconds.

Any idea how to speed things up further here?

UPDATE:

The subroutine blink() was too slow.
By manipulating the Register directly, it works at 1us

void __ISR(_TIMER_2_VECTOR, ipl1AUTO) IntHandlerDrvTmrInstance0(void)
{
    LATBINV = 1<<8;
    PLIB_INT_SourceFlagClear(INT_ID_0,INT_SOURCE_TIMER_2);
}


答:
Your function definition:

```<code>drop5 [a] = drop 5 [a]
</code>```

Specifies that the clause only "fires" for lists with exactly one element. Indeed in a function definition [a] is not the type of the parameter, it is a pattern. The pattern [a] means that we are working with a list with exactly one element.

If you compile with -Wall you will get:

```<code><interactive>:1:1: warning: [-Wincomplete-patterns]
    Pattern match(es) are non-exhaustive
    In an equation for ‘drop5’:
        Patterns not matched:
            []
            (_:_:_)
</code>```

The compiler/interpreter thus produces a warning that two patterns are not covered: one for an empty list, and one for a list with two or more elements.

Title: Haskell function definition not working as expected

Body:
Your function definition:

drop5 [a] = drop 5 [a]

Specifies that the clause only "fires" for lists with exactly one element. Indeed in a function definition [a] is not the type of the parameter, it is a pattern. The pattern [a] means that we are working with a list with exactly one element.

If you compile with -Wall you will get:

<interactive>:1:1: warning: [-Wincomplete-patterns]
    Pattern match(es) are non-exhaustive
    In an equation for ‘drop5’:
        Patterns not matched:
            []
            (_:_:_)

The compiler/interpreter thus produces a warning that two patterns are not covered: one for an empty list, and one for a list with two or more elements.


问:
Why do I need a different syntax when testing for an exception with Jasmine?
I'm new to Jasmine, so apologies if this is a dumb question.

I have a test like this...

```<code>it("should calculate factorial 5", function() {
  expect(MathsUtils.fact(5)).toBe(120);
});
</code>```

This works fine. My fact function throws an exception if you pass it a negative number, so I tried to test that with the following...

```<code>it("should throw an exception when passed -1", function() {
  expect(MathsUtils.fact(-1)).toThrow("n! does not exist for negative numbers");
});
</code>```

However, this failed. After some searching, I discovered that if I change this test to look like this...

```<code>it("should throw an exception when passed -1", function() {
  expect(function() { MathsUtils.fact(-1); }).toThrow("n! does not exist for negative numbers");
});
</code>```

...it passes. However, if I change my first test in a similar manner...

```<code>it("should calculate factorial 5", function() {
  expect(function() { MathsUtils.fact(5); }).toBe(120);
});
</code>```

...it fails.

Why do I need a different syntax for the two tests? Neither seems to work for the other.

As I said, I'm new with Jasmine, so if this is covered in the docs, please point me in the right direction, as I couldn't see any explanation.

答:
In the example

```<code>expect(MathsUtils.fact(-1))
</code>```

The fact is evaluated before expect is called, and hence it cannot catch the exception,

where

```<code>expect(function(){MathsUtils.fact(-1)})
</code>```

expect is doing the execution and can catch the exception as what is passed is a function pointer and not an already evaluated value

Body:
I'm new to Jasmine, so apologies if this is a dumb question.

I have a test like this...

it("should calculate factorial 5", function() {
  expect(MathsUtils.fact(5)).toBe(120);
});

This works fine. My fact function throws an exception if you pass it a negative number, so I tried to test that with the following...

it("should throw an exception when passed -1", function() {
  expect(MathsUtils.fact(-1)).toThrow("n! does not exist for negative numbers");
});

However, this failed. After some searching, I discovered that if I change this test to look like this...

it("should throw an exception when passed -1", function() {
  expect(function() { MathsUtils.fact(-1); }).toThrow("n! does not exist for negative numbers");
});

...it passes. However, if I change my first test in a similar manner...

it("should calculate factorial 5", function() {
  expect(function() { MathsUtils.fact(5); }).toBe(120);
});

...it fails.

Why do I need a different syntax for the two tests? Neither seems to work for the other.

As I said, I'm new with Jasmine, so if this is covered in the docs, please point me in the right direction, as I couldn't see any explanation.

Body:
In the example

expect(MathsUtils.fact(-1))

The fact is evaluated before expect is called, and hence it cannot catch the exception,

where

expect(function(){MathsUtils.fact(-1)})

expect is doing the execution and can catch the exception as what is passed is a function pointer and not an already evaluated value


问:
How to show to the user that a file is attached to an element
We are currently using a stereotype with an attached shape script to show that files are linked to an element

However, going this route means that our users cannot use another stereotype, or it will overwrite (Even if multiple stereotypes can be applied, only one will be shown and only one shape script will be applied)

I tried using the "A" icon for when a linked document has been created for an element by modifying the style property of the element, but setting MDoc=1 without a linked document will not show the icon.

What would be an effective way of showing there are files linked to a document without using stereotypes(if any)?

答:
You are out of luck here. The Link to Element Feature on Notes works for many things, but not for the related files.

In case you could link <<files>> stereotyped Notes to the elements and run a batch script that looks into the Related/Files and fills them in the Notes. Basically that would be something like:

```<code>for dia in all diagrams:
  for diaobj in dia.diagramobjects:
    obj = rep.GetElementByID(diaObj.ElementID)
    if obj.Type == "Note" and obj.Stereotype == "files":
      con = obj.connectors.getAt(0) # assume there's only one connected
      ident = con.clientId
      if ident == obj.ElementId: ident = obj.sourceId
      fObj = rep.GetElementByID(ident) # element connected to the note
      # parse fObj's files and write them as string to obj's Note attribute
</code>```

Body:
You are out of luck here. The Link to Element Feature on Notes works for many things, but not for the related files.

In case you could link <<files>> stereotyped Notes to the elements and run a batch script that looks into the Related/Files and fills them in the Notes. Basically that would be something like:

for dia in all diagrams:
  for diaobj in dia.diagramobjects:
    obj = rep.GetElementByID(diaObj.ElementID)
    if obj.Type == "Note" and obj.Stereotype == "files":
      con = obj.connectors.getAt(0) # assume there's only one connected
      ident = con.clientId
      if ident == obj.ElementId: ident = obj.sourceId
      fObj = rep.GetElementByID(ident) # element connected to the note
      # parse fObj's files and write them as string to obj's Note attribute


问:
Add css to component via service in Angular2, is it possible?
I have an component A with 5 pictures. Only 1 picture has colour and is clickable, the other 4 are grey with help of this css class

```<code>.not_opened{
  -webkit-filter: grayscale(85%);
}
</code>```

And are not clickable.

If I click on the first picture, I change component to component B (A disappears, because it is separate component, not child or parent) , do some manipulations in the new second component B and then I click the button, which returns me to component A. Everything stays the same there, but I would like to make 2 picture not grey ( so delete/change this class not_opened from picture 2) and make it clickable, then if I click picture 2 I go to third component C and then back and third picture is now not grey and clickable and so on...

How could I make something like this?
First thought was to make 4 different components, each with own css stylesheet, but maybe there is another way?..
Maybe somehow with help of service?
Could you please advice me something?

答:
First I suggest you to introduce a view-model notion to your project. View-model contains information on how to render a particular model. In your case you can pass something like Array<ImageViewModel> between components A and B. You can pass this data through some service if you find it suitable for your case, or you can use parent component, e.g.:

Parent component template:

```<code><component-a [images]="images" *ngIf="active === 'a'" (onImageSelected)="handleImageSelected($event)"></component-a>
<component-b [images]="images" *ngIf="active === 'b'" (onSettingsEditCompleted)="handleSettingsEditCompleted()"></component-b>
</code>```

Parent component code:

```<code>.... {
    images: Array<ImageViewModel> = [];
    active: string = "a";

    constructor(private _service: ImageService) {
        // Lets imagine that service returns array of image urls.
        this._service.fetchImages().subscribe((urls) => {
            this.images = urls.map(url => ({src: url, disabled: true}));
            if (this.images.length > 0) {
                this.images[0].disabled = false;
            }
        });
    }

    handleImageSelected(image: ImageViewModel) {
        this.active = "b";
        console.log("Image selected", image);
    }

    handleSettingsEditCompleted() {
        this.active = "a";
    }
}
</code>```

And where ImageViewModel is something like:

```<code>interface ImageViewModel {
    src: string;
    disabled: boolean;
}
</code>```

Now in componentA use [ngClass] directive in order to change image availability.

ComponentA template:

```<code><img *ngFor="let image of images" [src]="image.src" [ngClass]="{'not-opened': image.disabled}" (click)='!image.disabled && handleImageSelected(image)'/>
</code>```

ComponentA styles:

```<code>.not-opened {
    filter: grayscale(85%); // Why do you use -webkit version only?
    -webkit-filter: grayscale(85%);
}
</code>```

ComponentA code:

```<code>... {
   @Output()
   onImageSelected = new EventEmitter<ImageViewModel>();
   @Input()
   images: Array<ImageViewModel> = [];

   handleImageSelected(image: ImageViewModel) {
       this.images[1].disabled = false;
       this.onImageSelected.emit(image);
   }
}
</code>```

Read about @Input and @Output annotations at Angular documentation if something is not clear.

Body:
I have an component A with 5 pictures. Only 1 picture has colour and is clickable, the other 4 are grey with help of this css class

.not_opened{
  -webkit-filter: grayscale(85%);
}

And are not clickable.

If I click on the first picture, I change component to component B (A disappears, because it is separate component, not child or parent) , do some manipulations in the new second component B and then I click the button, which returns me to component A. Everything stays the same there, but I would like to make 2 picture not grey ( so delete/change this class not_opened from picture 2) and make it clickable, then if I click picture 2 I go to third component C and then back and third picture is now not grey and clickable and so on...

How could I make something like this?
First thought was to make 4 different components, each with own css stylesheet, but maybe there is another way?..
Maybe somehow with help of service?
Could you please advice me something?

Body:
First I suggest you to introduce a view-model notion to your project. View-model contains information on how to render a particular model. In your case you can pass something like Array<ImageViewModel> between components A and B. You can pass this data through some service if you find it suitable for your case, or you can use parent component, e.g.:

Parent component template:

<component-a [images]="images" *ngIf="active === 'a'" (onImageSelected)="handleImageSelected($event)"></component-a>
<component-b [images]="images" *ngIf="active === 'b'" (onSettingsEditCompleted)="handleSettingsEditCompleted()"></component-b>

Parent component code:

.... {
    images: Array<ImageViewModel> = [];
    active: string = "a";

    constructor(private _service: ImageService) {
        // Lets imagine that service returns array of image urls.
        this._service.fetchImages().subscribe((urls) => {
            this.images = urls.map(url => ({src: url, disabled: true}));
            if (this.images.length > 0) {
                this.images[0].disabled = false;
            }
        });
    }

    handleImageSelected(image: ImageViewModel) {
        this.active = "b";
        console.log("Image selected", image);
    }

    handleSettingsEditCompleted() {
        this.active = "a";
    }
}

And where ImageViewModel is something like:

interface ImageViewModel {
    src: string;
    disabled: boolean;
}

Now in componentA use [ngClass] directive in order to change image availability.

ComponentA template:

<img *ngFor="let image of images" [src]="image.src" [ngClass]="{'not-opened': image.disabled}" (click)='!image.disabled && handleImageSelected(image)'/>

ComponentA styles:

.not-opened {
    filter: grayscale(85%); // Why do you use -webkit version only?
    -webkit-filter: grayscale(85%);
}

ComponentA code:

... {
   @Output()
   onImageSelected = new EventEmitter<ImageViewModel>();
   @Input()
   images: Array<ImageViewModel> = [];

   handleImageSelected(image: ImageViewModel) {
       this.images[1].disabled = false;
       this.onImageSelected.emit(image);
   }
}

Read about @Input and @Output annotations at Angular documentation if something is not clear.


问:
Is there someway to do just a simple string manipulation in Azure Data Factory?
Is there someway to do just a simple string manipulation in Azure Data Factory?

Something as simple as I have a storage blob with a tab separated file, and I want to move it over into a storage table ... but make some

And I want to say, convert the tabs to commas, merge columns 4 through to the last column

答:
You could do this with a Custom Activity, but the thing to remember about Azure Data Factory is that it is mainly for orchestration (not transform).  That means it doesn't itself have a great deal of ability to do transform.

Another way to do this would be to use Azure Data Lake Analytics (ADLA), which would probably be my preference as I'm using it a lot at the moment.  If you don't already have an ADLA account though it might seem a bit of overhead.

I've taken a sample file and it converted it as per your requirements using U-SQL using this sample file:

```<code>DECLARE @inputFilepath string = "input/input67.tsv";
DECLARE @outputFilepath string = "output/output67.csv";

@input =
    EXTRACT rowId int,
            col1 int,
            col2 int,
            col3 int,
            col4 int
    FROM @inputFilepath
    USING Extractors.Tsv(skipFirstNRows : 1);

// Concat the four columns
@output =
    SELECT rowId,
           string.Concat(col1.ToString(), col2.ToString(), col3.ToString(), col4.ToString()) AS col5
    FROM @input;

// Export as csv
OUTPUT @output
TO @outputFilepath
USING Outputters.Csv(quoting:false);
</code>```

Body:
You could do this with a Custom Activity, but the thing to remember about Azure Data Factory is that it is mainly for orchestration (not transform).  That means it doesn't itself have a great deal of ability to do transform.

Another way to do this would be to use Azure Data Lake Analytics (ADLA), which would probably be my preference as I'm using it a lot at the moment.  If you don't already have an ADLA account though it might seem a bit of overhead.

I've taken a sample file and it converted it as per your requirements using U-SQL using this sample file:

DECLARE @inputFilepath string = "input/input67.tsv";
DECLARE @outputFilepath string = "output/output67.csv";

@input =
    EXTRACT rowId int,
            col1 int,
            col2 int,
            col3 int,
            col4 int
    FROM @inputFilepath
    USING Extractors.Tsv(skipFirstNRows : 1);

// Concat the four columns
@output =
    SELECT rowId,
           string.Concat(col1.ToString(), col2.ToString(), col3.ToString(), col4.ToString()) AS col5
    FROM @input;

// Export as csv
OUTPUT @output
TO @outputFilepath
USING Outputters.Csv(quoting:false);


问:
How may I dynamically insert a string into a large javascript template string in python?
Suppose a template javascript string like this:

```<code>js_string = u'function hello() { alert({0}); } function goodbye() { alert({1}); }'
</code>```

I would like to get following result:

```<code>function hello() { alert('Hello!'); } function goodbye() { alert('Goodbye!'); }
</code>```

My initial idea was to use the .format() method, which resulted in a KeyError due to the arbitrary curly braces. I then had a look at this question and replaced said curly braces with double curly braces. Although this produces the desired result, I cannot use it, as I'm working with a rather large javascript template and am not up for changing each and every single curly brace.

I have also tried the .replace() function:

```<code>js_string.replace("{0}", repr("Hello!")).replace("{1}", repr("Goodbye!"))
</code>```

However, calling .replace() more than once seems inconvenient to me, which is why I am asking if there is any straightforward alternative for this problem.

答:
If you're set on curly brace syntax, you can simply call .replace in a loop. No need for regexes.

```<code>for i, replacement in enumerate(["'hello'", "'Goodbye!'"]):
    js_string = js_string.replace('{%s}' % i, replacement)
</code>```

Body:
Suppose a template javascript string like this:

js_string = u'function hello() { alert({0}); } function goodbye() { alert({1}); }'

I would like to get following result:

function hello() { alert('Hello!'); } function goodbye() { alert('Goodbye!'); }

My initial idea was to use the .format() method, which resulted in a KeyError due to the arbitrary curly braces. I then had a look at this question and replaced said curly braces with double curly braces. Although this produces the desired result, I cannot use it, as I'm working with a rather large javascript template and am not up for changing each and every single curly brace.

I have also tried the .replace() function:

js_string.replace("{0}", repr("Hello!")).replace("{1}", repr("Goodbye!"))

However, calling .replace() more than once seems inconvenient to me, which is why I am asking if there is any straightforward alternative for this problem.

Body:
If you're set on curly brace syntax, you can simply call .replace in a loop. No need for regexes.

for i, replacement in enumerate(["'hello'", "'Goodbye!'"]):
    js_string = js_string.replace('{%s}' % i, replacement)


问:
Optimizing a Sort Method
I have a program that needs to sort matches into the following order (the following is a short example):

```<code>PIT
PREDICTIONS
Match 1
Match 2
Quarters 1 Match 1
Quarters 1 Match 2
Quarters 2 Match 1
Semis 1
Semis 2
Finals 1
Finals 2
</code>```

Note: There can be unlimited Matches, Quarters 1 - 4 only (with unlimited submatches), unlimited semis, and unlimited finals.

I've got the following method that assign a score to one of the above titles:

```<code>public static long getMatchScore(String name) {
    long score = 0;
    String matchName = name.toLowerCase();
    String[] tokens = matchName.split("\\s+");

    if(matchName.startsWith("pit")) score -= 100000;
    else if(matchName.startsWith("predictions")) score -= 1000;
    else if(matchName.startsWith("quals")) score = Integer.parseInt(matchName.split("\\s+")[1]);
    else if(matchName.startsWith("quarters")) {
        if(Integer.parseInt(tokens[1]) == 1) score += 1000;
        else if(Integer.parseInt(tokens[1]) == 2) score += 10000;
        else if(Integer.parseInt(tokens[1]) == 3) score += 100000;
        else if(Integer.parseInt(tokens[1]) == 4) score += 1000000;

        score += Integer.parseInt(tokens[3]);
    }
    else if(matchName.startsWith("semis")) {
        if(Integer.parseInt(tokens[1]) == 1) score += 10000000;
        else if(Integer.parseInt(tokens[1]) == 2) score += 100000000;

        score += Integer.parseInt(tokens[3]);
    }
    else if(matchName.startsWith("finals")) {
        score += 1000000000;
        score += Integer.parseInt(tokens[1]);
    }
    return score;
}
</code>```

Then the Java method compareTo() is used to sort it. Is there a better way to do this rather than assigning massive numbers like 100000000.

答:
First of all, and I don't say this sarcastically, if you're going to write code like getMatchScore, you should be spending more time learning how to write clean code, than actually whipping out more code. The cyclomatic complexity of that method is thorugh the roof.

That said, if we recognize that your input has groups that have inherent weightage, like Match < Quarters, we should capture that in code using an Enum. A simple one with integer weightage should suffice, don't need a complicated one as shown by "Java Guy next door". How about the following code that I've tested to be working?

```<code>private static final Comparator<String> BY_GROUP = (s1, s2) -> {
    Map.Entry<Integer, Integer> e1 = toTuple(s1);
    Map.Entry<Integer, Integer> e2 = toTuple(s2);

    Comparator<Map.Entry<Integer, Integer>> c = Comparator.<Map.Entry<Integer, Integer>, Integer>comparing(Map.Entry::getKey)
            .thenComparing(Map.Entry::getValue);

    return c.compare(e1, e2);
};

private static Map.Entry<Integer, Integer> toTuple(String s) {
    String[] tokens = s.toUpperCase().split("\\s");
    Group group = Group.valueOf(tokens[0]);
    int num = tokens.length > 1 ? Integer.valueOf(tokens[1]) : Integer.MIN_VALUE;

    return new AbstractMap.SimpleImmutableEntry<>(group.weightage(), num);
}

private enum Group {
    PIT(0), PREDICTIONS(1), MATCH(2), QUARTERS(3), SEMIS(4), FINALS(5);

    private int weightage;

    Group(int weightage) {
        this.weightage = weightage;
    }

    public int weightage() {
        return this.weightage;
    }
}

public static void main(String[] args) {
    List<String> input = Arrays.asList("PIT", "PREDICTIONS", "Match 1", "Match 2",
            "Quarters 1 Match 1", "Quarters 1 Match 2", "Quarters 2 Match 1", "Semis 1", "Semis 2",
            "Finals 1", "Finals 2");

    input.sort(BY_GROUP);
    System.out.println(input);
}
</code>```

Title: Optimizing a Sort Method

Body:
I have a program that needs to sort matches into the following order (the following is a short example):

PIT
PREDICTIONS
Match 1
Match 2
Quarters 1 Match 1
Quarters 1 Match 2
Quarters 2 Match 1
Semis 1
Semis 2
Finals 1
Finals 2

Note: There can be unlimited Matches, Quarters 1 - 4 only (with unlimited submatches), unlimited semis, and unlimited finals.

I've got the following method that assign a score to one of the above titles:

public static long getMatchScore(String name) {
    long score = 0;
    String matchName = name.toLowerCase();
    String[] tokens = matchName.split("\\s+");

    if(matchName.startsWith("pit")) score -= 100000;
    else if(matchName.startsWith("predictions")) score -= 1000;
    else if(matchName.startsWith("quals")) score = Integer.parseInt(matchName.split("\\s+")[1]);
    else if(matchName.startsWith("quarters")) {
        if(Integer.parseInt(tokens[1]) == 1) score += 1000;
        else if(Integer.parseInt(tokens[1]) == 2) score += 10000;
        else if(Integer.parseInt(tokens[1]) == 3) score += 100000;
        else if(Integer.parseInt(tokens[1]) == 4) score += 1000000;

        score += Integer.parseInt(tokens[3]);
    }
    else if(matchName.startsWith("semis")) {
        if(Integer.parseInt(tokens[1]) == 1) score += 10000000;
        else if(Integer.parseInt(tokens[1]) == 2) score += 100000000;

        score += Integer.parseInt(tokens[3]);
    }
    else if(matchName.startsWith("finals")) {
        score += 1000000000;
        score += Integer.parseInt(tokens[1]);
    }
    return score;
}

Then the Java method compareTo() is used to sort it. Is there a better way to do this rather than assigning massive numbers like 100000000.

Body:
First of all, and I don't say this sarcastically, if you're going to write code like getMatchScore, you should be spending more time learning how to write clean code, than actually whipping out more code. The cyclomatic complexity of that method is thorugh the roof.

That said, if we recognize that your input has groups that have inherent weightage, like Match < Quarters, we should capture that in code using an Enum. A simple one with integer weightage should suffice, don't need a complicated one as shown by "Java Guy next door". How about the following code that I've tested to be working?

private static final Comparator<String> BY_GROUP = (s1, s2) -> {
    Map.Entry<Integer, Integer> e1 = toTuple(s1);
    Map.Entry<Integer, Integer> e2 = toTuple(s2);

    Comparator<Map.Entry<Integer, Integer>> c = Comparator.<Map.Entry<Integer, Integer>, Integer>comparing(Map.Entry::getKey)
            .thenComparing(Map.Entry::getValue);

    return c.compare(e1, e2);
};

private static Map.Entry<Integer, Integer> toTuple(String s) {
    String[] tokens = s.toUpperCase().split("\\s");
    Group group = Group.valueOf(tokens[0]);
    int num = tokens.length > 1 ? Integer.valueOf(tokens[1]) : Integer.MIN_VALUE;

    return new AbstractMap.SimpleImmutableEntry<>(group.weightage(), num);
}

private enum Group {
    PIT(0), PREDICTIONS(1), MATCH(2), QUARTERS(3), SEMIS(4), FINALS(5);

    private int weightage;

    Group(int weightage) {
        this.weightage = weightage;
    }

    public int weightage() {
        return this.weightage;
    }
}

public static void main(String[] args) {
    List<String> input = Arrays.asList("PIT", "PREDICTIONS", "Match 1", "Match 2",
            "Quarters 1 Match 1", "Quarters 1 Match 2", "Quarters 2 Match 1", "Semis 1", "Semis 2",
            "Finals 1", "Finals 2");

    input.sort(BY_GROUP);
    System.out.println(input);
}


问:
Keras CNN for multiclass categorical crossentropy loss function
This is my code i typed to classify some classes consisting of birds, dogs and cats. Its the same code for the binary classification but when I add another class and changed the loss function of compile method to use categorical_Crossentropy, it gives me the following error ( => at the end of the code ). can anyone explain what is the issue here or the mistake I have made ?

```<code># Importing Keras and Tensorflow modules

import tensorflow as tf
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
from keras.preprocessing.image import ImageDataGenerator
from keras.models import load_model
from keras.utils.np_utils import to_categorical
import os.path

# Initilize the CNN

classifier = Sequential()
# Step 1 - Convolution

classifier.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu'))

# Step 2 - Pooling

classifier.add(MaxPooling2D(pool_size = (2, 2)))

# Step 2(b) - Add 2nd Convolution Layer making it Deep followed by a Pooling Layer

classifier.add(Conv2D(32, (3, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))

# Step 3 - Flattening

classifier.add(Flatten())

# Step 4 - Fully Connected Neural Network

# Hidden Layer - Activation Function RELU
classifier.add(Dense(units = 128, activation = 'relu'))
# Output Layer - Activation Function Softmax(to clasify multiple classes)
classifier.add(Dense(units = 1, activation = 'softmax'))

# Compile the CNN

# Categorical Crossentropy - to classify between multiple classes of images
classifier.compile(optimizer = 'adam', loss = 'categorical_crossentropy',
metrics = ['accuracy'])

# Image Augmentation and Training Section

# Image Augmentation to prevent Overfitting (Applying random transformation on
images to train set.ie.
# scalling, rotating and streching)

train_datagen = ImageDataGenerator(
        rescale=1./255,
        shear_range=0.2,
        zoom_range=0.2,
        horizontal_flip=True)

test_datagen = ImageDataGenerator(rescale=1./255)

training_set = train_datagen.flow_from_directory(
        'dataset/training_set',
        target_size=(64, 64),
        batch_size=8,
        class_mode='categorical')

test_set = test_datagen.flow_from_directory(
        'dataset/test_set',
        target_size=(64, 64),
        batch_size=8,
        class_mode='categorical')

#Fit the clasifier on the CNN data
if(os.path.isfile('my_model.h5') == False):
    classifier.fit_generator(
            training_set,
            steps_per_epoch=8000,
            epochs=2,
            validation_data=test_set,
            validation_steps=2000
                                  )
# Save the generated model to my_model.h5
classifier.save('my_model.h5')
else:
    classifier = load_model('my_model.h5')
</code>```

答:
Your dataset seems to have 3 classes so you need to change the last line in a model definition to:</p>

```<code>classifier.add(Dense(units = 3, activation = 'softmax'))
</code>```

Body:
This is my code i typed to classify some classes consisting of birds, dogs and cats. Its the same code for the binary classification but when I add another class and changed the loss function of compile method to use categorical_Crossentropy, it gives me the following error ( => at the end of the code ). can anyone explain what is the issue here or the mistake I have made ?

# Importing Keras and Tensorflow modules

import tensorflow as tf
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
from keras.preprocessing.image import ImageDataGenerator
from keras.models import load_model
from keras.utils.np_utils import to_categorical
import os.path

# Initilize the CNN

classifier = Sequential()
# Step 1 - Convolution

classifier.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu'))

# Step 2 - Pooling

classifier.add(MaxPooling2D(pool_size = (2, 2)))

# Step 2(b) - Add 2nd Convolution Layer making it Deep followed by a Pooling Layer

classifier.add(Conv2D(32, (3, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))

# Step 3 - Flattening

classifier.add(Flatten())

# Step 4 - Fully Connected Neural Network

# Hidden Layer - Activation Function RELU
classifier.add(Dense(units = 128, activation = 'relu'))
# Output Layer - Activation Function Softmax(to clasify multiple classes)
classifier.add(Dense(units = 1, activation = 'softmax'))

# Compile the CNN

# Categorical Crossentropy - to classify between multiple classes of images
classifier.compile(optimizer = 'adam', loss = 'categorical_crossentropy',
metrics = ['accuracy'])

# Image Augmentation and Training Section

# Image Augmentation to prevent Overfitting (Applying random transformation on
images to train set.ie.
# scalling, rotating and streching)

train_datagen = ImageDataGenerator(
        rescale=1./255,
        shear_range=0.2,
        zoom_range=0.2,
        horizontal_flip=True)

test_datagen = ImageDataGenerator(rescale=1./255)

training_set = train_datagen.flow_from_directory(
        'dataset/training_set',
        target_size=(64, 64),
        batch_size=8,
        class_mode='categorical')

test_set = test_datagen.flow_from_directory(
        'dataset/test_set',
        target_size=(64, 64),
        batch_size=8,
        class_mode='categorical')

#Fit the clasifier on the CNN data
if(os.path.isfile('my_model.h5') == False):
    classifier.fit_generator(
            training_set,
            steps_per_epoch=8000,
            epochs=2,
            validation_data=test_set,
            validation_steps=2000
                                  )
# Save the generated model to my_model.h5
classifier.save('my_model.h5')
else:
    classifier = load_model('my_model.h5')

Body:
Your dataset seems to have 3 classes so you need to change the last line in a model definition to:

classifier.add(Dense(units = 3, activation = 'softmax'))


问:
Any efficient way to create a list from cells range in Python?
I have an Excel file and I have some parameters that I need to return in specific cell range, but different rows.

```<code>def get_list(row, start, stop):
    arr = list[start:stop] #and somewhere here I need to iterate throgh row because I store row separately.
</code>```

Any suggestions? Thanks!

答:
You can pass the range for the following function. I'm using xlrd here.</p>

```<code>import xlrd

def excel_reader(excel_name):
    wb = xlrd.open_workbook(excel_name)
    sh = wb.sheet_by_index(0)
    for i in range(sh.nrows):
        if i > 0:
            cell_value_class = int(sh.cell_value(i, 0))
            cell_value_id = int(sh.cell_value(i, 1))
            DataList[cell_value_class] = cell_value_id
</code>```

Body:
I have an Excel file and I have some parameters that I need to return in specific cell range, but different rows.

def get_list(row, start, stop):
    arr = list[start:stop] #and somewhere here I need to iterate throgh row because I store row separately.

Any suggestions? Thanks!

Body:
You can pass the range for the following function. I'm using xlrd here.

import xlrd

def excel_reader(excel_name):
    wb = xlrd.open_workbook(excel_name)
    sh = wb.sheet_by_index(0)
    for i in range(sh.nrows):
        if i > 0:
            cell_value_class = int(sh.cell_value(i, 0))
            cell_value_id = int(sh.cell_value(i, 1))
            DataList[cell_value_class] = cell_value_id


问:
How to save and retrieve email signature by using Rich Text Box in winform
I wanted to create email signature for my bulk emailing software. I have tried creating a signature using Rich Text Box and it worked, but problem is after saving this in DB and when retrieving all colors and effects will be gone.
How it will be possible to get it back as same as I created it.
Here is what I have created. I want to retrieve this as same when going to send the mail.

Before saving

After retrieving from DB

Please kindly help me to solve this issue.

Thanks in advance.

答: You should use richTextBox.Rtf to get the text with all formatting.</p>


问:
Adding ARToolKit SDK to Android Studio project
ARToolKit is a library to create augmented reality aplications. I wanna know how to create Android AR apps and I have chosen this tool for this. I'm using Android Studio SDK in Windows7 and I have downloaded and unzip the ARToolKit5-bin-5.3.2-Android and then I have imported and proved the ARSimple example that is included in that package.
Well then, I wanna research into RA by myself creating my own app. For that, I need to add the ARToolKit package to my project and like this I can use the AR classes and methods, but I don't known how do it.
Please, is anyone there that can help me?

Thanks in advance!

答:
=== UPDATE 1: 15/Feb/2018 ===

For all of you that might read that in the future. The download of ARToolKit6 was taken down by DAQRI and I'm unsure if the program will be continued.

=== ORIGINAL post ===

I can tell you the steps for ARToolKit6. I'm aware that you have asked for the steps for ARToolKit5 but I believe they are not that different.

In short, these are the things that you need to do:

Open your project

Right click your app > Open Module Settings

In the top left select the +

Select Import .JAR/.AAR Package > Next

As File name on the right select ... and then navigate to the .aar file in the unziped ARToolKit6 Android SDK

Should be << ARToolKit6 Android SDK >>/SDK/lib/AR6J/AR6J-release.aar

Close the Open Module Settings dialouge with OK

Open it again Right click your app > Open Module Settings

There seems to be an issue with Android Studio reloading imported modules. That is why you need to close and open it again.

Select your app on the left and navigate to Dependencies tab

On the bottom left select the + > Module Dependencies and select AR6J-release

You can find a longer description and a step by step video on this page:
http://augmentmy.world/integrate-artoolkit6-android-sdk


问:
Golang non blocking channel doesn't work
I work the first time with goroutines and channels in go and do not come any further.

I have a websocket connection where every time a user connect a new goroutine is spawned. Now I want to stop this goroutine if the user disconnect from the websocket connection.

To manage the stop signale I have create a map of channels. Each entry can be identified by the users websocket connection. I pass the websocket connection, the map of channels for the stop signal and two other parameters to the goroutine. But the goroutine doesn't receive any values from the quit channel and I don't know why.

Here is the relevant code for the main package:

```<code>package main

import (
    "net/http"
    "time"

    "github.com/gorilla/websocket"
)

func wsHandler(w http.ResponseWriter, r *http.Request) {
    ...
    ws, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        return
    }
    defer ws.Close()

    data.Quit[ws] = make(chan bool)

    data.DB.ListenToTable(data.GetTableName(source), channel, data.Quit, ws)

    for {
        if _, _, err := ws.NextReader(); err != nil {
            data.Quit[ws] <- true

            ws.Close()
            break
        }
    }
}
</code>```

And the code of the data package where the goroutine is created:

```<code>package data

var Quit = make(map[*websocket.Conn](chan bool))

func (db *rethinkDB) ListenToTable(name string, ch chan Data, quit map[*websocket.Conn](chan bool), ws *websocket.Conn) {
    go func(name string, ws *websocket.Conn) {
        for {
            select {
            case <-quit[ws]:
                fmt.Println("QUIT GOROUTINE")
                break
            default:
                res, err := r.Table(name).Changes().Run(db.session)
                if err != nil {
                    log.Fatalln(err)
                }

                var response DataFeed
                for res.Next(&response) {
                    response.NewVal.WS = ws
                    ch <- response.NewVal
                }

                if res.Err() != nil {
                    log.Println(res.Err())
                }
            }
        }
    }(name, ws)
}
</code>```

I have also tried buffered channels or pass the channel instead of the map of channels to the goroutine but without success. The fmt.Println("QUIT GOROUTINE") command is never called and the goroutine isn't sopped.

I hope someone can help me and sorry if this question was already ask but I haven't found a solution that solves my problem.

答:
First to make things easier:

As far as I can see you do not need a global register for the quit channels. Just create a ch := make(chan bool) in main, pass it to ListenToTable (instead of the whole map of channels) and use it in the select. In main close(ch) it if you want to exit. But as you said, that doesn't solve your problem.

Theoretically you are on the right track with closing the go routine. I took your sample code and made the following runnable code from it:

```<code>package main

import (
    "fmt"
    "time"
)

func main() {

    chClose := make(chan bool)
    channel := make(chan string)

    ListenToTable("somestring", channel, chClose)

    time.Sleep(3 * time.Second)
    chClose <- true
    time.Sleep(1 * time.Second)
}

func ListenToTable(name string, ch chan string, chClose chan bool) {
    go func(name string) {
        for {
            select {
            case <-chClose:
                fmt.Println("QUIT GOROUTINE")
                return  // VERY IMPORTANT: not break!
            default:
            }
        }
    }(name)
}
</code>```

The problem must be with something else in you code, probably blocked by something in the default section and not even executing the select. Try printing fmt.Println("something") before the select {. If that is not printed regularly then you have your answer.

One more thing: As commented in the code above you cannot break out of a for { select { ... } } with a single break. You need to use a return (to exit the function) or another tactic (like a break with a label as Adrian suggested in the comments). The break will only exit the select, but not the for loop.

Body:
I work the first time with goroutines and channels in go and do not come any further.

I have a websocket connection where every time a user connect a new goroutine is spawned. Now I want to stop this goroutine if the user disconnect from the websocket connection.

To manage the stop signale I have create a map of channels. Each entry can be identified by the users websocket connection. I pass the websocket connection, the map of channels for the stop signal and two other parameters to the goroutine. But the goroutine doesn't receive any values from the quit channel and I don't know why.

Here is the relevant code for the main package:

package main

import (
    "net/http"
    "time"

    "github.com/gorilla/websocket"
)

func wsHandler(w http.ResponseWriter, r *http.Request) {
    ...
    ws, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        return
    }
    defer ws.Close()

    data.Quit[ws] = make(chan bool)

    data.DB.ListenToTable(data.GetTableName(source), channel, data.Quit, ws)

    for {
        if _, _, err := ws.NextReader(); err != nil {
            data.Quit[ws] <- true

            ws.Close()
            break
        }
    }
}

And the code of the data package where the goroutine is created:

package data

var Quit = make(map[*websocket.Conn](chan bool))

func (db *rethinkDB) ListenToTable(name string, ch chan Data, quit map[*websocket.Conn](chan bool), ws *websocket.Conn) {
    go func(name string, ws *websocket.Conn) {
        for {
            select {
            case <-quit[ws]:
                fmt.Println("QUIT GOROUTINE")
                break
            default:
                res, err := r.Table(name).Changes().Run(db.session)
                if err != nil {
                    log.Fatalln(err)
                }

                var response DataFeed
                for res.Next(&response) {
                    response.NewVal.WS = ws
                    ch <- response.NewVal
                }

                if res.Err() != nil {
                    log.Println(res.Err())
                }
            }
        }
    }(name, ws)
}

I have also tried buffered channels or pass the channel instead of the map of channels to the goroutine but without success. The fmt.Println("QUIT GOROUTINE") command is never called and the goroutine isn't sopped.

I hope someone can help me and sorry if this question was already ask but I haven't found a solution that solves my problem.

Body:
First to make things easier:

As far as I can see you do not need a global register for the quit channels. Just create a ch := make(chan bool) in main, pass it to ListenToTable (instead of the whole map of channels) and use it in the select. In main close(ch) it if you want to exit. But as you said, that doesn't solve your problem.

Theoretically you are on the right track with closing the go routine. I took your sample code and made the following runnable code from it:

package main

import (
    "fmt"
    "time"
)

func main() {

    chClose := make(chan bool)
    channel := make(chan string)

    ListenToTable("somestring", channel, chClose)

    time.Sleep(3 * time.Second)
    chClose <- true
    time.Sleep(1 * time.Second)
}

func ListenToTable(name string, ch chan string, chClose chan bool) {
    go func(name string) {
        for {
            select {
            case <-chClose:
                fmt.Println("QUIT GOROUTINE")
                return  // VERY IMPORTANT: not break!
            default:
            }
        }
    }(name)
}

The problem must be with something else in you code, probably blocked by something in the default section and not even executing the select. Try printing fmt.Println("something") before the select {. If that is not printed regularly then you have your answer.

One more thing: As commented in the code above you cannot break out of a for { select { ... } } with a single break. You need to use a return (to exit the function) or another tactic (like a break with a label as Adrian suggested in the comments). The break will only exit the select, but not the for loop.


问:
Spec looking for specific HTML tag does not work
I'm working on a rails application and want to test using capybara, so far I had no problem but now that I'm implementing a markdown parsing feature I cant make my test pass.

I added this test

```<code>it "Shows makdown as HTML" do
  visit_wiki
  expect(page).to have_tag('pre')  //**EDITED** becauseof typo
end
</code>```

And I can't make it work, visit_wiki is just a method to well... visit the wiki.

```<code>def visit_wiki
  visit topics_path
  click_link topic.name
  click_link sentence
  expect(current_path).to eq topic_wiki_path(@wiki.topic, @wiki.id)
end
</code>```

I know that works because I've been using that in other parts of this project.

Here is also my Factory where I make sure to always have one pre HTML tag.

```<code>require 'random_data'
FactoryGirl.define do
  factory :wiki do
    title Faker::Lorem.sentence
    body  RandomData.random_md
    private false
    topic
    user
  end
end

//where random_md is

module RandomData
    def self.random_md
        md = []
        md << Faker::Markdown.headers
        md << Faker::Markdown.block_code
        rand(4..10).times do
            md << Faker::Markdown.random
        end
        md.join("\n")
    end
end
</code>```

From that factory I'm able to seed data and display it correctly on my site.
I even tried this from this website:

```<code>expect("<html>
  <body>
    <h1>some html document</h1>
  </body>
 </html>").to have_tag('body')
</code>```

still, fails...

I guess I must be doing something wrom but don't know what, I would really appreciate any help. Thanks in advance!

EDIT
This is how body looks:

```<code><body>
  <div class="row">
    <div class="col-md-8">
      <h2>Labore</h2>
      .
      .
      .
      <div class="highlight">
        ```
            Quo
            voluptates
            et
            et
            excepturi
            sit
            .
         ```
      </div>
      .
      .
      .
    </div>
  </div>
</body>
</html>
</code>```

答:
have_tag is not Capybara provided and isn't what you should be using with Capybara.  This is because the have_tag matcher provided by rspec-html-matchers, grabs the page source as a string at time of call, parses it with nokogiri, and then queries against it.  That neuters the waiting/retrying behavior Capybara provides and will lead to unstable/non-working tests, not to mention the extra overhead that produces for every query.  What you want is have_css/have_xpath/have_selector

```<code>expect(page).to have_css('pre')
</code>```

A second issue in your test code is that you shouldn't be using current_path with the eq matcher, rather you should be using the have_current_path matcher which utilizes Capybaras waiting/retrying behavior

```<code>expect(page).to have_current_path(topic_wiki_path(@wiki.topic, @wiki.id))
</code>```

Body:
I'm working on a rails application and want to test using capybara, so far I had no problem but now that I'm implementing a markdown parsing feature I cant make my test pass.

I added this test

it "Shows makdown as HTML" do
  visit_wiki
  expect(page).to have_tag('pre')  //**EDITED** becauseof typo
end

And I can't make it work, visit_wiki is just a method to well... visit the wiki.

def visit_wiki
  visit topics_path
  click_link topic.name
  click_link sentence
  expect(current_path).to eq topic_wiki_path(@wiki.topic, @wiki.id)
end

I know that works because I've been using that in other parts of this project.

Here is also my Factory where I make sure to always have one pre HTML tag.

require 'random_data'
FactoryGirl.define do
  factory :wiki do
    title Faker::Lorem.sentence
    body  RandomData.random_md
    private false
    topic
    user
  end
end

//where random_md is

module RandomData
    def self.random_md
        md = []
        md << Faker::Markdown.headers
        md << Faker::Markdown.block_code
        rand(4..10).times do
            md << Faker::Markdown.random
        end
        md.join("\n")
    end
end

From that factory I'm able to seed data and display it correctly on my site.
I even tried this from this website:

expect("

some html document

 ").to have_tag('body')

still, fails...

I guess I must be doing something wrom but don't know what, I would really appreciate any help. Thanks in advance!

EDIT
This is how body looks:

Labore

      .
      .
      .

            Quo
            voluptates
            et
            et
            excepturi
            sit
            .

      .
      .
      .

Body:
have_tag is not Capybara provided and isn't what you should be using with Capybara.  This is because the have_tag matcher provided by rspec-html-matchers, grabs the page source as a string at time of call, parses it with nokogiri, and then queries against it.  That neuters the waiting/retrying behavior Capybara provides and will lead to unstable/non-working tests, not to mention the extra overhead that produces for every query.  What you want is have_css/have_xpath/have_selector

expect(page).to have_css('pre')

A second issue in your test code is that you shouldn't be using current_path with the eq matcher, rather you should be using the have_current_path matcher which utilizes Capybaras waiting/retrying behavior

expect(page).to have_current_path(topic_wiki_path(@wiki.topic, @wiki.id))


问:
SAPUI5 / OpenUI5: Double Conditional binding in XML view
I would like to use conditional binding in my XML view but have two conditions, such as this:

```<code>visible="{= ${viewModel>/selectedTabKey} === 'aaa' && ${viewModel>/editMode} === true}"
</code>```

This is equivalent to the example here (escaped "&&"!).
But when running this, I do get this error:

```<code>BindingParser-dbg.js:341 Uncaught (in promise) SyntaxError: Expected '}' and instead saw '' in expression binding {= ${viewModel>/editMode} === true at position 34
</code>```

What am I doing wrong?

Cheers

答:
The only point I see in your sample is that

```<code>${viewModel>/editMode} === true
</code>```

is redundant and should be simplified to

```<code>${viewModel>/editMode}
</code>```

BUT your error message seems to point elsewhere since it explicitly shows another code

```<code>{= ${viewModel>/editMode} === true
</code>```

(which is not in your sample)

Body:
I would like to use conditional binding in my XML view but have two conditions, such as this:

visible="{= ${viewModel>/selectedTabKey} === 'aaa' && ${viewModel>/editMode} === true}"

This is equivalent to the example here (escaped "&&"!).
But when running this, I do get this error:

BindingParser-dbg.js:341 Uncaught (in promise) SyntaxError: Expected '}' and instead saw '' in expression binding {= ${viewModel>/editMode} === true at position 34

What am I doing wrong?

Cheers

Body:
The only point I see in your sample is that

${viewModel>/editMode} === true

is redundant and should be simplified to

${viewModel>/editMode}

BUT your error message seems to point elsewhere since it explicitly shows another code

{= ${viewModel>/editMode} === true

(which is not in your sample)


问:
Sending Modified Images in PHP via Email
I am working on a script that opens an existing image of a form, and fills in the form. I have typed all of the code necessary to write the text in the form. The problem is that I am trying to send the modified image to email. I am using the GD library ImageCreate, ImageCopy and ImageJPEG. But instead of saving an image, the form is to be emailed. here's what I got so far

```<code>$tempname = "forms/temp".mt_rand().".jpg";
imagejpeg($image, $tempname);
$datamsg = chunk_split(base64_encode(file_get_contents($tempname)));
$uid = md5(uniqid(time()));

$message = "Please see attachment for your form";

$emailheader = "From: email@address.com\r\n";
$emailheader .= "Reply-To: email@address.com \r\n";
$emailheader .= "MIME-Version: 1.0\r\n";

$emailheader .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n";
$emailheader .= "This is a multipart message in Mime-Format\r\n";

$emailheader .= "--" .$uid."\r\n";
$emailheader .= "Content-Type: text/plain;\r\n";
$emailheader .= "Content-Transfer-Encoding: 7bit\r\n";
$emailheader .= $message ."\r\n";
$emailheader .= "--" .$uid."\r\n";
$emailheader .= "Content-Type: Image/JPEG;name=\"jtstemp.jpg\"\r\n";
$emailheader .= "Content-Transfer-Encoding: base64\r\n";
$emailheader .= "Content-Disposition: attachment; Filename=\"jtstemp.jpg\"\r\n";
$emailheader .= $datamsg."\r\n";

if(mail("recipient@address.com", "Sample Subject", "", $emailheader)){
  echo "success";
}else{
   echo "failure";
}
</code>```

The email is registered as having an attachment but it's blank. Also the plain test message isn't showing up.

答:
I would really advise you to use libraries which are build for it.

Good one for images: https://imagine.readthedocs.io/en/latest/

Good one for emails: http://swiftmailer.org/ or https://framework.zend.com/manual/2.1/en/modules/zend.mail.introduction.html

You would get the job done way faster than trying to reimplement it yourself.

Body:
I am working on a script that opens an existing image of a form, and fills in the form. I have typed all of the code necessary to write the text in the form. The problem is that I am trying to send the modified image to email. I am using the GD library ImageCreate, ImageCopy and ImageJPEG. But instead of saving an image, the form is to be emailed. here's what I got so far

$tempname = "forms/temp".mt_rand().".jpg";
imagejpeg($image, $tempname);
$datamsg = chunk_split(base64_encode(file_get_contents($tempname)));
$uid = md5(uniqid(time()));

$message = "Please see attachment for your form";

$emailheader = "From: email@address.com\r\n";
$emailheader .= "Reply-To: email@address.com \r\n";
$emailheader .= "MIME-Version: 1.0\r\n";

$emailheader .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n";
$emailheader .= "This is a multipart message in Mime-Format\r\n";

$emailheader .= "--" .$uid."\r\n";
$emailheader .= "Content-Type: text/plain;\r\n";
$emailheader .= "Content-Transfer-Encoding: 7bit\r\n";
$emailheader .= $message ."\r\n";
$emailheader .= "--" .$uid."\r\n";
$emailheader .= "Content-Type: Image/JPEG;name=\"jtstemp.jpg\"\r\n";
$emailheader .= "Content-Transfer-Encoding: base64\r\n";
$emailheader .= "Content-Disposition: attachment; Filename=\"jtstemp.jpg\"\r\n";
$emailheader .= $datamsg."\r\n";

if(mail("recipient@address.com", "Sample Subject", "", $emailheader)){
  echo "success";
}else{
   echo "failure";
}

The email is registered as having an attachment but it's blank. Also the plain test message isn't showing up.


问:
How do you log an int on Android?
I'm logging this:

```<code>Log.d(getClass().getName(), "BLA BLA BLA");
</code>```

How can I show an int value? What is the equivalent of C's %d?

答:
You can use string concatenation:

```<code>Log.d(getClass().getName(), "value = " + intVar);
</code>```

or more flexibly (and similar to c-style printf) you can use Java's String.format():

```<code>Log.d(getClass().getName(), String.format("value = %d", intVar));
</code>```

ContentLicense: CC BY-SA 4.0

Title: How do you log an int on Android?

Body:
I'm logging this:

Log.d(getClass().getName(), "BLA BLA BLA");

How can I show an int value? What is the equivalent of C's %d?

Body:
You can use string concatenation:

Log.d(getClass().getName(), "value = " + intVar);

or more flexibly (and similar to c-style printf) you can use Java's String.format():

Log.d(getClass().getName(), String.format("value = %d", intVar));

ContentLicense: CC BY-SA 2.5