问:
ImageLoader: connect timed out
I'm using ImageLoader to load images from internet. But I got error message "E ImageLoader: connect timed out", the trace is:

05-29 16:39:02.994  9988 10417 E ImageLoader: connect timed out 05-29
  16:39:02.994  9988 10417 E ImageLoader:
  java.net.SocketTimeoutException: connect timed out 05-29 16:39:02.994
  9988 10417 E ImageLoader:   at
  java.net.PlainSocketImpl.socketConnect(Native Method) 05-29
  16:39:02.994  9988 10417 E ImageLoader:   at
  java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:334)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:196)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356) 05-29
  16:39:02.994  9988 10417 E ImageLoader:   at
  java.net.Socket.connect(Socket.java:605) 05-29 16:39:02.994  9988
  10417 E ImageLoader:   at
  com.android.okhttp.internal.Platform.connectSocket(Platform.java:113)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  com.android.okhttp.Connection.connectSocket(Connection.java:196) 05-29
  16:39:02.994  9988 10417 E ImageLoader:   at
  com.android.okhttp.Connection.connect(Connection.java:172) 05-29
  16:39:02.994  9988 10417 E ImageLoader:   at
  com.android.okhttp.Connection.connectAndSetOwner(Connection.java:367)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:130)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:247)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:480)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:428)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:544)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getResponseCode(DelegatingHttpsURLConnection.java:105)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  com.nostra13.universalimageloader.core.download.BaseImageDownloader.getStreamFromNetwork(BaseImageDownloader.java:117)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  com.nostra13.universalimageloader.core.download.BaseImageDownloader.getStream(BaseImageDownloader.java:88)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  com.nostra13.universalimageloader.core.decode.BaseImageDecoder.getImageStream(BaseImageDecoder.java:98)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  com.nostra13.universalimageloader.core.decode.BaseImageDecoder.decode(BaseImageDecoder.java:74)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.decodeImage(LoadAndDisplayImageTask.java:265)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.tryLoadBitmap(LoadAndDisplayImageTask.java:238)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.run(LoadAndDisplayImageTask.java:136)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  java.lang.Thread.run(Thread.java:761) 05-29 16:39:02.995  9988  9988 D
  TweetAdapter: onLoadingFailed, uri is
  https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A%252520Photographer.jpg,
  failReason IO_ERROR

Here are my code:

```<code>private DisplayImageOptions mOptions;
mOptions = new DisplayImageOptions.Builder()
            .showImageForEmptyUri(R.mipmap.ic_launcher)
            .showImageOnFail(R.mipmap.ic_launcher)
            .cacheInMemory(true)
            .cacheOnDisk(true)
            .build();
mConfig = new ImageLoaderConfiguration.Builder(context)
            .defaultDisplayImageOptions(mOptions)
            .discCacheSize(50 * 1024 * 1024)
            .discCacheFileCount(100)
            .writeDebugLogs().build();
ImageLoader.getInstance().init(mConfig);
</code>```

The definition of ViewHolder is :

```<code>private static class ViewHolder {
    ImageView imageButtonSender;
    TextView textViewSenderUserName;
    TextView textViewSenderContent;
    FrameLayout frameLayoutImages;
    LinearLayout linearLayoutCommentContent;
}
</code>```

in the function "getView" of my adapter, I call this function:

```<code>ImageLoader.getInstance().loadImage("https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQW0S4wK02z4QilNvGE9YFtoJDJtbTsoZavc3INxbD9ZvdRgfxy",
             new ImageLoadingListener() {
                @Override
                public void onLoadingStarted(String imageUri, View view) {

                }

                @Override
                public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                    Log.d(TAG, "onLoadingFailed, uri is " + imageUri + ", failReason " + failReason.getType());
                }

                @Override
                public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                    Log.d(TAG, "onLoadingComplete imageUri " + imageUri);
                    holder.imageButtonSender.setImageBitmap(loadedImage);
                }

                @Override
                public void onLoadingCancelled(String imageUri, View view) {

                }
            });
</code>```

I've tried another URL,such as "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A%252520Photographer.jpg", but the same error happens again.

Who can help me ?

答: Solution: My cellphone can't access to these two URLs which need international internet permission, but my computer can do</p>

Title: ImageLoader: connect timed out

Body:
I'm using ImageLoader to load images from internet. But I got error message "E ImageLoader: connect timed out", the trace is:

05-29 16:39:02.994  9988 10417 E ImageLoader: connect timed out 05-29
  16:39:02.994  9988 10417 E ImageLoader:
  java.net.SocketTimeoutException: connect timed out 05-29 16:39:02.994
  9988 10417 E ImageLoader:   at
  java.net.PlainSocketImpl.socketConnect(Native Method) 05-29
  16:39:02.994  9988 10417 E ImageLoader:   at
  java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:334)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:196)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356) 05-29
  16:39:02.994  9988 10417 E ImageLoader:   at
  java.net.Socket.connect(Socket.java:605) 05-29 16:39:02.994  9988
  10417 E ImageLoader:   at
  com.android.okhttp.internal.Platform.connectSocket(Platform.java:113)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  com.android.okhttp.Connection.connectSocket(Connection.java:196) 05-29
  16:39:02.994  9988 10417 E ImageLoader:   at
  com.android.okhttp.Connection.connect(Connection.java:172) 05-29
  16:39:02.994  9988 10417 E ImageLoader:   at
  com.android.okhttp.Connection.connectAndSetOwner(Connection.java:367)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:130)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:247)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:480)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:428)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:544)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getResponseCode(DelegatingHttpsURLConnection.java:105)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  com.nostra13.universalimageloader.core.download.BaseImageDownloader.getStreamFromNetwork(BaseImageDownloader.java:117)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  com.nostra13.universalimageloader.core.download.BaseImageDownloader.getStream(BaseImageDownloader.java:88)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  com.nostra13.universalimageloader.core.decode.BaseImageDecoder.getImageStream(BaseImageDecoder.java:98)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  com.nostra13.universalimageloader.core.decode.BaseImageDecoder.decode(BaseImageDecoder.java:74)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.decodeImage(LoadAndDisplayImageTask.java:265)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.tryLoadBitmap(LoadAndDisplayImageTask.java:238)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  com.nostra13.universalimageloader.core.LoadAndDisplayImageTask.run(LoadAndDisplayImageTask.java:136)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
  05-29 16:39:02.994  9988 10417 E ImageLoader:   at
  java.lang.Thread.run(Thread.java:761) 05-29 16:39:02.995  9988  9988 D
  TweetAdapter: onLoadingFailed, uri is
  https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A%252520Photographer.jpg,
  failReason IO_ERROR

Here are my code:

private DisplayImageOptions mOptions;
mOptions = new DisplayImageOptions.Builder()
            .showImageForEmptyUri(R.mipmap.ic_launcher)
            .showImageOnFail(R.mipmap.ic_launcher)
            .cacheInMemory(true)
            .cacheOnDisk(true)
            .build();
mConfig = new ImageLoaderConfiguration.Builder(context)
            .defaultDisplayImageOptions(mOptions)
            .discCacheSize(50 * 1024 * 1024)
            .discCacheFileCount(100)
            .writeDebugLogs().build();
ImageLoader.getInstance().init(mConfig);

The definition of ViewHolder is :

private static class ViewHolder {
    ImageView imageButtonSender;
    TextView textViewSenderUserName;
    TextView textViewSenderContent;
    FrameLayout frameLayoutImages;
    LinearLayout linearLayoutCommentContent;
}

in the function "getView" of my adapter, I call this function:

ImageLoader.getInstance().loadImage("https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQW0S4wK02z4QilNvGE9YFtoJDJtbTsoZavc3INxbD9ZvdRgfxy",
             new ImageLoadingListener() {
                @Override
                public void onLoadingStarted(String imageUri, View view) {

                }

                @Override
                public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                    Log.d(TAG, "onLoadingFailed, uri is " + imageUri + ", failReason " + failReason.getType());
                }

                @Override
                public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                    Log.d(TAG, "onLoadingComplete imageUri " + imageUri);
                    holder.imageButtonSender.setImageBitmap(loadedImage);
                }

                @Override
                public void onLoadingCancelled(String imageUri, View view) {

                }
            });

I've tried another URL,such as "https://lh6.googleusercontent.com/-55osAWw3x0Q/URquUtcFr5I/AAAAAAAAAbs/rWlj1RUKrYI/s1024/A%252520Photographer.jpg", but the same error happens again.

Who can help me ?


来源: stackexchange

问:
BadTokenException: Unable to add window, is your activity running?
So I'm seeing the error

```<code>23  android.view.WindowManager$BadTokenException: Unable to add window --
            token android.os.BinderProxy@3970aa84 is not valid; is your activity running?
24  at android.view.ViewRootImpl.setView(ViewRootImpl.java:562)
25  at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:282)
26  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
27  at android.app.Dialog.show(Dialog.java:298)
28  at com.redacted.timerapp.TimerActivity.u(TimerActivity.java:1177)
29  at com.redacted.timerapp.TimerActivity.onStart(TimerActivity.java:271)
</code>```

It's being reported in maybe 0.1% of cases (around 10 a day) but I'm unable to reproduce it. The code for the method follows:

```<code>private void showDonePrompt() {
    if (isFinishing()) return;
    Dialog donePrompt = new Dialog(this, R.style.darkDialogDone);
    donePrompt.requestWindowFeature(Window.FEATURE_NO_TITLE);
    donePrompt.setContentView(R.layout.dialog_dark_done);
    donePrompt.setCancelable(false);

    Button btnRepeat = (Button)donePrompt.findViewById(R.id.btnRepeat);
    btnRepeat.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // some DB operations, etc
            donePrompt.dismiss();
        }
    }
    Button btnStop = (Button)donePrompt.findViewById(R.id.btnStop);
    btnStop.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // some DB operations, etc
            donePrompt.dismiss();
        }
    }

    donePrompt.show(); // this is line 1177 which presumably causes it
}
</code>```

Why is this happening? I check whether the activity isFinishing() and it shouldn't ever try to show the prompt if the activity is not running, right?

答:
You source of isFinishing .

```<code>/**
 * Check to see whether this activity is in the process of finishing,
 * either because you called {@link #finish} on it or someone else
 * has requested that it finished.  This is often used in
 * {@link #onPause} to determine whether the activity is simply pausing or
 * completely finishing.
 *
 * @return If the activity is finishing, returns true; else returns false.
 *
 * @see #finish
 */
public boolean isFinishing() {
    return mFinished;
}
</code>```

So if isFinishing is true , the Activity is destroyed .

You can try this .

```<code>if(!isFinishing()){
    donePrompt.show();
}
</code>```

or

