问:
Android AWS S3 SDK TransferUtility Not Working in Service
I am trying to use the AWS Android SDK for S3 in a started service. I am a little new to both the SDK and Services. I am pretty confident that the Transfer Utility is also running a service.

```<code>Handler (android.os.Handler) {11629d87} sending message to a Handler on a dead thread
    java.lang.IllegalStateException: Handler (android.os.Handler) {11629d87} sending message to a Handler on a dead thread
    at android.os.MessageQueue.enqueueMessage(MessageQueue.java:325)
    at android.os.Handler.enqueueMessage(Handler.java:631)
    at android.os.Handler.sendMessageAtTime(Handler.java:600)
    at android.os.Handler.sendMessageDelayed(Handler.java:570)
    at sksDoneLater(TransferService.java:189)
    at com.amazonaws.mobileconnectors.s3.transferutility.TransferService.access$200(TransferService.java:44)
    at com.amazonaws.mobileconnectors.s3.transferutility.TransferService$2.handleMessage(TransferService.java:166)
    at android.os.Handler.dispatchMessage(Handler.java:98)
    at android.os.Looper.loop(Looper.java:135)
    at android.os.HandlerThread.run(HandlerThread.java:61)
</code>```

Here is the code I am using to start it up:

```<code>    AmazonS3 amazonS3 = new AmazonS3Client(credentialsProvider);
    mTransferUtility = new TransferUtility(amazonS3, getApplicationContext());
    TransferObserver observer = mTransferUtility.upload(
            S3_RAW_BUCKET_ARN,
            mVidFileKey,
            mVidFile);

    observer.setTransferListener(new TransferListener() {...})
</code>```

The line previous it says it can't get s3 client. I created the client just as shown above in application class and successfully used the same code in an activity to perform a successful transfer so it must be something obvious about services that I am ignorant of. The above code is called in a method that is called from onStartCommand() in the service.

Any help would be much appreciated.

UPDATE - Whole Class was requested and is shown here:

```<code>public class VideoCompressionService extends Service {;

private Bus bus;
private TransferUtility mTransferUtility;
private int mVidWidth;
private int mVidHeight;
private File mCompressedVidFile;
private File mVidFile;
private String mVidFileKey;
private NotificationManager mNotificationManager;
private android.support.v4.app.NotificationCompat.Builder mNotification;

public VideoCompressionService() {

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null) {
        String realPath = MediaUtils.getRealVideoPathFromURI(this.getContentResolver(), intent.getData());
        if (realPath != null) {
            this.mVidFile = new File(realPath);
            this.mVidFileKey = intent.getStringExtra(EXTRA_VID_FILE_KEY);
            this.mVidWidth = intent.getIntExtra(EXTRA_VID_WIDTH, 0);
            this.mVidHeight = intent.getIntExtra(EXTRA_VID_HEIGHT, 0);
            this.bus = CoPhotoApplication.getVideoCompressionBus();
            if (mVidFile != null && mVidFile.exists() && mVidFile.canRead()) {
                mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
                mNotification = new NotificationCompat.Builder(this)
                        .setContentTitle("Compressing Video - Step 1 of 3")
                        .setContentText("Uploading video for processing...")
                        .setSmallIcon(R.drawable.ic_launcher);
                if (mVidWidth == 0 || mVidHeight == 0) {
                    MediaMetadataRetriever mmr = new MediaMetadataRetriever();
                    mmr.setDataSource(mVidFile.getAbsolutePath());
                    mVidWidth = Integer.parseInt(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH));
                    mVidHeight = Integer.parseInt(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT));
                    mmr.release();
                }
                uploadVidToS3();
            }
            return Service.START_NOT_STICKY;
        } else {
            VideoCompressionService.this.stopSelf();
            return Service.START_NOT_STICKY;
        }
    } else {
        VideoCompressionService.this.stopSelf();
        return Service.START_NOT_STICKY;
    }
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

private void uploadVidToS3() {
    compressionUploadStarted();
    CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
            getApplicationContext(),
            "*********ID HERE********", // Identity Pool ID
            Regions.US_EAST_1 // Region
    );

    AmazonS3 amazonS3 = new AmazonS3Client(credentialsProvider);
    mTransferUtility = new TransferUtility(amazonS3, getApplicationContext());
    TransferObserver observer = mTransferUtility.upload(
            S3_RAW_BUCKET_ARN,
            mVidFileKey,
            mVidFile);

    observer.setTransferListener(new TransferListener() {
        @Override
        public void onStateChanged(int id, TransferState state) {
            if (state == TransferState.COMPLETED) {
                compressionUploadFinished(true);
                zencodeVideo(mVidFileKey);
            } else if (state == TransferState.FAILED) {
                compressionUploadFinished(false);
            }
        }

        @Override
        public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
            int progress = Math.round(100 * ((float) bytesCurrent / bytesTotal));
            String progressPercentage = String.valueOf(progress) + "%";
            compressionUploadProgress(progress, progressPercentage);
        }

        @Override
        public void onError(int id, Exception ex) {
            compressionUploadFinished(false);
        }
    });
}

private void compressionUploadStarted() {
    bus.post(new CompressionUploadStartedEvent());
    updateNotification();
}

private void compressionUploadProgress(int progress, String progressPercentage) {
    bus.post(new CompressionUploadProgressEvent(progress, progressPercentage));
    mNotification.setProgress(100, progress, false);
    updateNotification();
}

private void compressionUploadFinished(boolean successfully) {
    bus.post(new CompressionUploadFinishedEvent(successfully));
    if (successfully) {
        mNotification.setContentText("Upload complete");
    } else {
        mNotification.setContentTitle("Compression Failed");
        mNotification.setContentText("Upload failed. Please try again later.");
    }
    updateNotification();
    if (!successfully) {
        VideoCompressionService.this.stopSelf();
    }
}

private void updateNotification() {
    mNotificationManager.notify(NOTIFICATION_ID, mNotification.build());
}
</code>```

答:
I found myself in the same issue...
Here it is what solved for me:

I noticed I had the following service for my SyncAdapter registered in Manifest:

```<code>        <service
        android:name=".sync.SyncService"
        android:exported="true"
        android:process=":sync">
        <intent-filter>
            <action android:name="android.content.SyncAdapter"/>
        </intent-filter>
        <meta-data android:name="android.content.SyncAdapter"
            android:resource="@xml/syncadapter" />
    </service>
</code>```

The android:process=":sync" tells service to run in a private process called :sync
So I just told the TransferService from Amazon SDK to run in this same thread.

```<code>        <service
        android:name="com.amazonaws.mobileconnectors.s3.transferutility.TransferService"
        android:process=":sync"
        android:enabled="true" />
</code>```

After that, I no more got the error TransferService can't get s3 client, and it will stop, and finally was able to upload my pictures to S3

Body:
I am trying to use the AWS Android SDK for S3 in a started service. I am a little new to both the SDK and Services. I am pretty confident that the Transfer Utility is also running a service.

Handler (android.os.Handler) {11629d87} sending message to a Handler on a dead thread
    java.lang.IllegalStateException: Handler (android.os.Handler) {11629d87} sending message to a Handler on a dead thread
    at android.os.MessageQueue.enqueueMessage(MessageQueue.java:325)
    at android.os.Handler.enqueueMessage(Handler.java:631)
    at android.os.Handler.sendMessageAtTime(Handler.java:600)
    at android.os.Handler.sendMessageDelayed(Handler.java:570)
    at sksDoneLater(TransferService.java:189)
    at com.amazonaws.mobileconnectors.s3.transferutility.TransferService.access$200(TransferService.java:44)
    at com.amazonaws.mobileconnectors.s3.transferutility.TransferService$2.handleMessage(TransferService.java:166)
    at android.os.Handler.dispatchMessage(Handler.java:98)
    at android.os.Looper.loop(Looper.java:135)
    at android.os.HandlerThread.run(HandlerThread.java:61)

Here is the code I am using to start it up:

    AmazonS3 amazonS3 = new AmazonS3Client(credentialsProvider);
    mTransferUtility = new TransferUtility(amazonS3, getApplicationContext());
    TransferObserver observer = mTransferUtility.upload(
            S3_RAW_BUCKET_ARN,
            mVidFileKey,
            mVidFile);

    observer.setTransferListener(new TransferListener() {...})

The line previous it says it can't get s3 client. I created the client just as shown above in application class and successfully used the same code in an activity to perform a successful transfer so it must be something obvious about services that I am ignorant of. The above code is called in a method that is called from onStartCommand() in the service.

Any help would be much appreciated.

UPDATE - Whole Class was requested and is shown here:

public class VideoCompressionService extends Service {;

private Bus bus;
private TransferUtility mTransferUtility;
private int mVidWidth;
private int mVidHeight;
private File mCompressedVidFile;
private File mVidFile;
private String mVidFileKey;
private NotificationManager mNotificationManager;
private android.support.v4.app.NotificationCompat.Builder mNotification;

public VideoCompressionService() {

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null) {
        String realPath = MediaUtils.getRealVideoPathFromURI(this.getContentResolver(), intent.getData());
        if (realPath != null) {
            this.mVidFile = new File(realPath);
            this.mVidFileKey = intent.getStringExtra(EXTRA_VID_FILE_KEY);
            this.mVidWidth = intent.getIntExtra(EXTRA_VID_WIDTH, 0);
            this.mVidHeight = intent.getIntExtra(EXTRA_VID_HEIGHT, 0);
            this.bus = CoPhotoApplication.getVideoCompressionBus();
            if (mVidFile != null && mVidFile.exists() && mVidFile.canRead()) {
                mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
                mNotification = new NotificationCompat.Builder(this)
                        .setContentTitle("Compressing Video - Step 1 of 3")
                        .setContentText("Uploading video for processing...")
                        .setSmallIcon(R.drawable.ic_launcher);
                if (mVidWidth == 0 || mVidHeight == 0) {
                    MediaMetadataRetriever mmr = new MediaMetadataRetriever();
                    mmr.setDataSource(mVidFile.getAbsolutePath());
                    mVidWidth = Integer.parseInt(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH));
                    mVidHeight = Integer.parseInt(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT));
                    mmr.release();
                }
                uploadVidToS3();
            }
            return Service.START_NOT_STICKY;
        } else {
            VideoCompressionService.this.stopSelf();
            return Service.START_NOT_STICKY;
        }
    } else {
        VideoCompressionService.this.stopSelf();
        return Service.START_NOT_STICKY;
    }
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

private void uploadVidToS3() {
    compressionUploadStarted();
    CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
            getApplicationContext(),
            "*********ID HERE********", // Identity Pool ID
            Regions.US_EAST_1 // Region
    );

    AmazonS3 amazonS3 = new AmazonS3Client(credentialsProvider);
    mTransferUtility = new TransferUtility(amazonS3, getApplicationContext());
    TransferObserver observer = mTransferUtility.upload(
            S3_RAW_BUCKET_ARN,
            mVidFileKey,
            mVidFile);

    observer.setTransferListener(new TransferListener() {
        @Override
        public void onStateChanged(int id, TransferState state) {
            if (state == TransferState.COMPLETED) {
                compressionUploadFinished(true);
                zencodeVideo(mVidFileKey);
            } else if (state == TransferState.FAILED) {
                compressionUploadFinished(false);
            }
        }

        @Override
        public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
            int progress = Math.round(100 * ((float) bytesCurrent / bytesTotal));
            String progressPercentage = String.valueOf(progress) + "%";
            compressionUploadProgress(progress, progressPercentage);
        }

        @Override
        public void onError(int id, Exception ex) {
            compressionUploadFinished(false);
        }
    });
}

