问:
Initialize the values into Mat object in OpenCV
I need to initialize these array values directly into a Mat object. I tried using obj.put(i,j,data) but this does not work and the Mat object is still empty. i need this in java

```<code>data [] = {103547.0, 2.0959531E7, 5.152769223E9, 1.415924406121E12, 2.0842905E7,
           4.195143491E9, 1.025510364741E12, 5.000561607E9, 9.99289545049E11,
           1.332451366923E12}
</code>```

Can explain to me me how to initialize a new Mat object where I directly insert the array data?

答:
Next, you can do:</p>

```<code>cv::Mat newMat(i,j,CV_32F,data);
</code>```

Body:
I need to initialize these array values directly into a Mat object. I tried using obj.put(i,j,data) but this does not work and the Mat object is still empty. i need this in java

data [] = {103547.0, 2.0959531E7, 5.152769223E9, 1.415924406121E12, 2.0842905E7,
           4.195143491E9, 1.025510364741E12, 5.000561607E9, 9.99289545049E11,
           1.332451366923E12}

Can explain to me me how to initialize a new Mat object where I directly insert the array data?

Body:
Next, you can do:

cv::Mat newMat(i,j,CV_32F,data);


来源: stackexchange

问:
How can I control Chromedriver open window size?
I'm using Selenium WebDriver for automation and I'm using Chromedriver.

I have noticed that when my driver runs and opens the chrome browser, it opens the browser with a strange size.
I tried to fixed it but in vain.

Does anybody know how can I change it?

答:
Python

Drivers

```<code>chrome = 57.0.2987.133
chromedriver = 2.27.440174
</code>```

Code:

```<code>from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--window-size=1920,1080")
driver = Chrome(chrome_options=chrome_options)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Python

Drivers

chrome = 57.0.2987.133
chromedriver = 2.27.440174

Code:

from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--window-size=1920,1080")
driver = Chrome(chrome_options=chrome_options)

ContentLicense: CC BY-SA 4.0


问:
covariant type A occurs in contravariant position in type A of value a
I have following class:

```<code>case class Box[+A](value: A) {

  def set(a: A): Box[A] = Box(a)

}
</code>```

And the compiler complain:

```<code>Error:(4, 11) covariant type A occurs in contravariant position in type A of value a
  def set(a: A): Box[A] = Box(a)
</code>```

I was searching a lot about the error, but could not find something useful that
help me to understand the error.

Could someone please explain, why the error occurs?

答:
Try to understand what it means for your Box[+A] to be covariant in A:

It means that a Box[Dog] should also be a Box[Animal], so any instance of Box[Dog] should have all the methods a Box[Animal] has.

In particular, a Box[Dog] should have a method

```<code>set(a: Animal): Box[Animal]
</code>```

However, it only has a method

```<code>set(a: Dog): Box[Dog]
</code>```

Now, you'd think you can infer the first one from the second, but that's not the case: I do you want to box a Cat using only the second signature? That's not doable, and that's what the compiler tells you: a parameter in a method is a contravariant position (you can only put contravariant  (or invariant) type parameters).

Body:
I have following class:

case class Box[+A](value: A) {

  def set(a: A): Box[A] = Box(a)

}

And the compiler complain:

Error:(4, 11) covariant type A occurs in contravariant position in type A of value a
  def set(a: A): Box[A] = Box(a)

I was searching a lot about the error, but could not find something useful that
help me to understand the error.

Could someone please explain, why the error occurs?

Body:
Try to understand what it means for your Box[+A] to be covariant in A:

It means that a Box[Dog] should also be a Box[Animal], so any instance of Box[Dog] should have all the methods a Box[Animal] has.

In particular, a Box[Dog] should have a method

set(a: Animal): Box[Animal]

However, it only has a method

set(a: Dog): Box[Dog]

Now, you'd think you can infer the first one from the second, but that's not the case: I do you want to box a Cat using only the second signature? That's not doable, and that's what the compiler tells you: a parameter in a method is a contravariant position (you can only put contravariant  (or invariant) type parameters).


问:
PL SQL : Create oracle record dynamically
I dont know if it is possible but I would like to do this in PL/SQL

Let's say I have a parameter in my procedure, a number : numberColumns.

Inside the procedure I would like to create a record :

```<code>TYPE arrayColumn IS RECORD (
   column1 VARCHAR2(200),
   column2 VARCHAR2(200)...
   ... as much à numberColumns value
   ....
);
</code>```

ty

答:
Rather than using a record, you could use a collection:

```<code>CREATE OR REPLACE TYPE stringlist IS TABLE OF VARCHAR2(4000);
/
</code>```

Then do:

```<code>CREATE OR REPLACE PROCEDURE your_procedure(
  number_columns IN  INTEGER,
  values         OUT stringlist
)
IS
BEGIN
  values := stringlist();
  IF number_columns < 1 THEN
    RETURN;
  END IF;
  values.EXTEND( number_columns );
  FOR i IN 1 .. number_columns LOOP
    values(i) := DBMS_RANDOM.STRING( 'X', 100 ); -- Assign some value
  END LOOP;
END;
/
</code>```

Otherwise, if you really want a record, then you will have to result to dynamic SQL.

Body:
I dont know if it is possible but I would like to do this in PL/SQL

Let's say I have a parameter in my procedure, a number : numberColumns.

Inside the procedure I would like to create a record :

TYPE arrayColumn IS RECORD (
   column1 VARCHAR2(200),
   column2 VARCHAR2(200)...
   ... as much à numberColumns value
   ....
);

ty

Body:
Rather than using a record, you could use a collection:

CREATE OR REPLACE TYPE stringlist IS TABLE OF VARCHAR2(4000);
/

Then do:

CREATE OR REPLACE PROCEDURE your_procedure(
  number_columns IN  INTEGER,
  values         OUT stringlist
)
IS
BEGIN
  values := stringlist();
  IF number_columns < 1 THEN
    RETURN;
  END IF;
  values.EXTEND( number_columns );
  FOR i IN 1 .. number_columns LOOP
    values(i) := DBMS_RANDOM.STRING( 'X', 100 ); -- Assign some value
  END LOOP;
END;
/

Otherwise, if you really want a record, then you will have to result to dynamic SQL.


问:
Selecting content to feature
in my Rails app users are able to write and publish posts.
On the homepage, I want to feature a couple of posts.

This is what I'm using to select posts at the moment:

posts_controller.rb

```<code>favorite_post_ids = [8,2,5]
@favorite_posts = Post.find(favorite_post_ids)
new_post_ids = [1,2,5]
@new_posts = Post.find(new_post_ids)
</code>```

and then in the view I loop over them to display the posts.

However, once a post is deleted and the controller can no longer find it, I get an error that says

```<code>Couldn't find all Posts with 'id': (1, 2, 5) (found 2 results, but was looking for 3)
</code>```

What's a better way to do this? I was thinking of individual tables, one for new_posts and one for favorite_posts and then do a relationship to posts. In the table I will have post_id referenced.

UPDATE :

I added a bunch of extra columns to posts with different types of featured content all with boolean values defaulted to false. I assign true if I want them featured.

答:
How would you solve this problem?

Make your posts have flag favorite of type boolean. Then you'd select them like this:

```<code>@favorite_posts = Post.where(favorite: true).limit(3)
</code>```

And for new posts, you can use the timestamp

```<code>@new_posts = Post.order(created_at: :desc).limit(3)
</code>```

Look, no hardcoding!

Title: Selecting content to feature

Body:
in my Rails app users are able to write and publish posts.
On the homepage, I want to feature a couple of posts.

This is what I'm using to select posts at the moment:

posts_controller.rb

favorite_post_ids = [8,2,5]
@favorite_posts = Post.find(favorite_post_ids)
new_post_ids = [1,2,5]
@new_posts = Post.find(new_post_ids)

and then in the view I loop over them to display the posts.

However, once a post is deleted and the controller can no longer find it, I get an error that says

Couldn't find all Posts with 'id': (1, 2, 5) (found 2 results, but was looking for 3)

What's a better way to do this? I was thinking of individual tables, one for new_posts and one for favorite_posts and then do a relationship to posts. In the table I will have post_id referenced.

UPDATE :

I added a bunch of extra columns to posts with different types of featured content all with boolean values defaulted to false. I assign true if I want them featured.

Body:
How would you solve this problem?

Make your posts have flag favorite of type boolean. Then you'd select them like this:

@favorite_posts = Post.where(favorite: true).limit(3)

And for new posts, you can use the timestamp

@new_posts = Post.order(created_at: :desc).limit(3)

Look, no hardcoding!


问:
No such column error in SQLITE database
I am getting error as NO SUCH COLUMN in logcat and it is inserting properly
         How can I rectify this problem.Values which are given by me are representing correctly but SELECT query is not working for that values which are located in database table.

```<code>    String search = "select * from "+ TABLE_NAME +" Where PHONENO =" +num+ "
           and NAME = "+name1+" and LASTNAME =" +lastname1;
           Cursor c = db.rawQuery(search,null);
           boolean res = c.moveToFirst();
         if (res) {
        String s1  = c.getString(0);
        String s2 = c.getString(1);
        String s3  = c.getString(2);
        String s4  = c.getString(3);
        String s5  = c.getString(4);
        String s6  = c.getString(5);
        String s7  = c.getString(6);
        String s8  = c.getString(7);
        String s9  = c.getString(8);
        String s10  = c.getString(9);
        String s11  = c.getString(10);
        String s12  = c.getString(11);
        String s13  = c.getString(12);
        String s14  = c.getString(13);
        String s15  = c.getString(14);
        String array[] ={s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11,s12,s13,s14,s15};
        Intent i  = new Intent(this,SelectMember.class);
        i.putExtra("k1",array);
        startActivity(i);
    }
</code>```

Logcat

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.database, PID: 9112
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.database.sqlite.SQLiteException: no such column: durga (code 1): , while compiling: select * from MASTER_ACCOUNTS Where PHONENO =8121680624 and NAME = durga and LASTNAME =veerepalli                      at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1255)
at com.example.user.database.Editoption.search(Editoption.java:36)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Application terminated.
</code>```