```<code>if(!hasWindowFocus()){
    donePrompt.show();
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So I'm seeing the error

23  android.view.WindowManager$BadTokenException: Unable to add window --
            token android.os.BinderProxy@3970aa84 is not valid; is your activity running?
24  at android.view.ViewRootImpl.setView(ViewRootImpl.java:562)
25  at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:282)
26  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
27  at android.app.Dialog.show(Dialog.java:298)
28  at com.redacted.timerapp.TimerActivity.u(TimerActivity.java:1177)
29  at com.redacted.timerapp.TimerActivity.onStart(TimerActivity.java:271)

It's being reported in maybe 0.1% of cases (around 10 a day) but I'm unable to reproduce it. The code for the method follows:

private void showDonePrompt() {
    if (isFinishing()) return;
    Dialog donePrompt = new Dialog(this, R.style.darkDialogDone);
    donePrompt.requestWindowFeature(Window.FEATURE_NO_TITLE);
    donePrompt.setContentView(R.layout.dialog_dark_done);
    donePrompt.setCancelable(false);

    Button btnRepeat = (Button)donePrompt.findViewById(R.id.btnRepeat);
    btnRepeat.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // some DB operations, etc
            donePrompt.dismiss();
        }
    }
    Button btnStop = (Button)donePrompt.findViewById(R.id.btnStop);
    btnStop.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // some DB operations, etc
            donePrompt.dismiss();
        }
    }

    donePrompt.show(); // this is line 1177 which presumably causes it
}

Why is this happening? I check whether the activity isFinishing() and it shouldn't ever try to show the prompt if the activity is not running, right?

Body:
You source of isFinishing .

/**
 * Check to see whether this activity is in the process of finishing,
 * either because you called {@link #finish} on it or someone else
 * has requested that it finished.  This is often used in
 * {@link #onPause} to determine whether the activity is simply pausing or
 * completely finishing.
 *
 * @return If the activity is finishing, returns true; else returns false.
 *
 * @see #finish
 */
public boolean isFinishing() {
    return mFinished;
}

So if isFinishing is true , the Activity is destroyed .

You can try this .

if(!isFinishing()){
    donePrompt.show();
}

or

if(!hasWindowFocus()){
    donePrompt.show();
}


问:
async / await looping through array of to get s3 signed URL's
I've written the following code.  The input (result) is an array of file names that exist on an S3 bucket.  What I'm hoping to do is loop through that list and retrieve a signed URL for each one.

let result = [{ fileName: "dog.jpg" },{ fileName: "cat.jpg"}];

async function getSignedUrl(key){
    let params = { Bucket: bucketName, Key: key };
    let url = await s3.getSignedUrl('getObject', params, (err, url) => {
      if (err) reject(err)
      return url;
    });
}

async function process(items) {
  for (let item of items) {
    const signedUrl = await getSignedUrl(item.fileName);
    item.url = signedUrl;
  }
  return items;
}

process(result).then(res => {
  console.log(res);
});```

The problem is when I console.log the result, the new URL isn't present.  I can't figure out what the problem is.  I'm guessing it's an async issue but I'm not experienced enough to figure it out.

答:
```<code>let result = [{ fileName: "dog.jpg" },{ fileName: "cat.jpg"}];

async function getSignedUrl(key){
    return new Promise((resolve,reject) => {
      let params = { Bucket: bucketName, Key: key };
      s3.getSignedUrl('getObject', params, (err, url) => {
        if (err) reject(err);
        resolve(url);
      });
});
}

async function process(items) {
  for (let item of items) {
    const signedUrl = await getSignedUrl(item.fileName);
    item.url = signedUrl;
  }
  return items;
}

process(result).then(res => {
  console.log(res);
});
</code>```

NOTE: it's better to use Promise.all() if you are processing an array of possible promises since await stops the execution of that code in async function (not the event loop) even though it's a none blocker function. Doing parallel request is much faster in this scenario

Body:
I've written the following code.  The input (result) is an array of file names that exist on an S3 bucket.  What I'm hoping to do is loop through that list and retrieve a signed URL for each one.

let result = [{ fileName: "dog.jpg" },{ fileName: "cat.jpg"}];

async function getSignedUrl(key){
    let params = { Bucket: bucketName, Key: key };
    let url = await s3.getSignedUrl('getObject', params, (err, url) => {
      if (err) reject(err)
      return url;
    });
}

async function process(items) {
  for (let item of items) {
    const signedUrl = await getSignedUrl(item.fileName);
    item.url = signedUrl;
  }
  return items;
}

process(result).then(res => {
  console.log(res);
});

The problem is when I console.log the result, the new URL isn't present.  I can't figure out what the problem is.  I'm guessing it's an async issue but I'm not experienced enough to figure it out.

Body:
let result = [{ fileName: "dog.jpg" },{ fileName: "cat.jpg"}];

async function getSignedUrl(key){
    return new Promise((resolve,reject) => {
      let params = { Bucket: bucketName, Key: key };
      s3.getSignedUrl('getObject', params, (err, url) => {
        if (err) reject(err);
        resolve(url);
      });
});
}

async function process(items) {
  for (let item of items) {
    const signedUrl = await getSignedUrl(item.fileName);
    item.url = signedUrl;
  }
  return items;
}

process(result).then(res => {
  console.log(res);
});

NOTE: it's better to use Promise.all() if you are processing an array of possible promises since await stops the execution of that code in async function (not the event loop) even though it's a none blocker function. Doing parallel request is much faster in this scenario

ContentLicense: CC BY-SA 4.0


问:
making a binary as little as possible
I have a program written in C and linked to a my static library (.a) in C too. How can I make this program as little as possible, without touch the code (I can recompile it etc)?</p>

答:
The first hing is to strip it from everything like debug symbols, etc.

On linux you can use in a terminal :

```<code>strip myexe
</code>```

You will see the size greatly decrease ^^

I'm no windows guru, but if you use VS, use the release variant.

On every platform, do not use compiler flags that generate debug symbols. If you can use flags that optimize size.

And of course, if you use system libraries or common installed libraries, use dynamically linked libs (dll) or shared objects (so). The libs will not be included in your executable.

my2c

ContentLicense: CC BY-SA 2.5

Title: making a binary as little as possible

Body:
The first hing is to strip it from everything like debug symbols, etc.

On linux you can use in a terminal :

strip myexe

You will see the size greatly decrease ^^

I'm no windows guru, but if you use VS, use the release variant.

On every platform, do not use compiler flags that generate debug symbols. If you can use flags that optimize size.

And of course, if you use system libraries or common installed libraries, use dynamically linked libs (dll) or shared objects (so). The libs will not be included in your executable.

my2c


问:
Jenkins SMTP connection refused. What am I missing?
I've got Jenkins ver 1.524 installed on a Windows 7 box and I'm trying to configure email but the "Test configuration" is reporting errors.  Jenkins is running as a service under my own domain account.

My settings are as follows:

```<code>SMTP server: smtp.corpdomain.com
Default user email suffix: @corpdomain.com
Not using authentication
Not using SSL
SMTP port: 25
Reply-To Address: tools@corpdomain.com
Charset: UTF-8
</code>```

When I test the configuration, I usually get the following exception:

```<code>javax.mail.MessagingException: Could not connect to SMTP host: smtp.amazon.com, port: 25;
  nested exception is:
    java.net.ConnectException: Connection timed out: connect
</code>```

Yet every once in a while I receive the following instead:

```<code>com.sun.mail.smtp.SMTPSendFailedException: 553 5.1.8 <nobody@nowhere>... Domain of sender address nobody@nowhere does not exist
;
  nested exception is:
    com.sun.mail.smtp.SMTPSenderFailedException: 553 5.1.8 <nobody@nowhere>... Domain of sender address nobody@nowhere does not exist
</code>```

However, I am able to send mail from the command line without errors via both python script and java (using javax.mail) without authentication, and I'm able to telnet to the SMTP server on port 25, so I don't see how it could be a firewall issue.

One other note that may be related:  When I try to install a plug-in via the Jenkins web interface, I receive a 403 response for the URL "http://updates.jenkins-ci.org/update-center.json?uctest".  However, I'm able to connect to that URL from a browser on the same machine.

Could this be a Tomcat configuration issue?  I'm not familiar with Tomcat so I'm not sure where to even start looking.  Maybe a Jenkins configuration that I've missed?  Any other ideas?

Thanks in advance!

答:
first, use port 465

second, get your email verified in AWS SES, and change your default sending email from here:
Jenkins -> Configure System -> Jenkins Location -> System Admin e-mail address

Body:
I've got Jenkins ver 1.524 installed on a Windows 7 box and I'm trying to configure email but the "Test configuration" is reporting errors.  Jenkins is running as a service under my own domain account.

My settings are as follows:

SMTP server: smtp.corpdomain.com
Default user email suffix: @corpdomain.com
Not using authentication
Not using SSL
SMTP port: 25
Reply-To Address: tools@corpdomain.com
Charset: UTF-8

When I test the configuration, I usually get the following exception:

javax.mail.MessagingException: Could not connect to SMTP host: smtp.amazon.com, port: 25;
  nested exception is:
    java.net.ConnectException: Connection timed out: connect

Yet every once in a while I receive the following instead:

com.sun.mail.smtp.SMTPSendFailedException: 553 5.1.8 <nobody@nowhere>... Domain of sender address nobody@nowhere does not exist
;
  nested exception is:
    com.sun.mail.smtp.SMTPSenderFailedException: 553 5.1.8 <nobody@nowhere>... Domain of sender address nobody@nowhere does not exist

However, I am able to send mail from the command line without errors via both python script and java (using javax.mail) without authentication, and I'm able to telnet to the SMTP server on port 25, so I don't see how it could be a firewall issue.

One other note that may be related:  When I try to install a plug-in via the Jenkins web interface, I receive a 403 response for the URL "http://updates.jenkins-ci.org/update-center.json?uctest".  However, I'm able to connect to that URL from a browser on the same machine.

Could this be a Tomcat configuration issue?  I'm not familiar with Tomcat so I'm not sure where to even start looking.  Maybe a Jenkins configuration that I've missed?  Any other ideas?

Thanks in advance!


问:
How do i multiply two one-dimensional arrays?
I will be honest with you, I have absolutely no idea what i am doing, nor have the slightest of ideas where to look and it is my homework so if someone would be kind enough to help me out, I would be truly grateful.

"Write a program that declares three arrays named price, qty, and amt.  Each  array should be declared in main()and capable of holding 3 values.  Make up numbers for price and qty (quantity).(ShoppingCart.java) (4 pts) Write a method to fill the amt array with the product of the corresponding elements in price and qty.  (3–create a method within the ShoppingCart class)"

What i have attempted is just this:

```<code>public class Shoppingjava {

    public static void main(String[] args) {

        int price[] = {4, 9, 7};
        int qty[] = {2, 5, 3};
        int amt[] = new int[3];

        System.out.println(product(price, qty));
    }

    public product(int P[], int Q[]) {
        int[][] c = new int[P.length][Q.length];
        return product;
    }

}
</code>```

But i really don't know where to go with this, I am sorry to bother anyone with this and if it someone is willing to help me out, thank you.