private void compressionUploadStarted() {
    bus.post(new CompressionUploadStartedEvent());
    updateNotification();
}

private void compressionUploadProgress(int progress, String progressPercentage) {
    bus.post(new CompressionUploadProgressEvent(progress, progressPercentage));
    mNotification.setProgress(100, progress, false);
    updateNotification();
}

private void compressionUploadFinished(boolean successfully) {
    bus.post(new CompressionUploadFinishedEvent(successfully));
    if (successfully) {
        mNotification.setContentText("Upload complete");
    } else {
        mNotification.setContentTitle("Compression Failed");
        mNotification.setContentText("Upload failed. Please try again later.");
    }
    updateNotification();
    if (!successfully) {
        VideoCompressionService.this.stopSelf();
    }
}

private void updateNotification() {
    mNotificationManager.notify(NOTIFICATION_ID, mNotification.build());
}

Body:
I found myself in the same issue...
Here it is what solved for me:

I noticed I had the following service for my SyncAdapter registered in Manifest:

        <service
        android:name=".sync.SyncService"
        android:exported="true"
        android:process=":sync">
        <intent-filter>
            <action android:name="android.content.SyncAdapter"/>
        </intent-filter>
        <meta-data android:name="android.content.SyncAdapter"
            android:resource="@xml/syncadapter" />
    </service>

The android:process=":sync" tells service to run in a private process called :sync
So I just told the TransferService from Amazon SDK to run in this same thread.

        <service
        android:name="com.amazonaws.mobileconnectors.s3.transferutility.TransferService"
        android:process=":sync"
        android:enabled="true" />

After that, I no more got the error TransferService can't get s3 client, and it will stop, and finally was able to upload my pictures to S3


来源: stackexchange

问:
problems with QByteArray and QString convertion
I've got a server and a client and they're connected by TCP (QTcpSocket and QTcpServer). data is sent using QByteArray.

```<code>void Receive::newConnection()
{
    while (server->hasPendingConnections())
        {
        QTcpSocket *socket = server->nextPendingConnection();
        connect(socket, SIGNAL(readyRead()), SLOT(readyRead()));
        connect(socket, SIGNAL(disconnected()), SLOT(disconnected()));
        QByteArray *buffer = new QByteArray();
        qint32 *s = new qint32(0);
        buffers.insert(socket, buffer);
        sizes.insert(socket, s);
        qDebug()<<buffer;

    }
}
</code>```

last Line prints the text entered in client in server's console. i want to convert buffer to QString. (or i want to send it to qml file). so when i try :

```<code>QString receivedText = QTextCodec::codecForMib(1015)->toUnicode(buffer);
</code>```

and give me the error :

```<code>no matching function for call to 'QTextCodec::toUnicode(QByteArray*&)'
         receivedText = QTextCodec::codecForMib(1015)->toUnicode(buffer);
                                                     ^
</code>```

when using fromAscii or fromStringC it says it's not a member of QString.

what should i do?

答:
According to the documentation:

QString QTextCodec::toUnicode(const QByteArray &a) const

Converts a from the encoding of this codec to Unicode, and returns the
  result in a QString.

From the above, it follows that the reference is needed and not the pointer. In your case you should change it to:

```<code> QString receivedText = QTextCodec::codecForMib(1015)->toUnicode(*buffer);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've got a server and a client and they're connected by TCP (QTcpSocket and QTcpServer). data is sent using QByteArray.

void Receive::newConnection()
{
    while (server->hasPendingConnections())
        {
        QTcpSocket *socket = server->nextPendingConnection();
        connect(socket, SIGNAL(readyRead()), SLOT(readyRead()));
        connect(socket, SIGNAL(disconnected()), SLOT(disconnected()));
        QByteArray *buffer = new QByteArray();
        qint32 *s = new qint32(0);
        buffers.insert(socket, buffer);
        sizes.insert(socket, s);
        qDebug()<<buffer;

    }
}

last Line prints the text entered in client in server's console. i want to convert buffer to QString. (or i want to send it to qml file). so when i try :

QString receivedText = QTextCodec::codecForMib(1015)->toUnicode(buffer);

and give me the error :

no matching function for call to 'QTextCodec::toUnicode(QByteArray*&)'
         receivedText = QTextCodec::codecForMib(1015)->toUnicode(buffer);
                                                     ^

when using fromAscii or fromStringC it says it's not a member of QString.

what should i do?

Body:
According to the documentation:

QString QTextCodec::toUnicode(const QByteArray &a) const

Converts a from the encoding of this codec to Unicode, and returns the
  result in a QString.

From the above, it follows that the reference is needed and not the pointer. In your case you should change it to:

 QString receivedText = QTextCodec::codecForMib(1015)->toUnicode(*buffer);


问:
Adding a 2 seconds delay between javascript lines
I want to animate something everytime I click on it. So I saved an animation in the class "animation".

```<code>function listClick() {
  toplist.classList.add("animation");
  toplist.classList.remove("animation");
}
</code>```

the animation lasts 2000 ms so I want a delay of 2000 ms between those two lines of code in my function. How can I achieve this using Javascript?

答:
```<code>function listClick() {
     toplist.classList.add("animation");
     setTimeout(function() {
          toplist.classList.remove("animation");
     }, 2000);
}
</code>```

Body:
I want to animate something everytime I click on it. So I saved an animation in the class "animation".

function listClick() {
  toplist.classList.add("animation");
  toplist.classList.remove("animation");
}

the animation lasts 2000 ms so I want a delay of 2000 ms between those two lines of code in my function. How can I achieve this using Javascript?


问:
A div is inheriting it's parent's width which is not what I want
Is there a way to make the div's width the same as the width of the image inside of it and ignore the width of the parent? My wrapper is 1200px, my image container's width is not set and the image inside the container is not hard coded so I can't hard code the width of the image container. I wanna make the image container wrap around the image and have the same width as it. Any way to do that?</p>

```<code>    <?php
        include 'header.php';
        include 'includes/comments.inc.php';
        include 'includes/images.inc.php';
    ?>
    <div class="wrapper">

    <?php

        $imagePath = $_SERVER['QUERY_STRING'];
        $realImagePath = substr($imagePath, 1);

        $sql = "SELECT * FROM image WHERE path='$realImagePath'";
        $result = mysqli_query($conn, $sql);
        $getResult = mysqli_fetch_assoc($result);

        echo "<div class='imageContainer'>"
                        ."<h1>".$getResult['name'].'</h1>'
                        .'<div class="relativeContainer"><img class="uploadedRealImg" src="uploads/'.$realImagePath .'" alt="Random image" /></div>'."<br><br>"
                        .$getResult['description']."<br><br>"
                        .$getResult['date']."<br><br>"
                        .$getResult['author']."<br><br></div>";

                            if (isset($_SESSION['id'])) {
                                $id = $_SESSION['id'];
                                $sql2 = "SELECT * FROM user WHERE id='$id'";
                                $result2 = mysqli_query($conn, $sql2);
                                $getResult2 = mysqli_fetch_assoc($result2);

                                    if ($getResult2['username'] == $getResult['author']) {
                                        echo "<form method='POST' action='".deleteImage($conn)."'>
                                                <input type='hidden' name='id' value='".$getResult['id']."'>
                                                <input type='hidden' name='path' value='".$getResult['path']."'>
                                                <input type='hidden' name='author' value='".$getResult['author']."'>
                                                <button id='delImage' type='submit' name='imageDelete'>Delete Image</button>
                                            </form>";
                                        }
                                }

        echo "<form method='POST' action='".setComments($conn)."'>
                <textarea class='commentSection' name='message'></textarea><br>
                <button type='submit' name='commentSubmit'>Comment</button>
            </form>";

    ?>

    <div id="comments">
        <?php
            getComments($conn);
        ?>
    </div>

    <?php
        echo "<button id='moreComments'>Show more comments</button>";
    ?>

</div>
<?php
    include 'footer.php';
?>

css

    .wrapper {
        width: 63.1%;
      margin: 0 auto;
      height: 100%;
    }
    .imageContainer {
      text-align: center;
      position: relative;
    }
    .uploadedImg {
      width: 500px;
      height: auto;
    }
    .uploadedRealImg {
      max-width: 1200px;
    }
    .commentSection {
      width: 100%;
      height: 150px;
    }
    #delImage {
      padding: 0;
      border: none;
      width: 100px;
      height: 100px;
      position: absolute;
      top: 0px;
      right: 0px;
    }
    .relativeContainer {
      position: relative;
    }
</code>```

答:
The .imageContainer is a div, and a div is a block element. Block elements try to fill 100% of their parent width.

You can change .imageContainer to an inline-block, which fits it's contents.

.wrapper {
  background: purple;
}

.imageContainer  {
  display: inline-block;
  border: 2px solid gold;
}

.image {
  display: block; /** optional - if you need the imageContainer height to be the same as that of the image
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="imageContainer">
    <img class="image" src="https://a.wattpad.com/useravatar/ReaderOfTheReads.256.435663.jpg">
  </div>
</div></code>```

Body:
Is there a way to make the div's width the same as the width of the image inside of it and ignore the width of the parent? My wrapper is 1200px, my image container's width is not set and the image inside the container is not hard coded so I can't hard code the width of the image container. I wanna make the image container wrap around the image and have the same width as it. Any way to do that?

    <?php
        include 'header.php';
        include 'includes/comments.inc.php';
        include 'includes/images.inc.php';
    ?>

    <?php

        $imagePath = $_SERVER['QUERY_STRING'];
        $realImagePath = substr($imagePath, 1);

        $sql = "SELECT * FROM image WHERE path='$realImagePath'";
        $result = mysqli_query($conn, $sql);
        $getResult = mysqli_fetch_assoc($result);

        echo "
"
                        ."
".$getResult['name'].'
'
                        .'

'."

"
                        .$getResult['description']."

"
                        .$getResult['date']."

"
                        .$getResult['author']."

";

                            if (isset($_SESSION['id'])) {
                                $id = $_SESSION['id'];
                                $sql2 = "SELECT * FROM user WHERE id='$id'";
                                $result2 = mysqli_query($conn, $sql2);
                                $getResult2 = mysqli_fetch_assoc($result2);

                                    if ($getResult2['username'] == $getResult['author']) {
                                        echo "<form method='POST' action='".deleteImage($conn)."'>
                                                <input type='hidden' name='id' value='".$getResult['id']."'>
                                                <input type='hidden' name='path' value='".$getResult['path']."'>
                                                <input type='hidden' name='author' value='".$getResult['author']."'>
                                                <button id='delImage' type='submit' name='imageDelete'>Delete Image</button>
                                            </form>";
                                        }
                                }

        echo "<form method='POST' action='".setComments($conn)."'>
                <textarea class='commentSection' name='message'></textarea>

                <button type='submit' name='commentSubmit'>Comment</button>
            </form>";

    ?>

        <?php
            getComments($conn);
        ?>

    <?php
        echo "<button id='moreComments'>Show more comments</button>";
    ?>

<?php
    include 'footer.php';
?>