答:
String literals should be put in single quotes (')

```<code>Where PHONENO ='" +num+ "' and NAME = '"+name1+"' and LASTNAME ='" +lastname1 +"'";
</code>```

By the way, this will blow up when the value contains a quote. Escape the string, or better use parameters.

Title: No such column error in SQLITE database

Body:
I am getting error as NO SUCH COLUMN in logcat and it is inserting properly
         How can I rectify this problem.Values which are given by me are representing correctly but SELECT query is not working for that values which are located in database table.

    String search = "select * from "+ TABLE_NAME +" Where PHONENO =" +num+ "
           and NAME = "+name1+" and LASTNAME =" +lastname1;
           Cursor c = db.rawQuery(search,null);
           boolean res = c.moveToFirst();
         if (res) {
        String s1  = c.getString(0);
        String s2 = c.getString(1);
        String s3  = c.getString(2);
        String s4  = c.getString(3);
        String s5  = c.getString(4);
        String s6  = c.getString(5);
        String s7  = c.getString(6);
        String s8  = c.getString(7);
        String s9  = c.getString(8);
        String s10  = c.getString(9);
        String s11  = c.getString(10);
        String s12  = c.getString(11);
        String s13  = c.getString(12);
        String s14  = c.getString(13);
        String s15  = c.getString(14);
        String array[] ={s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11,s12,s13,s14,s15};
        Intent i  = new Intent(this,SelectMember.class);
        i.putExtra("k1",array);
        startActivity(i);
    }

Logcat

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.database, PID: 9112
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.database.sqlite.SQLiteException: no such column: durga (code 1): , while compiling: select * from MASTER_ACCOUNTS Where PHONENO =8121680624 and NAME = durga and LASTNAME =veerepalli                      at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1255)
at com.example.user.database.Editoption.search(Editoption.java:36)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Application terminated.