答:
```<code>public class ShoppingCart {
    public static void main(String[] args) {

        int price[] = {4, 9, 7};
        int qty[] = {2, 5, 3};
        int amt[] = new int[3];

        for (int i = 0; i < price.length; i++) {
            amt[i] = price[i] * qty[i];
            System.out.println(amt[i]);    //TESTING
        }
    }
</code>```

Body:
I will be honest with you, I have absolutely no idea what i am doing, nor have the slightest of ideas where to look and it is my homework so if someone would be kind enough to help me out, I would be truly grateful.

"Write a program that declares three arrays named price, qty, and amt.  Each  array should be declared in main()and capable of holding 3 values.  Make up numbers for price and qty (quantity).(ShoppingCart.java) (4 pts) Write a method to fill the amt array with the product of the corresponding elements in price and qty.  (3–create a method within the ShoppingCart class)"

What i have attempted is just this:

public class Shoppingjava {

    public static void main(String[] args) {

        int price[] = {4, 9, 7};
        int qty[] = {2, 5, 3};
        int amt[] = new int[3];

        System.out.println(product(price, qty));
    }

    public product(int P[], int Q[]) {
        int[][] c = new int[P.length][Q.length];
        return product;
    }

}

But i really don't know where to go with this, I am sorry to bother anyone with this and if it someone is willing to help me out, thank you.


问:
How to run docker daemon?
I'm trying to run docker daemon using command:

```<code>docker -d
</code>```

but I receive in console:

```<code>unknown shorthand flag: 'd' in -d
</code>```

what should I do to run docker daemon?

答:
I believe the question is how to run the docker in detached mode and connect back, suppose one has Ubuntu image one can try this

```<code>sudo docker run -it -d --name myubdocker ubuntu:latest bash
</code>```

It will detach the docker and one can see it running when one tries this

```<code>sudo docker ps
</code>```

Now how will one attach back to the same docker, thru the following command (CONTAINERID will be listed when one does (docker ps)

```<code>sudo docker exec -it <CONTAINERID> bash
</code>```

This will give a root command prompt ( can one type exit and again connect back )

Title: How to run docker daemon?

Body:
I'm trying to run docker daemon using command:

docker -d

but I receive in console:

unknown shorthand flag: 'd' in -d

what should I do to run docker daemon?

Body:
I believe the question is how to run the docker in detached mode and connect back, suppose one has Ubuntu image one can try this

sudo docker run -it -d --name myubdocker ubuntu:latest bash

It will detach the docker and one can see it running when one tries this

sudo docker ps

Now how will one attach back to the same docker, thru the following command (CONTAINERID will be listed when one does (docker ps)

sudo docker exec -it <CONTAINERID> bash

This will give a root command prompt ( can one type exit and again connect back )


问:
How to upload an image file in a background session (iOS)?
I am unable to upload an image from my device's Photos in a background session.  When I call [session uploadTaskWithRequest:req fromFile:nsurl] the system immediately complains by sending

```<code>Failed to issue sandbox extension for file file:///var/mobile/Media/DCIM/103APPLE/IMG_3984.JPG, errno = 1
</code>```

to the console. (A similar Stack Overflow issue is here)

However, if I create my NSURLSessionConfiguration with [NSURLSessionConfiguration defaultSessionConfiguration] (instead of [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:id], which I need) and if I construct an NSData object out of the NSURL and upload that instead of uploading straight from a file (which is required by a background session) then the upload succeeds.  Btw I'm uploading files into our Rackspace Cloud account, and am able to do this successfully with a simple Postman PUT.

The problem occurs in my uploadObject method, which looks like:

```<code>-(void) uploadObject:(NSURL*)urlToBeUploadedIn
{
  NSDictionary *headers = @{ @"x-auth-token": state.tokenID,
                           @"content-type": @"image/jpeg",
                           @"cache-control": @"no-cache" };

  // create destination url for Rackspace cloud upload
  NSString *sURL = [NSString stringWithFormat:@"%@/testing_folder/%@.jpg", state.publicURL, [state generateImageName]];
  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:sURL]
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:10.0];
  [request setHTTPMethod:@"PUT"];
  [request setAllHTTPHeaderFields:headers];

  self.sessionIdentifier = [NSString stringWithFormat:@"my-background-session"];
  //    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];  // when I use this instead of the line below the sandbox error goes away
  NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:self.sessionIdentifier];
  self.session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];

  NSURLSessionUploadTask *uploadTask = [self.session uploadTaskWithRequest:request fromFile:urlToBeUploadedIn];

  [uploadTask resume];
}
</code>```

My call that invokes uploadObject: looks like:

```<code>    PHFetchResult *fetchResult = [PHAsset fetchAssetsWithLocalIdentifiers:state.arrImagesToBeUploaded options:nil];

    PHAsset *phAsset = [fetchResult objectAtIndex:0]; // yes the 0th item in array is guaranteed to exist, above.
    [phAsset requestContentEditingInputWithOptions:nil
                                   completionHandler:^(PHContentEditingInput *contentEditingInput, NSDictionary *info) {

                                       NSURL *imageURL = contentEditingInput.fullSizeImageURL;
                                       [self uploadObject:imageURL];

                                   }];
</code>```

Btw I first validate the NSURL I send to uploadObject: with a call to fileExistsAtPath: so I know my reference to the file is good.  Finally, my delegate calls

```<code>(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)dataIn

(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error does get invoked, although the data
</code>```

do get called by the server (although the response won't parse) so, I am getting something back from the server which never correctly receives the image.

答:
A solution is to first copy the image to be uploaded into the app's sandbox. I used:

```<code>NSError *err;
BOOL bVal = [myNSDataOb writeToURL:myDestinationURL options:0 error:&err];
</code>```

and copied into my app's 'Documents' directory, but one might also use:

```<code>NSError *err;
BOOL bVal = [[NSFileManager defaultManager] copyItemAtURL:myImageURL toURL:myDestinationURL error:&err];
</code>```

Body:
I am unable to upload an image from my device's Photos in a background session.  When I call [session uploadTaskWithRequest:req fromFile:nsurl] the system immediately complains by sending

Failed to issue sandbox extension for file file:///var/mobile/Media/DCIM/103APPLE/IMG_3984.JPG, errno = 1

to the console. (A similar Stack Overflow issue is here)

However, if I create my NSURLSessionConfiguration with [NSURLSessionConfiguration defaultSessionConfiguration] (instead of [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:id], which I need) and if I construct an NSData object out of the NSURL and upload that instead of uploading straight from a file (which is required by a background session) then the upload succeeds.  Btw I'm uploading files into our Rackspace Cloud account, and am able to do this successfully with a simple Postman PUT.

The problem occurs in my uploadObject method, which looks like:

-(void) uploadObject:(NSURL*)urlToBeUploadedIn
{
  NSDictionary *headers = @{ @"x-auth-token": state.tokenID,
                           @"content-type": @"image/jpeg",
                           @"cache-control": @"no-cache" };

  // create destination url for Rackspace cloud upload
  NSString *sURL = [NSString stringWithFormat:@"%@/testing_folder/%@.jpg", state.publicURL, [state generateImageName]];
  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:sURL]
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:10.0];
  [request setHTTPMethod:@"PUT"];
  [request setAllHTTPHeaderFields:headers];

  self.sessionIdentifier = [NSString stringWithFormat:@"my-background-session"];
  //    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];  // when I use this instead of the line below the sandbox error goes away
  NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:self.sessionIdentifier];
  self.session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];

  NSURLSessionUploadTask *uploadTask = [self.session uploadTaskWithRequest:request fromFile:urlToBeUploadedIn];

  [uploadTask resume];
}

My call that invokes uploadObject: looks like:

    PHFetchResult *fetchResult = [PHAsset fetchAssetsWithLocalIdentifiers:state.arrImagesToBeUploaded options:nil];

    PHAsset *phAsset = [fetchResult objectAtIndex:0]; // yes the 0th item in array is guaranteed to exist, above.
    [phAsset requestContentEditingInputWithOptions:nil
                                   completionHandler:^(PHContentEditingInput *contentEditingInput, NSDictionary *info) {

                                       NSURL *imageURL = contentEditingInput.fullSizeImageURL;
                                       [self uploadObject:imageURL];

                                   }];

Btw I first validate the NSURL I send to uploadObject: with a call to fileExistsAtPath: so I know my reference to the file is good.  Finally, my delegate calls

(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)dataIn