css

    .wrapper {
        width: 63.1%;
      margin: 0 auto;
      height: 100%;
    }
    .imageContainer {
      text-align: center;
      position: relative;
    }
    .uploadedImg {
      width: 500px;
      height: auto;
    }
    .uploadedRealImg {
      max-width: 1200px;
    }
    .commentSection {
      width: 100%;
      height: 150px;
    }
    #delImage {
      padding: 0;
      border: none;
      width: 100px;
      height: 100px;
      position: absolute;
      top: 0px;
      right: 0px;
    }
    .relativeContainer {
      position: relative;
    }

Body:
The .imageContainer is a div, and a div is a block element. Block elements try to fill 100% of their parent width.

You can change .imageContainer to an inline-block, which fits it's contents.

.wrapper {
  background: purple;
}

.imageContainer  {
  display: inline-block;
  border: 2px solid gold;
}

.image {
  display: block; /** optional - if you need the imageContainer height to be the same as that of the image
}

<div class="wrapper">
  <div class="imageContainer">
    <img class="image" src="https://a.wattpad.com/useravatar/ReaderOfTheReads.256.435663.jpg">
  </div>
</div>


答: You have the setTimeout(function(), timeoutInMilliSecs); you can throw in there and use.

Title: Adding a 2 seconds delay between javascript lines


问:
Showing Filename Differences in List Array (Java)
I am trying to compare files and my solution works with folders that have a small amount of files in them like 10 but not folders with like over 200 filenames in them. The last part of my codes comes back NULL or Results = [ ] usually the text file(s) name is in here that shows the difference between both folders any help is appreciated. The problem is the last part of my code

```<code>package nameCompare;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

// https://stackoverflow.com/questions/19662384/comparing-file-names
// http://www.javaprogrammingforums.com/java-programming-tutorials/3-java-program-can-list-all-files-given-directory.html

public class fileNameCompare {

    public static void main(String[] args) {
                             // first directory path here
        String path1 = "C:/Users/Jonathan/Desktop/ADP/MagMediaAfter";
        //String path1 = "C:/Users/Jonathan/Desktop/FolderA";

        // second directory path here
        String path2 = "C:/Users/Jonathan/Desktop/ADP/MagMediaAfter";
        //String path2 = "C:/Users/Jonathan/Desktop/FolderB";

        File folder1 = new File(path1);
        int fileCount = folder1.list().length;

        File folder2 = new File(path2);
        int fileCountTwo = folder2.list().length;

        File[] listOfFiles1 = folder1.listFiles();
        File[] listOfFiles2 = folder2.listFiles();

        //we'll need these to store the file names as Strings
        ArrayList<String> BeforeMM = new ArrayList<String>();
        ArrayList<String> AfterMM = new ArrayList<String>();

        //get file names from directory
        for (int i = 0; i < listOfFiles1.length; i++)
        {
            if (listOfFiles1[i].isFile())
            {
                BeforeMM.add(listOfFiles1[i].getName());//wow
            }
        }

        for (int i = 0; i < listOfFiles2.length; i++)
        {
            if (listOfFiles2[i].isFile())
            {
                AfterMM.add(listOfFiles2[i].getName());//seriously wow
            }
        }

            // Number of Files in each Folder or Directory
            System.out.println("Files in FolderA / BeforeMM ----> " + fileCount );
            System.out.println("Files in FolderB / AfterMM -----> " + fileCountTwo );
            System.out.println("------------------------------------");

            System.out.println( "Size/Number of Array Elements BeforeMM -----> "+BeforeMM.size() );
            System.out.println( "Size/Number of Array Elements AfterMM  -----> "+AfterMM.size() );
            System.out.println("------------------------------------");

            System.out.println("Before Media Folder Conatins----> " + BeforeMM );
            System.out.println("After Media Folder  Conatins----> " + AfterMM );
            System.out.println("------------------------------------");
            //this is where problems start
            List<String> result = AfterMM.stream().filter(elem -> !BeforeMM.contains(elem)).collect(Collectors.toList());
            System.out.println("Result: File(s) present in After BUT NOT BeforeMM folder:\n" + result);
            // Result equals Test2.txt

            /*// Remove all elements in BeforeFolder from AfterFolder
            BeforeMM.removeAll(AfterMM);
            // Show results
            System.out.println("Result: " + AfterMM);
            */

    }

}
</code>```

答:
There are a number of improvements and simplifications we can make to your code, first you might build your paths using System.getProperty("user.home") and the File(String, String) constructor. Next, you can collect your list of files with streams. Then you can use removeAll to build your final List. Like,

```<code>File desktop = new File(System.getProperty("user.home"), "Desktop");
File adp = new File(desktop, "ADP");
File folder1 = new File(adp, "MagMediaBefore");
File folder2 = new File(adp, "MagMediaAfter");
List<String> beforeMM = Stream.of(folder1.listFiles()) //
        .filter(File::isFile).map(File::getName) //
        .collect(Collectors.toList());
List<String> afterMM = Stream.of(folder2.listFiles()) //
        .filter(File::isFile).map(File::getName) //
        .collect(Collectors.toList());

// Number of Files in each Folder or Directory
System.out.println("Files in FolderA / BeforeMM ----> " //
        + beforeMM.size());
System.out.println("Files in FolderB / AfterMM -----> " //
        + afterMM.size());
System.out.println("------------------------------------");

System.out.println("Before Media Folder Conatins----> " //
        + beforeMM);
System.out.println("After Media Folder  Conatins----> " //
        + afterMM);
System.out.println("------------------------------------");
List<String> result = new ArrayList<>(afterMM);
result.removeAll(beforeMM);
System.out.println("Result: File(s) present in After BUT NOT " //
        + "BeforeMM folder: " + result);
</code>```

Note that you are currently reading the same folder in folder1 and folder2. Also, please follow Java variable naming conventions (beforeMM and afterMM, yours' looked like class names).

Body:
I am trying to compare files and my solution works with folders that have a small amount of files in them like 10 but not folders with like over 200 filenames in them. The last part of my codes comes back NULL or Results = [ ] usually the text file(s) name is in here that shows the difference between both folders any help is appreciated. The problem is the last part of my code

package nameCompare;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

// https://stackoverflow.com/questions/19662384/comparing-file-names
// http://www.javaprogrammingforums.com/java-programming-tutorials/3-java-program-can-list-all-files-given-directory.html

public class fileNameCompare {

    public static void main(String[] args) {
                             // first directory path here
        String path1 = "C:/Users/Jonathan/Desktop/ADP/MagMediaAfter";
        //String path1 = "C:/Users/Jonathan/Desktop/FolderA";

        // second directory path here
        String path2 = "C:/Users/Jonathan/Desktop/ADP/MagMediaAfter";
        //String path2 = "C:/Users/Jonathan/Desktop/FolderB";

        File folder1 = new File(path1);
        int fileCount = folder1.list().length;

        File folder2 = new File(path2);
        int fileCountTwo = folder2.list().length;

        File[] listOfFiles1 = folder1.listFiles();
        File[] listOfFiles2 = folder2.listFiles();

        //we'll need these to store the file names as Strings
        ArrayList<String> BeforeMM = new ArrayList<String>();
        ArrayList<String> AfterMM = new ArrayList<String>();

        //get file names from directory
        for (int i = 0; i < listOfFiles1.length; i++)
        {
            if (listOfFiles1[i].isFile())
            {
                BeforeMM.add(listOfFiles1[i].getName());//wow
            }
        }

        for (int i = 0; i < listOfFiles2.length; i++)
        {
            if (listOfFiles2[i].isFile())
            {
                AfterMM.add(listOfFiles2[i].getName());//seriously wow
            }
        }

            // Number of Files in each Folder or Directory
            System.out.println("Files in FolderA / BeforeMM ----> " + fileCount );
            System.out.println("Files in FolderB / AfterMM -----> " + fileCountTwo );
            System.out.println("------------------------------------");

            System.out.println( "Size/Number of Array Elements BeforeMM -----> "+BeforeMM.size() );
            System.out.println( "Size/Number of Array Elements AfterMM  -----> "+AfterMM.size() );
            System.out.println("------------------------------------");

            System.out.println("Before Media Folder Conatins----> " + BeforeMM );
            System.out.println("After Media Folder  Conatins----> " + AfterMM );
            System.out.println("------------------------------------");
            //this is where problems start
            List<String> result = AfterMM.stream().filter(elem -> !BeforeMM.contains(elem)).collect(Collectors.toList());
            System.out.println("Result: File(s) present in After BUT NOT BeforeMM folder:\n" + result);
            // Result equals Test2.txt

            /*// Remove all elements in BeforeFolder from AfterFolder
            BeforeMM.removeAll(AfterMM);
            // Show results
            System.out.println("Result: " + AfterMM);
            */

    }

}

Body:
There are a number of improvements and simplifications we can make to your code, first you might build your paths using System.getProperty("user.home") and the File(String, String) constructor. Next, you can collect your list of files with streams. Then you can use removeAll to build your final List. Like,

File desktop = new File(System.getProperty("user.home"), "Desktop");
File adp = new File(desktop, "ADP");
File folder1 = new File(adp, "MagMediaBefore");
File folder2 = new File(adp, "MagMediaAfter");
List<String> beforeMM = Stream.of(folder1.listFiles()) //
        .filter(File::isFile).map(File::getName) //
        .collect(Collectors.toList());
List<String> afterMM = Stream.of(folder2.listFiles()) //
        .filter(File::isFile).map(File::getName) //
        .collect(Collectors.toList());

// Number of Files in each Folder or Directory
System.out.println("Files in FolderA / BeforeMM ----> " //
        + beforeMM.size());
System.out.println("Files in FolderB / AfterMM -----> " //
        + afterMM.size());
System.out.println("------------------------------------");

System.out.println("Before Media Folder Conatins----> " //
        + beforeMM);
System.out.println("After Media Folder  Conatins----> " //
        + afterMM);
System.out.println("------------------------------------");
List<String> result = new ArrayList<>(afterMM);
result.removeAll(beforeMM);
System.out.println("Result: File(s) present in After BUT NOT " //
        + "BeforeMM folder: " + result);

Note that you are currently reading the same folder in folder1 and folder2. Also, please follow Java variable naming conventions (beforeMM and afterMM, yours' looked like class names).


问:
Google assistant gRPC call hung
Server doesn't reply when a GRPC call is made to "embeddedassistant.googleapis.com". I see the request being received at google server end when I check the Google API web interface.
I set the request with proper configuration (when I set wrong configuration I do get error message from server). Is there anything I'm missing here?</p>

```<code>  std::string Converse(const std::string& user) {

   AudioInConfig audio_in_config;
   audio_in_config.set_encoding(google::assistant::embedded::v1alpha1::AudioInConfig_Encoding_FLAC);
   audio_in_config.set_sample_rate_hertz(16000);

   AudioOutConfig audio_out_config;
   audio_out_config.set_encoding(google::assistant::embedded::v1alpha1::AudioOutConfig_Encoding_MP3);
   audio_out_config.set_sample_rate_hertz(16000);
   audio_out_config.set_volume_percentage(50);

   ConverseState converse_state;
   const char * conversation_state = "a";
   converse_state.set_conversation_state(conversation_state);

   ConverseConfig config;
   config.set_allocated_audio_in_config(&audio_in_config);
   config.set_allocated_audio_out_config(&audio_out_config);
   config.set_allocated_converse_state(&converse_state);

   ConverseRequest request;
   request.set_allocated_config(&config);

   ConverseResponse reply;

   ClientContext context;

   auto status = stub_->Converse(&context, request, &reply);

   config.release_audio_in_config();
   config.release_audio_out_config();
   config.release_converse_state();
   request.release_config();
   // Act upon its status.
   if (status.ok()) {
     return reply.result().conversation_state();
   } else {
     std::cout << "Error: " << status.error_code() << ": " << status.error_message()
            << std::endl;
     return "RPC failed";
   }
   return "";
 }