Body:
String literals should be put in single quotes (')

Where PHONENO ='" +num+ "' and NAME = '"+name1+"' and LASTNAME ='" +lastname1 +"'";

By the way, this will blow up when the value contains a quote. Escape the string, or better use parameters.


问:
Install R Packages in Azure ML
Its my 1st time using Azure ML and I am having a rough time. I need to install multiple R packages that are not provided by default in Azure ML. To make it simple, lets assume that I only need to install the forecast package.

Based on what is written here, I also need to plan the installation of the dependencies of the forecast package. However, based on the documentation, the forecast package has almost a dozen dependencies. Furthermore, these dependencies probably have dependencies that are not installed by default in Azure ML. In addition, it does not seem quite right to upload a zip file in Azure ML and to try to make all the dependencies work out.

Is there any other way to install the forecast package that is easier and simpler than what I found online? What do companies do? Uploading a zip file does not seem viable!

答:
Unfortunately yes. You can do 2 things.

First figure out which of the dependencies are already installed in azureml.
See this blogpost

Use Execute R script task in AML studio and copy paste the below script:

```<code>out <- data.frame(installed.packages(,,,fields=”Description”))
maml.mapOutputPort(“out”)
</code>```

Collect all depended packages (imports and linkingto) and add these to the zip file (in the correct order) and follow the information in the blogpost you linked to.

I use option 1, since that limits the amount of packages needed. But be aware of version differences on azureML and cran.

Title: Install R Packages in Azure ML

Body:
Unfortunately yes. You can do 2 things.

First figure out which of the dependencies are already installed in azureml.
See this blogpost

Use Execute R script task in AML studio and copy paste the below script:

out <- data.frame(installed.packages(,,,fields=”Description”))
maml.mapOutputPort(“out”)

Collect all depended packages (imports and linkingto) and add these to the zip file (in the correct order) and follow the information in the blogpost you linked to.

I use option 1, since that limits the amount of packages needed. But be aware of version differences on azureML and cran.


问:
How to play video from youku using javascript?
How to play video from youku using javascript ?

I tried to do like this but not work, how can i do that ?

```<code><iframe id="test" src="https://player.youku.com/embed/XMjUzMzY2ODQ4OA==" frameborder="0" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen="" style="position: absolute; top: 0; left: 0; width: 50%; height: 50%;"></iframe>

<div style=" position: fixed; top: 56%; " onclick="play_fn()">Play</div>

<script>
function play_fn(){
    var test = document.getElementById('test');
    test.play();
}
</script>
</code>```

答:
play() is a method found on <video> and <audio> elements. An  is just a means to embed a URL in a page. It provides no API for playing media.

Unless youku provide an API that you can access (I couldn't find one with a quick search), then there is no way to trigger playback from your page.

Standard cross origin security restrictions imposed by browsers prevent you manipulating the embedded page with JavaScript.

Body:
How to play video from youku using javascript ?

I tried to do like this but not work, how can i do that ?

Play

Body:
play() is a method found on <video> and <audio> elements. An <iframe> is just a means to embed a URL in a page. It provides no API for playing media.

Unless youku provide an API that you can access (I couldn't find one with a quick search), then there is no way to trigger playback from your page.

Standard cross origin security restrictions imposed by browsers prevent you manipulating the embedded page with JavaScript.


答:
Caused by: android.database.sqlite.SQLiteException: no such column:
durga (code 1): , while compiling: select * from MASTER_ACCOUNTS Where
PHONENO =8121680624 and NAME = durga and LASTNAME =veerepalli

Rectify Your Query first.

Informed you NO such table.

```<code>"SELECT * FROM "+ TABLE_NAME +" WHERE PHONENO ='" +num+ "' AND NAME = '"+ name1 +"' AND LASTNAME ='" + lastname1 +"'";
</code>```

Then Uninstall old App and Clean-Rebuild-Run .

Title: No such column error in SQLITE database

Body:
Caused by: android.database.sqlite.SQLiteException: no such column:
durga (code 1): , while compiling: select * from MASTER_ACCOUNTS Where
PHONENO =8121680624 and NAME = durga and LASTNAME =veerepalli

Rectify Your Query first.

Informed you NO such table.

"SELECT * FROM "+ TABLE_NAME +" WHERE PHONENO ='" +num+ "' AND NAME = '"+ name1 +"' AND LASTNAME ='" + lastname1 +"'";

Then Uninstall old App and Clean-Rebuild-Run .


答:
Your question is not entirely clear to me, but I'm going to assume you are trying to load a float array into a OpenCV Mat object in a single row. First of all, be sure to check the documentation on constructing a Mat in C++. Since you have a 1D array and (I assume) you know the rows and columns you want to give your Mat, you should use this constructor:

```<code>cv::Mat::Mat (int rows, int cols, int type, void * data, size_t step = AUTO_STEP)
</code>```

Here's a code example:

```<code>float data[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
cv::Mat your_matrix = cv::Mat(1, 10, CV_32F, data);

cout << your_matrix.at<float>(0,2) << endl;
cout << your_matrix << endl;
</code>```

It will output:

```<code>3
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
</code>```

Of course you can change the datatype according to your needs (e.g. use int instead of float). You can ignore the AUTO_STEP parameter, but be sure to check the documentation on the usage if you want to use it. Also, if you want to change the structure of your Mat (e.g. split the array into multiple rows) you can achieve this by changing the rows and cols arguments in the constructor:

```<code>float data[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
cv::Mat your_matrix = cv::Mat(2, 5, CV_32F, data);

cout << your_matrix.at<float>(1,2) << endl;
cout << your_matrix << endl;
</code>```

It will output:

```<code>8
[1, 2, 3, 4, 5;
6, 7, 8, 9, 10]
</code>```

You have now split your Mat object into two rows of 5 columns, instead of 1 row of 10 columns.

In case of Java:
If you want to do this in Java, you were already on the right track. However, you probably forgot to specify the rows, columns and channels/depth. Change the rows, cols and CvType according to whatever suits your data as before. You can do the following:

```<code>float data[] = new float[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Mat mat = new Mat(1, 10, CvType.CV_32F);
mat.put(0, 0, data);
</code>```

Be sure to check the Java documentation on Mat as well!

Title: Initialize the values into Mat object in OpenCV

Body:
Your question is not entirely clear to me, but I'm going to assume you are trying to load a float array into a OpenCV Mat object in a single row. First of all, be sure to check the documentation on constructing a Mat in C++. Since you have a 1D array and (I assume) you know the rows and columns you want to give your Mat, you should use this constructor:

cv::Mat::Mat (int rows, int cols, int type, void * data, size_t step = AUTO_STEP)

Here's a code example:

float data[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
cv::Mat your_matrix = cv::Mat(1, 10, CV_32F, data);

cout << your_matrix.at<float>(0,2) << endl;
cout << your_matrix << endl;

It will output:

3
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Of course you can change the datatype according to your needs (e.g. use int instead of float). You can ignore the AUTO_STEP parameter, but be sure to check the documentation on the usage if you want to use it. Also, if you want to change the structure of your Mat (e.g. split the array into multiple rows) you can achieve this by changing the rows and cols arguments in the constructor:

float data[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
cv::Mat your_matrix = cv::Mat(2, 5, CV_32F, data);

cout << your_matrix.at<float>(1,2) << endl;
cout << your_matrix << endl;

It will output:

8
[1, 2, 3, 4, 5;
6, 7, 8, 9, 10]

You have now split your Mat object into two rows of 5 columns, instead of 1 row of 10 columns.

In case of Java:
If you want to do this in Java, you were already on the right track. However, you probably forgot to specify the rows, columns and channels/depth. Change the rows, cols and CvType according to whatever suits your data as before. You can do the following:

float data[] = new float[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Mat mat = new Mat(1, 10, CvType.CV_32F);
mat.put(0, 0, data);

Be sure to check the Java documentation on Mat as well!


问:
Android Studio throwing warnings on everything
The first project I created since I updated Android Studio to 2.3, I get that everything on MainActivity is marked with a warning. At first I thought it was because I was creating the project inside another folder within AndroidStudioProjects, so I corrected that but still no dice.

Here's a picture of MainActivity:

I get errors like package-info.java file missing or Single class import blablabla, or package name too long (even though I once tried with a very short one) and more.

I updated Android SDK tools but nothing changed. One thing to notice is that previously created projects do work as normal, and even now I keep working on them. Any help would be appreciated

答: Clean and rebuild your project that may remove your warning problem.</p>


问:
How do I use an attribute directive inside an element directive template in angularjs?
I have a need to show a list of check boxes on my site listing products and other items.  The checklist-model attribute directive works well for this because I can bind it to a list of items that relates to the items selected.

All this works fine when I simply use this code in my angular controller.  However, I have several list boxes that need to be displayed the same way with the same "select all" and "select none" buttons for each list.  I don't want to repeat this code and layout so I've created my own directive for the entire list.

The problem is when I use my own directive it doesn't bind correctly back to my data, the select all only works once, and the select none doesn't work at all.

I suspect it has something to do with how I'm passing the scope around, and the two directives are not working well together.

Why does this not work inside a directive?

Here is a jsfiddle: https://jsfiddle.net/fande455/m9qhnr9c/7/

HTML

```<code><section ng-app="myApp"   ng-controller="couponEditController">
<script type="text/ng-template" id="checkboxlist.template.html">
  <div>
    <div class="form-input form-list">
      <label ng-repeat="item in valuelist | orderBy:value">
        <input type="checkbox" checklist-model="model" checklist-value="item" /> {{item[value]}}
        <br />
      </label>
    </div>
    <button class="btn btn-default" style="float:left; margin-bottom: 5px;margin-left: 10px;margin-right:10px" ng-click="selectNone()">Select None</button>
    <button class="btn btn-default" style="float:left; margin-bottom: 5px;" ng-click="selectAll()">Select All</button>

    <div class="cleared"></div>
  </div>
</script>

<div>
  <checkboxlist model="coupon.Products" value="Name" valuelist="productsList"></checkboxlist>
</div>
</section>
</code>```

JS

```<code>var myApp = angular.module('myApp', ['checklist-model']);

myApp.directive('checkboxlist', [function() {
  return {
    restrict: 'E',
    templateUrl: 'checkboxlist.template.html',
    controller: 'checkboxlistController',
    scope: {
      model: "=",
      value: "@",
      valuelist: "="
    },
    require: '^checklist-model'
  }
}]);

myApp.controller('checkboxlistController', ['$scope', function($scope) {

  $scope.selectAll = function() {
    $scope.model = angular.copy($scope.valuelist);
  };

  $scope.selectNone = function() {
    $scope.model = [];
  };
}]);

myApp.controller('couponEditController', ['$scope', function($scope) {

  $scope.coupon =
    {"Id": 1,
    "Name": "My Coupon",
    "Products": []
    }
  ;

  $scope.productsList = [{
    "Id": 1,
    "Name": "Product 1"
  }, {
    "Id": 2,
    "Name": "Product 2"
  }];
}]);
</code>```

答:
From documentation:

Instead of doing checklistModelList = [] it is better to do
  checklistModelList.splice(0, checklistModelList.length)

In your code you should do

```<code>$scope.selectAll = function() {
    $scope.selectNone();
    $scope.model.push.apply($scope.model, $scope.valuelist);
};

$scope.selectNone = function() {
    $scope.model.length = 0;
};
</code>```

Here's the updated fiddle: https://jsfiddle.net/m9qhnr9c/9/

The idea is not to replace the array with a new one, but modify only its elements.

Body:
I have a need to show a list of check boxes on my site listing products and other items.  The checklist-model attribute directive works well for this because I can bind it to a list of items that relates to the items selected.

All this works fine when I simply use this code in my angular controller.  However, I have several list boxes that need to be displayed the same way with the same "select all" and "select none" buttons for each list.  I don't want to repeat this code and layout so I've created my own directive for the entire list.

The problem is when I use my own directive it doesn't bind correctly back to my data, the select all only works once, and the select none doesn't work at all.

I suspect it has something to do with how I'm passing the scope around, and the two directives are not working well together.

Why does this not work inside a directive?

Here is a jsfiddle: https://jsfiddle.net/fande455/m9qhnr9c/7/

HTML

  <checkboxlist model="coupon.Products" value="Name" valuelist="productsList"></checkboxlist>

JS

var myApp = angular.module('myApp', ['checklist-model']);

myApp.directive('checkboxlist', [function() {
  return {
    restrict: 'E',
    templateUrl: 'checkboxlist.template.html',
    controller: 'checkboxlistController',
    scope: {
      model: "=",
      value: "@",
      valuelist: "="
    },
    require: '^checklist-model'
  }
}]);

myApp.controller('checkboxlistController', ['$scope', function($scope) {

  $scope.selectAll = function() {
    $scope.model = angular.copy($scope.valuelist);
  };

  $scope.selectNone = function() {
    $scope.model = [];
  };
}]);

myApp.controller('couponEditController', ['$scope', function($scope) {

  $scope.coupon =
    {"Id": 1,
    "Name": "My Coupon",
    "Products": []
    }
  ;

  $scope.productsList = [{
    "Id": 1,
    "Name": "Product 1"
  }, {
    "Id": 2,
    "Name": "Product 2"
  }];
}]);

Body:
From documentation:

Instead of doing checklistModelList = [] it is better to do
  checklistModelList.splice(0, checklistModelList.length)

In your code you should do

$scope.selectAll = function() {
    $scope.selectNone();
    $scope.model.push.apply($scope.model, $scope.valuelist);
};

$scope.selectNone = function() {
    $scope.model.length = 0;
};

Here's the updated fiddle: https://jsfiddle.net/m9qhnr9c/9/

The idea is not to replace the array with a new one, but modify only its elements.


问:
SSRS report accessable to clients
I'm new in SSRS, my question is how do i make my reports accessible to client?
and can i change the url from:"http://serverName/ReportServer/Pages/ReportViewer.aspx?%2fReports%" to
"http://company.co.za/ReportServer/Pages/ReportViewer.aspx?%2fReports%"
? do i need to authenticate users in Site Settings?</p>

答:
The Report Manager portal is not especially designed to make reports accessible to the outside world. You can do it, but it needs careful planning and consideration. Here's your starting point:

Planning For Extranet or Internet Deployment

Note that the link suggests you create a custom web application and embed the Report Viewer control: this will allow you to present the user interface of your choice to the users and help you deal with security. However the Report Manager portal you ask about is also an option.

Title: SSRS report accessable to clients


问:
MYSQL where x in all
I am running a query like this

```<code>SELECT .......  WHERE column_name IN (1,2,3)
</code>```

How can I use the same query and say

```<code>SELECT ........WHERE column_name IN (*)
</code>```

and select all rows?

Edit: The reason I need to do this is because of a bad database design and bad coding in general, for now I need to hack it. If I don't pass the query 1,2,3 .. I need to pass it something so it will return me all records. Is there a way to do it without changing the query? If you don't think this is possible then you should say that it is not possible in your answer.

答:
If you absolutely must have the WHERE clause, you could say:

```<code>WHERE 1
</code>```

Or if you need to do the column_name IN bit, you could do something like:

```<code>SELECT .......  WHERE column_name IN (1,2,3) OR 1
</code>```

ContentLicense: CC BY-SA 2.5

Title: MYSQL where x in all

Body:
I am running a query like this

SELECT .......  WHERE column_name IN (1,2,3)

How can I use the same query and say

SELECT ........WHERE column_name IN (*)

and select all rows?

Edit: The reason I need to do this is because of a bad database design and bad coding in general, for now I need to hack it. If I don't pass the query 1,2,3 .. I need to pass it something so it will return me all records. Is there a way to do it without changing the query? If you don't think this is possible then you should say that it is not possible in your answer.

Body:
If you absolutely must have the WHERE clause, you could say:

WHERE 1

Or if you need to do the column_name IN bit, you could do something like:

SELECT .......  WHERE column_name IN (1,2,3) OR 1


问:
SSIS process greyed out
Unfortunately my SSIS process is greyed out like shown below (the tasks are not disabled!). The executed process stops immediately with "Validation is completed". Is there any way to reactivate the process? All connections/containers/tasks are working fine if executed manually.

Greyed out process:

All tasks are enabled:

答: Created a new package and copy-pasted all tasks and connections from the old package into the new one.</p>

Title: SSIS process greyed out


问:
Jenkins - failed: No test report files were found. Configuration error?
I'm beginner for "Jenkins" and following this tutorial.

At the Sixth step I got below error.

xcodebuild: error: Scheme JenkinsTest is not currently configured for the test action.

Build step 'Xcode' marked build as failure
  Recording test results
  ERROR: Step ‘Publish JUnit test result report’ failed: No test report files were found. Configuration error?
  Finished: FAILURE

In the Test report XMLs I did set "test-reports/.*xml"

I tried to find my solution and also many questions are founded on SO like same issue I have too but did not get solution.

I have some confusion, Is .xml file automatically generated by "Jenkins" or First we manually need to add .xml file ?

In short guide me on right direction based on above error.

答:
First make sure junit.xml is getting generated after the test run.

Jenkins job at times cannot see past the current workspace. so it is always a good idea to copy the reports back to the current workspace before using it.

```<code>    cd <path to report>
    cp *.xml $WORKSPACE
</code>```

Now the jenkins should pick-up the report.
Note: The config may show error first(since it cannot find the xml file in workspace) but after a build this should go away and also the result should get recorded

Body:
First make sure junit.xml is getting generated after the test run.

Jenkins job at times cannot see past the current workspace. so it is always a good idea to copy the reports back to the current workspace before using it.

    cd <path to report>
    cp *.xml $WORKSPACE

Now the jenkins should pick-up the report.
Note: The config may show error first(since it cannot find the xml file in workspace) but after a build this should go away and also the result should get recorded


问:
VueJs2 using stores with components
I am using vuejs 2.0 with vue-router and webpack.

I need to list items in a component using the session-store.js which is inside src/stores folder, but I am not able to read data from the store in App.vue and inside my components.

session-store.js

```<code>import $ from 'jquery'

var SessionStore = {
  state: {
    data: []
  },
  fetchSessionScheduleData: function () {
    $.ajax({
      url: 'https://www.myapi.com/items',
      success: function (response) {
        if (response.data) {
          SessionStore.state.data = response.data
        }
      }
    })
  }
}
</code>```

App.vue

```<code><script>
import SessionStore from './stores/session-store.js'

export default {
  name: 'app',
  components: {
    Test
  },
  data () {
    return {
      SessionStore: SessionStore.state
    }
  },
  created: function () {
    this.fetchData()
  },
  methods: {
    fetchData: function () {
      SessionStore.fetchSessionScheduleData()
    }
  }
}
</script>
</code>```

main.js

```<code>import './assets/css/materialize.css'
import './assets/css/oclock-styles.css'
import './assets/css/styles.css'

import Vue from 'vue'
import App from './App'
import VueRouter from 'vue-router'

import Hello from './components/Hello.vue'
import Schedule from './components/Schedule.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/', component: Schedule },
  { path: '/foo', component: Hello },
  { path: '/schedule', component: Schedule }
]

const router = new VueRouter({
  routes // short for routes: routes
})

/* eslint-disable no-new */
new Vue({
  router,
  el: '#app',
  template: '<App/>',
  components: { App }
})
</code>```

Schedule.Vue

```<code><template>
  <div v-once>
        <h4>{{ formatDate(index) }}</h4>
        <ul class="collapsible" data-collapsible="expandable">
          <session-schedule v-for="log in item" v-bind:item="log"></session-schedule>
        </ul>
      </div>
</template>

<script>
export default {

  name: 'Schedule',
  data () {
    return 'Hello'
  },
  methods: {
    formatDate (date) {
      var moment = require('moment')
      var now = moment(new Date())
      var sessionDate = moment(date, 'DD-MM-YYYY', true).format()
      var diff = now.diff(sessionDate, 'd')
      if (diff === 0) {
        return 'Today'
      } else if (diff === 1) {
        return 'Yesterday'
      } else {
        return date
      }
    }
  }
}
</script>
</code>```

How should I modify it in order to be able to fetch the data?
and how to call the session-schedule component from the schedule component?

答:
I think that you should use vue-resource. (Two reasons: no jQuery, designed for vue).
In my application, I also use vuex which you don't need I guess however the vue-resource would look like this.

in bootstrap.js required by app.js (alternative for main.js) I have:

```<code>window.Vue = require('vue')
require('vue-resource')
</code>```

point: require of vue-resource adds http into Vue (js is so random)

```<code>Vue.http.options.root = '//localhost:8000/api/v1'
</code>```

Then in api/devices.js there is:

```<code>export function getDevices() {
  Vue.http.get('devices').then(response => {
    console.log(response)
  }, response => {
    console.log(response.status)
  })
}
</code>```

*Keep an eye on the url slashes because vue-resource will use the root only when you don't write slash before the relative one and also not after root.

Finally in app.js (main.js) there will be something like that:

```<code>require('./bootstrap')

import http from 'vue'
import * as api from 'api/devices'

Vue.config.devtools = true
Vue.config.silent = false

new Vue({
  api,
  http,
  el: '#app',
  created() {
    console.log(this.api.getDevices())
  }
})
</code>```

In child components you would access api as this.$api

Maybe I wrote something wrong. This is just an example of how it works. I am not a vue pro ...yet :D Good luck. Btw, if you decide for vue-resource, check their examples coz I've shown you only the console.logs

Title: VueJs2 using stores with components

Body:
I am using vuejs 2.0 with vue-router and webpack.

I need to list items in a component using the session-store.js which is inside src/stores folder, but I am not able to read data from the store in App.vue and inside my components.

session-store.js

import $ from 'jquery'

var SessionStore = {
  state: {
    data: []
  },
  fetchSessionScheduleData: function () {
    $.ajax({
      url: 'https://www.myapi.com/items',
      success: function (response) {
        if (response.data) {
          SessionStore.state.data = response.data
        }
      }
    })
  }
}

App.vue

main.js

import './assets/css/materialize.css'
import './assets/css/oclock-styles.css'
import './assets/css/styles.css'

import Vue from 'vue'
import App from './App'
import VueRouter from 'vue-router'

import Hello from './components/Hello.vue'
import Schedule from './components/Schedule.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/', component: Schedule },
  { path: '/foo', component: Hello },
  { path: '/schedule', component: Schedule }
]

const router = new VueRouter({
  routes // short for routes: routes
})

/* eslint-disable no-new */
new Vue({
  router,
  el: '#app',
  template: '<App/>',
  components: { App }
})

Schedule.Vue

<template>

{{ formatDate(index) }}

          <session-schedule v-for="log in item" v-bind:item="log"></session-schedule>

</template>

How should I modify it in order to be able to fetch the data?
and how to call the session-schedule component from the schedule component?

Body:
I think that you should use vue-resource. (Two reasons: no jQuery, designed for vue).
In my application, I also use vuex which you don't need I guess however the vue-resource would look like this.

in bootstrap.js required by app.js (alternative for main.js) I have:

window.Vue = require('vue')
require('vue-resource')

point: require of vue-resource adds http into Vue (js is so random)

Vue.http.options.root = '//localhost:8000/api/v1'

Then in api/devices.js there is:

export function getDevices() {
  Vue.http.get('devices').then(response => {
    console.log(response)
  }, response => {
    console.log(response.status)
  })
}

*Keep an eye on the url slashes because vue-resource will use the root only when you don't write slash before the relative one and also not after root.

Finally in app.js (main.js) there will be something like that:

require('./bootstrap')

import http from 'vue'
import * as api from 'api/devices'

Vue.config.devtools = true
Vue.config.silent = false

new Vue({
  api,
  http,
  el: '#app',
  created() {
    console.log(this.api.getDevices())
  }
})

In child components you would access api as this.$api

Maybe I wrote something wrong. This is just an example of how it works. I am not a vue pro ...yet :D Good luck. Btw, if you decide for vue-resource, check their examples coz I've shown you only the console.logs


问:
Does Informatica Powercenter provide API to access session logs
Question - Does Informatica PowerCenter provide API to access session logs - I believe No but wanted to through in forum to be sure?

Objective -Actually I want to extract session logs and process them through Logstash and perform reactive analytics periodically.

Alternate - The same could be solved using Logstash input plugin for Informatica - but I did not find that either.

Usage - This will be used to determine common causes, analyze usage of cache at session level, throughput, and any performance bottlenecks.

答: You can call Informatica Webservice's getSessionLog. Here's a sample blog post with details: http://www.kpipartners.com/blog/bid/157919/Accessing-Informatica-Web-Services-from-3rd-Party-Apps


问:
C++ Aborted (Core Dumped) when returning a vector from a function
I'm trying to return a vector from a function. My code compiles and I've checked my function and reckon that the error comes from the return part. It compiles fine (using Cygwin) but when running it, I get an Aborted (core dumped) error.
Here is my code:

```<code>#include <iostream>
#include <vector>
#include <string>
using namespace std;

//function that returns the square
int f(int n)
{
    return n*n;
}
vector<int> myVec;
int counter = 0;
//function that uses f on all elements in a list
vector<int> map(vector<int> something)
{
    //base case
    if(counter == something.size())
    {
        /*cout << "hello" << endl;
        for (int i=0; i<counter; i++)
        {
            cout << "vector: " << myVec[i] << endl;
        }*/
        counter=0;
        return myVec;
    }
    //recursion
    else
    {
        //cout << "counter: " << counter << endl;
        int n = f(something[counter]);
        //cout << "n: " << n << endl;
        myVec.push_back(n);
        //cout << "vector: " << myVec[counter] << endl;
        counter++;
        map(something);
    }
}

int main()
{
    //making vectors
    vector<int> L;
    vector<int> L1;
    vector<int> L2;
    for (int i=0; i<20; i++)
    {
        L.push_back(i);
    }
    L1 = map(L);
}
</code>```

The code was originally from a class file.

答:
In your recursion, you do not return anything. The function is expected to return a Vector.

In your case, what happens if the function enters the "else" case on its first call? It reenters map() until the condition is met, then returns a vector. That vector is passed to the previous recursive call and immediately deleted, as it is not passed any further.

The solution here would be to change the last line of the else-case to

```<code>return map(something);
</code>```

so the value is not lost and correctly passed through to the original caller (your main function).

Body:
I'm trying to return a vector from a function. My code compiles and I've checked my function and reckon that the error comes from the return part. It compiles fine (using Cygwin) but when running it, I get an Aborted (core dumped) error.
Here is my code:

#include <iostream>
#include <vector>
#include <string>
using namespace std;

//function that returns the square
int f(int n)
{
    return n*n;
}
vector<int> myVec;
int counter = 0;
//function that uses f on all elements in a list
vector<int> map(vector<int> something)
{
    //base case
    if(counter == something.size())
    {
        /*cout << "hello" << endl;
        for (int i=0; i<counter; i++)
        {
            cout << "vector: " << myVec[i] << endl;
        }*/
        counter=0;
        return myVec;
    }
    //recursion
    else
    {
        //cout << "counter: " << counter << endl;
        int n = f(something[counter]);
        //cout << "n: " << n << endl;
        myVec.push_back(n);
        //cout << "vector: " << myVec[counter] << endl;
        counter++;
        map(something);
    }
}

int main()
{
    //making vectors
    vector<int> L;
    vector<int> L1;
    vector<int> L2;
    for (int i=0; i<20; i++)
    {
        L.push_back(i);
    }
    L1 = map(L);
}

The code was originally from a class file.

Body:
In your recursion, you do not return anything. The function is expected to return a Vector.

In your case, what happens if the function enters the "else" case on its first call? It reenters map() until the condition is met, then returns a vector. That vector is passed to the previous recursive call and immediately deleted, as it is not passed any further.

The solution here would be to change the last line of the else-case to

return map(something);

so the value is not lost and correctly passed through to the original caller (your main function).


问:
Activate/Desactivate usb device from distant computer
I would like to turn on/off an USB device (light) from a distant computer, is it possible ?

More details

This is for a digital display at work, we would like to power a light everytime the display is changing. We are using web browser to make our display but I don't think there is a way to activate/desactivate USB through browser.
I'm thinking about using PHP and event-trigger on C to make this work, what do you think ?

Thank you !

答:
Since most browsers removed plugin support (at least native plug-ins), the common way to solve this problem now is to have a separate driver that provides an http service to javascript.

This sounds like a situation where you have control over the client machine. So, yes, you need a native app of some sort to control the USB device. You can write this in a language that works to control the device and can listen for http connections on a local port. Java may be a good choice. or C#. With the right libraries it can be done in just about any language.

You then can use Ajax to communicate with the native program from javascript.


问:
Compare 2 strings in Java upto a delimiter
String 1:

```<code>func1(test1)
</code>```

String 2:

```<code>func1(test2)
</code>```

I want to compare these 2 strings upto the first open braces '('.

So for the given example it should return true since the string upto '(' in both the strings is 'func1'.

Is there any way to do that without splitting?

答:
Alternatively you can compare the strings directly by replacing everything after '(' by empty string.</p>

```<code>    String str1 = "func1(test1)";
    String str2 = "func1(test2)";
    System.out.println(str1.replaceAll("\\(.*", "").equals(str2.replaceAll("\\(.*", "")));
</code>```

Body:
String 1:

func1(test1)

String 2:

func1(test2)

I want to compare these 2 strings upto the first open braces '('.

So for the given example it should return true since the string upto '(' in both the strings is 'func1'.

Is there any way to do that without splitting?

Body:
Alternatively you can compare the strings directly by replacing everything after '(' by empty string.

    String str1 = "func1(test1)";
    String str2 = "func1(test2)";
    System.out.println(str1.replaceAll("\\(.*", "").equals(str2.replaceAll("\\(.*", "")));


问:
Outlook save only pdf attachments
Hi I have found this code and been using it for a while now but I am looking to add a rule to only save the PDF attachments and count how many PDF files have been saved.

I have got it saving all files and it loops the duplicated files but I just want it to save pdf files.

can someone assist please?

thanks

```<code>' ######################################################
'  Returns the number of attachements in the selection.
' ######################################################
Public Function SaveAttachmentsFromSelection() As Long
    Dim objFSO              As Object       ' Computer's file system object.
    Dim objShell            As Object       ' Windows Shell application object.
    Dim objFolder           As Object       ' The selected folder object from Browse for Folder dialog box.
    Dim objItem             As Object       ' A specific member of a Collection object either by position or by key.
    Dim selItems            As Selection    ' A collection of Outlook item objects in a folder.
    Dim Atmt                As Attachment   ' A document or link to a document contained in an Outlook item.
    Dim strAtmtPath         As String       ' The full saving path of the attachment.
    Dim strAtmtFullName     As String       ' The full name of an attachment.
    Dim strAtmtName(1)      As String       ' strAtmtName(0): to save the name; strAtmtName(1): to save the file extension. They are separated by dot of an attachment file name.
    Dim strAtmtNameTemp     As String       ' To save a temporary attachment file name.
    Dim intDotPosition      As Integer      ' The dot position in an attachment name.
    Dim atmts               As Attachments  ' A set of Attachment objects that represent the attachments in an Outlook item.
    Dim lCountEachItem      As Long         ' The number of attachments in each Outlook item.
    Dim lCountAllItems      As Long         ' The number of attachments in all Outlook items.
    Dim strFolderpath       As String       ' The selected folder path.
    Dim blnIsEnd            As Boolean      ' End all code execution.
    Dim blnIsSave           As Boolean      ' Consider if it is need to save.
    Dim oItem               As Object
    Dim iAttachments        As Integer

    blnIsEnd = False
    blnIsSave = False
    lCountAllItems = 0

    On Error Resume Next

    Set selItems = ActiveExplorer.Selection

    If Err.Number = 0 Then

        ' Get the handle of Outlook window.
        lHwnd = FindWindow(olAppCLSN, vbNullString)

        If lHwnd <> 0 Then

            ' /* Create a Shell application object to pop-up BrowseForFolder dialog box. */
            Set objShell = CreateObject("Shell.Application")
            Set objFSO = CreateObject("Scripting.FileSystemObject")
            Set objFolder = objShell.BrowseForFolder(lHwnd, "Select folder to save attachments:", _
                                                     BIF_RETURNONLYFSDIRS + BIF_DONTGOBELOWDOMAIN, CSIDL_DESKTOP)

            ' /* Failed to create the Shell application. */
            If Err.Number <> 0 Then
                MsgBox "Run-time error '" & CStr(Err.Number) & " (0x" & CStr(Hex(Err.Number)) & ")':" & vbNewLine & _
                       Err.Description & ".", vbCritical, "Error from Attachment Saver"
                blnIsEnd = True
                GoTo PROC_EXIT
            End If

            If objFolder Is Nothing Then
                strFolderpath = ""
                blnIsEnd = True
                GoTo PROC_EXIT
            Else
                strFolderpath = CGPath(objFolder.Self.Path)

                ' /* Go through each item in the selection. */
                For Each objItem In selItems
                    lCountEachItem = objItem.Attachments.Count

                    ' /* If the current item contains attachments. */
                    If lCountEachItem > 0 Then
                        Set atmts = objItem.Attachments

                        ' /* Go through each attachment in the current item. */
                        For Each Atmt In atmts

                            ' Get the full name of the current attachment.
                            strAtmtFullName = Atmt.FileName

                            ' Find the dot postion in atmtFullName.
                            intDotPosition = InStrRev(strAtmtFullName, ".")

                            ' Get the name.
                            strAtmtName(0) = Left$(strAtmtFullName, intDotPosition - 1)
                            ' Get the file extension.
                            strAtmtName(1) = Right$(strAtmtFullName, Len(strAtmtFullName) - intDotPosition)
                            ' Get the full saving path of the current attachment.
                            strAtmtPath = strFolderpath & Atmt.FileName

                            ' /* If the length of the saving path is not larger than 260 characters.*/
                            If Len(strAtmtPath) <= MAX_PATH Then
                                ' True: This attachment can be saved.
                                blnIsSave = True

                                ' /* Loop until getting the file name which does not exist in the folder. */
                                Do While objFSO.FileExists(strAtmtPath)
                                    strAtmtNameTemp = strAtmtName(0) & _
                                                      Format(Now, "_mmddhhmmss") & _
                                                      Format(Timer * 1000 Mod 1000, "000")
                                    strAtmtPath = strFolderpath & strAtmtNameTemp & "." & strAtmtName(1)

                                    ' /* If the length of the saving path is over 260 characters.*/
                                    If Len(strAtmtPath) > MAX_PATH Then
                                        lCountEachItem = lCountEachItem - 1
                                        ' False: This attachment cannot be saved.
                                        blnIsSave = False
                                        Exit Do
                                    End If
                                Loop

                                ' /* Save the current attachment if it is a valid file name. */
                                If blnIsSave Then Atmt.SaveAsFile strAtmtPath
                            Else
                                lCountEachItem = lCountEachItem - 1
                            End If
                        Next
                    End If

                    ' Count the number of attachments in all Outlook items.
                    lCountAllItems = lCountAllItems + lCountEachItem
                Next
            End If
        Else
            MsgBox "Failed to get the handle of Outlook window!", vbCritical, "Error from Attachment Saver"
            blnIsEnd = True
            GoTo PROC_EXIT
        End If

    ' /* For run-time error:
    '    The Explorer has been closed and cannot be used for further operations.
    '    Review your code and restart Outlook. */
    Else
        MsgBox "Please select an Outlook item at least.", vbExclamation, "Message from Attachment Saver"
        blnIsEnd = True
    End If

PROC_EXIT:
    SaveAttachmentsFromSelection = lCountAllItems

    ' /* Release memory. */
    If Not (objFSO Is Nothing) Then Set objFSO = Nothing
    If Not (objItem Is Nothing) Then Set objItem = Nothing
    If Not (selItems Is Nothing) Then Set selItems = Nothing
    If Not (Atmt Is Nothing) Then Set Atmt = Nothing
    If Not (atmts Is Nothing) Then Set atmts = Nothing

    ' /* End all code execution if the value of blnIsEnd is True. */
    If blnIsEnd Then End
End Function

' #####################
' Convert general path.
' #####################
Public Function CGPath(ByVal Path As String) As String
    If Right(Path, 1) <> "\" Then Path = Path & "\"
    CGPath = Path
End Function

' ######################################
' Run this macro for saving attachments.
' ######################################
Public Sub ExecuteSaving()
    Dim oItem As Object
    Dim iAttachments As Integer

    For Each oItem In ActiveExplorer.Selection
    iAttachments = oItem.Attachments.Count + iAttachments
    Next
    MsgBox "Selected " & ActiveExplorer.Selection.Count & " messages with " & iAttachments & " attachements"
End Sub
</code>```

答:
Just change

```<code>If Len(strAtmtPath) <= MAX_PATH Then
</code>```

to

```<code>If Len(strAtmtPath) <= MAX_PATH And LCase(strAtmtName(1)) = "pdf" Then
</code>```

Full code :

```<code>' ######################################################
'  Returns the number of attachements in the selection.
' ######################################################
Public Function SaveAttachmentsFromSelection() As Long
    Dim objFSO              As Object       ' Computer's file system object.
    Dim objShell            As Object       ' Windows Shell application object.
    Dim objFolder           As Object       ' The selected folder object from Browse for Folder dialog box.
    Dim objItem             As Object       ' A specific member of a Collection object either by position or by key.
    Dim selItems            As Selection    ' A collection of Outlook item objects in a folder.
    Dim Atmt                As Attachment   ' A document or link to a document contained in an Outlook item.
    Dim strAtmtPath         As String       ' The full saving path of the attachment.
    Dim strAtmtFullName     As String       ' The full name of an attachment.
    Dim strAtmtName(1)      As String       ' strAtmtName(0): to save the name; strAtmtName(1): to save the file extension. They are separated by dot of an attachment file name.
    Dim strAtmtNameTemp     As String       ' To save a temporary attachment file name.
    Dim intDotPosition      As Integer      ' The dot position in an attachment name.
    Dim atmts               As Attachments  ' A set of Attachment objects that represent the attachments in an Outlook item.
    Dim lCountEachItem      As Long         ' The number of attachments in each Outlook item.
    Dim lCountAllItems      As Long         ' The number of attachments in all Outlook items.
    Dim strFolderpath       As String       ' The selected folder path.
    Dim blnIsEnd            As Boolean      ' End all code execution.
    Dim blnIsSave           As Boolean      ' Consider if it is need to save.
    Dim oItem               As Object
    Dim iAttachments        As Integer

    blnIsEnd = False
    blnIsSave = False
    lCountAllItems = 0

    On Error Resume Next

    Set selItems = ActiveExplorer.Selection

    If Err.Number = 0 Then

        ' Get the handle of Outlook window.
        lHwnd = FindWindow(olAppCLSN, vbNullString)

        If lHwnd <> 0 Then

            ' /* Create a Shell application object to pop-up BrowseForFolder dialog box. */
            Set objShell = CreateObject("Shell.Application")
            Set objFSO = CreateObject("Scripting.FileSystemObject")
            Set objFolder = objShell.BrowseForFolder(lHwnd, "Select folder to save attachments:", _
                                                     BIF_RETURNONLYFSDIRS + BIF_DONTGOBELOWDOMAIN, CSIDL_DESKTOP)

            ' /* Failed to create the Shell application. */
            If Err.Number <> 0 Then
                MsgBox "Run-time error '" & CStr(Err.Number) & " (0x" & CStr(Hex(Err.Number)) & ")':" & vbNewLine & _
                       Err.Description & ".", vbCritical, "Error from Attachment Saver"
                blnIsEnd = True
                GoTo PROC_EXIT
            End If

            If objFolder Is Nothing Then
                strFolderpath = ""
                blnIsEnd = True
                GoTo PROC_EXIT
            Else
                strFolderpath = CGPath(objFolder.Self.Path)

                ' /* Go through each item in the selection. */
                For Each objItem In selItems
                    lCountEachItem = objItem.Attachments.Count

                    ' /* If the current item contains attachments. */
                    If lCountEachItem > 0 Then
                        Set atmts = objItem.Attachments

                        ' /* Go through each attachment in the current item. */
                        For Each Atmt In atmts

                            ' Get the full name of the current attachment.
                            strAtmtFullName = Atmt.FileName

                            ' Find the dot postion in atmtFullName.
                            intDotPosition = InStrRev(strAtmtFullName, ".")

                            ' Get the name.
                            strAtmtName(0) = Left$(strAtmtFullName, intDotPosition - 1)
                            ' Get the file extension.
                            strAtmtName(1) = Right$(strAtmtFullName, Len(strAtmtFullName) - intDotPosition)
                            ' Get the full saving path of the current attachment.
                            strAtmtPath = strFolderpath & Atmt.FileName

                            ' /* If the length of the saving path is not larger than 260 characters.*/
                            If Len(strAtmtPath) <= MAX_PATH And LCase(strAtmtName(1)) = "pdf" Then
                                ' True: This attachment can be saved.
                                blnIsSave = True

                                ' /* Loop until getting the file name which does not exist in the folder. */
                                Do While objFSO.FileExists(strAtmtPath)
                                    strAtmtNameTemp = strAtmtName(0) & _
                                                      Format(Now, "_mmddhhmmss") & _
                                                      Format(Timer * 1000 Mod 1000, "000")
                                    strAtmtPath = strFolderpath & strAtmtNameTemp & "." & strAtmtName(1)

                                    ' /* If the length of the saving path is over 260 characters.*/
                                    If Len(strAtmtPath) > MAX_PATH Then
                                        lCountEachItem = lCountEachItem - 1
                                        ' False: This attachment cannot be saved.
                                        blnIsSave = False
                                        Exit Do
                                    End If
                                Loop

                                ' /* Save the current attachment if it is a valid file name. */
                                If blnIsSave Then Atmt.SaveAsFile strAtmtPath
                            Else
                                lCountEachItem = lCountEachItem - 1
                            End If
                        Next
                    End If

                    ' Count the number of attachments in all Outlook items.
                    lCountAllItems = lCountAllItems + lCountEachItem
                Next
            End If
        Else
            MsgBox "Failed to get the handle of Outlook window!", vbCritical, "Error from Attachment Saver"
            blnIsEnd = True
            GoTo PROC_EXIT
        End If

    ' /* For run-time error:
    '    The Explorer has been closed and cannot be used for further operations.
    '    Review your code and restart Outlook. */
    Else
        MsgBox "Please select an Outlook item at least.", vbExclamation, "Message from Attachment Saver"
        blnIsEnd = True
    End If

PROC_EXIT:
    SaveAttachmentsFromSelection = lCountAllItems

    ' /* Release memory. */
    If Not (objFSO Is Nothing) Then Set objFSO = Nothing
    If Not (objItem Is Nothing) Then Set objItem = Nothing
    If Not (selItems Is Nothing) Then Set selItems = Nothing
    If Not (Atmt Is Nothing) Then Set Atmt = Nothing
    If Not (atmts Is Nothing) Then Set atmts = Nothing

    ' /* End all code execution if the value of blnIsEnd is True. */
    If blnIsEnd Then End
End Function

' #####################
' Convert general path.
' #####################
Public Function CGPath(ByVal Path As String) As String
    If Right(Path, 1) <> "\" Then Path = Path & "\"
    CGPath = Path
End Function

' ######################################
' Run this macro for saving attachments.
' ######################################
Public Sub ExecuteSaving()
    Dim oItem As Object
    Dim iAttachments As Integer

    For Each oItem In ActiveExplorer.Selection
    iAttachments = oItem.Attachments.Count + iAttachments
    Next
    MsgBox "Selected " & ActiveExplorer.Selection.Count & " messages with " & iAttachments & " attachements"
End Sub
</code>```

Title: Outlook save only pdf attachments

Body:
Hi I have found this code and been using it for a while now but I am looking to add a rule to only save the PDF attachments and count how many PDF files have been saved.

I have got it saving all files and it loops the duplicated files but I just want it to save pdf files.

can someone assist please?

thanks

' ######################################################
'  Returns the number of attachements in the selection.
' ######################################################
Public Function SaveAttachmentsFromSelection() As Long
    Dim objFSO              As Object       ' Computer's file system object.
    Dim objShell            As Object       ' Windows Shell application object.
    Dim objFolder           As Object       ' The selected folder object from Browse for Folder dialog box.
    Dim objItem             As Object       ' A specific member of a Collection object either by position or by key.
    Dim selItems            As Selection    ' A collection of Outlook item objects in a folder.
    Dim Atmt                As Attachment   ' A document or link to a document contained in an Outlook item.
    Dim strAtmtPath         As String       ' The full saving path of the attachment.
    Dim strAtmtFullName     As String       ' The full name of an attachment.
    Dim strAtmtName(1)      As String       ' strAtmtName(0): to save the name; strAtmtName(1): to save the file extension. They are separated by dot of an attachment file name.
    Dim strAtmtNameTemp     As String       ' To save a temporary attachment file name.
    Dim intDotPosition      As Integer      ' The dot position in an attachment name.
    Dim atmts               As Attachments  ' A set of Attachment objects that represent the attachments in an Outlook item.
    Dim lCountEachItem      As Long         ' The number of attachments in each Outlook item.
    Dim lCountAllItems      As Long         ' The number of attachments in all Outlook items.
    Dim strFolderpath       As String       ' The selected folder path.
    Dim blnIsEnd            As Boolean      ' End all code execution.
    Dim blnIsSave           As Boolean      ' Consider if it is need to save.
    Dim oItem               As Object
    Dim iAttachments        As Integer

    blnIsEnd = False
    blnIsSave = False
    lCountAllItems = 0

    On Error Resume Next

    Set selItems = ActiveExplorer.Selection

    If Err.Number = 0 Then

        ' Get the handle of Outlook window.
        lHwnd = FindWindow(olAppCLSN, vbNullString)

        If lHwnd <> 0 Then

            ' /* Create a Shell application object to pop-up BrowseForFolder dialog box. */
            Set objShell = CreateObject("Shell.Application")
            Set objFSO = CreateObject("Scripting.FileSystemObject")
            Set objFolder = objShell.BrowseForFolder(lHwnd, "Select folder to save attachments:", _
                                                     BIF_RETURNONLYFSDIRS + BIF_DONTGOBELOWDOMAIN, CSIDL_DESKTOP)

            ' /* Failed to create the Shell application. */
            If Err.Number <> 0 Then
                MsgBox "Run-time error '" & CStr(Err.Number) & " (0x" & CStr(Hex(Err.Number)) & ")':" & vbNewLine & _
                       Err.Description & ".", vbCritical, "Error from Attachment Saver"
                blnIsEnd = True
                GoTo PROC_EXIT
            End If

            If objFolder Is Nothing Then
                strFolderpath = ""
                blnIsEnd = True
                GoTo PROC_EXIT
            Else
                strFolderpath = CGPath(objFolder.Self.Path)

                ' /* Go through each item in the selection. */
                For Each objItem In selItems
                    lCountEachItem = objItem.Attachments.Count

                    ' /* If the current item contains attachments. */
                    If lCountEachItem > 0 Then
                        Set atmts = objItem.Attachments

                        ' /* Go through each attachment in the current item. */
                        For Each Atmt In atmts

                            ' Get the full name of the current attachment.
                            strAtmtFullName = Atmt.FileName

                            ' Find the dot postion in atmtFullName.
                            intDotPosition = InStrRev(strAtmtFullName, ".")

                            ' Get the name.
                            strAtmtName(0) = Left$(strAtmtFullName, intDotPosition - 1)
                            ' Get the file extension.
                            strAtmtName(1) = Right$(strAtmtFullName, Len(strAtmtFullName) - intDotPosition)
                            ' Get the full saving path of the current attachment.
                            strAtmtPath = strFolderpath & Atmt.FileName

                            ' /* If the length of the saving path is not larger than 260 characters.*/
                            If Len(strAtmtPath) <= MAX_PATH Then
                                ' True: This attachment can be saved.
                                blnIsSave = True

                                ' /* Loop until getting the file name which does not exist in the folder. */
                                Do While objFSO.FileExists(strAtmtPath)
                                    strAtmtNameTemp = strAtmtName(0) & _
                                                      Format(Now, "_mmddhhmmss") & _
                                                      Format(Timer * 1000 Mod 1000, "000")
                                    strAtmtPath = strFolderpath & strAtmtNameTemp & "." & strAtmtName(1)

                                    ' /* If the length of the saving path is over 260 characters.*/
                                    If Len(strAtmtPath) > MAX_PATH Then
                                        lCountEachItem = lCountEachItem - 1
                                        ' False: This attachment cannot be saved.
                                        blnIsSave = False
                                        Exit Do
                                    End If
                                Loop

                                ' /* Save the current attachment if it is a valid file name. */
                                If blnIsSave Then Atmt.SaveAsFile strAtmtPath
                            Else
                                lCountEachItem = lCountEachItem - 1
                            End If
                        Next
                    End If

                    ' Count the number of attachments in all Outlook items.
                    lCountAllItems = lCountAllItems + lCountEachItem
                Next
            End If
        Else
            MsgBox "Failed to get the handle of Outlook window!", vbCritical, "Error from Attachment Saver"
            blnIsEnd = True
            GoTo PROC_EXIT
        End If

    ' /* For run-time error:
    '    The Explorer has been closed and cannot be used for further operations.
    '    Review your code and restart Outlook. */
    Else
        MsgBox "Please select an Outlook item at least.", vbExclamation, "Message from Attachment Saver"
        blnIsEnd = True
    End If

PROC_EXIT:
    SaveAttachmentsFromSelection = lCountAllItems

    ' /* Release memory. */
    If Not (objFSO Is Nothing) Then Set objFSO = Nothing
    If Not (objItem Is Nothing) Then Set objItem = Nothing
    If Not (selItems Is Nothing) Then Set selItems = Nothing
    If Not (Atmt Is Nothing) Then Set Atmt = Nothing
    If Not (atmts Is Nothing) Then Set atmts = Nothing

    ' /* End all code execution if the value of blnIsEnd is True. */
    If blnIsEnd Then End
End Function

' #####################
' Convert general path.
' #####################
Public Function CGPath(ByVal Path As String) As String
    If Right(Path, 1) <> "\" Then Path = Path & "\"
    CGPath = Path
End Function

' ######################################
' Run this macro for saving attachments.
' ######################################
Public Sub ExecuteSaving()
    Dim oItem As Object
    Dim iAttachments As Integer

    For Each oItem In ActiveExplorer.Selection
    iAttachments = oItem.Attachments.Count + iAttachments
    Next
    MsgBox "Selected " & ActiveExplorer.Selection.Count & " messages with " & iAttachments & " attachements"
End Sub

Body:
Just change

If Len(strAtmtPath) <= MAX_PATH Then

to

If Len(strAtmtPath) <= MAX_PATH And LCase(strAtmtName(1)) = "pdf" Then

Full code :

' ######################################################
'  Returns the number of attachements in the selection.
' ######################################################
Public Function SaveAttachmentsFromSelection() As Long
    Dim objFSO              As Object       ' Computer's file system object.
    Dim objShell            As Object       ' Windows Shell application object.
    Dim objFolder           As Object       ' The selected folder object from Browse for Folder dialog box.
    Dim objItem             As Object       ' A specific member of a Collection object either by position or by key.
    Dim selItems            As Selection    ' A collection of Outlook item objects in a folder.
    Dim Atmt                As Attachment   ' A document or link to a document contained in an Outlook item.
    Dim strAtmtPath         As String       ' The full saving path of the attachment.
    Dim strAtmtFullName     As String       ' The full name of an attachment.
    Dim strAtmtName(1)      As String       ' strAtmtName(0): to save the name; strAtmtName(1): to save the file extension. They are separated by dot of an attachment file name.
    Dim strAtmtNameTemp     As String       ' To save a temporary attachment file name.
    Dim intDotPosition      As Integer      ' The dot position in an attachment name.
    Dim atmts               As Attachments  ' A set of Attachment objects that represent the attachments in an Outlook item.
    Dim lCountEachItem      As Long         ' The number of attachments in each Outlook item.
    Dim lCountAllItems      As Long         ' The number of attachments in all Outlook items.
    Dim strFolderpath       As String       ' The selected folder path.
    Dim blnIsEnd            As Boolean      ' End all code execution.
    Dim blnIsSave           As Boolean      ' Consider if it is need to save.
    Dim oItem               As Object
    Dim iAttachments        As Integer

    blnIsEnd = False
    blnIsSave = False
    lCountAllItems = 0

    On Error Resume Next

    Set selItems = ActiveExplorer.Selection

    If Err.Number = 0 Then

        ' Get the handle of Outlook window.
        lHwnd = FindWindow(olAppCLSN, vbNullString)

        If lHwnd <> 0 Then

            ' /* Create a Shell application object to pop-up BrowseForFolder dialog box. */
            Set objShell = CreateObject("Shell.Application")
            Set objFSO = CreateObject("Scripting.FileSystemObject")
            Set objFolder = objShell.BrowseForFolder(lHwnd, "Select folder to save attachments:", _
                                                     BIF_RETURNONLYFSDIRS + BIF_DONTGOBELOWDOMAIN, CSIDL_DESKTOP)

            ' /* Failed to create the Shell application. */
            If Err.Number <> 0 Then
                MsgBox "Run-time error '" & CStr(Err.Number) & " (0x" & CStr(Hex(Err.Number)) & ")':" & vbNewLine & _
                       Err.Description & ".", vbCritical, "Error from Attachment Saver"
                blnIsEnd = True
                GoTo PROC_EXIT
            End If

            If objFolder Is Nothing Then
                strFolderpath = ""
                blnIsEnd = True
                GoTo PROC_EXIT
            Else
                strFolderpath = CGPath(objFolder.Self.Path)

                ' /* Go through each item in the selection. */
                For Each objItem In selItems
                    lCountEachItem = objItem.Attachments.Count

                    ' /* If the current item contains attachments. */
                    If lCountEachItem > 0 Then
                        Set atmts = objItem.Attachments

                        ' /* Go through each attachment in the current item. */
                        For Each Atmt In atmts

                            ' Get the full name of the current attachment.
                            strAtmtFullName = Atmt.FileName

                            ' Find the dot postion in atmtFullName.
                            intDotPosition = InStrRev(strAtmtFullName, ".")

                            ' Get the name.
                            strAtmtName(0) = Left$(strAtmtFullName, intDotPosition - 1)
                            ' Get the file extension.
                            strAtmtName(1) = Right$(strAtmtFullName, Len(strAtmtFullName) - intDotPosition)
                            ' Get the full saving path of the current attachment.
                            strAtmtPath = strFolderpath & Atmt.FileName

                            ' /* If the length of the saving path is not larger than 260 characters.*/
                            If Len(strAtmtPath) <= MAX_PATH And LCase(strAtmtName(1)) = "pdf" Then
                                ' True: This attachment can be saved.
                                blnIsSave = True

                                ' /* Loop until getting the file name which does not exist in the folder. */
                                Do While objFSO.FileExists(strAtmtPath)
                                    strAtmtNameTemp = strAtmtName(0) & _
                                                      Format(Now, "_mmddhhmmss") & _
                                                      Format(Timer * 1000 Mod 1000, "000")
                                    strAtmtPath = strFolderpath & strAtmtNameTemp & "." & strAtmtName(1)

                                    ' /* If the length of the saving path is over 260 characters.*/
                                    If Len(strAtmtPath) > MAX_PATH Then
                                        lCountEachItem = lCountEachItem - 1
                                        ' False: This attachment cannot be saved.
                                        blnIsSave = False
                                        Exit Do
                                    End If
                                Loop

                                ' /* Save the current attachment if it is a valid file name. */
                                If blnIsSave Then Atmt.SaveAsFile strAtmtPath
                            Else
                                lCountEachItem = lCountEachItem - 1
                            End If
                        Next
                    End If

                    ' Count the number of attachments in all Outlook items.
                    lCountAllItems = lCountAllItems + lCountEachItem
                Next
            End If
        Else
            MsgBox "Failed to get the handle of Outlook window!", vbCritical, "Error from Attachment Saver"
            blnIsEnd = True
            GoTo PROC_EXIT
        End If

    ' /* For run-time error:
    '    The Explorer has been closed and cannot be used for further operations.
    '    Review your code and restart Outlook. */
    Else
        MsgBox "Please select an Outlook item at least.", vbExclamation, "Message from Attachment Saver"
        blnIsEnd = True
    End If

PROC_EXIT:
    SaveAttachmentsFromSelection = lCountAllItems

    ' /* Release memory. */
    If Not (objFSO Is Nothing) Then Set objFSO = Nothing
    If Not (objItem Is Nothing) Then Set objItem = Nothing
    If Not (selItems Is Nothing) Then Set selItems = Nothing
    If Not (Atmt Is Nothing) Then Set Atmt = Nothing
    If Not (atmts Is Nothing) Then Set atmts = Nothing

    ' /* End all code execution if the value of blnIsEnd is True. */
    If blnIsEnd Then End
End Function

' #####################
' Convert general path.
' #####################
Public Function CGPath(ByVal Path As String) As String
    If Right(Path, 1) <> "\" Then Path = Path & "\"
    CGPath = Path
End Function

' ######################################
' Run this macro for saving attachments.
' ######################################
Public Sub ExecuteSaving()
    Dim oItem As Object
    Dim iAttachments As Integer

    For Each oItem In ActiveExplorer.Selection
    iAttachments = oItem.Attachments.Count + iAttachments
    Next
    MsgBox "Selected " & ActiveExplorer.Selection.Count & " messages with " & iAttachments & " attachements"
End Sub


问:
Draw line in canvas with another dashed line next to it
For an app I am working on I am drawing a line on a canvas using given coordinates. The problem is that I need to draw a dashed line next to it. Since the coordinates are coming from the API I only can use those coordinates for the dashed line. Is there any way to accomplish this? I really can't figure it out.

What I want:

The way I draw my current line:

```<code>Path line = new Path();
boolean first = true;
for (CircleArea circle : mCircles) {

    canv.drawCircle(circle.getDrawX(), circle.getDrawY(), mCircleRadius, mCirclePaint);
    if(!first) {
        line.lineTo(circle.getDrawX(), circle.getDrawY());
    } else {
        line.moveTo(circle.getDrawX(), circle.getDrawY());
    }

    first = false;
}
canv.drawPath(line, mLinePaint);
</code>```

Sample coordinates:

50,50

75,75

100,75

150,10

170,10

170,75

160,75

答:
This code snippet can be used to draw a dash path</p>

```<code>Paint paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setPathEffect(new DashPathEffect(new float[] {20,20}, 0));
paint.setColor(Color.RED);
paint.setStrokeWidth(10);
canvas.drawPath(line, paint);
</code>```

Body:
For an app I am working on I am drawing a line on a canvas using given coordinates. The problem is that I need to draw a dashed line next to it. Since the coordinates are coming from the API I only can use those coordinates for the dashed line. Is there any way to accomplish this? I really can't figure it out.

What I want:

The way I draw my current line:

Path line = new Path();
boolean first = true;
for (CircleArea circle : mCircles) {

    canv.drawCircle(circle.getDrawX(), circle.getDrawY(), mCircleRadius, mCirclePaint);
    if(!first) {
        line.lineTo(circle.getDrawX(), circle.getDrawY());
    } else {
        line.moveTo(circle.getDrawX(), circle.getDrawY());
    }

    first = false;
}
canv.drawPath(line, mLinePaint);

Sample coordinates:

50,50

75,75

100,75

150,10

170,10

170,75

160,75

Body:
This code snippet can be used to draw a dash path

Paint paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setPathEffect(new DashPathEffect(new float[] {20,20}, 0));
paint.setColor(Color.RED);
paint.setStrokeWidth(10);
canvas.drawPath(line, paint);


问:
Is it possible to change the size of the text in an HTML input tag?
I have a client who wants bigger text in an <input> box.  I would prefer to not have to make custom graphic button for this as it's on a really resource-constrained embedded system.

答:
The input tag can be styled just like any other element in HTML, including padding, borders, text font face/size, etc.

```<code>input{
    font: sans-serif italic 20pt bold;
    border: 2px black solid;
}
</code>```

Or what ever you would like.

Body:
The input tag can be styled just like any other element in HTML, including padding, borders, text font face/size, etc.

input{
    font: sans-serif italic 20pt bold;
    border: 2px black solid;
}

Or what ever you would like.


问:
Paginate long text using php
I've a long text (More than 10,000 words) contains html tags stored in a string.

And want to wrap every 1000 words with

 with considering auto close opened html tags and auto open closed html tags in the different chunks.

I found many solutions but they depend on the number of characters and don't consider auto open/close html tags.

Also the php function wordwrap neglects fixing html tags problem.

Simulation

```<code><div id="long-text">
   Dynamic long text more than 10,000 words (Text contains HTML (img, p, span, i, ...etc) tags)
</div>
</code>```

Wrong result

```<code><div id="long-text">
   <div class="chunk">
      <p>Chunk 1 : first approximately 1000 words with their html tags
         <img src="image.jpg"> ## Unclosed <p> tag ##
   </div>

   <div class="chunk">
      ## The closed <p> tag of the previous chunk ##
      </p><p>Chunk 2 : second approximately 1000 words with their html tags
      <img src="image.jpg"> </p><p> ## unclosed <p> tag ##
   </div>

   <div class="chunk">
      ## Missing open <p> tag because it was cut in the previous chunk ##
      Chunk 3 : third approximately 1000 words with their html tags</p>
   </div>
</div>
</code>```

Expected result

```<code><div id="long-text">
       <div class="chunk">
          <p>Chunk 1 : first approximately 1000 words with their html tags
             <img src="image.jpg"> </p>
       </div>

       <div class="chunk">
          <p>Chunk 2 : second approximately 1000 words with their html tags
          <img src="image.jpg"> </p>
       </div>

       <div class="chunk">
          <p>Chunk 3 : third approximately 1000 words with their html tags</p>
       </div>
    </div>
</code>```

And then i can paginate the result with javascript.

After searching i found the accepted answer here: Shortening text tweet-like without cutting links inside

cutting the text (from the start only) and auto close opened html tags.

I tried to modify the code to auto open closed tags if i cut from the middle of the text but unfortunately i failed to do the job.

I don't mind if there are another better solutions to paginate the long text according to the number of words using (php or javascript or both of them).

答:
So the idea is to use JQuery to chunk the immediate children via cloning and splitting the internal text. It may need some more work for further nested HTML but it's a start:

```<code>function chunkText(length) {
    var words = $(this).text().split(" ");
  var res = [$(this)];
  if (words.length > br) {
    var overflow = $(this).clone();
    var keepText = words.slice(0,length);
    $(this).text(keepText.join(" "));
    overflow.text(words.slice(length).join(" "));
    res = res.concat(chunkText.call(overflow, length));

    }
  return res;
}

var br = 10; //Words to split on

$("#long-text > *").each( function () {
        var chunks = chunkText.call(this,br);
    $.each(chunks, function (i,v) {
      $("#long-text")
          .append($("<div>").addClass("chunk").append(v))
          .append($("<img>").attr("src","image.jpg")));
    });

});
</code>```

Basic demo:
https://jsfiddle.net/o2d8zf4v/

Title: Paginate long text using php

Body:
I've a long text (More than 10,000 words) contains html tags stored in a string.

And want to wrap every 1000 words with

 with considering auto close opened html tags and auto open closed html tags in the different chunks.

I found many solutions but they depend on the number of characters and don't consider auto open/close html tags.

Also the php function wordwrap neglects fixing html tags problem.

Simulation

   Dynamic long text more than 10,000 words (Text contains HTML (img, p, span, i, ...etc) tags)

Wrong result

Chunk 1 : first approximately 1000 words with their html tags
          ## Unclosed
 tag ##

      ## The closed
 tag of the previous chunk ##

Chunk 2 : second approximately 1000 words with their html tags

 ## unclosed
 tag ##

      ## Missing open
 tag because it was cut in the previous chunk ##
      Chunk 3 : third approximately 1000 words with their html tags

Expected result

Chunk 1 : first approximately 1000 words with their html tags

Chunk 2 : second approximately 1000 words with their html tags

Chunk 3 : third approximately 1000 words with their html tags

And then i can paginate the result with javascript.

After searching i found the accepted answer here: Shortening text tweet-like without cutting links inside

cutting the text (from the start only) and auto close opened html tags.

I tried to modify the code to auto open closed tags if i cut from the middle of the text but unfortunately i failed to do the job.

I don't mind if there are another better solutions to paginate the long text according to the number of words using (php or javascript or both of them).

Body:
So the idea is to use JQuery to chunk the immediate children via cloning and splitting the internal text. It may need some more work for further nested HTML but it's a start:

function chunkText(length) {
    var words = $(this).text().split(" ");
  var res = [$(this)];
  if (words.length > br) {
    var overflow = $(this).clone();
    var keepText = words.slice(0,length);
    $(this).text(keepText.join(" "));
    overflow.text(words.slice(length).join(" "));
    res = res.concat(chunkText.call(overflow, length));

    }
  return res;
}

var br = 10; //Words to split on

$("#long-text > *").each( function () {
        var chunks = chunkText.call(this,br);
    $.each(chunks, function (i,v) {
      $("#long-text")
          .append($("<div>").addClass("chunk").append(v))
          .append($("<img>").attr("src","image.jpg")));
    });

});

Basic demo:
https://jsfiddle.net/o2d8zf4v/


问:
Store an already UTC timestamp in TIMESTAMP field without further conversion in MySQL
As per the MySQL documentation:

MySQL converts TIMESTAMP values from the current time zone to UTC for storage, and back from UTC to the current time zone for retrieval.

I am ok with the conversion for the retrieval but for storage I already have an UTC timestamp. It is sent like this from the client as it is a value calculated on the client side and I want to avoid time zone conversions (because I think this will add complexity to the client-server communication).

How can I insert this value avoiding further conversion?

答:
If you don't want MySQL to do any conversions, maybe the simplest way is to just store the timestamp in a numeric field.

This might be bad practice depending on what you are going to do with it, this thread has some discussion on the pros and cons:
Using MySQL's TIMESTAMP vs storing timestamps directly


问:
Angular - getting ng-bind to work on nested directives
I've built a small pattern that recursively creates different sub-directives based on the model. I'm using $compile to build child directives recursively, then append them to the parent.

The directive building itself seems to work just fine, but for some reason, embedded expressions or ng-bind or interpolation doesn't seem to work on nested directive.

Here's a snippet:

```<code>app.directive("child", function ($compile) {
  function getTemplate(depth) {
    if (depth % 2 == 0) {
      return "<even depth='deeper'/>"
    } else {
      return "<odd depth='deeper'/>"
    }
  }
  return {
    scope: {
      depth: "="
    },
    link: function linker($scope, $element) {
      if ($scope.depth == 0) {
        var child = angular.element("<span ng-bind='depth'/>");
        child = $compile(child)($scope);
        $element.append(child);
      } else {
        $scope.deeper = $scope.depth - 1;
        var child = angular.element(getTemplate($scope.depth));
        child = $compile(child)($scope);
        $element.append(child);
      }
    }
  }
})
</code>```

Basically in this test the directive will recursively dive down until the depth reaches 0, then spit out a  element.

The expected result should be a span element with the value of 0. But it doesn't seem to evaluate. Using {{depth}} also results in in a literal html instead of evaluating the contents.

I'm trying to achieve a result of nested <even><odd><even> directives removing the surrounding <child> - directive.

Here's a complete jsFiddle: https://jsfiddle.net/eg1e1aLz/

The resulting DOM should look like this:

<test depth="4" class="ng-isolate-scope">
  <even depth="depth-1" class="ng-scope ng-isolate-scope">
    <odd depth="depth-1" class="ng-scope ng-isolate-scope">
      <even depth="depth-1" class="ng-scope ng-isolate-scope">
        <odd depth="depth-1" class="ng-scope ng-isolate-scope">0</odd>
      </even>
    </odd>
  </even>
</test>```

答: Your html might not be sanitized that's why it is not compiling try using ngSanatize ti might solve your problem https://docs.angularjs.org/api/ngSanitize/service/$sanitize it will remove all the potentially dangerous tokens and will return you a proper html.

Body:
I've built a small pattern that recursively creates different sub-directives based on the model. I'm using $compile to build child directives recursively, then append them to the parent.

The directive building itself seems to work just fine, but for some reason, embedded expressions or ng-bind or interpolation doesn't seem to work on nested directive.

Here's a snippet:

app.directive("child", function ($compile) {
  function getTemplate(depth) {
    if (depth % 2 == 0) {
      return "<even depth='deeper'/>"
    } else {
      return "<odd depth='deeper'/>"
    }
  }
  return {
    scope: {
      depth: "="
    },
    link: function linker($scope, $element) {
      if ($scope.depth == 0) {
        var child = angular.element("");
        child = $compile(child)($scope);
        $element.append(child);
      } else {
        $scope.deeper = $scope.depth - 1;
        var child = angular.element(getTemplate($scope.depth));
        child = $compile(child)($scope);
        $element.append(child);
      }
    }
  }
})

Basically in this test the directive will recursively dive down until the depth reaches 0, then spit out a  element.

The expected result should be a span element with the value of 0. But it doesn't seem to evaluate. Using {{depth}} also results in in a literal html instead of evaluating the contents.

I'm trying to achieve a result of nested <even><odd><even> directives removing the surrounding <child> - directive.

Here's a complete jsFiddle: https://jsfiddle.net/eg1e1aLz/

The resulting DOM should look like this:

<test depth="4" class="ng-isolate-scope">
  <even depth="depth-1" class="ng-scope ng-isolate-scope">
    <odd depth="depth-1" class="ng-scope ng-isolate-scope">
      <even depth="depth-1" class="ng-scope ng-isolate-scope">
        <odd depth="depth-1" class="ng-scope ng-isolate-scope">0</odd>
      </even>
    </odd>
  </even>
</test>