(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error does get invoked, although the data

do get called by the server (although the response won't parse) so, I am getting something back from the server which never correctly receives the image.

Body:
A solution is to first copy the image to be uploaded into the app's sandbox. I used:

NSError *err;
BOOL bVal = [myNSDataOb writeToURL:myDestinationURL options:0 error:&err];

and copied into my app's 'Documents' directory, but one might also use:

NSError *err;
BOOL bVal = [[NSFileManager defaultManager] copyItemAtURL:myImageURL toURL:myDestinationURL error:&err];


问:
stop javascript loop, setTimeout
This animation should stop playing (stop snowing) after 10 seconds. I added a function to the bottom, but it actually starts the animation after 10 seconds, rather than stopping the animation after 10 seconds.

I only want it to play for 10 seconds total time, and start right-away, see my codePen to see what I mean.

```<code>setTimeout(function() {
createSnow(20);
loop();
}, 10000)
</code>```

here is a codePen to see what I mean:
https://codepen.io/celli/pen/XzzjRW

答:
You were close. You just needed a way to tell the system to stop the animation loop. See my codepen: https://codepen.io/intervalia/pen/zPPoBZ

I added a variable to indicate if animation should be happening:

```<code>var animating = true;
</code>```

A routine to stop the animation:

```<code>function stopAnimation() {
  animating = false;
  //Add something in here to clear the screen
}
</code>```

A validation check in the animation loop:

```<code>function loop() {
  if (animating) {
    draw();
    update();
    animFrame(loop);
  }
}
</code>```

And changed your timeout to turn off the animation:

```<code>createSnow(150);
loop();

setTimeout(stopAnimation, 10000);
</code>```

Cool animation!!

Title: stop javascript loop, setTimeout

Body:
This animation should stop playing (stop snowing) after 10 seconds. I added a function to the bottom, but it actually starts the animation after 10 seconds, rather than stopping the animation after 10 seconds.

I only want it to play for 10 seconds total time, and start right-away, see my codePen to see what I mean.

setTimeout(function() {
createSnow(20);
loop();
}, 10000)

here is a codePen to see what I mean:
https://codepen.io/celli/pen/XzzjRW

Body:
You were close. You just needed a way to tell the system to stop the animation loop. See my codepen: https://codepen.io/intervalia/pen/zPPoBZ

I added a variable to indicate if animation should be happening:

var animating = true;

A routine to stop the animation:

function stopAnimation() {
  animating = false;
  //Add something in here to clear the screen
}

A validation check in the animation loop:

function loop() {
  if (animating) {
    draw();
    update();
    animFrame(loop);
  }
}

And changed your timeout to turn off the animation:

createSnow(150);
loop();

setTimeout(stopAnimation, 10000);

Cool animation!!


问:
Responsive sidebar images don't show on resize
This is my sidebar : https://jsfiddle.net/8ejwykwv/1/

The issue is that on small screens, sidebar completely disappears. Whereas what I'm trying to  achieve is on a certain screen size, have only images displayed. example : Home icon without Home text. And on a very small screen have only a button that slides the sidebar left and right or top-down.

I tried using

```<code> @media(min-width:42em){
     .sidebar{
        width:4em;
     }
 }
</code>```

But I'm pretty much lost.
I understand media queries and what can be done with them, but I'm not sure how to manipulate with my sidebar and topbar so that I have like fa-fa bars that on click will show more than just an image.

Link as a reference to what I have been trying:

This link and/or This example

Any help is appreciated. I'm a beginner so I apologize in advance if it may be simple thing. Any help is appreciated!

答:
Just fix the width in sidebar class:

```<code>.sidebar {
    position: fixed;
    top: 50px;
    bottom: 0;
    width:160px !important;
    left: 0;
    z-index: 1000;
    padding: 0;
    overflow-x: hidden;
    overflow-y: auto;
    border-right: 1px solid #eee;
    background-color: black

}
</code>```

Here is the fiddle https://jsfiddle.net/c8h5ede7/8/

EDIT
You can also try this solution

```<code> @media only screen and (max-width: 42em) {
    .sidebar{
        width:8em !important;
     }
}
</code>```

https://jsfiddle.net/c8h5ede7/12/

Body:
This is my sidebar : https://jsfiddle.net/8ejwykwv/1/

The issue is that on small screens, sidebar completely disappears. Whereas what I'm trying to  achieve is on a certain screen size, have only images displayed. example : Home icon without Home text. And on a very small screen have only a button that slides the sidebar left and right or top-down.

I tried using

 @media(min-width:42em){
     .sidebar{
        width:4em;
     }
 }

But I'm pretty much lost.
I understand media queries and what can be done with them, but I'm not sure how to manipulate with my sidebar and topbar so that I have like fa-fa bars that on click will show more than just an image.

Link as a reference to what I have been trying:

This link and/or This example

Any help is appreciated. I'm a beginner so I apologize in advance if it may be simple thing. Any help is appreciated!

Body:
Just fix the width in sidebar class:

.sidebar {
    position: fixed;
    top: 50px;
    bottom: 0;
    width:160px !important;
    left: 0;
    z-index: 1000;
    padding: 0;
    overflow-x: hidden;
    overflow-y: auto;
    border-right: 1px solid #eee;
    background-color: black

}

Here is the fiddle https://jsfiddle.net/c8h5ede7/8/

EDIT
You can also try this solution

 @media only screen and (max-width: 42em) {
    .sidebar{
        width:8em !important;
     }
}

https://jsfiddle.net/c8h5ede7/12/


问:
how can i assign no in column A based on Value in B and if there is any Duplicated values assign the same no.?

if Column "A" was empty how can i make excel assign unique no# to unique cells and duplicated no# to duplicated cells just like the image attached.

答:
While I am sure there is probably an easier way to accomplish your task, this one seems to work okay (disclaimer: lightly tested).

So essentially, serialNumber attempts to find the highest value in Col A. If none is found, it's assigned a value of 1.

RetCel attempts to set itself to a previous cell that matches. If no match is found, it will assign the current serialNumber value. If a match is found, then it will use the value of the match.

serialNumber only increases itself when the value has been used.

```<code>Option Explicit

Sub AssignUnique()

    On Error GoTo ErrHandler
    Dim ws As Worksheet, RngA As Range, RngB As Range, cel As Range
    Set ws = ThisWorkbook.Worksheets("Sheet3")
    Set RngA = ws.UsedRange.Columns("A")
    Set RngB = ws.UsedRange.Columns("B")

    If RngA.Column = 2 Then
        'In the event RngA is empty, UsedRange will make it col B
        Set RngA = RngA.Offset(, -1)
        Set RngB = RngB.Offset(, -1)
        If RngA.Column <> 1 Then
            Err.Raise vbObjectError + 1000, , "Error setting RngA"
        End If
    End If

    Dim RetCel As Range, serialNumber As Long
    serialNumber = WorksheetFunction.Max(RngA)
    If serialNumber = 0 Then serialNumber = 1
    For Each cel In RngB.Cells
        Set RetCel = Nothing
        On Error Resume Next
        Set RetCel = ws.Cells.Find(cel.Value, After:=Cells(cel.Row - 1, 2), _
            SearchDirection:=xlPrevious)
        Debug.Print RetCel.Address
        On Error GoTo ErrHandler
        If cel.Value = vbNullString Then
            'Do Nothing
        ElseIf RetCel Is Nothing Then
            cel.Offset(, -1).Value = serialNumber
            serialNumber = serialNumber + 1
        Else
            cel.Offset(, -1).Value = RetCel.Offset(, -1).Value
            If cel.Offset(, -1).Value = vbNullString Then
                cel.Offset(, -1).Value = serialNumber
                serialNumber = serialNumber + 1
            End If
        End If
    Next cel
    Exit Sub
ErrHandler:
    MsgBox Err.Description, vbCritical, "Runtime # " & Err.Number

End Sub
</code>```

Body:
While I am sure there is probably an easier way to accomplish your task, this one seems to work okay (disclaimer: lightly tested).

So essentially, serialNumber attempts to find the highest value in Col A. If none is found, it's assigned a value of 1.

RetCel attempts to set itself to a previous cell that matches. If no match is found, it will assign the current serialNumber value. If a match is found, then it will use the value of the match.

serialNumber only increases itself when the value has been used.

Option Explicit

Sub AssignUnique()

    On Error GoTo ErrHandler
    Dim ws As Worksheet, RngA As Range, RngB As Range, cel As Range
    Set ws = ThisWorkbook.Worksheets("Sheet3")
    Set RngA = ws.UsedRange.Columns("A")
    Set RngB = ws.UsedRange.Columns("B")

    If RngA.Column = 2 Then
        'In the event RngA is empty, UsedRange will make it col B
        Set RngA = RngA.Offset(, -1)
        Set RngB = RngB.Offset(, -1)
        If RngA.Column <> 1 Then
            Err.Raise vbObjectError + 1000, , "Error setting RngA"
        End If
    End If

    Dim RetCel As Range, serialNumber As Long
    serialNumber = WorksheetFunction.Max(RngA)
    If serialNumber = 0 Then serialNumber = 1
    For Each cel In RngB.Cells
        Set RetCel = Nothing
        On Error Resume Next
        Set RetCel = ws.Cells.Find(cel.Value, After:=Cells(cel.Row - 1, 2), _
            SearchDirection:=xlPrevious)
        Debug.Print RetCel.Address
        On Error GoTo ErrHandler
        If cel.Value = vbNullString Then
            'Do Nothing
        ElseIf RetCel Is Nothing Then
            cel.Offset(, -1).Value = serialNumber
            serialNumber = serialNumber + 1
        Else
            cel.Offset(, -1).Value = RetCel.Offset(, -1).Value
            If cel.Offset(, -1).Value = vbNullString Then
                cel.Offset(, -1).Value = serialNumber
                serialNumber = serialNumber + 1
            End If
        End If
    Next cel
    Exit Sub
ErrHandler:
    MsgBox Err.Description, vbCritical, "Runtime # " & Err.Number

End Sub


问:
returning an iterator from a function
I have the following example:

```<code>#include <stdio.h>
#include <map>
#include <conio.h>

typedef std::map<int,int> mi;
typedef std::map<int,int>::iterator mit;

mit myfind(mi mymap)
{
    mit it = mymap.find(1);
    printf("in function: %d\n",it->second);

    return it;
}

void main()
{
    mi a;
    a.insert(std::pair<int,int>(1,2));
    a.insert(std::pair<int,int>(3,4));

    mit it = myfind(a);

    printf("out of function: %d\n",it->second);

    _getch();

}
</code>```

The output is:

in function: 2

out of function: -17891602

Why? Does the iterator become invalid? Why? Thanks in advance.

答: You're passing the map by value. Therefore, myfind() operates on a copy of the map, and the iterator is only valid for the copy. Pass the map by reference instead.</p>

Title: returning an iterator from a function

Body:
I have the following example:

#include <stdio.h>
#include <map>
#include <conio.h>

typedef std::map<int,int> mi;
typedef std::map<int,int>::iterator mit;

mit myfind(mi mymap)
{
    mit it = mymap.find(1);
    printf("in function: %d\n",it->second);

    return it;
}

void main()
{
    mi a;
    a.insert(std::pair<int,int>(1,2));
    a.insert(std::pair<int,int>(3,4));

    mit it = myfind(a);

    printf("out of function: %d\n",it->second);

    _getch();

}

The output is:

in function: 2

out of function: -17891602

Why? Does the iterator become invalid? Why? Thanks in advance.


问:
Gradle cannot find module's output jar when executing custom task
I have a Gradle project with three modules, each with nested dependency on the next:

```<code>android app module, which depends on...
   android lib module, which depends on ...
      java lib module (called core)
</code>```

Inside my lib module I'm trying to create a custom task (to generate javadocs, but that's prob not relevant)

library/build.gradle:

```<code>apply plugin: 'com.android.library'

android {
    ...
}

android.libraryVariants.all { variant ->
    task("${variant.name}Docs", type: Javadoc) {
        failOnError true
        source = variant.javaCompiler.source
        classpath = files(((Object) android.bootClasspath.join(File.pathSeparator)))
        classpath += files(variant.javaCompiler.classpath.files) // THIS LINE IS CAUSING ERROR
    }
}

dependencies {
    implementation project(':core')
    ...
}
</code>```

The problem is that when I run any Gradle task (even Gradle clean), I get an error about not finding core.jar

org.gradle.api.ProjectConfigurationException: A problem occurred
  configuring project ':library'.

Caused by:
  org.gradle.api.artifacts.transform.ArtifactTransformException: Failed
  to transform file 'core.jar' to match attributes
  {artifactType=android-classes} using transform JarTransform

Caused by: org.gradle.api.InvalidUserDataException: Transform output
  file ******/core/build/libs/core.jar does not exist.

I guess this is happening because Gradle is looking for all files needed library's classpath (including core.jar) during the configuration phase. But why?

Why doesn't gradle only resolve dependencies during execution? (i.e. Why do I see this error for every gradle task?)

How to I tell gradle to build core.jar before executing this custom task?

答:
I don't really know why this worked, but simply removing the .files from the problem line solved things:

```<code>classpath += files(variant.javaCompiler.classpath)
</code>```

Body:
I have a Gradle project with three modules, each with nested dependency on the next:

android app module, which depends on...
   android lib module, which depends on ...
      java lib module (called core)

Inside my lib module I'm trying to create a custom task (to generate javadocs, but that's prob not relevant)

library/build.gradle:

apply plugin: 'com.android.library'

android {
    ...
}