</code>```

答:
Why have you set the conversation_state to "a". It should be in bytes or empty. You also need to send an audio data captured depending upon the situation. You can do that by including the ALSA sound API in C++ in your code.

The conversation_state value returned in the prior ConverseResponse. Omit (do not set the field) if there was no prior ConverseResponse. If there was a prior ConverseResponse, do not omit this field; doing so will end that conversation (and this new request will start a new conversation).

You can see from here:-
https://developers.google.com/assistant/sdk/reference/rpc/google.assistant.embedded.v1alpha1

Title: Google assistant gRPC call hung

Body:
Server doesn't reply when a GRPC call is made to "embeddedassistant.googleapis.com". I see the request being received at google server end when I check the Google API web interface.
I set the request with proper configuration (when I set wrong configuration I do get error message from server). Is there anything I'm missing here?

  std::string Converse(const std::string& user) {

   AudioInConfig audio_in_config;
   audio_in_config.set_encoding(google::assistant::embedded::v1alpha1::AudioInConfig_Encoding_FLAC);
   audio_in_config.set_sample_rate_hertz(16000);

   AudioOutConfig audio_out_config;
   audio_out_config.set_encoding(google::assistant::embedded::v1alpha1::AudioOutConfig_Encoding_MP3);
   audio_out_config.set_sample_rate_hertz(16000);
   audio_out_config.set_volume_percentage(50);

   ConverseState converse_state;
   const char * conversation_state = "a";
   converse_state.set_conversation_state(conversation_state);

   ConverseConfig config;
   config.set_allocated_audio_in_config(&audio_in_config);
   config.set_allocated_audio_out_config(&audio_out_config);
   config.set_allocated_converse_state(&converse_state);

   ConverseRequest request;
   request.set_allocated_config(&config);

   ConverseResponse reply;

   ClientContext context;

   auto status = stub_->Converse(&context, request, &reply);

   config.release_audio_in_config();
   config.release_audio_out_config();
   config.release_converse_state();
   request.release_config();
   // Act upon its status.
   if (status.ok()) {
     return reply.result().conversation_state();
   } else {
     std::cout << "Error: " << status.error_code() << ": " << status.error_message()
            << std::endl;
     return "RPC failed";
   }
   return "";
 }


问:
Partial rendering after page loaded
I have a page that contains some usercontrols. I would like to load these usercontrols after postback like an ajax rendering.

Each usercontrols display a list from database and I dont want the user to wait while server code builds up the response I think it will be useful if the page is displayed for the user and after the usercontrols are loaded through an ajax request.

Is there an exist solution in ASP.NET MVC? Is there an exist solution for this problem?

thanks advance: l.

答:
I usually do this way:

In the markup I reserve space for the user control to be loaded like

```<code><div id="i-tabs-5">
    <div style="text-align:right;margin-bottom:6px;">...</div>
    <div id="issueNoteListPlaceholder"></div>
</div>
</code>```

then on DOM Ready I make an ajax call that return a partial view result and replace the content of the placeholder

```<code>$(document).ready(function () {
    loadIssueNotes();
});

function loadIssueNotes() {
    $.ajax({
        type: "get",
        dataType: "html",
        url: '<%: Url.Content("~/Controller/Action") %>',
        data: {},
        success: function (response) {
            $("#issueNoteListPlaceholder").html('').html(response);
        }
    });
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Partial rendering after page loaded

Body:
I usually do this way:

In the markup I reserve space for the user control to be loaded like

<div id="i-tabs-5">
    <div style="text-align:right;margin-bottom:6px;">...</div>
    <div id="issueNoteListPlaceholder"></div>
</div>

then on DOM Ready I make an ajax call that return a partial view result and replace the content of the placeholder

$(document).ready(function () {
    loadIssueNotes();
});

function loadIssueNotes() {
    $.ajax({
        type: "get",
        dataType: "html",
        url: '<%: Url.Content("~/Controller/Action") %>',
        data: {},
        success: function (response) {
            $("#issueNoteListPlaceholder").html('').html(response);
        }
    });
}


问:
c# amazon AWS s3: Any way to upload user browsed images directly to s3 without downloading it on our local servers?
We have a website where users upload their product images. We have given user browse option to pick images from their local system. Currently:

Once the user clicks on browser button, and select some local image for uploading, we save the user browsed image to some location on our server.

We show a thumbnail of the image to the user.

In the background, we pass our server image path to s3 and get back the s3 path of the same image.

What we want to achieve is, we don't want to save the image on our server in the 1st step as we have created piles of images by saving it on our server.

Is there any way where we could upload image to s3 without saving the image on our server? Though we want to display the thumbnail of the uploaded image.

答:
You can directly upload the images to AWS S3 from your Client's browser without saving in your server and its one of the main use cases of S3. Have a look at AWS S3 JavaScript SDK for more details.

You might need to store the file names, for querying in your server database or similar but not the image itself. Apart from that, if you plan to allow only authorized parties to upload images from their Web Browser. Go through the AWS S3 Signed URLs section for more details.

Also you can do the thumbnail creation using AWS Lambda, S3 trigger where, thumbnail creation happens automatically when, the user uploads an image.


问:
How to have more than one dropdown in Materialize CSS?
I'm currently working in OpenCart 3 and using Materialize 0.99.0.
But I've run into an issue with the dropdowns on my main menu. I need to have more than one dropdown in it but the catch is that it's all being generated. Looking at the code for dropdowns on Materialize it goes like this:

```<code>  <!-- Dropdown Trigger -->
  <a class='dropdown-button btn' href='#' data-activates='dropdown1'>Drop Me!</a>

  <!-- Dropdown Structure -->
  <ul id='dropdown1' class='dropdown-content'>
    <li><a href="#!">one</a></li>
    <li><a href="#!">two</a></li>
    <li class="divider"></li>
    <li><a href="#!">three</a></li>
    <li><a href="#!"><i class="material-icons">view_module</i>four</a></li>
    <li><a href="#!"><i class="material-icons">cloud</i>five</a></li>
  </ul>
</code>```

If I put this in my OpenCart template it uses the 'Dropdown1' ID for every dropdown which of course will not work. How do I solve this?

The code in OpenCart goes like this:

```<code>{% if categories %}
    {% for category in categories %}
        {% if category.children %}
            <li>
                <a href="#" class="dropdown-button" data-activates="dropdown1">{{ category.name }}<i class="mdi mdi-menu-down"></i></a>
                {% for children in category.children|batch(category.children|length / category.column|round(1, 'ceil')) %}
                    <ul id="dropdown1" class="dropdown-content">
                        {% for child in children %}
                            <li><a href="{{ child.href }}">{{ child.name }}</a></li>
                        {% endfor %}
                        <li class="divider"></li>
                        <li><a href="{{ category.href }}" class="see-all">{{ text_all }} {{ category.name }}</a></li>
                    </ul>
                {% endfor %}
            </li>
        {% else %}
            <li><a href="{{ category.href }}">{{ category.name }}</a></li>
        {% endif %}
    {% endfor %}
{% endif %}
</code>```

So basically what I need is that either Materialize can be converted to not use ID's but something else that doesn't have to be unique but still works or I need a function that generates a unique ID for every loop and puts the ID there.

I really need your help with this and I can't believe I can't find anything about it on the internet. How can I be the only one running into this problem?

答:
I managed to solve it along with help from a good friend on Twitch.
What we did is we set an 'I' value and let that increment for every loop and then print that out accordingly in the 'Data Activates' and 'ID'.

The code for the menu.twig goes as follows now:

```<code>{% if categories %}
{% for category in categories %}
    {% if category.children %}
        <li>
            {% set i = i + 1 %}
            <a href="#" class="dropdown-button" data-activates="{{ i }}">{{ category.name }}<i class="mdi mdi-menu-down"></i></a>
            {% for children in category.children|batch(category.children|length / category.column|round(1, 'ceil')) %}
                <ul id="{{ i }}" class="dropdown-content">
                    {% for child in children %}
                        <li><a href="{{ child.href }}">{{ child.name }}</a></li>
                    {% endfor %}
                    <li class="divider"></li>
                    <li><a href="{{ category.href }}" class="see-all">{{ text_all }} {{ category.name }}</a></li>
                </ul>

            {% endfor %}
        </li>
    {% else %}
        <li><a href="{{ category.href }}">{{ category.name }}</a></li>
    {% endif %}
{% endfor %}
{% endif %}
</code>```

Body:
I'm currently working in OpenCart 3 and using Materialize 0.99.0.
But I've run into an issue with the dropdowns on my main menu. I need to have more than one dropdown in it but the catch is that it's all being generated. Looking at the code for dropdowns on Materialize it goes like this:

  Drop Me!

one

two

three

view_modulefour

cloudfive

If I put this in my OpenCart template it uses the 'Dropdown1' ID for every dropdown which of course will not work. How do I solve this?

The code in OpenCart goes like this:

{% if categories %}
    {% for category in categories %}
        {% if category.children %}

                {{ category.name }}
                {% for children in category.children|batch(category.children|length / category.column|round(1, 'ceil')) %}

                        {% for child in children %}

{{ child.name }}

                        {% endfor %}

{{ text_all }} {{ category.name }}

                {% endfor %}

        {% else %}

{{ category.name }}

        {% endif %}
    {% endfor %}
{% endif %}

So basically what I need is that either Materialize can be converted to not use ID's but something else that doesn't have to be unique but still works or I need a function that generates a unique ID for every loop and puts the ID there.

I really need your help with this and I can't believe I can't find anything about it on the internet. How can I be the only one running into this problem?

Body:
I managed to solve it along with help from a good friend on Twitch.
What we did is we set an 'I' value and let that increment for every loop and then print that out accordingly in the 'Data Activates' and 'ID'.

The code for the menu.twig goes as follows now:

{% if categories %}
{% for category in categories %}
    {% if category.children %}
        <li>
            {% set i = i + 1 %}
            <a href="#" class="dropdown-button" data-activates="{{ i }}">{{ category.name }}<i class="mdi mdi-menu-down"></i></a>
            {% for children in category.children|batch(category.children|length / category.column|round(1, 'ceil')) %}
                <ul id="{{ i }}" class="dropdown-content">
                    {% for child in children %}
                        <li><a href="{{ child.href }}">{{ child.name }}</a></li>
                    {% endfor %}
                    <li class="divider"></li>
                    <li><a href="{{ category.href }}" class="see-all">{{ text_all }} {{ category.name }}</a></li>
                </ul>

            {% endfor %}
        </li>
    {% else %}
        <li><a href="{{ category.href }}">{{ category.name }}</a></li>
    {% endif %}
{% endfor %}
{% endif %}


问:
Missing nodes when trying to parse xml in php
I am using the following feed: http://feeds.livep2000.nl/

I try to parse it with the following line of code:

```<code>$xml = simplexml_load_string(file_get_contents($url), null, LIBXML_NOCDATA);
</code>```

It shows me data like i expect but missing the geo:lat and geo:long like this:

XML

```<code><item>
<title>
<![CDATA[
A2 (DIA: ) some title
]]>
</title>
<link>http://monitor.livep2000.nl?SPI=1707082033480217</link>
<pubDate>Sat, 08 Jul 2017 20:33:48 +0200</pubDate>
<description>
<![CDATA[
1420999 MKA Rotterdam-Rijnmond ( Monitorcode )<br/>1420029 MKA Rotterdam-Rijnmond ( Ambulance 17-129 )<br/>
]]>
</description>
<guid>1707082033480217</guid>
<author/>
<geo:lat>51.8431255</geo:lat>
<geo:long>4.3429498</geo:long>
</item>
</code>```

Response

```<code>    ["item"]=>
        array(50) {
          [0]=>
              object(SimpleXMLElement)#163 (6) {
                ["title"]=>
                string(41) "some title"
                ["link"]=>
                string(48) "http://monitor.livep2000.nl?SPI=1707082036240209"
                ["pubDate"]=>
                string(31) "Sat, 08 Jul 2017 20:36:24 +0200"
                ["description"]=>
                string(44) "description ( Ambulance 09-129 )"
                ["guid"]=>
                string(16) "1707082036240209"
                ["author"]=>
                object(SimpleXMLElement)#213 (0) {
                }
              }

etc....
</code>```

Any idea why the geo nodes are missing?

答:
The problem is that lat and long are a part of geo namespace in the mentioned XML and simplexml does not allow you to access them by default.

You need to use something like:

```<code>$ns = $xml->getNamespaces(TRUE);

foreach ($xml->channel[0]->item as $item) {
    var_dump($item->children($ns['geo'])->lat);
    var_dump($item->children($ns['geo'])->lon);
    // do other stuff with $item here
}
</code>```

Body:
I am using the following feed: http://feeds.livep2000.nl/

I try to parse it with the following line of code:

$xml = simplexml_load_string(file_get_contents($url), null, LIBXML_NOCDATA);

It shows me data like i expect but missing the geo:lat and geo:long like this:

XML

<item>
<title>
<![CDATA[
A2 (DIA: ) some title
]]>
</title>
<link>http://monitor.livep2000.nl?SPI=1707082033480217</link>
<pubDate>Sat, 08 Jul 2017 20:33:48 +0200</pubDate>
<description>
<![CDATA[
1420999 MKA Rotterdam-Rijnmond ( Monitorcode )
1420029 MKA Rotterdam-Rijnmond ( Ambulance 17-129 )

]]>
</description>
<guid>1707082033480217</guid>
<author/>
<geo:lat>51.8431255</geo:lat>
<geo:long>4.3429498</geo:long>
</item>

Response

    ["item"]=>
        array(50) {
          [0]=>
              object(SimpleXMLElement)#163 (6) {
                ["title"]=>
                string(41) "some title"
                ["link"]=>
                string(48) "http://monitor.livep2000.nl?SPI=1707082036240209"
                ["pubDate"]=>
                string(31) "Sat, 08 Jul 2017 20:36:24 +0200"
                ["description"]=>
                string(44) "description ( Ambulance 09-129 )"
                ["guid"]=>
                string(16) "1707082036240209"
                ["author"]=>
                object(SimpleXMLElement)#213 (0) {
                }
              }

etc....

Any idea why the geo nodes are missing?

Body:
The problem is that lat and long are a part of geo namespace in the mentioned XML and simplexml does not allow you to access them by default.

You need to use something like:

$ns = $xml->getNamespaces(TRUE);

foreach ($xml->channel[0]->item as $item) {
    var_dump($item->children($ns['geo'])->lat);
    var_dump($item->children($ns['geo'])->lon);
    // do other stuff with $item here
}


问:
Inserting developerPayload to getBuyIntent() method
I try to make Google Play Billing Service via com.android.billingclient:billing-dp1 library. I try starting the billing process by calling:

```<code>billingClient.launchBillingFlow(activity, params);
</code>```

So the question is how to pass "developerPayload" argument to this flow? Both launchBillingFlow and it's params argument don't contain such a field.

答:
Is the InitiatePurchase command used in billing?  Because you pass the developerPayload in the InitiatePurchase command...

```<code>string developerPayload = "the info you are passing in the developerPayload";
m_storeController.InitiatePurchase (product, developerPayload);
</code>```

That's it.

Body:
I try to make Google Play Billing Service via com.android.billingclient:billing-dp1 library. I try starting the billing process by calling:

billingClient.launchBillingFlow(activity, params);

So the question is how to pass "developerPayload" argument to this flow? Both launchBillingFlow and it's params argument don't contain such a field.

Body:
Is the InitiatePurchase command used in billing?  Because you pass the developerPayload in the InitiatePurchase command...

string developerPayload = "the info you are passing in the developerPayload";
m_storeController.InitiatePurchase (product, developerPayload);

That's it.


问:
border and panel orginization
I'm having a very hard time with borders, I've looked through tutorials and examples and each seems to use a different style, I'm just trying to organise the content into separated borders. The content for the bottom panal isn't finished yet but I'm just trying to get it to work as is before adding more.

The compiler says there are problems on two lines java.lang.NullPointerException:

```<code>package question2;

import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;

/**
 * @author Matt Headley
  This frame shows a data set and its statistics.
  */
 public class ComputerStoreGUI extends JFrame
 {

   private JCheckBox item1;
   private JCheckBox item2;
   private JCheckBox item3;
   private JCheckBox item4;
   private JCheckBox item5;
   private TitledBorder border;
   private TitledBorder border2;
   private static JPanel content;
   private static JPanel top;
   private static JPanel bottom;
    private JTextField parts;

public ComputerStoreGUI()
 {
  JCheckBox item1 = new JCheckBox("Install Hard Drive - $25.00");
  JCheckBox item2 = new JCheckBox("Install RAM - $15.00");
  JCheckBox item3 = new JCheckBox("Remove Virus - $50.00");
  JCheckBox item4 = new JCheckBox("Format Hard Drive - $80.00");
  JCheckBox item5 = new JCheckBox("Quote Hourly Labour - $10.00");
  item1.setHorizontalAlignment(JCheckBox.LEFT);
  item2.setHorizontalAlignment(JCheckBox.LEFT);
  item3.setHorizontalAlignment(JCheckBox.LEFT);
  item4.setHorizontalAlignment(JCheckBox.LEFT);
  item5.setHorizontalAlignment(JCheckBox.LEFT);
  JTextField cost = new JTextField(10);

  top = new JPanel(new FlowLayout(FlowLayout.LEFT));
  top.add(item1);
  top.add(item2);
  top.add(item3);
  top.add(item4);
  top.add(item5);
  bottom.add(cost); //here ????????
  cost.setHorizontalAlignment(JTextField.CENTER);

}

public static void main(String[] args)
{
JFrame frame = new ComputerStoreGUI(); // and here ???????

content = new JPanel();
content.setBorder(BorderFactory.createEmptyBorder(10, 10, 10,  10));

top = new JPanel();
top.setBorder(BorderFactory.createTitledBorder("Standard Services"));

bottom = new JPanel();
bottom.setBorder(BorderFactory.createTitledBorder("Hourly Service"));

    frame.setSize(250, 400);
    frame.setTitle("LU Computer Store");
    frame.setContentPane(content);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    content.add(top);
    content.add(bottom);
    frame.setVisible(true);
}
</code>```

}

the end goal is to look something like this:

答:
First, I dont see a reson to extend JFrame in your example. So without inheritance you can use composition like:

```<code>JFrmae frame = new JFrame();
</code>```

Read more: Why do we need to extend JFrame in a swing application?

The compiler says there are problems on two lines
  java.lang.NullPointerException:

Reason is, you have declared the JPanel bottom but without initializing you are trying to use it, from this line: bottom.add(cost);

Do something like:

```<code>bottom = new JPanel(new FlowLayout(FlowLayout.LEFT));
bottom.add(cost);
</code>```

EDIT:

comment: It runs now, but the panels are tiny

Because you need to set layout for the parent JPanel, you can use BoxLayout, to add child panels one below another, like below:

```<code>content = new JPanel();
content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS));
</code>```

In case if you want to add space between those two child panels, use as below:

```<code>content.add(top);
content.add(Box.createRigidArea(new Dimension(0,10)));
content.add(bottom);
</code>```

Title: border and panel orginization

Body:
I'm having a very hard time with borders, I've looked through tutorials and examples and each seems to use a different style, I'm just trying to organise the content into separated borders. The content for the bottom panal isn't finished yet but I'm just trying to get it to work as is before adding more.

The compiler says there are problems on two lines java.lang.NullPointerException:

package question2;

import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;

/**
 * @author Matt Headley
  This frame shows a data set and its statistics.
  */
 public class ComputerStoreGUI extends JFrame
 {

   private JCheckBox item1;
   private JCheckBox item2;
   private JCheckBox item3;
   private JCheckBox item4;
   private JCheckBox item5;
   private TitledBorder border;
   private TitledBorder border2;
   private static JPanel content;
   private static JPanel top;
   private static JPanel bottom;
    private JTextField parts;

public ComputerStoreGUI()
 {
  JCheckBox item1 = new JCheckBox("Install Hard Drive - $25.00");
  JCheckBox item2 = new JCheckBox("Install RAM - $15.00");
  JCheckBox item3 = new JCheckBox("Remove Virus - $50.00");
  JCheckBox item4 = new JCheckBox("Format Hard Drive - $80.00");
  JCheckBox item5 = new JCheckBox("Quote Hourly Labour - $10.00");
  item1.setHorizontalAlignment(JCheckBox.LEFT);
  item2.setHorizontalAlignment(JCheckBox.LEFT);
  item3.setHorizontalAlignment(JCheckBox.LEFT);
  item4.setHorizontalAlignment(JCheckBox.LEFT);
  item5.setHorizontalAlignment(JCheckBox.LEFT);
  JTextField cost = new JTextField(10);

  top = new JPanel(new FlowLayout(FlowLayout.LEFT));
  top.add(item1);
  top.add(item2);
  top.add(item3);
  top.add(item4);
  top.add(item5);
  bottom.add(cost); //here ????????
  cost.setHorizontalAlignment(JTextField.CENTER);

}

public static void main(String[] args)
{
JFrame frame = new ComputerStoreGUI(); // and here ???????

content = new JPanel();
content.setBorder(BorderFactory.createEmptyBorder(10, 10, 10,  10));

top = new JPanel();
top.setBorder(BorderFactory.createTitledBorder("Standard Services"));

bottom = new JPanel();
bottom.setBorder(BorderFactory.createTitledBorder("Hourly Service"));

    frame.setSize(250, 400);
    frame.setTitle("LU Computer Store");
    frame.setContentPane(content);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    content.add(top);
    content.add(bottom);
    frame.setVisible(true);
}

}

the end goal is to look something like this:

Body:
First, I dont see a reson to extend JFrame in your example. So without inheritance you can use composition like:

JFrmae frame = new JFrame();

Read more: Why do we need to extend JFrame in a swing application?

The compiler says there are problems on two lines
  java.lang.NullPointerException:

Reason is, you have declared the JPanel bottom but without initializing you are trying to use it, from this line: bottom.add(cost);

Do something like:

bottom = new JPanel(new FlowLayout(FlowLayout.LEFT));
bottom.add(cost);

EDIT:

comment: It runs now, but the panels are tiny

Because you need to set layout for the parent JPanel, you can use BoxLayout, to add child panels one below another, like below:

content = new JPanel();
content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS));

In case if you want to add space between those two child panels, use as below:

content.add(top);
content.add(Box.createRigidArea(new Dimension(0,10)));
content.add(bottom);


问:
Updating screen with messages from a thread that raises events (ASP.NET)
I have a very long running process that I start in a thread. This raises events with messages to say what it is doing.

How can I update a label on screen with these messages? (The label is in an update panel if that makes it easier).

If this is not possible, is there a better way you can suggest?

答:
Yes, you can. Create a method that will have a parameter (message string to be shown). Like:

```<code>private void SetLabelText(string message)
{
            if (label.InvokeRequired)
            {
                Invoke(new MethodInvoker(() => SetLabelText(message)
                           ));
            }
            else
            {
                label.Text = message;
            }
}
</code>```

Use this method in your event handler.

Body:
Yes, you can. Create a method that will have a parameter (message string to be shown). Like:

private void SetLabelText(string message)
{
            if (label.InvokeRequired)
            {
                Invoke(new MethodInvoker(() => SetLabelText(message)
                           ));
            }
            else
            {
                label.Text = message;
            }
}

Use this method in your event handler.


问:
Efficient way to convert all data frame columns in Scala
I am trying to do type cast of all data frame columns based on an input as shown below, how can I do this with a single command that converts all data frame columns? The following code works fine, but I need a generic command that works for any data frame. Thanks in advance for your kind suggestions.</p>

```<code>    for (colIndex <- 0 to tmpDF.columns.length - 1) {

      val columns = df.columns
      newdf = df.withColumn(columns(0), df(columns(0)).cast(dataType(0)))
        .withColumn(columns(1), df(columns(1)).cast(dataType(1)))
        .withColumn(columns(2), df(columns(2)).cast(dataType(2)))
        .withColumn(columns(3), df(columns(3)).cast(dataType(3)))
        .withColumn(columns(4), df(columns(4)).cast(dataType(4)))

   //  newdf = df.withColumn(columns(colIndex), df(columns(colIndex)).cast(dataType(colIndex))) --> This didn't work, only last column was updated

}
</code>```

答:
It only updates the last column because you always append to column to df, you should keep appending to newDF This should work:

```<code>var newDF = df
val columns = df.columns
for (colIndex <- tmpDF.columns.indices) {
    newDF = newDF.withColumn(columns(colIndex), df(columns(colIndex)).cast(dataType(colIndex)))
}
</code>```

Body:
I am trying to do type cast of all data frame columns based on an input as shown below, how can I do this with a single command that converts all data frame columns? The following code works fine, but I need a generic command that works for any data frame. Thanks in advance for your kind suggestions.

    for (colIndex <- 0 to tmpDF.columns.length - 1) {

      val columns = df.columns
      newdf = df.withColumn(columns(0), df(columns(0)).cast(dataType(0)))
        .withColumn(columns(1), df(columns(1)).cast(dataType(1)))
        .withColumn(columns(2), df(columns(2)).cast(dataType(2)))
        .withColumn(columns(3), df(columns(3)).cast(dataType(3)))
        .withColumn(columns(4), df(columns(4)).cast(dataType(4)))

   //  newdf = df.withColumn(columns(colIndex), df(columns(colIndex)).cast(dataType(colIndex))) --> This didn't work, only last column was updated

}

Body:
It only updates the last column because you always append to column to df, you should keep appending to newDF This should work:

var newDF = df
val columns = df.columns
for (colIndex <- tmpDF.columns.indices) {
    newDF = newDF.withColumn(columns(colIndex), df(columns(colIndex)).cast(dataType(colIndex)))
}


答:
Create a new function

```<code>function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

function listClick() {
    toplist.classList.add("animation");
    await sleep(2000);
    toplist.classList.remove("animation");
}
</code>```

What is the JavaScript version of sleep()?

Body:
I want to animate something everytime I click on it. So I saved an animation in the class "animation".

function listClick() {
  toplist.classList.add("animation");
  toplist.classList.remove("animation");
}

the animation lasts 2000 ms so I want a delay of 2000 ms between those two lines of code in my function. How can I achieve this using Javascript?

Body:
Create a new function

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

function listClick() {
    toplist.classList.add("animation");
    await sleep(2000);
    toplist.classList.remove("animation");
}

What is the JavaScript version of sleep()?


问:
How I can get intagram photo url with youtube-dl lib?
I want to create my first RoR application for downloading video/photo (like this one)content from popular websites. I found youtube-dl.rb gem and configured downloading videos from instagram, but I can't get images from photo and gallery Instagram posts. I should to use API directly or another gem. Can I do this only with youtube-dl library?</p>

答: You have to use Instagram API directly. youtube-dl library only for videos and metadata for videos.</p>


问:
How to retrieve certain file elements using groovy and store elements as arraylist
I’m new to groovy programming and I am trying to use groovy to retrieve phone numbers that are randomly present in a text file and then store these values in an arraylist in my groovy program.  An example of what the text file looks like is this:

Line of code
Hello how are you 111-111-1111
Cat dog dog cat
999-999-9999
Another line of code  777-777-7777

The output I’m trying to display:
111-111-1111
999-999-9999
777-777-7777

I know how to reference the file and retrieve all lines of code and specific numbers/words/etc., but I am unsure of the groovy way to retrieve just the phone numbers present in the text file

答:
The easiest way to add an element to a list is += operator.

Below you have an example program, which extracts phone numbers from
each source row of a multiline string, collects them in a list,
and prints the list.

```<code>def src = '''\
Line of code Hello how are you 111-111-1111 Cat dog dog cat 999-999-9999.
I'm fine and how are you 111-111-2222 Cat dog dog cat 999-999-8888.
No phone number here.
Another line of code  777-777-8888\
'''
def pat = ~/\b\d{3}-\d{3}-\d{4}\b/
def phones = []
def cnt = 0
src.eachLine{
  def matcher = (it =~ pat)
  def mCnt = matcher.getCount()
  printf("Row %d: %s / %d phones.\n", ++cnt, it, mCnt)
  for (i = 0; i < mCnt; ++i) {
    phones += matcher[i]
  }
}
printf("%d phones: %s.\n", phones.size(), phones.join(', '))
</code>```

Body:
The easiest way to add an element to a list is += operator.

Below you have an example program, which extracts phone numbers from
each source row of a multiline string, collects them in a list,
and prints the list.

def src = '''\
Line of code Hello how are you 111-111-1111 Cat dog dog cat 999-999-9999.
I'm fine and how are you 111-111-2222 Cat dog dog cat 999-999-8888.
No phone number here.
Another line of code  777-777-8888\
'''
def pat = ~/\b\d{3}-\d{3}-\d{4}\b/
def phones = []
def cnt = 0
src.eachLine{
  def matcher = (it =~ pat)
  def mCnt = matcher.getCount()
  printf("Row %d: %s / %d phones.\n", ++cnt, it, mCnt)
  for (i = 0; i < mCnt; ++i) {
    phones += matcher[i]
  }
}
printf("%d phones: %s.\n", phones.size(), phones.join(', '))


问:
Transform image via a given matrix using OpenCv
what I'm trying to do is transforming an image using an (Matlab) transformation matrix. It is the following 2D transformation matrix with a 3x3 dimension:

```<code>aaa   bbb   0
ccc   ddd   0
eee   fff   1
</code>```

I found a pretty good explanation here: how to transform an image with a transformation Matrix in OpenCv? but I'm not able to fill the 3x3 matrix (and apply it to the image). This is my code:

```<code>cv::Mat t(3,3,CV_64F,cvScalar(0.0));

t.at<double>(0, 0) = aaa;
t.at<double>(1, 0) = bbb;
t.at<double>(2, 0) = 0;

t.at<double>(0, 1) = ccc;
t.at<double>(1, 1) = ddd;
t.at<double>(2, 1) = 0;

t.at<double>(0, 2) = eee;
t.at<double>(1, 2) = fff;
t.at<double>(2, 2) = 1;

cv::Mat dest;
cv::Size size(imageToTransform.cols,imageToTransform.rows);
warpAffine(imageToTransform, outputImage, t, size, INTER_LINEAR, BORDER_CONSTANT);

imshow("outputImage", outputImage);
</code>```

Causes the following error:

OpenCV Error: Assertion failed ((M0.type() == CV_32F || M0.type() == CV_64F) && M0.rows == 2 && M0.cols == 3)

Any idea whats wrong here?

答:
The transformation matrix used in warp affine is an affine transformation matrix, which representation is as follows:

```<code>a11 a12 b1
a21 a22 b2
0   0   1
</code>```

this means it is a 3x3 matrix indeed. However OpenCV doesn't care about the last row, since it will always be the same (look at the link before). Then, you can eliminate this row and have the input needed (2x3):

```<code>a11 a12 b1
a21 a22 b2
</code>```

In getAffineTransform you can see why they want it like that (to have an homgeneous point mapped to the new 2d point and have it already in 2d and avoid extra multiplications).

You have a matrix of the type:

```<code>aaa   bbb   0
ccc   ddd   0
eee   fff   1
</code>```

This seems to be transpose somehow? since I do not know how did you generate the matrix, I can't tell for sure. Maybe you have transpose it and then assign it to opencv (or do it directly). The funny part is that (intentionally or otherwise) you had it in your c++ code the matrix transpose. Remember that OpenCV notation is usually (rows, columns) in most of the cases.

Your code should look like:

```<code>cv::Mat t(2,3,CV_64F,cvScalar(0.0));

t.at<double>(0, 0) = aaa;
t.at<double>(1, 0) = bbb;

t.at<double>(0, 1) = ccc;
t.at<double>(1, 1) = ddd;

t.at<double>(0, 2) = eee;
t.at<double>(1, 2) = fff;

cv::Mat dest;
cv::Size size(imageToTransform.cols,imageToTransform.rows);
warpAffine(imageToTransform, outputImage, t, size, INTER_LINEAR, BORDER_CONSTANT);

imshow("outputImage", outputImage);
</code>```

I hope this helps you with the problem.

Body:
what I'm trying to do is transforming an image using an (Matlab) transformation matrix. It is the following 2D transformation matrix with a 3x3 dimension:

aaa   bbb   0
ccc   ddd   0
eee   fff   1

I found a pretty good explanation here: how to transform an image with a transformation Matrix in OpenCv? but I'm not able to fill the 3x3 matrix (and apply it to the image). This is my code:

cv::Mat t(3,3,CV_64F,cvScalar(0.0));

t.at<double>(0, 0) = aaa;
t.at<double>(1, 0) = bbb;
t.at<double>(2, 0) = 0;

t.at<double>(0, 1) = ccc;
t.at<double>(1, 1) = ddd;
t.at<double>(2, 1) = 0;

t.at<double>(0, 2) = eee;
t.at<double>(1, 2) = fff;
t.at<double>(2, 2) = 1;

cv::Mat dest;
cv::Size size(imageToTransform.cols,imageToTransform.rows);
warpAffine(imageToTransform, outputImage, t, size, INTER_LINEAR, BORDER_CONSTANT);

imshow("outputImage", outputImage);

Causes the following error:

OpenCV Error: Assertion failed ((M0.type() == CV_32F || M0.type() == CV_64F) && M0.rows == 2 && M0.cols == 3)