android.libraryVariants.all { variant ->
    task("${variant.name}Docs", type: Javadoc) {
        failOnError true
        source = variant.javaCompiler.source
        classpath = files(((Object) android.bootClasspath.join(File.pathSeparator)))
        classpath += files(variant.javaCompiler.classpath.files) // THIS LINE IS CAUSING ERROR
    }
}

dependencies {
    implementation project(':core')
    ...
}

The problem is that when I run any Gradle task (even Gradle clean), I get an error about not finding core.jar

org.gradle.api.ProjectConfigurationException: A problem occurred
  configuring project ':library'.

Caused by:
  org.gradle.api.artifacts.transform.ArtifactTransformException: Failed
  to transform file 'core.jar' to match attributes
  {artifactType=android-classes} using transform JarTransform

Caused by: org.gradle.api.InvalidUserDataException: Transform output
  file ******/core/build/libs/core.jar does not exist.

I guess this is happening because Gradle is looking for all files needed library's classpath (including core.jar) during the configuration phase. But why?

Why doesn't gradle only resolve dependencies during execution? (i.e. Why do I see this error for every gradle task?)

How to I tell gradle to build core.jar before executing this custom task?

Body:
I don't really know why this worked, but simply removing the .files from the problem line solved things:

classpath += files(variant.javaCompiler.classpath)


问:
Add json object to php array
I have two arrays, or so I thought. One passes a Javascript object to php via a POST, the other gets data from a JS API which returns another object. I want to join both of these arrays. Here's the sample data and how it is obtained.

Name array which I get from API:-

```<code>array(5) { [0]=> string(1) "D" [1]=> string(1) "a" [2]=> string(1) "v" [3]=> string(1) "i" [4]=> string(1) "d" }
</code>```

User array which is POST'd to my php script:-

```<code>array (
  'userID' => '12345',
  'time' => 'Monday 26th June 2017 22:12:37 AM',
)
</code>```

Now I use the following to (try) and get both of these pieces of data into the same array to log to a file.

```<code>$nameoriginal = file_get_contents("/api");
$namejson = json_decode($name);

$user = var_export($_POST, true);

$detailstolog = $namejson + $user;

file_put_contents('/logs/names.log', $detailstolog);
</code>```

However, I get a php error which states the first argument is not a valid array (i.e. $name is not valid). Why is this? What can I do to 'make' it an array?

I think the name 'array' is actually a string, hence the error. How do I make this an array, and is $array1 + $array2 the best way to do this?

I am trying to create something like:-

```<code>array (
  'name' => 'david',
  'userID' => '12345',
  'time' => 'Monday 26th June 2017 22:12:37 AM',
)
</code>```

Thanks for any help you can provide!

答:
Copy the $_POST array to a new variable, then add the name to it.

```<code>$detailstolog = $_POST;
$name = implode('', $namejson);
$detailstolog['name'] = $name;
</code>```

Title: Add json object to php array

Body:
I have two arrays, or so I thought. One passes a Javascript object to php via a POST, the other gets data from a JS API which returns another object. I want to join both of these arrays. Here's the sample data and how it is obtained.

Name array which I get from API:-

array(5) { [0]=> string(1) "D" [1]=> string(1) "a" [2]=> string(1) "v" [3]=> string(1) "i" [4]=> string(1) "d" }

User array which is POST'd to my php script:-

array (
  'userID' => '12345',
  'time' => 'Monday 26th June 2017 22:12:37 AM',
)

Now I use the following to (try) and get both of these pieces of data into the same array to log to a file.

$nameoriginal = file_get_contents("/api");
$namejson = json_decode($name);

$user = var_export($_POST, true);

$detailstolog = $namejson + $user;

file_put_contents('/logs/names.log', $detailstolog);

However, I get a php error which states the first argument is not a valid array (i.e. $name is not valid). Why is this? What can I do to 'make' it an array?

I think the name 'array' is actually a string, hence the error. How do I make this an array, and is $array1 + $array2 the best way to do this?

I am trying to create something like:-

array (
  'name' => 'david',
  'userID' => '12345',
  'time' => 'Monday 26th June 2017 22:12:37 AM',
)

Thanks for any help you can provide!

Body:
Copy the $_POST array to a new variable, then add the name to it.

$detailstolog = $_POST;
$name = implode('', $namejson);
$detailstolog['name'] = $name;


问:
Use grep to extract specific words from a string under conditions and print it to variable file names
I have a sample file like this:

r 2.1238 /NodeList/1/DeviceList/1/ ( type=0x806, source=00:00, destination=ff:ff) ns3::IPv4Header (source ipv4: 10.1.2.1 dest ipv4: 10.1.2.4)

+ 2.0076 /NodeList/0/DeviceList/1/ ( type=0x806, source=00:00, destination=ff:ff) ns3::ArpHeader (source ipv4: 10.1.2.1 dest ipv4: 10.1.2.4)

- 2.0077 /NodeList/1/DeviceList/1/ ( type=0x806, source=00:00, destination=ff:ff) ns3::IPv4Header (source ipv4: 10.1.2.1 dest ipv4: 10.1.2.4)

d 4.0042 /NodeList/2/DeviceList/1/ ( type=0x806, source=00:00, destination=ff:ff) ns3::IPv4Header (source ipv4: 10.1.2.1 dest ipv4: 10.1.2.4)

and so on.

The bold parts are the important fields. The first field can be '-', '+', 'r' or 'd'. The second field has a time stamp, in bold. Third field is to be the Node number, again in bold. The node number refers to the file to which the previous two fields is to be printed.

The restriction is that I want data from only those lines containing IPv4Header, eg. 1st, 3rd and 4th line in above sample.

So, I want my output to be like:

Node0.txt:
+ 2.0076

Node1.txt:
r 2.1238
- 2.0077

As you can see Node0 in line 2 is rejected as it does not contain IPv4Header. As we can see the number of output files being generated is equal to the number of nodes having IPv4Header.

Assume the number of lines and nodes to be multiple and variable for different files. Can someone please provide me with the necessary grep code?

答:
awk to the rescue!

```<code>$ awk -F/ '/IPv4Header/{print $1 > "Node" $3 ".txt" }' file
</code>```

should create two files with contents

```<code>Node1.txt: r 2.1238
           - 2.0077
Node2.txt: d 4.0042
</code>```

note that Node0 won't be created as per your definition.

Body:
awk to the rescue!

$ awk -F/ '/IPv4Header/{print $1 > "Node" $3 ".txt" }' file

should create two files with contents

Node1.txt: r 2.1238
           - 2.0077
Node2.txt: d 4.0042

note that Node0 won't be created as per your definition.