Any idea whats wrong here?

Body:
The transformation matrix used in warp affine is an affine transformation matrix, which representation is as follows:

a11 a12 b1
a21 a22 b2
0   0   1

this means it is a 3x3 matrix indeed. However OpenCV doesn't care about the last row, since it will always be the same (look at the link before). Then, you can eliminate this row and have the input needed (2x3):

a11 a12 b1
a21 a22 b2

In getAffineTransform you can see why they want it like that (to have an homgeneous point mapped to the new 2d point and have it already in 2d and avoid extra multiplications).

You have a matrix of the type:

aaa   bbb   0
ccc   ddd   0
eee   fff   1

This seems to be transpose somehow? since I do not know how did you generate the matrix, I can't tell for sure. Maybe you have transpose it and then assign it to opencv (or do it directly). The funny part is that (intentionally or otherwise) you had it in your c++ code the matrix transpose. Remember that OpenCV notation is usually (rows, columns) in most of the cases.

Your code should look like:

cv::Mat t(2,3,CV_64F,cvScalar(0.0));

t.at<double>(0, 0) = aaa;
t.at<double>(1, 0) = bbb;

t.at<double>(0, 1) = ccc;
t.at<double>(1, 1) = ddd;

t.at<double>(0, 2) = eee;
t.at<double>(1, 2) = fff;

cv::Mat dest;
cv::Size size(imageToTransform.cols,imageToTransform.rows);
warpAffine(imageToTransform, outputImage, t, size, INTER_LINEAR, BORDER_CONSTANT);

imshow("outputImage", outputImage);

I hope this helps you with the problem.


问:
Slick slider wrong width on initialization
I am trying to implement Slick slider, but calculated width of each slide is wrong (padding on right side of image).

```<code><div class="responsive-slick">
    <img src="Gallery/large/01.jpeg">
    <img src="Gallery/large/02.jpeg">
    <img src="Gallery/large/03.jpeg">
    <img src="Gallery/large/04.jpeg">
    <img src="Gallery/large/05.jpeg">
    <img src="Gallery/large/06.jpeg">
</div>

$(document).ready(function(){
   $('.responsive-slick').slick({
       dots: true,
       mobileFirst:true,
       prevArrow: '<a class="slick-prev">Previous</button>',
       nextArrow: '<a class="slick-prev">Previous</button>',
       slidesToShow: 3,
       slidesToScroll: 8
   });
</code>```

});

Output:

What am I doing wrong?

答:
Your current code is having problem

```<code>$('.responsive-slick').slick({
   dots: true,
   mobileFirst:true,
   **prevArrow: '<a class="slick-prev">Previous</button>',
   nextArrow: '<a class="slick-prev">Previous</button>',**
   slidesToShow: 3,
   slidesToScroll: 8
});
</code>```

You are opening an anchor tag and closing a button. Thats wrong.

Body:
I am trying to implement Slick slider, but calculated width of each slide is wrong (padding on right side of image).

$(document).ready(function(){
   $('.responsive-slick').slick({
       dots: true,
       mobileFirst:true,
       prevArrow: 'Previous</button>',
       nextArrow: 'Previous</button>',
       slidesToShow: 3,
       slidesToScroll: 8
   });

});

Output:

What am I doing wrong?

Body:
Your current code is having problem

$('.responsive-slick').slick({
   dots: true,
   mobileFirst:true,
   **prevArrow: '<a class="slick-prev">Previous</button>',
   nextArrow: '<a class="slick-prev">Previous</button>',**
   slidesToShow: 3,
   slidesToScroll: 8
});

You are opening an anchor tag and closing a button. Thats wrong.


问:
ImageMagick and Paperclip on Rails only accepts bmp file
I'm trying to set up a rails app with paperclip and ImageMagick on Ubunutu 10.10, I have managed to make it work but only with bmp files, when i try to upload any other kind of file I get the error:

```<code>Image Paperclip::CommandNotFoundError
Image Paperclip::CommandNotFoundError
</code>```

I thought it had something to do with ImageMagic so I found this old tutorial

http://www.randycullom.com/chatterbox/archives/2006/12/installing_imag.html

So I uninstall ImageMagick, installed jpg,tiff and png libraries, on jgp library I used

./configure --enable-shared
...

And then install ImageMagic with configure

./configure --enable-lzw=yes --enable-shared=yes --disable-static --without-perl
make
sudo make install

and the error still apears, on my enviroment.rb I have

Paperclip.options[:command_path] = "/usr/local/bin/"

Which is the path than running 'which convert' gave me, on gem file:

gem "paperclip", "~> 2.3"
gem 'rmagick'

What am I missing? Help would be much appreciated.

答:
Ubuntu 16.04:

sudo apt-get -y install imagemagick libmagickcore-dev libmagickwand-dev

Body:
I'm trying to set up a rails app with paperclip and ImageMagick on Ubunutu 10.10, I have managed to make it work but only with bmp files, when i try to upload any other kind of file I get the error:

Image Paperclip::CommandNotFoundError
Image Paperclip::CommandNotFoundError

I thought it had something to do with ImageMagic so I found this old tutorial

http://www.randycullom.com/chatterbox/archives/2006/12/installing_imag.html

So I uninstall ImageMagick, installed jpg,tiff and png libraries, on jgp library I used

./configure --enable-shared
...

And then install ImageMagic with configure

./configure --enable-lzw=yes --enable-shared=yes --disable-static --without-perl
make
sudo make install

and the error still apears, on my enviroment.rb I have

Paperclip.options[:command_path] = "/usr/local/bin/"

Which is the path than running 'which convert' gave me, on gem file:

gem "paperclip", "~> 2.3"
gem 'rmagick'

What am I missing? Help would be much appreciated.


问:
Tomcat 6 server creation using eclipse IDE on ubuntu
I'm having a problem running tomcat 6 with eclipse 3 in ubuntu.

I installed tomcat 6 on my machine and when I tested it using http://localhost:8080, it worked fine.

But whenever i want to create a server in eclipse, i select Tomcat 6 , i get the following message
"Cannot create a server using the selected type", and i can't click next.

Any idea why?

答:
I you have the newer version of eclipse, try to update the Web Tool Plateform plugins in Help/software Updates...
If both eclipse and WTP are up to date I don't see were the problem can be...

PS : there is a "comment" button, do not post an answer to comment an answer ;)

OwnerDisplayName: Oussama

OwnerDisplayName: Vinze


问:
I have two images that I want to display in a single row next to each other
I am unable to display in one row. I will be looping the images dynamically. So if there are 4 to 5 images, then it should come in one row. But if there are more than 5 images or you can say 9, then it should come in next rows. In the below code, I am using HTML and CSS but unable to get in same row.

#umar {
  display: inline;
  width: 100%;
}

.card {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
  width: 20%;
}

.card:hover {
  box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
}

.container {
  padding: 2px 16px;
  margin-bottom: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>Card</h2>

<div id="umar">
  <div class="card">
    <img src="images/img.jpg" alt="Avatar" style="width:100%">
    <div class="container">
      <h4><b>John Doe</b></h4>
      <p>Architect & Engineer</p>
    </div>
  </div>

  <div class="card">
    <img src="images/img1.jpg" alt="Avatar" style="width:100%">
    <div class="container">
      <h4><b>John Doe</b></h4>
      <p>Architect & Engineer</p>
    </div>
  </div>
</div></code>```

答:
use float:left in card class like this:-</p>

```<code> .card {
      box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
      transition: 0.3s;
      float:left;
      width: 20%;
 }
</code>```

Body:
I am unable to display in one row. I will be looping the images dynamically. So if there are 4 to 5 images, then it should come in one row. But if there are more than 5 images or you can say 9, then it should come in next rows. In the below code, I am using HTML and CSS but unable to get in same row.

#umar {
  display: inline;
  width: 100%;
}

.card {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
  width: 20%;
}

.card:hover {
  box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
}

.container {
  padding: 2px 16px;
  margin-bottom: 10px;
}

Card

John Doe

Architect & Engineer

John Doe

Architect & Engineer

Body:
use float:left in card class like this:-

 .card {
      box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
      transition: 0.3s;
      float:left;
      width: 20%;
 }


问:
Remove [ ' ' ] from a string in Node.js
I know how to remove for example only [, but how can I do for remove multiple things?

I have to remove 3 things, the two ', the [ & ] and the space

The string when I print it's something like this: [ 'Chroma 2 Case' ]

Thank you so much!

答: I used .toString() and now it works.

Title: Remove [ ' ' ] from a string in Node.js

Body: I used .toString() and now it works.

ContentLicense: CC BY-SA 4.0


问:
Memory Ordering, Out of other Execution and Multi thread Safety
I have been reading on memory re-ordering lately. My question is with regarding to multi threading scenarios. Consider the example below:

```<code>A = 0;
B = 0;

Thread 1 on Processor 1                       Thread 2 on Processor 2

    A = 100;                                      while(B== 0);
    B = 1;                                       //access A here
</code>```

I have been coding on X86-64 windows platforms and never considered that stores to A and B could be reordered (either  at compiler level or at hardware level) and I may end up with B = 0 in thread 2 and find A to be still 0. And never ran into any issues or pesky bugs with such a code. Is it because x86-x64 are strongly ordered and so are windows C compilers.

For such a code to be executing on any other platform with weakly ordered memory, do I need to make sure I update and access A and B within a lock (assuming the underlying lock implementation uses memory barriers and make sures the lock is released only after all the prior loads and stores are visible across all processor cores).

Thanks

答:
Is it because x86-x64 are strongly ordered and so are windows C compilers.

Indeed, X86 is a strongly ordered CPU that does not allow store reordering. So all CPU cores will observe the order emitted by the compiler.

However, B is modified  on processor 1, while read on processor 2. That is not allowed by the C memory model without synchronization (try maximum compiler optimization, it may stop working).

Although locking can be used to synchronize between cores, it may be problematic since your are spinning on B. If that happens with the lock acquired, processor 1 can not update the value.

A correct solution is to make B atomic. That will guarantee correct ordering on all levels.

Body:
I have been reading on memory re-ordering lately. My question is with regarding to multi threading scenarios. Consider the example below:

A = 0;
B = 0;

Thread 1 on Processor 1                       Thread 2 on Processor 2

    A = 100;                                      while(B== 0);
    B = 1;                                       //access A here

I have been coding on X86-64 windows platforms and never considered that stores to A and B could be reordered (either  at compiler level or at hardware level) and I may end up with B = 0 in thread 2 and find A to be still 0. And never ran into any issues or pesky bugs with such a code. Is it because x86-x64 are strongly ordered and so are windows C compilers.

For such a code to be executing on any other platform with weakly ordered memory, do I need to make sure I update and access A and B within a lock (assuming the underlying lock implementation uses memory barriers and make sures the lock is released only after all the prior loads and stores are visible across all processor cores).

Thanks


问:
Duplicate hash into independent hash (shallow copy)
What is the best way to duplicate a hash in Ruby, and have it independent from the original? For example:

```<code>a = { foo1: "bar1" }
b = a # or b = a.clone / b = a.dup for that matter
b[:foo2] = "bar2"
</code>```

This results in:

```<code>{:foo1=>"bar1", :foo2=>"bar2"} # a
{:foo1=>"bar1", :foo2=>"bar2"} # b
</code>```

Where I would like it to be

```<code>{:foo1=>"bar1"}                # a
{:foo1=>"bar1", :foo2=>"bar2"} # b
</code>```

Now I know about b = Marshal.load(Marshal.dump(a)) but that seems like a little overkill, and I was wondering if there is a better way, because I can't really find it.

Body:
What is the best way to duplicate a hash in Ruby, and have it independent from the original? For example:

a = { foo1: "bar1" }
b = a # or b = a.clone / b = a.dup for that matter
b[:foo2] = "bar2"

This results in:

{:foo1=>"bar1", :foo2=>"bar2"} # a
{:foo1=>"bar1", :foo2=>"bar2"} # b

Where I would like it to be

{:foo1=>"bar1"}                # a
{:foo1=>"bar1", :foo2=>"bar2"} # b

Now I know about b = Marshal.load(Marshal.dump(a)) but that seems like a little overkill, and I was wondering if there is a better way, because I can't really find it.

Body:
You could write

a = { k: 'dog' }
b = {}.merge(a)
  #=> {:k=>"dog"}
b[:cat] = 'meow'

a #=> {:k=>"dog"}
b #=> {:k=>"dog", :cat=>"meow"}

but we wary of

a = { k: [:cow, :pig] }
b = {}.merge(a)
  #=> {:k=>[:cow, :pig]}
b[:k] << 'chicken'
  #=> [:cow, :pig, "chicken"]

a #=> {:k=>[:cow, :pig, "chicken"]}
b #=> {:k=>[:cow, :pig, "chicken"]}

a is not what we want.

One way to ensure you create a deep copy of the hash is to use Marshal#dump and Marshal#load:

a = { :k=>[1, [2, [3, { :m=>[4] }]]] }
b = Marshal.load(Marshal.dump(a))
  #=> {:k=>[1, [2, [3, {:m=>[4]}]]]}

b[:k][-1][-1][-1][:m] << 5

a #=> {:k=>[1, [2, [3, {:m=>[4]}]]]}
b #=> {:k=>[1, [2, [3, {:m=>[4, 5]}]]]}


问:
Rails + Postgres - Decimals stored as strings in database
I have a table - boot_camps. It has a price field, which is a decimal(8,2) in the schema. For some reason the values seem to convert to strings. It makes the validation in the model fail:

```<code>validates :price, numericality: { greater_than: 0 }
</code>```

With this error:
ArgumentError: comparison of String with 0 failed

schema.rb:

```<code>create_table "boot_camps", force: :cascade do |t|
  t.string   "title"
  t.decimal  "price",             precision: 8, scale: 2
  t.integer  "capacity"
  t.date     "start_date"
  t.date     "end_date"
end
</code>```

If I run \d boot_camps in psql I get:

```<code>                         Table "public.boot_camps"
  Column       |            Type             |
Modifiers
-------------------+-----------------------------+---------------------
 id                | integer                     | not null default
 title             | character varying           |
 price             | numeric(8,2)                |
 capacity          | integer                     |
 start_date        | date                        |
 end_date          | date                        |
</code>```

but a BooCamp record, viewed in the rails console, shows:

```<code>#<BootCamp:0x007fc3a8e7abd0> {
               :id => 1,
            :title => "test",
            :price => "30.00",
         :capacity => 11,
       :start_date => nil,
         :end_date => nil,
}
</code>```

and

```<code>BootCamp.last.price.class //=> String < Object
</code>```

Thanks.

答:
So... found out it was just my oversight actually.

I inherited a codebase that I'm trying to salvage and I just found a method on the model that converts price to String. I'll leave this here, in case it happens to anyone else...

Body:
I have a table - boot_camps. It has a price field, which is a decimal(8,2) in the schema. For some reason the values seem to convert to strings. It makes the validation in the model fail:

validates :price, numericality: { greater_than: 0 }

With this error:
ArgumentError: comparison of String with 0 failed

schema.rb:

create_table "boot_camps", force: :cascade do |t|
  t.string   "title"
  t.decimal  "price",             precision: 8, scale: 2
  t.integer  "capacity"
  t.date     "start_date"
  t.date     "end_date"
end

If I run \d boot_camps in psql I get:

                         Table "public.boot_camps"
  Column       |            Type             |
Modifiers
-------------------+-----------------------------+---------------------
 id                | integer                     | not null default
 title             | character varying           |
 price             | numeric(8,2)                |
 capacity          | integer                     |
 start_date        | date                        |
 end_date          | date                        |

but a BooCamp record, viewed in the rails console, shows:

#<BootCamp:0x007fc3a8e7abd0> {
               :id => 1,
            :title => "test",
            :price => "30.00",
         :capacity => 11,
       :start_date => nil,
         :end_date => nil,
}

and

BootCamp.last.price.class //=> String < Object

Thanks.


问:
Displaying an image in a github readme
I'm trying to get a screenshot of my program to display on the main repository page in github. Every article online I've found was saying to simply add the markdown , but it's not working for me.

Here's the repo page: https://github.com/PainterAndHacker/LambdaCrypt

I've tried both

```<code>![Screenshot]\(http://i.imgur.com/ebuHuem.png)
</code>```

and

```<code>![Screenshot](http://i.imgur.com/ebuHuem.png?raw=true)
</code>```

But it's simply not displaying the screenshot on the repo page for me. Any suggestions?

答:
You can add these to GitHub. The trick is to provide the image extension, which you don't get with the default share link Imgur provides.

e.g.

```<code>![Imgur Image](http://i.imgur.com/zTONrOD.jpg)
</code>```

NOT

```<code>![Imgur Image](http://i.imgur.com/zTONrOD)
</code>```

You can get this under the MarkDown links in the copy menu

See embedded example readme.md

Title: Displaying an image in a github readme

Body:
I'm trying to get a screenshot of my program to display on the main repository page in github. Every article online I've found was saying to simply add the markdown , but it's not working for me.

Here's the repo page: https://github.com/PainterAndHacker/LambdaCrypt

I've tried both

![Screenshot]\(http://i.imgur.com/ebuHuem.png)

and

![Screenshot](http://i.imgur.com/ebuHuem.png?raw=true)

But it's simply not displaying the screenshot on the repo page for me. Any suggestions?

Body:
You can add these to GitHub. The trick is to provide the image extension, which you don't get with the default share link Imgur provides.

e.g.

![Imgur Image](http://i.imgur.com/zTONrOD.jpg)

NOT

![Imgur Image](http://i.imgur.com/zTONrOD)

You can get this under the MarkDown links in the copy menu

See embedded example readme.md


问:
Text-hover-blur with CSS3?
Whenever I hover over my box, it's supposed to blur the img, turn down the brightness of the img down 60%, and then some text will appear. Which does work however, whenever I hover over the text, the blur goes away and the text remains in the box until I hover out of it. I was wondering how I can fix this so everything can react simultaneously?

html Code:
`

```<code><section class="container">
  <div class="row">
    <figure class="col-sm-6">
      <img src="edge.jpg">
      <h2>COBAN Technologies</h2>
      <h4>Quality Control Specialist</h4>
</section>
</code>```

`

CSS code:

```<code>    /*work panels*/

section .col-sm-6 img {
  margin: 0 0 30px 0;
  width: 100%;
  height: 100%;
  -webkit-transition: 0.2s;
  transition: 0.2s;
}

section .col-sm-6 img:hover {
  filter: blur(2px) brightness(60%);

}

section .col-sm-6 :not(img) {
  position: absolute;
  top: 30%;
  z-index: 1;
  color: #ffffff;
  width: 100%;
  text-align: center;
  letter-spacing: 0.2rem;
  opacity: 0;
  -webkit-transition: 0.2s;
  transition: 0.2s;
}

section .col-sm-6:hover :not(img) {
  opacity: 1;
}

section .col-sm-6 h4 {
  top: 50%;
}
</code>```

答:
Change your hover line to

```<code>section .col-sm-6:hover img {
  filter: blur(2px) brightness(60%);
}
</code>```

So that you apply the style if you hover the whole element containing both the text and image, instead of when hovering only the .

    /*work panels*/

section .col-sm-6 img {
  margin: 0 0 30px 0;
  width: 100%;
  height: 100%;
  -webkit-transition: 0.2s;
  transition: 0.2s;
}

section .col-sm-6:hover img {
  filter: blur(2px) brightness(60%);
}

section .col-sm-6 :not(img) {
  position: absolute;
  top: 30%;
  z-index: 1;
  color: #ffffff;
  width: 100%;
  text-align: center;
  letter-spacing: 0.2rem;
  opacity: 0;
  -webkit-transition: 0.2s;
  transition: 0.2s;
}

section .col-sm-6:hover :not(img) {
  opacity: 1;
}

section .col-sm-6 h4 {
  top: 50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="container">
  <div class="row">
    <figure class="col-sm-6">
      <img src="https://lastfm-img2.akamaized.net/i/u/avatar300s/a96ecf5e524449ec866a6674709bb212.jpg">
      <h2>COBAN Technologies</h2>
      <h4>Quality Control Specialist</h4>
    </figure>
  </div>
</section></code>```

Title: Text-hover-blur with CSS3?

Body:
Whenever I hover over my box, it's supposed to blur the img, turn down the brightness of the img down 60%, and then some text will appear. Which does work however, whenever I hover over the text, the blur goes away and the text remains in the box until I hover out of it. I was wondering how I can fix this so everything can react simultaneously?

html Code:
`

COBAN Technologies

Quality Control Specialist

`

CSS code:

    /*work panels*/

section .col-sm-6 img {
  margin: 0 0 30px 0;
  width: 100%;
  height: 100%;
  -webkit-transition: 0.2s;
  transition: 0.2s;
}

section .col-sm-6 img:hover {
  filter: blur(2px) brightness(60%);

}

section .col-sm-6 :not(img) {
  position: absolute;
  top: 30%;
  z-index: 1;
  color: #ffffff;
  width: 100%;
  text-align: center;
  letter-spacing: 0.2rem;
  opacity: 0;
  -webkit-transition: 0.2s;
  transition: 0.2s;
}

section .col-sm-6:hover :not(img) {
  opacity: 1;
}

section .col-sm-6 h4 {
  top: 50%;
}

Body:
Change your hover line to

section .col-sm-6:hover img {
  filter: blur(2px) brightness(60%);
}

So that you apply the style if you hover the whole element containing both the text and image, instead of when hovering only the <img>.

    /*work panels*/

section .col-sm-6 img {
  margin: 0 0 30px 0;
  width: 100%;
  height: 100%;
  -webkit-transition: 0.2s;
  transition: 0.2s;
}

section .col-sm-6:hover img {
  filter: blur(2px) brightness(60%);
}

section .col-sm-6 :not(img) {
  position: absolute;
  top: 30%;
  z-index: 1;
  color: #ffffff;
  width: 100%;
  text-align: center;
  letter-spacing: 0.2rem;
  opacity: 0;
  -webkit-transition: 0.2s;
  transition: 0.2s;
}

section .col-sm-6:hover :not(img) {
  opacity: 1;
}

section .col-sm-6 h4 {
  top: 50%;
}

<section class="container">
  <div class="row">
    <figure class="col-sm-6">
      <img src="https://lastfm-img2.akamaized.net/i/u/avatar300s/a96ecf5e524449ec866a6674709bb212.jpg">
      <h2>COBAN Technologies</h2>
      <h4>Quality Control Specialist</h4>
    </figure>
  </div>
</section>