问:
How do I get a consistent byte representation of strings in C# without manually specifying an encoding?
How do I convert a string to a byte[] in .NET (C#) without manually specifying a specific encoding?

I'm going to encrypt the string. I can encrypt it without converting, but I'd still like to know why encoding comes to play here.

Also, why should encoding even be taken into consideration? Can't I simply get what bytes the string has been stored in? Why is there a dependency on character encodings?

答:
The first part of your question (how to get the bytes) was already answered by others: look in the System.Text.Encoding namespace.

I will address your follow-up question: why do you need to pick an encoding?  Why can't you get that from the string class itself?

The answer is in two parts.

First of all, the bytes used internally by the string class don't matter, and whenever you assume they do you're likely introducing a bug.

If your program is entirely within the .Net world then you don't need to worry about getting byte arrays for strings at all, even if you're sending data across a network. Instead, use .Net Serialization to worry about transmitting the data.  You don't worry about the actual bytes anymore: the Serialization formatter does it for you.

On the other hand, what if you are sending these bytes somewhere that you can't guarantee will pull in data from a .Net serialized stream? In this case, you definitely do need to worry about encoding, because obviously, this external system cares. So again, the internal bytes used by the string don't matter: you need to pick an encoding so you can be explicit about this encoding on the receiving end, even if it's the same encoding used internally by .Net.

I understand that in this case, you might prefer to use the actual bytes stored by the string variable in memory where possible, with the idea that it might save some work creating your byte stream. However, I put it to you it's just not important compared to making sure that your output is understood at the other end, and to guarantee that you must be explicit with your encoding. Additionally, if you really want to match your internal bytes, you can already just choose the Unicode encoding, and get those performance savings.

This brings me to the second part... picking the Unicode encoding is telling .Net to use the underlying bytes. You do need to pick this encoding because when some new-fangled Unicode-Plus comes out the .Net runtime needs to be free to use this newer, better encoding model without breaking your program. But, for the moment (and foreseeable future), just choosing the Unicode encoding gives you what you want.

It's also important to understand your string has to be rewritten to wire, and that involves at least some translation of the bit-pattern even when you use a matching encoding. The computer needs to account for things like Big vs Little Endian, network byte order, packetization, session information, etc.

OwnerDisplayName: Vulcan Eager

LastEditorDisplayName: Dale Ragan

OwnerDisplayName: Joel Coehoorn

LastEditorDisplayName: Joel Coehoorn


问:
JQuery not keyword
```<code>$("li a").click(function() {
    $(this).parent().css({ width: 160 });
    $("li").unbind('mouseenter mouseleave');
    $("#Container").css({ width: 200 }).animate({ width: 700 }, 1000);
});
</code>```

I wanna set width 120 for all li's except current(this).

Thanks

Title: JQuery not keyword

Body:
$("li a").click(function() {
    $(this).parent().css({ width: 160 });
    $("li").unbind('mouseenter mouseleave');
    $("#Container").css({ width: 200 }).animate({ width: 700 }, 1000);
});

I wanna set width 120 for all li's except current(this).

Thanks

Body:
$("li a").click(function() {
      $("li").not($(this).parent()).width(120);
});


问:
Ionic Native Storage is not persisting after rebuilding app
I am using ionic 3 native storage and store a value like this:

```<code>this.storage.set('myValue', this.value);
</code>```

Then I rebuild the app and try to get that value and it returns null:

```<code>this.storage.get('myValue').then(value => {
console.log('My value: ' + value);
})
</code>```

The result is: My value: null

Not sure why its doing this isn't storage suppose to store it in the database so it should not matter if I rebuild the app or not?

答:
You need to install SQLite plugin.

When running in a native app context, Storage will prioritize using
  SQLite, as it's one of the most stable and widely used file-based
  databases, and avoids some of the pitfalls of things like localstorage
  and IndexedDB, such as the OS deciding to clear out such data in low
  disk-space situations.

```<code>ionic cordova plugin add cordova-sqlite-storage
</code>```

Body:
I am using ionic 3 native storage and store a value like this:

this.storage.set('myValue', this.value);

Then I rebuild the app and try to get that value and it returns null:

this.storage.get('myValue').then(value => {
console.log('My value: ' + value);
})

The result is: My value: null

Not sure why its doing this isn't storage suppose to store it in the database so it should not matter if I rebuild the app or not?

Body:
You need to install SQLite plugin.

When running in a native app context, Storage will prioritize using
  SQLite, as it's one of the most stable and widely used file-based
  databases, and avoids some of the pitfalls of things like localstorage
  and IndexedDB, such as the OS deciding to clear out such data in low
  disk-space situations.

ionic cordova plugin add cordova-sqlite-storage


问:
SVG and Canvas read SVG data differently
I am attempting to write some JS which uses Canvas to emulate how SVG draws a shape on an image but I can't seem to get it to work.

I have some SVG data which draws a mouth on a face.

```<code><svg id="svgTag" style="background: url('https://image.ibb.co/h9CWiR/odd_size.png') no-repeat " xmlns="http://www.w3.org/2000/svg" version="1.0" width="379.000000" height="540.000000" viewBox="0 0 379.000000 540.000000" preserveAspectRatio="xMidYMid meet">
    <g transform="translate(0.000000,540.0000) scale(1.000000,-1.000000)" fill="#000000" stroke="none">
        <path d="M172 147
               c-21 -1 -69 -8 -74 -10
               l-2 -1 0 -32 0 -33 3 -4
               c9 -14 31 -36 44 -45
               12 -9 16 -11 27 -13
               2 -1 8 -2 12 -2
               9 -2 33 -3 34 -1
               0 1 1 1 2 1
               2 0 6 1 9 2
               16 5 29 14 47 32
               l9 8 0 44
               c0 33 0 43 -1 44 -4 3 -31 8 -49 10 -14 1 -44 1 -61 0
               z"/>
    </g>
</svg>
</code>```

I have a fiddle of this here: https://jsfiddle.net/nhoughto5/5dhn1nm1/

I have written some javascript which takes the path data from the SVG element, parses it then uses Canvas methods to draw the same mouth. I've implemented a recursive solution to step through each command and draw it in exactly the same way.

```<code> const commandString = /[\-0-9,. ]+/ig;
  const commandPattern = /[A-z]+/ig;
  const stringSplit = /[, ]+/ig;
  const shiftX = 0, shiftY = 0;

  function cleanArray(array) {
    const tmpArray = [];
    for (let i = 0; i < array.length; i++) {
      if (array[i].length > 0) {
        tmpArray.push(parseInt(array[i]));
      }
    }
    return tmpArray;
  }
  function move(array, context) {
    let x = array[0];
    let y = array[1];
    context.moveTo(x + shiftX, y + shiftY);
    //context.fill();
  }

  function quadraticTo(array, context) {
    let x = array[0];
    let y = array[1];
    let x1 = array[2];
    let y1 = array[3];
    context.quadraticCurveTo(x + shiftX, y + shiftY, x1 + shiftX, y1 + shiftY);
    context.fill();
    if (array.length > 4) {
      quadraticTo(array.splice(4, array.length), context);
    }
  }

  function lineTo(array, context) {
    let x = array[0];
    let y = array[1];
    context.lineTo(x + shiftX, y + shiftY);
    context.fill();
    if (array.length > 2) {
      lineTo(array.splice(2, array.length), context);
    }
  }

  function curveTo(array, context) {
    let x = array[0];
    let y = array[1];
    let x1 = array[2];
    let y1 = array[3];
    let x2 = array[4];
    let y2 = array[5];
    context.bezierCurveTo(x + shiftX, y + shiftY, x1 + shiftX, y1 + shiftY, x2 + shiftX, y2 + shiftY);
    context.fill();
    if (array.length > 6) {
      this._curveTo(array.splice(6, array.length), context);
    }
  }
  function draw(path, context){
    var commands = path.split(commandPattern);
    var commandArray = path.split(commandString);

    for (let i = 0, len = commandArray.length; i < len; i++) {
      let action = commandArray[i].toUpperCase();
      if (typeof commands[i] === 'undefined') break;

      const array = cleanArray(commands[i].split(stringSplit));
      switch (action) {
        case "M":
          move(array, context);
          break;
        case "C":
          curveTo(array, context);
          break;
        case "Q":
          quadraticTo(array, context);
          break;
        case "L":
          lineTo(array, context);
          break;
        case "Z":
          context.closePath();
          break;
        default:
      }
    }
  }
  function makeCanvas(canvas, ctx, img){
    var svg = document.getElementById("svgTag");
    var groups = svg.getElementsByTagName("g");
    var path = groups[0].childNodes[1].getAttribute("d");
    ctx.drawImage(img, 10, 10);
    ctx.fillStyle = "black";
    console.log(path);
    draw(path, ctx);
  }
  function imageCanvas() {
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var img = document.createElement("IMG");
    img.addEventListener('load', function() {
      makeCanvas(c, ctx, img);
    }.bind(this), false);
    img.setAttribute("src", "https://image.ibb.co/h9CWiR/odd_size.png");

  }

  window.onload = imageCanvas();
</code>```

Again, I have created a fiddle demonstrating this here:https://jsfiddle.net/nhoughto5/whwxtxcp/1/

The problem is that it seems completely wrong. At first I thought that it might be an issue with the translate value in the SVG group. I added a constant at the top of the JS to easily translate it around. If you modify the translate constants to: const translateX = 100, translateY = 300; what it draws will move into the middle and you can see that it is fantastically wrong.

I've stepped through my solution and checked that the data is being spliced and drawn onto the canvas in the correct order. Does canvas do something different to SVG that I'm not aware of? Not to toot my own horn but I'm fairly confident that my implementation is correct but there is something that I'm missing.

答:
Setting the relative origin for Path2D

Your problem is that you are incorrectly setting the relative positions. Also you need to set the correct transform.

Transform

The SVG transform is  translate(0.000000,540.0000) scale(1.000000,-1.000000)

Which is the equivalent to

```<code>ctx.setTransform(1, 0, 0, -1, 0, 540);
//               |         |  |  |
//              (x scale)  | (x  y  translate)
//                        (y scale)
</code>```

d Path

For the command "M x1 y1 c x2 y2 x3 y3 x4 y4 l x5 y5" where x,y represent coord pairs.

The equivalent canvas commands are

```<code>var ox = 0, oy = 0; // the relative origin
ox = X1; oy = Y1;
ctx.moveTo(ox, oy);
ctx.bezierCurveTo(ox + x2, oy + y2, ox + x3, oy + y3, ox = ox + x4, oy = oy + y4)
//                                                    ^^ new origin ^^ new origin
ctx.lineTo(ox = ox + x5, oy = ox + y5);
//         ^^ new origin ^^ new origin
</code>```

Note that the last point for each segment is used to set the new relative origin

The code below is a modification of some of your snippet that correctly parses and executes the path commands.

```<code>// Only partial solution
// implement a subset of the 2D path string commands
const canvasPath = (()=>{
    var ctx, ox = 0, oy = 0;
    const [x, y] = [(p) => ox + p.shift(), (p) => oy + p.shift()];
    const X = (p) => p.shift(), Y = X;
    return {
        set context(ctx_) { ctx = ctx_ },
        c(p) { while(p.length > 0) { ctx.bezierCurveTo(x(p), y(p), x(p), y(p), ox = x(p), oy = y(p)) } },
        q(p) { while(p.length > 0) { ctx.quadraticCurveTo(x(p), y(p), ox = x(p), oy = y(p)) } },
        l(p) { while(p.length > 0) { ctx.lineTo(ox = x(p), oy = y(p)) } },
        z()  { ctx.closePath() },
        M(p) { ctx.moveTo(ox = X(p), oy = Y(p)) },
    };
})();

// This may throw for some paths as it cobers only some path commands
function parsePath(path) {
    var subPath, paths = [];
    path.replace(/([Mzlqc])|([\-0-9.]+)/g, s => {
        if ("Mzlqc".indexOf(s) > -1) { paths.push(subPath = {type : s , points : []}) }
        else { subPath.points.push(Number(s)) }
        return s;
    });
    return paths;
}

// parses a path string and then adds that path to the canvas via canvasPath
function draw(path) {
    const subPaths = parsePath(path);
    for (const {type, points} of subPaths) { canvasPath[type](points) }
}

// Taken from OP snippet and modified to use above functions.
function makeCanvas(canvas, ctx, img) {
    var svg = document.getElementById("svgTag");
    var groups = svg.getElementsByTagName("g");
    var path = groups[0].childNodes[1].getAttribute("d");
    ctx.drawImage(img, 0, 0); // NOTE image moved to 0,0

    // from SVG "translate(0.000000,540.0000) scale(1.000000,-1.000000)
    ctx.setTransform(1, 0, 0, -1, 0, 540);
    canvasPath.context = ctx;
    ctx.beginPath();
    draw(path);
    ctx.fill()
}
</code>```

Use Path2D

But that is a lot of hard work, and why do all that when you can use the Path2D object to do the work for you.

Path2D will accept a SVG path

```<code>const path = new Path2D(`M172 147
    c-21 -1 -69 -8 -74 -10
    l-2 -1 0 -32 0 -33 3 -4
    c9 -14 31 -36 44 -45 12 -9 16 -11 27 -13  2 -1 8 -2 12 -2  9 -2 33 -3 34 -1 0 1
    1 1 2 1 2 0 6 1 9 2 16 5 29 14 47 32
    l9 8 0 44
    c0 33 0 43 -1 44 -4 3 -31 8 -49 10 -14 1 -44 1 -61 0 z`
);
</code>```

You can render the path with the fill and stroke commands

```<code>ctx.fill(path);
ctx.stroke(path);
</code>```

Thus your code is simplified to.

```<code>  function makeCanvas(canvas, ctx, img){
    var svg = document.getElementById("svgTag");
    var groups = svg.getElementsByTagName("g");
    var path = new Path2D(groups[0].childNodes[1].getAttribute("d"));
    ctx.drawImage(img, 0, 0); // NOTE image moved to 0,0 was 10,10
    // from SVG "translate(0.000000,540.0000) scale(1.000000,-1.000000)
    ctx.setTransform(1,0,0,-1,0,540);
    ctx.fillStyle = "black";
    ctx.beginPath();
    ctx.fill(path);
  }
</code>```

MDN is out of date Path2D is supported by Chrome and FireFox. Though you should check browser for compatibility as it is a recent addition.

Body:
I am attempting to write some JS which uses Canvas to emulate how SVG draws a shape on an image but I can't seem to get it to work.

I have some SVG data which draws a mouth on a face.

<svg id="svgTag" style="background: url('https://image.ibb.co/h9CWiR/odd_size.png') no-repeat " xmlns="http://www.w3.org/2000/svg" version="1.0" width="379.000000" height="540.000000" viewBox="0 0 379.000000 540.000000" preserveAspectRatio="xMidYMid meet">
    <g transform="translate(0.000000,540.0000) scale(1.000000,-1.000000)" fill="#000000" stroke="none">
        <path d="M172 147
               c-21 -1 -69 -8 -74 -10
               l-2 -1 0 -32 0 -33 3 -4
               c9 -14 31 -36 44 -45
               12 -9 16 -11 27 -13
               2 -1 8 -2 12 -2
               9 -2 33 -3 34 -1
               0 1 1 1 2 1
               2 0 6 1 9 2
               16 5 29 14 47 32
               l9 8 0 44
               c0 33 0 43 -1 44 -4 3 -31 8 -49 10 -14 1 -44 1 -61 0
               z"/>
    </g>
</svg>

I have a fiddle of this here: https://jsfiddle.net/nhoughto5/5dhn1nm1/

I have written some javascript which takes the path data from the SVG element, parses it then uses Canvas methods to draw the same mouth. I've implemented a recursive solution to step through each command and draw it in exactly the same way.

 const commandString = /[\-0-9,. ]+/ig;
  const commandPattern = /[A-z]+/ig;
  const stringSplit = /[, ]+/ig;
  const shiftX = 0, shiftY = 0;

  function cleanArray(array) {
    const tmpArray = [];
    for (let i = 0; i < array.length; i++) {
      if (array[i].length > 0) {
        tmpArray.push(parseInt(array[i]));
      }
    }
    return tmpArray;
  }
  function move(array, context) {
    let x = array[0];
    let y = array[1];
    context.moveTo(x + shiftX, y + shiftY);
    //context.fill();
  }

  function quadraticTo(array, context) {
    let x = array[0];
    let y = array[1];
    let x1 = array[2];
    let y1 = array[3];
    context.quadraticCurveTo(x + shiftX, y + shiftY, x1 + shiftX, y1 + shiftY);
    context.fill();
    if (array.length > 4) {
      quadraticTo(array.splice(4, array.length), context);
    }
  }

  function lineTo(array, context) {
    let x = array[0];
    let y = array[1];
    context.lineTo(x + shiftX, y + shiftY);
    context.fill();
    if (array.length > 2) {
      lineTo(array.splice(2, array.length), context);
    }
  }

  function curveTo(array, context) {
    let x = array[0];
    let y = array[1];
    let x1 = array[2];
    let y1 = array[3];
    let x2 = array[4];
    let y2 = array[5];
    context.bezierCurveTo(x + shiftX, y + shiftY, x1 + shiftX, y1 + shiftY, x2 + shiftX, y2 + shiftY);
    context.fill();
    if (array.length > 6) {
      this._curveTo(array.splice(6, array.length), context);
    }
  }
  function draw(path, context){
    var commands = path.split(commandPattern);
    var commandArray = path.split(commandString);

    for (let i = 0, len = commandArray.length; i < len; i++) {
      let action = commandArray[i].toUpperCase();
      if (typeof commands[i] === 'undefined') break;

      const array = cleanArray(commands[i].split(stringSplit));
      switch (action) {
        case "M":
          move(array, context);
          break;
        case "C":
          curveTo(array, context);
          break;
        case "Q":
          quadraticTo(array, context);
          break;
        case "L":
          lineTo(array, context);
          break;
        case "Z":
          context.closePath();
          break;
        default:
      }
    }
  }
  function makeCanvas(canvas, ctx, img){
    var svg = document.getElementById("svgTag");
    var groups = svg.getElementsByTagName("g");
    var path = groups[0].childNodes[1].getAttribute("d");
    ctx.drawImage(img, 10, 10);
    ctx.fillStyle = "black";
    console.log(path);
    draw(path, ctx);
  }
  function imageCanvas() {
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var img = document.createElement("IMG");
    img.addEventListener('load', function() {
      makeCanvas(c, ctx, img);
    }.bind(this), false);
    img.setAttribute("src", "https://image.ibb.co/h9CWiR/odd_size.png");

  }

  window.onload = imageCanvas();

Again, I have created a fiddle demonstrating this here:https://jsfiddle.net/nhoughto5/whwxtxcp/1/

The problem is that it seems completely wrong. At first I thought that it might be an issue with the translate value in the SVG group. I added a constant at the top of the JS to easily translate it around. If you modify the translate constants to: const translateX = 100, translateY = 300; what it draws will move into the middle and you can see that it is fantastically wrong.

I've stepped through my solution and checked that the data is being spliced and drawn onto the canvas in the correct order. Does canvas do something different to SVG that I'm not aware of? Not to toot my own horn but I'm fairly confident that my implementation is correct but there is something that I'm missing.

Body:
Setting the relative origin for Path2D

Your problem is that you are incorrectly setting the relative positions. Also you need to set the correct transform.

Transform

The SVG transform is  translate(0.000000,540.0000) scale(1.000000,-1.000000)

Which is the equivalent to

ctx.setTransform(1, 0, 0, -1, 0, 540);
//               |         |  |  |
//              (x scale)  | (x  y  translate)
//                        (y scale)

d Path

For the command "M x1 y1 c x2 y2 x3 y3 x4 y4 l x5 y5" where x,y represent coord pairs.

The equivalent canvas commands are

var ox = 0, oy = 0; // the relative origin
ox = X1; oy = Y1;
ctx.moveTo(ox, oy);
ctx.bezierCurveTo(ox + x2, oy + y2, ox + x3, oy + y3, ox = ox + x4, oy = oy + y4)
//                                                    ^^ new origin ^^ new origin
ctx.lineTo(ox = ox + x5, oy = ox + y5);
//         ^^ new origin ^^ new origin

Note that the last point for each segment is used to set the new relative origin

The code below is a modification of some of your snippet that correctly parses and executes the path commands.

// Only partial solution
// implement a subset of the 2D path string commands
const canvasPath = (()=>{
    var ctx, ox = 0, oy = 0;
    const [x, y] = [(p) => ox + p.shift(), (p) => oy + p.shift()];
    const X = (p) => p.shift(), Y = X;
    return {
        set context(ctx_) { ctx = ctx_ },
        c(p) { while(p.length > 0) { ctx.bezierCurveTo(x(p), y(p), x(p), y(p), ox = x(p), oy = y(p)) } },
        q(p) { while(p.length > 0) { ctx.quadraticCurveTo(x(p), y(p), ox = x(p), oy = y(p)) } },
        l(p) { while(p.length > 0) { ctx.lineTo(ox = x(p), oy = y(p)) } },
        z()  { ctx.closePath() },
        M(p) { ctx.moveTo(ox = X(p), oy = Y(p)) },
    };
})();

// This may throw for some paths as it cobers only some path commands
function parsePath(path) {
    var subPath, paths = [];
    path.replace(/([Mzlqc])|([\-0-9.]+)/g, s => {
        if ("Mzlqc".indexOf(s) > -1) { paths.push(subPath = {type : s , points : []}) }
        else { subPath.points.push(Number(s)) }
        return s;
    });
    return paths;
}

// parses a path string and then adds that path to the canvas via canvasPath
function draw(path) {
    const subPaths = parsePath(path);
    for (const {type, points} of subPaths) { canvasPath[type](points) }
}

// Taken from OP snippet and modified to use above functions.
function makeCanvas(canvas, ctx, img) {
    var svg = document.getElementById("svgTag");
    var groups = svg.getElementsByTagName("g");
    var path = groups[0].childNodes[1].getAttribute("d");
    ctx.drawImage(img, 0, 0); // NOTE image moved to 0,0

    // from SVG "translate(0.000000,540.0000) scale(1.000000,-1.000000)
    ctx.setTransform(1, 0, 0, -1, 0, 540);
    canvasPath.context = ctx;
    ctx.beginPath();
    draw(path);
    ctx.fill()
}

Use Path2D

But that is a lot of hard work, and why do all that when you can use the Path2D object to do the work for you.

Path2D will accept a SVG path

const path = new Path2D(`M172 147
    c-21 -1 -69 -8 -74 -10
    l-2 -1 0 -32 0 -33 3 -4
    c9 -14 31 -36 44 -45 12 -9 16 -11 27 -13  2 -1 8 -2 12 -2  9 -2 33 -3 34 -1 0 1
    1 1 2 1 2 0 6 1 9 2 16 5 29 14 47 32
    l9 8 0 44
    c0 33 0 43 -1 44 -4 3 -31 8 -49 10 -14 1 -44 1 -61 0 z`
);

You can render the path with the fill and stroke commands

ctx.fill(path);
ctx.stroke(path);

Thus your code is simplified to.

  function makeCanvas(canvas, ctx, img){
    var svg = document.getElementById("svgTag");
    var groups = svg.getElementsByTagName("g");
    var path = new Path2D(groups[0].childNodes[1].getAttribute("d"));
    ctx.drawImage(img, 0, 0); // NOTE image moved to 0,0 was 10,10
    // from SVG "translate(0.000000,540.0000) scale(1.000000,-1.000000)
    ctx.setTransform(1,0,0,-1,0,540);
    ctx.fillStyle = "black";
    ctx.beginPath();
    ctx.fill(path);
  }

MDN is out of date Path2D is supported by Chrome and FireFox. Though you should check browser for compatibility as it is a recent addition.


问:
Pass vector elements to a function in c++
I now have a vector of objects. And a pre-defined function that can take objects as parameters. Just curious if there's a way of passing these objects to this function?

```<code>std::vector<obj> objects; //contains obj1, obj2 .., objn
</code>```

And I'd like to achieve something like this:

```<code> foo(obj1, obj2 ... , objn) //foo can take as many objects as I want
</code>```

答:
I don't think there is.

That being said, your std::vector<obj> also is an object though, and you can pass it as an argument to your function (indirectly passing its contents). For example, if you need to modify obj1 or any other, you can write your function like so:

```<code>void foo(std::vector<obj>& p_objects)
{
    // Do something to obj1 and so on using p_objects.
}
</code>```

If you don't need to modify obj1 to objn, then use a const reference:

```<code>void foo(const std::vector<obj>& p_objects)
{
    // Do something to obj1 and so on using p_objects,
    // but you can't modify anything!
}
</code>```

I know it is not exactly what you are looking for, but it is a standard way to achieve something very similar (and to my opinion cleaner) in C++.

Body:
I now have a vector of objects. And a pre-defined function that can take objects as parameters. Just curious if there's a way of passing these objects to this function?

std::vector<obj> objects; //contains obj1, obj2 .., objn

And I'd like to achieve something like this:

 foo(obj1, obj2 ... , objn) //foo can take as many objects as I want

Body:
I don't think there is.

That being said, your std::vector<obj> also is an object though, and you can pass it as an argument to your function (indirectly passing its contents). For example, if you need to modify obj1 or any other, you can write your function like so:

void foo(std::vector<obj>& p_objects)
{
    // Do something to obj1 and so on using p_objects.
}

If you don't need to modify obj1 to objn, then use a const reference:

void foo(const std::vector<obj>& p_objects)
{
    // Do something to obj1 and so on using p_objects,
    // but you can't modify anything!
}

I know it is not exactly what you are looking for, but it is a standard way to achieve something very similar (and to my opinion cleaner) in C++.


问:
Call Parent Activity method from Child Activity
I have Activity A that starts Activity B. Let me start by saying that I believe that Activity A can't use "startActivityForResult()" because Activity B can replace himself for another Activity B (this means, starting another activity and finishing himself), and if that happened Activity A wouldn't be expecting a result anymore and that second Activity B couldn't pass Activity A the result.

Activity A has the instance of the Model. Is there anyway I can get access to the Model from Activity B?

答:
I solved this by adding into my MainActivity:

```<code>private static MainActivity main;

public static MainActivity getMain() {
    return main;
}
</code>```

I am aware this is not a good practice.

Body:
I solved this by adding into my MainActivity:

private static MainActivity main;

public static MainActivity getMain() {
    return main;
}

I am aware this is not a good practice.


问:
Android Studio 3.0 - SDK path not specified
I tried to update Android Studio to 3.0 but got some crazy error, so I uninstalled AS and installed AS 3.0, but now when I try to open a file, I get an "SDK path not specified" error and nothing I select is accepted.

I cannot find any file called "android-sdk" or something similar, which is what most of the other solutions on Stack Overflow suggest selecting.

How do I fix this?

Right now I'm trying this, but no clue if it will help:

1.  I went to File -> Settings -> System Settings -> Android SDK

2.  I specified C:\ProgramFiles\Android and it's installing.

UPDATE: This more or less worked. I had to install a million updates afterwards, but it solved the problem.

答:
This is halfway there. I found going through the File -> Settings tree that even though I hadn't selected NDK (Native) options, the folder names must not contain spaces. I created an Android/SDK folder tree on a spare drive all its own to alleviate this concern by AS.

Then without a space in the name, I was able to choose SDKs to download, and so it has begun.

Your question and self-confirmation of a work around got me there after I, myself was looking for a couple weeks. Thanks


问:
Purescript Halogen Component, Input vs State
I want to make a Halogen Component where the component's input differs from its state. According to the guide for Halogen (https://github.com/slamdata/purescript-halogen/blob/master/docs/5%20-%20Parent%20and%20child%20components.md#input-values) this should be possible. I changed the example from the guide as follows

```<code>import Prelude
import Data.Int (decimal, toStringAs)
import Halogen as H
import Halogen.HTML as HH
import Halogen.HTML.Events as HHE

type Input = Int

type State = String

data Query a = HandleInput Input a

component :: forall m. H.Component HH.HTML Query Input Void m
component =
  H.component
    { initialState: id
    , render
    , eval
    , receiver: HHE.input HandleInput
    }
  where

  render :: State -> H.ComponentHTML Query
  render state =
    HH.div_
      [ HH.text "My input value is:"
      , HH.strong_ [ HH.text (show state) ]
      ]

  eval :: Query ~> H.ComponentDSL State Query Void m
  eval = case _ of
    HandleInput n next -> do
      oldN <- H.get
      when (oldN /= (toStringAs decimal n)) $ H.put $ toStringAs decimal n
      pure next
</code>```

But then I get a compile error at the line with , receiver: HHE.input HandleInput

```<code>Could not match type

  String

with type

  Int
</code>```

What am I doing wrong here?

答: The initialState is computed using the input value, and in the code you pasted it's implemented as id, so it's trying to force the input and state types to match.

Body:
I want to make a Halogen Component where the component's input differs from its state. According to the guide for Halogen (https://github.com/slamdata/purescript-halogen/blob/master/docs/5%20-%20Parent%20and%20child%20components.md#input-values) this should be possible. I changed the example from the guide as follows

import Prelude
import Data.Int (decimal, toStringAs)
import Halogen as H
import Halogen.HTML as HH
import Halogen.HTML.Events as HHE

type Input = Int

type State = String

data Query a = HandleInput Input a

component :: forall m. H.Component HH.HTML Query Input Void m
component =
  H.component
    { initialState: id
    , render
    , eval
    , receiver: HHE.input HandleInput
    }
  where

  render :: State -> H.ComponentHTML Query
  render state =
    HH.div_
      [ HH.text "My input value is:"
      , HH.strong_ [ HH.text (show state) ]
      ]

  eval :: Query ~> H.ComponentDSL State Query Void m
  eval = case _ of
    HandleInput n next -> do
      oldN <- H.get
      when (oldN /= (toStringAs decimal n)) $ H.put $ toStringAs decimal n
      pure next

But then I get a compile error at the line with , receiver: HHE.input HandleInput

Could not match type

  String

with type

  Int

What am I doing wrong here?


问:
Pentaho Analysis Report date format
I'm fairly new to Pentaho. I have set it up on a linux server and am trying to build an analysis report in the web-browser accessed user console. One of my data sources is a date in the format yyyy-MM-dd. When this is put into a report it displays an additional 00:00:00.0 timestamp.

I have searched around the options in the Analysis Report editor. I have also edited the Data Source Model so that that dimension is recognized as a time dimension along with its source format.

Any help is greatly appreciated, thanks!

答:
You can change the field type from Date type to Text type.

1. Insert a new text field

2. Go to Structure > Attributes

3. Edit the value of the field by choosing your Date data

The new output will just be e.g. 2017-03-12

Title: Pentaho Analysis Report date format


问:
Cognitive Service API
I'm exploring the Azure Cognitive Service for one of our project. We had a Classified Community website called DewaList.com and this site is battling with spam. We had an Robotic Process Automation (RPA) that identify and remove the ads based on the listed spam keyword that we as human identify and marked as a spam.

Our next project is to generate intelligently  this spam keyword list using this Machine Learning. The logic is look at regularly new ads or a week or a month that coming through and if it's repetitive more than few time in a day or week. Then flagged that as a spam. The keyword will be based on phone number, website or email.

Can this be done  though via this Cognitive Service? What sort of API?

Any pointer that will be good for us as a starting point.

Thanks

答:
I am guessing you're referring the Azure Machine Learning.

You have to configure the inputs to train you model, what did you configure? Below is the code - I would configure div container with the placeholder as an input and co-relate that to your spam prediction, by that I mean extract and feed that as your content to the engine

```<code>global inputs_dc, prediction_dc
inputs_dc = ModelDataCollector('model.pkl',identifier="inputs")
prediction_dc = ModelDataCollector('model.pkl', identifier="prediction")
</code>```

Title: Cognitive Service API

Body:
I am guessing you're referring the Azure Machine Learning.

You have to configure the inputs to train you model, what did you configure? Below is the code - I would configure div container with the placeholder as an input and co-relate that to your spam prediction, by that I mean extract and feed that as your content to the engine

global inputs_dc, prediction_dc
inputs_dc = ModelDataCollector('model.pkl',identifier="inputs")
prediction_dc = ModelDataCollector('model.pkl', identifier="prediction")


问:
Recursively remove element from tuple
having some issues with getting the correct result. I am trying to, by recursion, pass in a tuple of words and an item that is one word. The method should return the tuple minus the item. However I am getting an error that reads 'must be str, not tuple'. Here is what I have so far. Thanks in advance.

```<code>def filter_sequence(seq, item):
    try:
        if not seq:
            return ()
        elif item is seq[0]:
            return filter_sequence(seq[1:], item)
        else:
            return seq[0] + filter_sequence(seq[1:], item)
    except TypeError as e:
        print(e)
</code>```

Example:

If I call filter_sequence(("jelly","butter", "mustard"), 'butter')

 I should receive the tuple of ("jelly", "mustard")

I've attempted wrapping the last recursive call in str(), but then I just get a string back. Which I would have to break apart and format, which is not what I want to do.

I should mention that it is my goal to achieve this result with using built in solutions like for loops, while loops, if x in y... etc.

答:
The last concatenation should be a singleton tuple, not an item in the tuple - a string. Also, an equality check is sufficient for matching the item in the tuple with the parameter, you don't need is here:

```<code>def filter_sequence(seq, item):
    if not seq:
        return ()
    elif item == seq[0]:
        return filter_sequence(seq[1:], item)
    else:
        return (seq[0],) + filter_sequence(seq[1:], item)
    #          ^^^^^^^^^
</code>```

Note: The is check may work for smaller strings as those in your code due to some CPython optimization (string interning), but will definitely not work for large strings and is not guaranteed to work the same way across Python implementations. Therefore, use ==.

Title: Recursively remove element from tuple

Body:
having some issues with getting the correct result. I am trying to, by recursion, pass in a tuple of words and an item that is one word. The method should return the tuple minus the item. However I am getting an error that reads 'must be str, not tuple'. Here is what I have so far. Thanks in advance.

def filter_sequence(seq, item):
    try:
        if not seq:
            return ()
        elif item is seq[0]:
            return filter_sequence(seq[1:], item)
        else:
            return seq[0] + filter_sequence(seq[1:], item)
    except TypeError as e:
        print(e)

Example:

If I call filter_sequence(("jelly","butter", "mustard"), 'butter')

 I should receive the tuple of ("jelly", "mustard")

I've attempted wrapping the last recursive call in str(), but then I just get a string back. Which I would have to break apart and format, which is not what I want to do.

I should mention that it is my goal to achieve this result with using built in solutions like for loops, while loops, if x in y... etc.

Body:
The last concatenation should be a singleton tuple, not an item in the tuple - a string. Also, an equality check is sufficient for matching the item in the tuple with the parameter, you don't need is here:

def filter_sequence(seq, item):
    if not seq:
        return ()
    elif item == seq[0]:
        return filter_sequence(seq[1:], item)
    else:
        return (seq[0],) + filter_sequence(seq[1:], item)
    #          ^^^^^^^^^

Note: The is check may work for smaller strings as those in your code due to some CPython optimization (string interning), but will definitely not work for large strings and is not guaranteed to work the same way across Python implementations. Therefore, use ==.


问:
jQuery UI Dialog - Keeping a clicked link inside an already open jQuery UI Dialog
```<code><script type="text/javascript">
$(document).ready(function() {
    $('#mardicion').each(function() {
        var $link = $(this);

        $link.click(function() {
            var $dialog = $('<div></div>')
                .load($link.attr('href') + ' #content')
                .dialog({
                    autoOpen: false,
                    title: $link.attr('title'),
                    width: (pageWidth()*0.9),
                    height: (pageHeight()*0.9)
                });
                $dialog.dialog('open');

                return false;
        });
    });
});
</script>
</code>```

I use the above javascript to load a page when I click a link, the page loads correctly but when I click another link inside the dialog the clicked link opens in the browser window instead of inside the dialog. I've heard that using a click handler is the proper way to do this (that the link opens inside the Dialog), but I'm not sure how to implement it with a  jQuery UI Dialog.

Thanks!

答:
You'll have use the live() function. At a certain time (I guess on page load) you attach a click event handler to a certain number of items with the ID mardicion. When the page is loaded into your dialog, the links inside that page, even though they might have the madicion ID, their click events are not hooked up.

Use $('#madicion').live('click' , function(e)  {}) to catch the click events also of all items, even if they are added to the page at a later stage.

As a side note:

it seems like you are misusing the ID attribute. You are only allowed to have one element per ID. Seeing $('#XXX').each() shows that you have more than 1 item. The correct way to handle these things is to give those elements a CSS class, and use $('.XXX').each();

The use of each is not necessary: $('#XXX').click(function() { }) applies the stated function to each one of the elements.