问:
Git commit opens blank text file, for what?
In all the Git tutorials I've read they say that you can do:

```<code>git init
git add .
git commit
</code>```

When I do that I get a big text file opened up. None of the tutorials seem to address this, so I don't know what to do with the file or what to put in it if anything.

答:
As mentioned by Ben Collins, without the -m "..." argument to type the commit inline (which is generally a bad idea as it encourages you to be brief), this "big text file" that is opened up is a window in which to type the commit message.

Usually it's recommended to write a summary in the first line, skip a line, and then write more detailed notes beneath; this helps programs that do things like email the commit messages with an appropriate subject line and the full list of changes made in the body.

Instead of changing the EDITOR shell variable, you can also change the editor used by adding the additional lines in your ~/.gitconfig file:

```<code>[core]
    editor = emacs
    excludesfile = /Users/will/.gitignore
</code>```

That second line actually has nothing to do with your problem, but I find it really useful so I can populate my ~/.gitignore file with all those filetypes I know I'll never, ever, want to commit to a repository.

OwnerDisplayName: Alex

LastEditorDisplayName: Baishampayan Ghose

Body:
In all the Git tutorials I've read they say that you can do:

git init
git add .
git commit

When I do that I get a big text file opened up. None of the tutorials seem to address this, so I don't know what to do with the file or what to put in it if anything.

Body:
As mentioned by Ben Collins, without the -m "..." argument to type the commit inline (which is generally a bad idea as it encourages you to be brief), this "big text file" that is opened up is a window in which to type the commit message.

Usually it's recommended to write a summary in the first line, skip a line, and then write more detailed notes beneath; this helps programs that do things like email the commit messages with an appropriate subject line and the full list of changes made in the body.

Instead of changing the EDITOR shell variable, you can also change the editor used by adding the additional lines in your ~/.gitconfig file:

[core]
    editor = emacs
    excludesfile = /Users/will/.gitignore

That second line actually has nothing to do with your problem, but I find it really useful so I can populate my ~/.gitignore file with all those filetypes I know I'll never, ever, want to commit to a repository.

OwnerDisplayName: Will Robertson

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Will Robertson


来源: stackexchange

问:
LINQ Inner-Join vs Left-Join
Using extension syntax I'm trying to create a left-join using LINQ on two lists that I have. The following is from the Microsoft help but I've modified it to show that the pets list has no elements. What I'm ending up with is a list of 0 elements. I assume that this is because an inner-join is taking place. What I want to end up with is a list of 3 elements (the 3 Person objects) with null data filled in for the missing elements. i.e. a Left-Join. Is this possible?</p>

```<code>Person magnus = new Person { Name = "Hedlund, Magnus" };
Person terry = new Person { Name = "Adams, Terry" };
Person charlotte = new Person { Name = "Weiss, Charlotte" };

//Pet barley = new Pet { Name = "Barley", Owner = terry };
//Pet boots = new Pet { Name = "Boots", Owner = terry };
//Pet whiskers = new Pet { Name = "Whiskers", Owner = charlotte };
//Pet daisy = new Pet { Name = "Daisy", Owner = magnus };

List<Person> people = new List<Person> { magnus, terry, charlotte };
//List<Pet> pets = new List<Pet> { barley, boots, whiskers, daisy };
List<Pet> pets = new List<Pet>();

// Create a list of Person-Pet pairs where
// each element is an anonymous type that contains a
// Pet's name and the name of the Person that owns the Pet.
var query =
    people.Join(pets,
                person => person,
                pet => pet.Owner,
                (person, pet) =>
                    new { OwnerName = person.Name, Pet = pet.Name }).ToList();
</code>```

答:
I the following error message when faced this same problem:

The type of one of the expressions in the join clause is incorrect.  Type inference failed in the call to 'GroupJoin'.

Solved when I used the same property name, it worked.

(...)

```<code>join enderecoST in db.PessoaEnderecos on
    new
      {
         CD_PESSOA          = nf.CD_PESSOA_ST,
         CD_ENDERECO_PESSOA = nf.CD_ENDERECO_PESSOA_ST
      } equals
    new
    {
         enderecoST.CD_PESSOA,
         enderecoST.CD_ENDERECO_PESSOA
    } into eST
</code>```

(...)

OwnerDisplayName: Guy

Title: LINQ Inner-Join vs Left-Join

Body:
Using extension syntax I'm trying to create a left-join using LINQ on two lists that I have. The following is from the Microsoft help but I've modified it to show that the pets list has no elements. What I'm ending up with is a list of 0 elements. I assume that this is because an inner-join is taking place. What I want to end up with is a list of 3 elements (the 3 Person objects) with null data filled in for the missing elements. i.e. a Left-Join. Is this possible?

Person magnus = new Person { Name = "Hedlund, Magnus" };
Person terry = new Person { Name = "Adams, Terry" };
Person charlotte = new Person { Name = "Weiss, Charlotte" };

//Pet barley = new Pet { Name = "Barley", Owner = terry };
//Pet boots = new Pet { Name = "Boots", Owner = terry };
//Pet whiskers = new Pet { Name = "Whiskers", Owner = charlotte };
//Pet daisy = new Pet { Name = "Daisy", Owner = magnus };

List<Person> people = new List<Person> { magnus, terry, charlotte };
//List<Pet> pets = new List<Pet> { barley, boots, whiskers, daisy };
List<Pet> pets = new List<Pet>();

// Create a list of Person-Pet pairs where
// each element is an anonymous type that contains a
// Pet's name and the name of the Person that owns the Pet.
var query =
    people.Join(pets,
                person => person,
                pet => pet.Owner,
                (person, pet) =>
                    new { OwnerName = person.Name, Pet = pet.Name }).ToList();

Body:
I the following error message when faced this same problem:

The type of one of the expressions in the join clause is incorrect.  Type inference failed in the call to 'GroupJoin'.

Solved when I used the same property name, it worked.

(...)

join enderecoST in db.PessoaEnderecos on
    new
      {
         CD_PESSOA          = nf.CD_PESSOA_ST,
         CD_ENDERECO_PESSOA = nf.CD_ENDERECO_PESSOA_ST
      } equals
    new
    {
         enderecoST.CD_PESSOA,
         enderecoST.CD_ENDERECO_PESSOA
    } into eST

(...)

OwnerDisplayName: João Vieira


问:
Javascript object creation best practice
I have the following javascript :

```<code>            var MyObject = (function() {

                function Setup(args) {
                    this.prop1 = args.x;
                    this.prop2 = args.y
                    this.prop3 = this.prop1 + this.prop2;

                    this.Create = function() {
                        return 'a' + helperFunc();
                    }

                    function helperFunc() {
                        return this.prop3;
                    }
                }

                return {
                    init : function(args) {
                        var setup = new Setup(args);

                        setup.Create();
                    }
                }

            })();

            $(function() {

                MyObject.init(someArgs);

            });
</code>```

Is my approach to object construction a good practice?

I am getting undefined in the helperFunc when trying to access this.prop3.

I have also tried to assign this.prop1 + this.prop2 to a local variable and use a function to return this value like so:

```<code>        function Setup(args) {
                var total;

                this.prop1 = args.x;
                this.prop2 = args.y

                total = this.prop1 + this.prop2;
                this.getTotal = function() {
                        return total;
                };

                this.prop3 = this.prop1 + this.prop2;
                ...
</code>```

...and when calling this in the helperFunc like this:

```<code>                       return this.getTotal();
</code>```

.. i get this.getTotal is not a function

I have been reading around object creation and using closures to mimic private members and so on and since there is no one way to define objects I am getting confused.

TBH - I don't really understand the construct:

```<code>                       var myObject = (function() { ... } ();
</code>```

I've seen it used a lot in jQuery plugins but what does the first parenth followed by empty parenth at the end mean and do?

Any knowledge imparted would be much appreciated.

Also, I have on order the Douglas Crockford book on javascript and until it arrives I need to try to solve this problem

答:
To cite Xhalent's wonderful article (really well done and clearly wirtten) mentioned by him:

That is because the value of “this” is
  different to the value of “this” when
  the object was created.

So in your case:

```<code>...
  var _this = this.prop3;
  function helperFunc() {
    return _this;
  }
...
</code>```

might achieve what's desired.

ContentLicense: CC BY-SA 3.0

Body:
I have the following javascript :

            var MyObject = (function() {

                function Setup(args) {
                    this.prop1 = args.x;
                    this.prop2 = args.y
                    this.prop3 = this.prop1 + this.prop2;

                    this.Create = function() {
                        return 'a' + helperFunc();
                    }

                    function helperFunc() {
                        return this.prop3;
                    }
                }

                return {
                    init : function(args) {
                        var setup = new Setup(args);

                        setup.Create();
                    }
                }

            })();

            $(function() {

                MyObject.init(someArgs);

            });

Is my approach to object construction a good practice?

I am getting undefined in the helperFunc when trying to access this.prop3.

I have also tried to assign this.prop1 + this.prop2 to a local variable and use a function to return this value like so:

        function Setup(args) {
                var total;

                this.prop1 = args.x;
                this.prop2 = args.y

                total = this.prop1 + this.prop2;
                this.getTotal = function() {
                        return total;
                };

                this.prop3 = this.prop1 + this.prop2;
                ...

...and when calling this in the helperFunc like this:

                       return this.getTotal();

.. i get this.getTotal is not a function

I have been reading around object creation and using closures to mimic private members and so on and since there is no one way to define objects I am getting confused.

TBH - I don't really understand the construct:

                       var myObject = (function() { ... } ();

I've seen it used a lot in jQuery plugins but what does the first parenth followed by empty parenth at the end mean and do?

Any knowledge imparted would be much appreciated.

Also, I have on order the Douglas Crockford book on javascript and until it arrives I need to try to solve this problem

Body:
To cite Xhalent's wonderful article (really well done and clearly wirtten) mentioned by him:

That is because the value of “this” is
  different to the value of “this” when
  the object was created.

So in your case:

...
  var _this = this.prop3;
  function helperFunc() {
    return _this;
  }
...

might achieve what's desired.


问:
How download 600k emails from a POP3 server
How to download all emails (632,000 emails) from a POP server? Currently MacOS Mail limits me to 200,000 emails. Is there a client capable of doing the job without limitation? I do not have access to the server configuration, I am a user.</p>

答: Wow, that quite a collection! Provided there's no way of using IMAP. although i haven't tried to do this myself thunderbird could quite possibly do it, as i don't believe there is a limit along as you don't run out of disk space or RAM, and Attachments will be compressed.</p>

ContentLicense: CC BY-SA 4.0


问:
Select top n elements from list of lists in Python
I'm trying to create a new list of lists from an existing one. I'm trying to select top N values from the inner lists and output a new list of lists. The current list looks like this:

```<code>[[('with', -3.608809242675524),
  ('cruz', -3.6553518286125546),
  ('rt', -2.962847001582534)],
[ ('his', -2.9577717646107025),
  ('is', -2.9627189839205403),
  ('to', -2.968666793195209)]]
</code>```

Now I want to take this as an input and output the top 1 element from each list. The real list is longer and has more than 2 lists, and I would want to take top N elements. The output should look like this:

```<code>[[('with', -3.608809242675524)],
[('his', -2.9577717646107025)]]
</code>```

Any help would be appreciated!

答:
Use a list comprehension with slicing of the inner lists.</p>

```<code>result = [l[:N] for l in original_list]
</code>```

Body:
I'm trying to create a new list of lists from an existing one. I'm trying to select top N values from the inner lists and output a new list of lists. The current list looks like this:

[[('with', -3.608809242675524),
  ('cruz', -3.6553518286125546),
  ('rt', -2.962847001582534)],
[ ('his', -2.9577717646107025),
  ('is', -2.9627189839205403),
  ('to', -2.968666793195209)]]

Now I want to take this as an input and output the top 1 element from each list. The real list is longer and has more than 2 lists, and I would want to take top N elements. The output should look like this:

[[('with', -3.608809242675524)],
[('his', -2.9577717646107025)]]

Any help would be appreciated!

Body:
Use a list comprehension with slicing of the inner lists.

result = [l[:N] for l in original_list]


问:
MongoDB: User defined variable into query
I'm new to MongoDB shell and I need some help !

I have 2 collections: movies and comments. I want to store a value from the second collection and use it to find something in the first.

This is what I have tried :

```<code>var result = db.comments.findOne({name: "Arya Stark"})
var movieId = JSON.stringify(result.movie_id.valueOf())
db.movies.findOne({_id: ObjectId($$movieId)})
</code>```

The above prints that $$movieId is not defined. I have also tried :

```<code>db.movies.find({_id: {$toObjectId: movieId}})
</code>```

and even though my version is 4.2.3, it prints:

unknown operator: $toObjectId.

I have tried everything, I don't know what else to do.

EDIT :

Here's the printed result :

```<code>{
        "_id" : ObjectId("5a9427648b0beebeb6957d48"),
        "name" : "Arya Stark",
        "email" : "maisie_williams@gameofthron.es",
        "movie_id" : ObjectId("573a1392f29313caabcd9906"),
        "text" : "Laborum incidunt asperiores accusamus facilis vitae ut quidem. Praesentium provident explicabo odit dolores unde amet architecto. Iure id vero temporibus assumenda eum quia.",
        "date" : ISODate("1978-07-29T23:20:45Z")
}
</code>```

Basically I want to take the movie_id from the collection comments and use it in the collection movies to search from which movie it is.

答:
You don't need to do two database calls, instead use $lookup for JOINS, try to execute below query in shell :

```<code>db.comments.aggregate([{ $match: { name: "Arya Stark" } }, {
    $lookup:
    {
        from: "movies",
        localField: "movie_id",
        foreignField: "_id",
        as: "movie"
    }
}, { $unwind: '$movie' }])
</code>```

Your two issues are :

when you use $$ in your query that respective variable has to be declared locally in query itself.

$toObjectId is an aggregation operator, which can't be used like that in .find().

Body:
I'm new to MongoDB shell and I need some help !

I have 2 collections: movies and comments. I want to store a value from the second collection and use it to find something in the first.

This is what I have tried :

var result = db.comments.findOne({name: "Arya Stark"})
var movieId = JSON.stringify(result.movie_id.valueOf())
db.movies.findOne({_id: ObjectId($$movieId)})

The above prints that $$movieId is not defined. I have also tried :

db.movies.find({_id: {$toObjectId: movieId}})

and even though my version is 4.2.3, it prints:

unknown operator: $toObjectId.

I have tried everything, I don't know what else to do.

EDIT :

Here's the printed result :

{
        "_id" : ObjectId("5a9427648b0beebeb6957d48"),
        "name" : "Arya Stark",
        "email" : "maisie_williams@gameofthron.es",
        "movie_id" : ObjectId("573a1392f29313caabcd9906"),
        "text" : "Laborum incidunt asperiores accusamus facilis vitae ut quidem. Praesentium provident explicabo odit dolores unde amet architecto. Iure id vero temporibus assumenda eum quia.",
        "date" : ISODate("1978-07-29T23:20:45Z")
}

Basically I want to take the movie_id from the collection comments and use it in the collection movies to search from which movie it is.

Body:
You don't need to do two database calls, instead use $lookup for JOINS, try to execute below query in shell :

db.comments.aggregate([{ $match: { name: "Arya Stark" } }, {
    $lookup:
    {
        from: "movies",
        localField: "movie_id",
        foreignField: "_id",
        as: "movie"
    }
}, { $unwind: '$movie' }])

Your two issues are :

when you use $$ in your query that respective variable has to be declared locally in query itself.

$toObjectId is an aggregation operator, which can't be used like that in .find().


问:
React Native Development Server Error 500
Hey I'm trying to make my first app in react-native and I am running into an issue after trying to install react-navigation and react-navigation stack.

When i try to run react-native start I get this error:

```<code> BUNDLE  [android, dev] ./index.js ▓▓▓▓▓▓▓▓▓░░░░░░░ 57.2% (431/570)::ffff:127.0.0.1 - - [19/Feb/2020:23:06:17 +0000] "GET /index.bundle?platform=android&dev=true&minify=false HTTP/1.1" 500 - "-" "okhttp/3.12.1"
error: bundling failed: Error: Unable to resolve module `@react-native-community/masked-view` from `node_modules/react-navigation-stack/lib/module/vendor/views/MaskedView.native.js`: @react-native-community/masked-view could not be found within the project.
</code>```

but I have react-native-community in my node modules folder and have tried installing it again but it doesn't seem to exist when i do npm install react-native-community.

Also I'm not sure if this is related but when i do react-native run-android It gets stuck at 99% now on the app:installDebug step.

Edit: Fixed needed to do npm install @react-native-community/masked-view

答: Run npm list in your working folder to see all dependencies in your project folder and look out for UNMET PEER DEPENDENCY, then install all dependencies that are unmet

Body:
Hey I'm trying to make my first app in react-native and I am running into an issue after trying to install react-navigation and react-navigation stack.

When i try to run react-native start I get this error:

 BUNDLE  [android, dev] ./index.js ▓▓▓▓▓▓▓▓▓░░░░░░░ 57.2% (431/570)::ffff:127.0.0.1 - - [19/Feb/2020:23:06:17 +0000] "GET /index.bundle?platform=android&dev=true&minify=false HTTP/1.1" 500 - "-" "okhttp/3.12.1"
error: bundling failed: Error: Unable to resolve module `@react-native-community/masked-view` from `node_modules/react-navigation-stack/lib/module/vendor/views/MaskedView.native.js`: @react-native-community/masked-view could not be found within the project.

but I have react-native-community in my node modules folder and have tried installing it again but it doesn't seem to exist when i do npm install react-native-community.

Also I'm not sure if this is related but when i do react-native run-android It gets stuck at 99% now on the app:installDebug step.

Edit: Fixed needed to do npm install @react-native-community/masked-view


问:
Rails multiple developers environments
In our company, people are using different operating systems. I am using Linux and have line in development.rb like:

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

Designer, who is on Windows need different line. Is there any way, how to manage different developers in ruby on rails? Thanks a lot!

答:
If it's just a platform issue, try something like this:

```<code>if RUBY_PLATFORM =~ /mswin/
  Paperclip.options[:command_path] = 'c://ruby/bin'
else
  Paperclip.options[:command_path] = '/usr/bin'
end
</code>```

A good way to keep machine-specific settings is with a configuration file.
Treat the settings.yml like database.yml and copy the example to settings.yml on each user's machine.

```<code># .gitignore
config/settings.yml

# config/settings.yml.example
paperclip_command_path: /usr/bin
some_api_key: put_key_here

# config/initializers/load_settings.rb
filename = File.join(File.dirname(__FILE__), '..', 'settings.yml')
if File.file?(filename)
  APP_CONFIG = YAML::load_file(filename)
  APP_CONFIG.each do |k, v|
    v.symbolize_keys! if v.respond_to?(:symbolize_keys!)
  end
end
</code>```

This way you could set the above like this:

```<code>Paperclip.options[:command_path] = APP_CONFIG[:paperclip_command_path]
</code>```

Title: Rails multiple developers environments

Body:
If it's just a platform issue, try something like this:

if RUBY_PLATFORM =~ /mswin/
  Paperclip.options[:command_path] = 'c://ruby/bin'
else
  Paperclip.options[:command_path] = '/usr/bin'
end

A good way to keep machine-specific settings is with a configuration file.
Treat the settings.yml like database.yml and copy the example to settings.yml on each user's machine.

# .gitignore
config/settings.yml

# config/settings.yml.example
paperclip_command_path: /usr/bin
some_api_key: put_key_here

# config/initializers/load_settings.rb
filename = File.join(File.dirname(__FILE__), '..', 'settings.yml')
if File.file?(filename)
  APP_CONFIG = YAML::load_file(filename)
  APP_CONFIG.each do |k, v|
    v.symbolize_keys! if v.respond_to?(:symbolize_keys!)
  end
end

This way you could set the above like this:

Paperclip.options[:command_path] = APP_CONFIG[:paperclip_command_path]


问:
How to do remove jagged edges of an object in an image with python and opencv
I have tried to search and found two solutions that could solve the problem I have but are not working by my side. I want to remove the jagged edges or smooth the image attached. I have tried to implement the following codes

```<code>import cv2
import numpy as np
import os
os.chdir("F:/Examples")
image = cv2.imread("image1.jpeg")
blur = cv2.GaussianBlur(image, (21, 21), 0)
mask = np.zeros(image.shape[:2], dtype=np.uint8)

output = np.where(mask==np.array([255, 255, 255]), blur, image)
cv2.imwrite("", output)
</code>```

The above codes returns unchanged image as if the applied mask didn't work. Here is the input image

I also tried to implement some solutions from different links including (How to blur the image according to segmentation map) without success. Any help will be acknowledged
While the edges or the external contour should be clear as in this image

答:
I almost managed to solve it.

The main problem is that the contour is partially curved, and partially with straight lines.

Explanations are in the comments:

```<code>import numpy as np
import cv2
from scipy.interpolate import splprep, splev

im = cv2.imread('image1.jpeg')

bk = im.copy()

# Fill background with black color
cv2.floodFill(im, None, seedPoint=(1,1), newVal=(0, 0, 0), loDiff=(5, 5, 5), upDiff=(5, 5, 5))
gray = cv2.cvtColor(im, cv2.COLOR_RGB2GRAY)

ret, thresh_gray = cv2.threshold(gray, 5, 255, cv2.THRESH_BINARY)

# Use "open" morphological operation for removing small contours (noise)
thresh_gray = cv2.morphologyEx(thresh_gray, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5)));

# Background
bk[(thresh_gray > 0)] = 0
bk = cv2.morphologyEx(bk, cv2.MORPH_DILATE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (20,20)));
#cv2.imshow('bk', bk)

# Foreground
fg = im.copy()
tmm_fg = cv2.morphologyEx(fg, cv2.MORPH_DILATE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (20,20)));
fg_gray = cv2.cvtColor(fg, cv2.COLOR_RGB2GRAY)
fg[(fg_gray==0)] = tmm_fg[(fg_gray==0)]

#thresh_gray = cv2.morphologyEx(thresh_gray, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (50,50)));

# Find contours (there is only one contour)
# _, contours, _ = cv2.findContours(thresh_gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)  # 3 outputs works only in OpenCV 3. [-2:] is used for compatibility.
contours, _ = cv2.findContours(thresh_gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[-2:]  # https://stackoverflow.com/questions/48291581/how-to-use-cv2-findcontours-in-different-opencv-versions
c = contours[0]

# Smooth contour
# https://agniva.me/scipy/2016/10/25/contour-smoothing.html
x,y = c.T
x = x.tolist()[0]
y = y.tolist()[0]
tck, u = splprep([x,y], u=None, s=1.0, per=1)
u_new = np.linspace(u.min(), u.max(), 150)
x_new, y_new = splev(u_new, tck, der=0)
res_array = [[[int(i[0]), int(i[1])]] for i in zip(x_new,y_new)]
smoothened = np.asarray(res_array, dtype=np.int32)

# Build a mask
mask = np.zeros_like(thresh_gray)
cv2.drawContours(mask, [smoothened], -1, 255, -1)

# For testig
test_im = cv2.cvtColor(thresh_gray, cv2.COLOR_GRAY2RGB)
cv2.drawContours(test_im, [smoothened], 0, (0, 255, 0), 1)

res = bk
res[(mask > 0)] = fg[(mask > 0)]

cv2.imshow('test_im', test_im)
cv2.imshow('res', res)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

Body:
I have tried to search and found two solutions that could solve the problem I have but are not working by my side. I want to remove the jagged edges or smooth the image attached. I have tried to implement the following codes

import cv2
import numpy as np
import os
os.chdir("F:/Examples")
image = cv2.imread("image1.jpeg")
blur = cv2.GaussianBlur(image, (21, 21), 0)
mask = np.zeros(image.shape[:2], dtype=np.uint8)

output = np.where(mask==np.array([255, 255, 255]), blur, image)
cv2.imwrite("", output)

The above codes returns unchanged image as if the applied mask didn't work. Here is the input image

I also tried to implement some solutions from different links including (How to blur the image according to segmentation map) without success. Any help will be acknowledged
While the edges or the external contour should be clear as in this image

Body:
I almost managed to solve it.

The main problem is that the contour is partially curved, and partially with straight lines.

Explanations are in the comments:

import numpy as np
import cv2
from scipy.interpolate import splprep, splev

im = cv2.imread('image1.jpeg')

bk = im.copy()

# Fill background with black color
cv2.floodFill(im, None, seedPoint=(1,1), newVal=(0, 0, 0), loDiff=(5, 5, 5), upDiff=(5, 5, 5))
gray = cv2.cvtColor(im, cv2.COLOR_RGB2GRAY)

ret, thresh_gray = cv2.threshold(gray, 5, 255, cv2.THRESH_BINARY)

# Use "open" morphological operation for removing small contours (noise)
thresh_gray = cv2.morphologyEx(thresh_gray, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5)));

# Background
bk[(thresh_gray > 0)] = 0
bk = cv2.morphologyEx(bk, cv2.MORPH_DILATE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (20,20)));
#cv2.imshow('bk', bk)

# Foreground
fg = im.copy()
tmm_fg = cv2.morphologyEx(fg, cv2.MORPH_DILATE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (20,20)));
fg_gray = cv2.cvtColor(fg, cv2.COLOR_RGB2GRAY)
fg[(fg_gray==0)] = tmm_fg[(fg_gray==0)]

#thresh_gray = cv2.morphologyEx(thresh_gray, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (50,50)));

# Find contours (there is only one contour)
# _, contours, _ = cv2.findContours(thresh_gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)  # 3 outputs works only in OpenCV 3. [-2:] is used for compatibility.
contours, _ = cv2.findContours(thresh_gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[-2:]  # https://stackoverflow.com/questions/48291581/how-to-use-cv2-findcontours-in-different-opencv-versions
c = contours[0]

# Smooth contour
# https://agniva.me/scipy/2016/10/25/contour-smoothing.html
x,y = c.T
x = x.tolist()[0]
y = y.tolist()[0]
tck, u = splprep([x,y], u=None, s=1.0, per=1)
u_new = np.linspace(u.min(), u.max(), 150)
x_new, y_new = splev(u_new, tck, der=0)
res_array = [[[int(i[0]), int(i[1])]] for i in zip(x_new,y_new)]
smoothened = np.asarray(res_array, dtype=np.int32)

# Build a mask
mask = np.zeros_like(thresh_gray)
cv2.drawContours(mask, [smoothened], -1, 255, -1)

# For testig
test_im = cv2.cvtColor(thresh_gray, cv2.COLOR_GRAY2RGB)
cv2.drawContours(test_im, [smoothened], 0, (0, 255, 0), 1)

res = bk
res[(mask > 0)] = fg[(mask > 0)]

cv2.imshow('test_im', test_im)
cv2.imshow('res', res)
cv2.waitKey(0)
cv2.destroyAllWindows()


问:
Extract all values when I have key : value and store all value in an array
If I have an array,I want to extract each values in each line (values after (:) )

```<code>Array =
0:Object {node-input-audio_services1: "79388", audio_ip: "127.0.0.1", audio_port_1: "7654"}
1:Object {node-input-video_services1: "80788", video_ip: "127.0.0.1", video_port_1: "7654"}
2:Object {node-input-audio_services1: "4fe10"}
3:Object {node-input-video_services1: "4fe10"}
</code>```

Imagine I have several key : value then I want to extract Just value like bellow:

```<code>Array =
0:Object {key1 : "value" , Key2 : "value2" , key3: "value3"}
1:Object {key1 : "value5" , Key2 : "value6" , key3: "value7"}

</code>```

I have the result like this :

```<code>var result = ["value","value2",value3","value5","value6","value7"];
</code>```

The problem is, I can't use (key1.array) because each time in my program have one key's name.I really new in JavaScript and don't know how I can start

答:
```<code>var arr = [{ndeInput_audio_services1: "79388", audio_ip: "127.0.0.1", audio_port_1: "7654"},
           {nodeInput_video_services1: "80788", video_ip: "127.0.0.1", video_port_1: "7654"},
           {nodeInput_audio_services1: "4fe10"},
           {nodeInput_video_services1: "4fe10"}];
</code>```

If we have an array of objects like the ones you showed, I would use the underscore library and the .values() function that can be applied to an array. Here is an example (underscore is denoted by the _ symbol):

```<code>var result = [];

_.map(arr, obj => _.each(_.values(obj), val => result.push(val)));
</code>```

first, we create an empty array to store the result. Next we map through each object in the array. We then return the VALUE associated with each object in the array. We then push that value to the result array. The result will be all of the values associated with each key in the array:

```<code>console.log(result);

[
  '79388',     '127.0.0.1',
  '7654',      '80788',
  '127.0.0.1', '7654',
  '4fe10',     '4fe10'
]
</code>```

Body:
If I have an array,I want to extract each values in each line (values after (:) )

Array =
0:Object {node-input-audio_services1: "79388", audio_ip: "127.0.0.1", audio_port_1: "7654"}
1:Object {node-input-video_services1: "80788", video_ip: "127.0.0.1", video_port_1: "7654"}
2:Object {node-input-audio_services1: "4fe10"}
3:Object {node-input-video_services1: "4fe10"}

Imagine I have several key : value then I want to extract Just value like bellow:

Array =
0:Object {key1 : "value" , Key2 : "value2" , key3: "value3"}
1:Object {key1 : "value5" , Key2 : "value6" , key3: "value7"}

I have the result like this :

var result = ["value","value2",value3","value5","value6","value7"];

The problem is, I can't use (key1.array) because each time in my program have one key's name.I really new in JavaScript and don't know how I can start

Body:
var arr = [{ndeInput_audio_services1: "79388", audio_ip: "127.0.0.1", audio_port_1: "7654"},
           {nodeInput_video_services1: "80788", video_ip: "127.0.0.1", video_port_1: "7654"},
           {nodeInput_audio_services1: "4fe10"},
           {nodeInput_video_services1: "4fe10"}];

If we have an array of objects like the ones you showed, I would use the underscore library and the .values() function that can be applied to an array. Here is an example (underscore is denoted by the _ symbol):

var result = [];

_.map(arr, obj => _.each(_.values(obj), val => result.push(val)));

first, we create an empty array to store the result. Next we map through each object in the array. We then return the VALUE associated with each object in the array. We then push that value to the result array. The result will be all of the values associated with each key in the array:

console.log(result);

[
  '79388',     '127.0.0.1',
  '7654',      '80788',
  '127.0.0.1', '7654',
  '4fe10',     '4fe10'
]


问:
Add progress bar in flutter when open pdf file from url
I have a problem and I cannot solve it and I did not find a source to solve it on Google, I have a page where I view a PDF file through a link, and I have a CircularProgressIndicator and I want to replace it with a progress bar showing the percentage of downloading the file, can I do that?
I have attached my code</p>

```<code>import 'package:flutter/material.dart';
import 'package:flutter_plugin_pdf_viewer/flutter_plugin_pdf_viewer.dart';

class ReadPdf extends StatefulWidget {

  final String value;
  ReadPdf({Key key, this.value}) : super(key: key);

  @override
  _ReadPdfState createState() => _ReadPdfState();
}

class _ReadPdfState extends  State<ReadPdf>{
  bool _isloading = false, _isInit = true;
  PDFDocument document;

  @override
  void initState() {

    super.initState();

  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Color.fromRGBO(58, 66, 86, 1.0),
        body: Container(
          child: Column(
            children: <Widget>[
              Expanded(child:Center(
                child: _isInit?  MaterialButton(child: Text('Go'), onPressed: () {_loadFromURL(widget.value);},
                color: Color.fromRGBO(64, 75, 96, .9),
                textColor: Colors.white,
                ) : _isloading? Center(child: CircularProgressIndicator(),) : PDFViewer(document: document,indicatorBackground: Colors.deepPurple,),
              ),),
              Row(
                mainAxisSize: MainAxisSize.max,
                children: <Widget>[

                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  _loadFromURL(String url) async{
    setState(() {
      _isInit = false;
      _isloading = true;
    });
    document = await PDFDocument.fromURL('${url}');    setState(() {
      _isloading = false;
    });

  }

}
</code>```

答:
Never used this for pdf, but I've tried it for NetworkImage().
Not sure if it'll help. But you can just try it if there's a way to use loadingBuilder in your code.</p>

```<code>Image.network(
  imageUrl,
  fit: BoxFit.cover,
  loadingBuilder: (BuildContext context, Widget child,
      ImageChunkEvent loadingProgress) {
    if (loadingProgress == null)
      return child;
    else {
      return Center(
        child: CircularProgressIndicator(
          value: loadingProgress.expectedTotalBytes != null
              ? loadingProgress.cumulativeBytesLoaded /
                  loadingProgress.expectedTotalBytes
              : null,
        ),
      );
    }
  },
);
</code>```

Body:
I have a problem and I cannot solve it and I did not find a source to solve it on Google, I have a page where I view a PDF file through a link, and I have a CircularProgressIndicator and I want to replace it with a progress bar showing the percentage of downloading the file, can I do that?
I have attached my code

import 'package:flutter/material.dart';
import 'package:flutter_plugin_pdf_viewer/flutter_plugin_pdf_viewer.dart';

class ReadPdf extends StatefulWidget {

  final String value;
  ReadPdf({Key key, this.value}) : super(key: key);

  @override
  _ReadPdfState createState() => _ReadPdfState();
}

class _ReadPdfState extends  State<ReadPdf>{
  bool _isloading = false, _isInit = true;
  PDFDocument document;

  @override
  void initState() {

    super.initState();

  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        backgroundColor: Color.fromRGBO(58, 66, 86, 1.0),
        body: Container(
          child: Column(
            children: <Widget>[
              Expanded(child:Center(
                child: _isInit?  MaterialButton(child: Text('Go'), onPressed: () {_loadFromURL(widget.value);},
                color: Color.fromRGBO(64, 75, 96, .9),
                textColor: Colors.white,
                ) : _isloading? Center(child: CircularProgressIndicator(),) : PDFViewer(document: document,indicatorBackground: Colors.deepPurple,),
              ),),
              Row(
                mainAxisSize: MainAxisSize.max,
                children: <Widget>[

                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  _loadFromURL(String url) async{
    setState(() {
      _isInit = false;
      _isloading = true;
    });
    document = await PDFDocument.fromURL('${url}');    setState(() {
      _isloading = false;
    });

  }

}

Body:
Never used this for pdf, but I've tried it for NetworkImage().
Not sure if it'll help. But you can just try it if there's a way to use loadingBuilder in your code.

Image.network(
  imageUrl,
  fit: BoxFit.cover,
  loadingBuilder: (BuildContext context, Widget child,
      ImageChunkEvent loadingProgress) {
    if (loadingProgress == null)
      return child;
    else {
      return Center(
        child: CircularProgressIndicator(
          value: loadingProgress.expectedTotalBytes != null
              ? loadingProgress.cumulativeBytesLoaded /
                  loadingProgress.expectedTotalBytes
              : null,
        ),
      );
    }
  },
);


问:
Annoying messages while running copy-item to a PSSession
I am copying some files to a server, using PowerShell 5 with copy-item and new-PSSession. The relevant lines in my script are (or that's what I think):

```<code>  $session = New-PSSession -ComputerName $server -Credential $psCred ;
  Copy-Item $source -ToSession $session -Destination $target -Force;
</code>```

My real script has a few copy-item calls more. When this script runs, I see messages flicker in the PS Window. When I run it from command line, they are in text-mode with a powershell-blue background; when I run it from the ISE, they are GUIfied and shown as a textbox. They disappear quickly, but the look like "Copying" and the name of the currently copied file. So, they are progresss messages.

But I want a silent copy. I didn't consciously activate some debug flag. How can I suppress the progress messages?

I tried to append | Out-Null to the Copy-Item. I tried -InformationAction SilentlyIgnore. I looked at PSSessionOption, found nothing that might help. I tried to search the net, but everybody seems to be asking for MORE messages, not less.

答:
Per comment by @Bruce Payette:

Set $ProgressPreference = "SilentlyContinue" to suppress the progress display.

There are a bunch of other preference variables you can set as well: PowerShell Preference Variables

Body:
I am copying some files to a server, using PowerShell 5 with copy-item and new-PSSession. The relevant lines in my script are (or that's what I think):

  $session = New-PSSession -ComputerName $server -Credential $psCred ;
  Copy-Item $source -ToSession $session -Destination $target -Force;

My real script has a few copy-item calls more. When this script runs, I see messages flicker in the PS Window. When I run it from command line, they are in text-mode with a powershell-blue background; when I run it from the ISE, they are GUIfied and shown as a textbox. They disappear quickly, but the look like "Copying" and the name of the currently copied file. So, they are progresss messages.

But I want a silent copy. I didn't consciously activate some debug flag. How can I suppress the progress messages?

I tried to append | Out-Null to the Copy-Item. I tried -InformationAction SilentlyIgnore. I looked at PSSessionOption, found nothing that might help. I tried to search the net, but everybody seems to be asking for MORE messages, not less.


问:
counting sql rows , adding value of every row to the next
I have a two columns and I want to add the value of every row to the next row.
My table with two columns and 4 rows is like:

```<code>date           users
2011-01-01      1
2011-02-02      1
2011-03-02      2
2011-04-02      4
</code>```

and I want the users to be shown like below , and add every row to it's previous row value:

users:

```<code>1
2
4
8
</code>```

Is there a function in for MS SQL Server to do that?

thanks

答:
```<code>With cte_Test(Sequence,Name,Value)
As
(
select  ROW_NUMBER() OVER(ORDER BY value) as 'Sequence' ,name,value from test
)

select t1.Name,sum(T2.Value) AS Value from cte_Test t1
cross JOIN cte_Test t2 where t2.Sequence <= t1.Sequence
group BY t1.Name
order by 2
</code>```

Body:
I have a two columns and I want to add the value of every row to the next row.
My table with two columns and 4 rows is like:

date           users
2011-01-01      1
2011-02-02      1
2011-03-02      2
2011-04-02      4

and I want the users to be shown like below , and add every row to it's previous row value:

users:

1
2
4
8

Is there a function in for MS SQL Server to do that?

thanks


问:
Create a 10 minute running average of data with uneven time steps
I'm attempting to create a 10 minute running average of wind speeds in order to plot on a graph. My data has numerous uneven time steps within it. I am currently using the CSV module to read in and gather my data, I am not very familiar with pandas and have had issues in the past with it.

```<code>import matplotlib.pyplot as plt
import csv
from datetime import datetime

x=[]
y=[]

with open('KART_201901010000_201912310000.txt') as csvfile:
    plots = csv.reader(csvfile, delimiter=',')
    for row in plots:
        if 'M' == row[1]:
            continue
        else:
            x.append(datetime.strptime(row[0],'%Y-%m-%d %H:%M'))
            y.append(int(row[1]))

plt.plot(x,y, label='Wind Speed')
plt.xlabel('Date and Time')
plt.ylabel('Wind Speed (Kts)')
plt.title('Wind Speed\nVersus Time')
plt.legend()
plt.show()
</code>```

Here is a snippet of my data set showing one of the many uneven time steps.

```<code>2019-11-01 11:40,30
2019-11-01 11:45,35
2019-11-01 11:50,32
2019-11-01 11:55,34
2019-11-01 11:56,33
2019-11-01 12:00,33
2019-11-01 12:05,36
2019-11-01 12:10,31
</code>```

The obvious general idea is to use a for loop to continue the calculations that I would need to average the data. The issue I am running into is how do I account for the uneven steps? Is there a way to use datetime to achieve this that I have no idea about?

Body:
I'm attempting to create a 10 minute running average of wind speeds in order to plot on a graph. My data has numerous uneven time steps within it. I am currently using the CSV module to read in and gather my data, I am not very familiar with pandas and have had issues in the past with it.

import matplotlib.pyplot as plt
import csv
from datetime import datetime

x=[]
y=[]

with open('KART_201901010000_201912310000.txt') as csvfile:
    plots = csv.reader(csvfile, delimiter=',')
    for row in plots:
        if 'M' == row[1]:
            continue
        else:
            x.append(datetime.strptime(row[0],'%Y-%m-%d %H:%M'))
            y.append(int(row[1]))

plt.plot(x,y, label='Wind Speed')
plt.xlabel('Date and Time')
plt.ylabel('Wind Speed (Kts)')
plt.title('Wind Speed\nVersus Time')
plt.legend()
plt.show()

Here is a snippet of my data set showing one of the many uneven time steps.

2019-11-01 11:40,30
2019-11-01 11:45,35
2019-11-01 11:50,32
2019-11-01 11:55,34
2019-11-01 11:56,33
2019-11-01 12:00,33
2019-11-01 12:05,36
2019-11-01 12:10,31

The obvious general idea is to use a for loop to continue the calculations that I would need to average the data. The issue I am running into is how do I account for the uneven steps? Is there a way to use datetime to achieve this that I have no idea about?

Body:
Something along the lines of:

import pandas as pd
df = pd.read_csv('KART_201901010000_201912310000.txt', header=1)
df.index = pd.to_datetime(df.index, format='%Y-%m-%d %H:%M')
df.rolling('10min', min_periods=1).mean()

I haven't tested it, details might differ. I know you are not familiar with pandas but implementing this feature on your own will take precious time I'm sure you'd gladly invest elsewhere.

This definitely works for the data you provided:

>>> series = pd.Series([30, 35, 32, 34, 33, 33, 36, 31],
                    index=[pd.Timestamp('2019-11-01 11:40'),
                        pd.Timestamp('2019-11-01 11:45'),
                        pd.Timestamp('2019-11-01 11:50'),
                        pd.Timestamp('2019-11-01 11:55'),
                        pd.Timestamp('2019-11-01 11:56'),
                        pd.Timestamp('2019-11-01 12:00'),
                        pd.Timestamp('2019-11-01 12:05'),
                        pd.Timestamp('2019-11-01 12:10')])
>>> series.rolling('10min', min_periods=1).mean()
Out:
2019-11-01 11:40:00    30.000000
2019-11-01 11:45:00    32.500000
2019-11-01 11:50:00    33.500000
2019-11-01 11:55:00    33.000000
2019-11-01 11:56:00    33.000000
2019-11-01 12:00:00    33.333333
2019-11-01 12:05:00    34.000000
2019-11-01 12:10:00    33.500000
dtype: float64


问:
Java - Why is the whitespace being read in as a word?
I am attempting to read in a .txt file and print out the top twenty most common words and the top twenty least common words. However, whitespace appears as a word when it should not be counted as one. As I show in the Output, the whitespace appears as the second most common word, when it should not.
Here is my code.

```<code>public class WordFreqCount {

    public static void main(String[] args) throws IOException {

        HashMap<String, Integer> frequencyMap = new HashMap<String, Integer>();

        FileReader bookFile = new FileReader("book.txt");
        Scanner s = new Scanner(new FileReader("book.txt"));

        while(s.hasNext()) {
            String line = s.nextLine();
            line.trim();
            String[] words = line.split("\\W+");
            for (int i = 0; i < words.length; i ++) {

                if (frequencyMap.containsKey(words[i])) {
                    frequencyMap.replace(words[i], frequencyMap.get(words[i]) + 1);
                }
                else {
                    frequencyMap.put(words[i], 1);
                }
            }
        }
        s.close();

        List<Entry<String,Integer>> list = sortByValue(frequencyMap);

        System.out.println("Top 20 Most Appeared Words:");

        int counter1 = 1;
        List<Map.Entry<String, Integer>> topTwenty = list.subList(0, 20);
        for(Map.Entry<String, Integer> word : topTwenty) {
            System.out.println("(" + counter1 + "): " + word.getKey() + " --> " + word.getValue());
            counter1 += 1;
        }

        System.out.println();
        System.out.println("Top 20 Least Appeared Words:");

        int counter2 = 1;
        Collections.reverse(list);
        List<Map.Entry<String, Integer>> bottomTwenty = list.subList(0, 20);
        for(Map.Entry<String, Integer> word : bottomTwenty) {
            System.out.println("(" + counter2 + "): " + word.getKey() + " --> " + word.getValue());
            counter2 += 1;
        }
    }
}
</code>```

And the Output of my code is

```<code>(1): the --> 5426
(2):  --> 4986
(3): I --> 3038
(4): and --> 2887
(5): to --> 2788
(6): of --> 2733
(7): a --> 2595
(8): in --> 1747
(9): that --> 1664
(10): was --> 1393
(11): it --> 1303
(12): you --> 1283
(13): he --> 1168
(14): is --> 1131
(15): his --> 1103
(16): have --> 908
(17): my --> 907
(18): with --> 849
(19): had --> 821
(20): as --> 780

Top 20 Least Appeared Words:
(1): rival --> 1
(2): category --> 1
(3): arguments --> 1
(4): Bought --> 1
(5): billycock --> 1
(6): incoherent --> 1
(7): hail --> 1
(8): idle --> 1
(9): illustrious --> 1
(10): terminated --> 1
(11): Apaches --> 1
(12): topped --> 1
(13): laudanum --> 1
(14): filthy --> 1
(15): drama --> 1
(16): tune --> 1
(17): geology --> 1
(18): Mademoiselle --> 1
(19): balls --> 1
(20): Atkinson --> 1
</code>```

It was my understanding that using line.split("\W+") would parse the sentences to make sure nothing like whitespace, commas, etc. were counted in as words or within words. Am I missing something here?

A small portion of book.txt file

===========================================================================

```<code>almost no restrictions whatsoever.  You may copy it, give it away or
re-use it under the terms of the Project Gutenberg License included
with this eBook or online at www.gutenberg.net

Title: The Adventures of Sherlock Holmes

Author: Arthur Conan Doyle

Posting Date: April 18, 2011 [EBook #1661]
First Posted: November 29, 2002

Language: English

*** START OF THIS PROJECT GUTENBERG EBOOK THE ADVENTURES OF SHERLOCK HOLMES ***

Produced by an anonymous Project Gutenberg volunteer and Jose Menendez

THE ADVENTURES OF SHERLOCK HOLMES

by

SIR ARTHUR CONAN DOYLE

   I. A Scandal in Bohemia
  II. The Red-headed League
 III. A Case of Identity
  IV. The Boscombe Valley Mystery
   V. The Five Orange Pips
  VI. The Man with the Twisted Lip
 VII. The Adventure of the Blue Carbuncle
VIII. The Adventure of the Speckled Band
  IX. The Adventure of the Engineer's Thumb
   X. The Adventure of the Noble Bachelor
  XI. The Adventure of the Beryl Coronet
 XII. The Adventure of the Copper Beeches

ADVENTURE I. A SCANDAL IN BOHEMIA

I.

To Sherlock Holmes she is always THE woman. I have seldom heard
him mention her under any other name. In his eyes she eclipses
and predominates the whole of her sex. It was not that he felt
any emotion akin to love for Irene Adler. All emotions, and that
one particularly, were abhorrent to his cold, precise but
admirably balanced mind. He was, I take it, the most perfect
reasoning and observing machine that the world has seen, but as a
lover he would have placed himself in a false position. He never
spoke of the softer passions, save with a gibe and a sneer. They
were admirable things for the observer--excellent for drawing the
veil from men's motives and actions. But for the trained reasoner
to admit such intrusions into his own delicate and finely
adjusted temperament was to introduce a distracting factor which
might throw a doubt upon all his mental results. Grit in a
sensitive instrument, or a crack in one of his own high-power
lenses, would not be more disturbing than a strong emotion in a
nature such as his. And yet there was but one woman to him, and
that woman was the late Irene Adler, of dubious and questionable
memory.

I had seen little of Holmes lately. My marriage had drifted us
away from each other. My own complete happiness, and the
home-centred interests which rise up around the man who first
finds himself master of his own establishment, were sufficient to
absorb all my attention, while Holmes, who loathed every form of
society with his whole Bohemian soul, remained in our lodgings in
Baker Street, buried among his old books, and alternating from
week to week between cocaine and ambition, the drowsiness of the
drug, and the fierce energy of his own keen nature. He was still,
as ever, deeply attracted by the study of crime, and occupied his
immense faculties and extraordinary powers of observation in
following out those clues, and clearing up those mysteries which
had been abandoned as hopeless by the official police. From time
to time I heard some vague account of his doings: of his summons
to Odessa in the case of the Trepoff murder, of his clearing up
of the singular tragedy of the Atkinson brothers at Trincomalee,
and finally of the mission which he had accomplished so
delicately and successfully for the reigning family of Holland.
Beyond these signs of his activity, however, which I merely
shared with all the readers of the daily press, I knew little of
my former friend and companion.```

```

答:
I suppose the point here is that your're not doing trim in fact. This construction

```<code>line.trim();
</code>```

doesn't actually trims a string, it returns a new trimmed one. Strings are immutable in java. You should do something like that

```<code>String line = s.nextLine().trim();
</code>```

in order to make it work.

Body:
I am attempting to read in a .txt file and print out the top twenty most common words and the top twenty least common words. However, whitespace appears as a word when it should not be counted as one. As I show in the Output, the whitespace appears as the second most common word, when it should not.
Here is my code.

public class WordFreqCount {

    public static void main(String[] args) throws IOException {

        HashMap<String, Integer> frequencyMap = new HashMap<String, Integer>();

        FileReader bookFile = new FileReader("book.txt");
        Scanner s = new Scanner(new FileReader("book.txt"));

        while(s.hasNext()) {
            String line = s.nextLine();
            line.trim();
            String[] words = line.split("\\W+");
            for (int i = 0; i < words.length; i ++) {

                if (frequencyMap.containsKey(words[i])) {
                    frequencyMap.replace(words[i], frequencyMap.get(words[i]) + 1);
                }
                else {
                    frequencyMap.put(words[i], 1);
                }
            }
        }
        s.close();

        List<Entry<String,Integer>> list = sortByValue(frequencyMap);

        System.out.println("Top 20 Most Appeared Words:");

        int counter1 = 1;
        List<Map.Entry<String, Integer>> topTwenty = list.subList(0, 20);
        for(Map.Entry<String, Integer> word : topTwenty) {
            System.out.println("(" + counter1 + "): " + word.getKey() + " --> " + word.getValue());
            counter1 += 1;
        }

        System.out.println();
        System.out.println("Top 20 Least Appeared Words:");

        int counter2 = 1;
        Collections.reverse(list);
        List<Map.Entry<String, Integer>> bottomTwenty = list.subList(0, 20);
        for(Map.Entry<String, Integer> word : bottomTwenty) {
            System.out.println("(" + counter2 + "): " + word.getKey() + " --> " + word.getValue());
            counter2 += 1;
        }
    }
}

And the Output of my code is

(1): the --> 5426
(2):  --> 4986
(3): I --> 3038
(4): and --> 2887
(5): to --> 2788
(6): of --> 2733
(7): a --> 2595
(8): in --> 1747
(9): that --> 1664
(10): was --> 1393
(11): it --> 1303
(12): you --> 1283
(13): he --> 1168
(14): is --> 1131
(15): his --> 1103
(16): have --> 908
(17): my --> 907
(18): with --> 849
(19): had --> 821
(20): as --> 780

Top 20 Least Appeared Words:
(1): rival --> 1
(2): category --> 1
(3): arguments --> 1
(4): Bought --> 1
(5): billycock --> 1
(6): incoherent --> 1
(7): hail --> 1
(8): idle --> 1
(9): illustrious --> 1
(10): terminated --> 1
(11): Apaches --> 1
(12): topped --> 1
(13): laudanum --> 1
(14): filthy --> 1
(15): drama --> 1
(16): tune --> 1
(17): geology --> 1
(18): Mademoiselle --> 1
(19): balls --> 1
(20): Atkinson --> 1

It was my understanding that using line.split("\W+") would parse the sentences to make sure nothing like whitespace, commas, etc. were counted in as words or within words. Am I missing something here?

A small portion of book.txt file

===========================================================================

almost no restrictions whatsoever.  You may copy it, give it away or
re-use it under the terms of the Project Gutenberg License included
with this eBook or online at www.gutenberg.net

Title: The Adventures of Sherlock Holmes

Author: Arthur Conan Doyle

Posting Date: April 18, 2011 [EBook #1661]
First Posted: November 29, 2002

Language: English

*** START OF THIS PROJECT GUTENBERG EBOOK THE ADVENTURES OF SHERLOCK HOLMES ***

Produced by an anonymous Project Gutenberg volunteer and Jose Menendez

THE ADVENTURES OF SHERLOCK HOLMES

by

SIR ARTHUR CONAN DOYLE

   I. A Scandal in Bohemia
  II. The Red-headed League
 III. A Case of Identity
  IV. The Boscombe Valley Mystery
   V. The Five Orange Pips
  VI. The Man with the Twisted Lip
 VII. The Adventure of the Blue Carbuncle
VIII. The Adventure of the Speckled Band
  IX. The Adventure of the Engineer's Thumb
   X. The Adventure of the Noble Bachelor
  XI. The Adventure of the Beryl Coronet
 XII. The Adventure of the Copper Beeches

ADVENTURE I. A SCANDAL IN BOHEMIA

I.

To Sherlock Holmes she is always THE woman. I have seldom heard
him mention her under any other name. In his eyes she eclipses
and predominates the whole of her sex. It was not that he felt
any emotion akin to love for Irene Adler. All emotions, and that
one particularly, were abhorrent to his cold, precise but
admirably balanced mind. He was, I take it, the most perfect
reasoning and observing machine that the world has seen, but as a
lover he would have placed himself in a false position. He never
spoke of the softer passions, save with a gibe and a sneer. They
were admirable things for the observer--excellent for drawing the
veil from men's motives and actions. But for the trained reasoner
to admit such intrusions into his own delicate and finely
adjusted temperament was to introduce a distracting factor which
might throw a doubt upon all his mental results. Grit in a
sensitive instrument, or a crack in one of his own high-power
lenses, would not be more disturbing than a strong emotion in a
nature such as his. And yet there was but one woman to him, and
that woman was the late Irene Adler, of dubious and questionable
memory.

I had seen little of Holmes lately. My marriage had drifted us
away from each other. My own complete happiness, and the
home-centred interests which rise up around the man who first
finds himself master of his own establishment, were sufficient to
absorb all my attention, while Holmes, who loathed every form of
society with his whole Bohemian soul, remained in our lodgings in
Baker Street, buried among his old books, and alternating from
week to week between cocaine and ambition, the drowsiness of the
drug, and the fierce energy of his own keen nature. He was still,
as ever, deeply attracted by the study of crime, and occupied his
immense faculties and extraordinary powers of observation in
following out those clues, and clearing up those mysteries which
had been abandoned as hopeless by the official police. From time
to time I heard some vague account of his doings: of his summons
to Odessa in the case of the Trepoff murder, of his clearing up
of the singular tragedy of the Atkinson brothers at Trincomalee,
and finally of the mission which he had accomplished so
delicately and successfully for the reigning family of Holland.
Beyond these signs of his activity, however, which I merely
shared with all the readers of the daily press, I knew little of
my former friend and companion.```

Body:
I suppose the point here is that your're not doing trim in fact. This construction

line.trim();

doesn't actually trims a string, it returns a new trimmed one. Strings are immutable in java. You should do something like that

String line = s.nextLine().trim();

in order to make it work.


问:
Taylor series expansion in maxima
How to expand taylor series/polynomials about Q=0 , and then extract coefficients as a list

example :

```<code>taylor ( (sin(q)), q, 0, 9); //taylor expansion for first 9 terms gives the next line

(%o1)/T/    q\-q^3/6+q^5/120\-q^7/5040+q^9/362880+...
</code>```

then using coeff ((%o1), q ^n); gives me the coefficient at n only, what i want is a list for all the coefficients of that expression

答: Try coeff plus makelist, e.g. something like: makelist(coeff(%o1, q, n), n, 0, 9);

Title: Taylor series expansion in maxima

Body:
How to expand taylor series/polynomials about Q=0 , and then extract coefficients as a list

example :

taylor ( (sin(q)), q, 0, 9); //taylor expansion for first 9 terms gives the next line

(%o1)/T/    q\-q^3/6+q^5/120\-q^7/5040+q^9/362880+...

then using coeff ((%o1), q ^n); gives me the coefficient at n only, what i want is a list for all the coefficients of that expression


问:
In shellscript, how to add +1 to a particular digit in a string
I have a set of many back-to-back systems, each named like m2001-1 which connects to s3001-1 and so on. here's a few for example: m2002-2 connects to s3002-2, m2003-3 connects to s3003-3, m2008-8 connects to s3008-8 (hope you can see the pattern, the m2/s3 is all that changes. m2* system doing the work, s3* is the system collecting the results)
I would like to figure out a way in bash shell-script to look at my current hostname (for example m2005-5) and +1 to the 2nd digit so that the script can figure out it's partner. I'm guessing some linux-foo sed/awk will be needed.
P.S. I realized after posting this that I would have to still change the letter... so I am thankful that the suggested solution works so easily to do both the numeric and letter change.</p>

答:
Use the string replacement operator in parameter expansion</p>

```<code>worker=m2002-2
collector=${worker/m2/s3}
echo "$collector"
</code>```

Body:
Use the string replacement operator in parameter expansion

worker=m2002-2
collector=${worker/m2/s3}
echo "$collector"


问:
jquery dialog button to do the same as asp.net mvc submit button
I have tried to figure out a way of letting a jquery dialog button called Create do the same as an asp.net submit button.

```<code><input type="submit" value="Create" />
</code>```

I am using jquery 1.3.2

I have come up with the following to let the dialog use the correct controller method.

```<code>       var url = '<%= Url.Action("Create1", "Home") %>';
       $.post(url,data,
                            function(data) {
                                alert("Successful. Id for this client is " + data.ClientNo);
                                $("#CreateForm input").attr("value", ""); // Success
                            },
                            "json"); // DataType
</code>```

However, the method requires a model parameter

```<code>    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create1(ClientDetail client)
</code>```

Looking at http://api.jquery.com/jQuery.post/ data parameter is a map or string sent to the server

I am wondering is it possible to convert a model into a map or string possibly using the .attr method?

Thank you

答:
See http://api.jquery.com/submit/

```<code><form id="target" action="destination.html">
  <input type="text" value="Hello there" />
  <input type="submit" value="Go" />
</form>
<div id="other">
  Trigger the handler
</div>
</code>```

Jquery function:

```<code>$('#other').click(function() {
  $('#target').submit();
});
</code>```

Body:
I have tried to figure out a way of letting a jquery dialog button called Create do the same as an asp.net submit button.

<input type="submit" value="Create" />

I am using jquery 1.3.2

I have come up with the following to let the dialog use the correct controller method.

       var url = '<%= Url.Action("Create1", "Home") %>';
       $.post(url,data,
                            function(data) {
                                alert("Successful. Id for this client is " + data.ClientNo);
                                $("#CreateForm input").attr("value", ""); // Success
                            },
                            "json"); // DataType

However, the method requires a model parameter

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create1(ClientDetail client)

Looking at http://api.jquery.com/jQuery.post/ data parameter is a map or string sent to the server

I am wondering is it possible to convert a model into a map or string possibly using the .attr method?

Thank you

Body:
See http://api.jquery.com/submit/

<form id="target" action="destination.html">
  <input type="text" value="Hello there" />
  <input type="submit" value="Go" />
</form>
<div id="other">
  Trigger the handler
</div>

Jquery function:

$('#other').click(function() {
  $('#target').submit();
});


问:
ValueError: cannot infer type for <class 'NoneType'> - Flask, sqlite
I'm trying to upload a dataframe to sqlite database which has no problem unless I add the 'quarters' column.

```<code>df['quarters'] = pd.PeriodIndex(pd.df(empres_df.date), freq='Q')
df.to_sql("table_name", con, if_exists="append")
</code>```

Because when I do, it gives me this error:

```<code>Traceback (most recent call last):
  File "/opt/anaconda3/lib/python3.7/site-packages/flask/app.py", line 2446, in wsgi_app
    response = self.full_dispatch_request()
  File "/opt/anaconda3/lib/python3.7/site-packages/flask/app.py", line 1951, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/opt/anaconda3/lib/python3.7/site-packages/flask/app.py", line 1820, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/opt/anaconda3/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/opt/anaconda3/lib/python3.7/site-packages/flask/app.py", line 1949, in full_dispatch_request
    rv = self.dispatch_request()
  File "/opt/anaconda3/lib/python3.7/site-packages/flask/app.py", line 1935, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/Users/mkhumtai/Desktop/IndividualProject/avian/app/views.py", line 145, in import_data
    empres_df.to_sql("empres", con, if_exists="append")
  File "/opt/anaconda3/lib/python3.7/site-packages/pandas/core/generic.py", line 2712, in to_sql
    method=method,
  File "/opt/anaconda3/lib/python3.7/site-packages/pandas/io/sql.py", line 518, in to_sql
    method=method,
  File "/opt/anaconda3/lib/python3.7/site-packages/pandas/io/sql.py", line 1747, in to_sql
    dtype=dtype,
  File "/opt/anaconda3/lib/python3.7/site-packages/pandas/io/sql.py", line 1440, in __init__
    super().__init__(*args, **kwargs)
  File "/opt/anaconda3/lib/python3.7/site-packages/pandas/io/sql.py", line 619, in __init__
    self.table = self._create_table_setup()
  File "/opt/anaconda3/lib/python3.7/site-packages/pandas/io/sql.py", line 1476, in _create_table_setup
    column_names_and_types = self._get_column_names_and_types(self._sql_type_name)
  File "/opt/anaconda3/lib/python3.7/site-packages/pandas/io/sql.py", line 860, in _get_column_names_and_types
    for i in range(len(self.frame.columns))
  File "/opt/anaconda3/lib/python3.7/site-packages/pandas/io/sql.py", line 860, in <listcomp>
    for i in range(len(self.frame.columns))
  File "/opt/anaconda3/lib/python3.7/site-packages/pandas/io/sql.py", line 1532, in _sql_type_name
    col_type = lib.infer_dtype(col, skipna=True)
  File "pandas/_libs/lib.pyx", line 1246, in pandas._libs.lib.infer_dtype
ValueError: cannot infer type for <class 'NoneType'>
</code>```

Adding the 'quarters' column to the dataframe itself doesn't give an error as long as I don't include that column to the database.

How do I fix this?

答:
Just wanted to update,

I fixed the issue by adding

```<code>df['quarters'] = pd.PeriodIndex(pd.df(empres_df.date), freq='Q').astype(str)
</code>```

As it seems that the database doesn't recognise the column type

Body:
I'm trying to upload a dataframe to sqlite database which has no problem unless I add the 'quarters' column.

df['quarters'] = pd.PeriodIndex(pd.df(empres_df.date), freq='Q')
df.to_sql("table_name", con, if_exists="append")

Because when I do, it gives me this error:

Traceback (most recent call last):
  File "/opt/anaconda3/lib/python3.7/site-packages/flask/app.py", line 2446, in wsgi_app
    response = self.full_dispatch_request()
  File "/opt/anaconda3/lib/python3.7/site-packages/flask/app.py", line 1951, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/opt/anaconda3/lib/python3.7/site-packages/flask/app.py", line 1820, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/opt/anaconda3/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/opt/anaconda3/lib/python3.7/site-packages/flask/app.py", line 1949, in full_dispatch_request
    rv = self.dispatch_request()
  File "/opt/anaconda3/lib/python3.7/site-packages/flask/app.py", line 1935, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/Users/mkhumtai/Desktop/IndividualProject/avian/app/views.py", line 145, in import_data
    empres_df.to_sql("empres", con, if_exists="append")
  File "/opt/anaconda3/lib/python3.7/site-packages/pandas/core/generic.py", line 2712, in to_sql
    method=method,
  File "/opt/anaconda3/lib/python3.7/site-packages/pandas/io/sql.py", line 518, in to_sql
    method=method,
  File "/opt/anaconda3/lib/python3.7/site-packages/pandas/io/sql.py", line 1747, in to_sql
    dtype=dtype,
  File "/opt/anaconda3/lib/python3.7/site-packages/pandas/io/sql.py", line 1440, in __init__
    super().__init__(*args, **kwargs)
  File "/opt/anaconda3/lib/python3.7/site-packages/pandas/io/sql.py", line 619, in __init__
    self.table = self._create_table_setup()
  File "/opt/anaconda3/lib/python3.7/site-packages/pandas/io/sql.py", line 1476, in _create_table_setup
    column_names_and_types = self._get_column_names_and_types(self._sql_type_name)
  File "/opt/anaconda3/lib/python3.7/site-packages/pandas/io/sql.py", line 860, in _get_column_names_and_types
    for i in range(len(self.frame.columns))
  File "/opt/anaconda3/lib/python3.7/site-packages/pandas/io/sql.py", line 860, in <listcomp>
    for i in range(len(self.frame.columns))
  File "/opt/anaconda3/lib/python3.7/site-packages/pandas/io/sql.py", line 1532, in _sql_type_name
    col_type = lib.infer_dtype(col, skipna=True)
  File "pandas/_libs/lib.pyx", line 1246, in pandas._libs.lib.infer_dtype
ValueError: cannot infer type for <class 'NoneType'>

Adding the 'quarters' column to the dataframe itself doesn't give an error as long as I don't include that column to the database.

How do I fix this?

Body:
Just wanted to update,

I fixed the issue by adding

df['quarters'] = pd.PeriodIndex(pd.df(empres_df.date), freq='Q').astype(str)

As it seems that the database doesn't recognise the column type


问:
How can we create multiple PDF files using different win32com instances?
I have been trying to create multiple pdf files using DispatchEx but when I try to test my code, it creates only first pdf file while all other requests fail with strange errors. What am I doing wrong and/or how can I effectively handle multiple clients calls simultaneously to generate their respective pdf files they request?

Here is that part of my code:

```<code>            rundate = "Quote_{:%d%m%Y_%H%M%S%f}".format(datetime.now())
            pythoncom.CoInitialize()
            FILENAME = "D:/packages/abc.pptx"
            APPLICATION = win32com.client.DispatchEx("PowerPoint.Application")
            APPLICATION.Visible = True
            path_ppt = shutil.copy(FILENAME, "D:/{0}.pptx".format(rundate))
            PRESENTATION = APPLICATION.Presentations.Open(path_ppt)
            Slide1 = PRESENTATION.Slides(1)
            Shape1 = Slide1.Shapes(1)
            print(Shape1.AlternativeText)
            for shape in Slide1.Shapes:
                if shape.AlternativeText:
                    print(shape.AlternativeText)
                if shape.HasTextFrame:
                    shape.TextFrame.TextRange.Replace(FindWhat="#abc",ReplaceWhat="THAILAND", WholeWords=False)
                if shape.AlternativeText == "1":
                    shape.Fill.UserPicture("D:/1.jpg")
                if shape.AlternativeText == "2":
                    shape.Fill.UserPicture("D:/2.jpg")
                if shape.AlternativeText == "3":
                    shape.Fill.UserPicture("D:/3.jpg")
            PATH_TO_PDF = "{0}{1}{2}".format(r'd:/',rundate,'.pdf')
            PRESENTATION.SaveAs(PATH_TO_PDF, 32)
            APPLICATION.Quit()
            PRESENTATION.Close()
            PRESENTATION =  None
            APPLICATION = None
            os.remove(path_ppt)
</code>```

PS - The code successfully creates as many ppt copies (using shutil) as requests sent to it, but the win32com gives error when multiple requests are made in short interval of time, like shape.AlternativeText not found, object does not exist etc.

答:
You may be able to solve the APPLICATION exit problem by running this code in a separate process. (Ignoring the risk of using a hard coded file name when simultaneous calls).

Create another module in your project package

powerpointer.py

```<code>import shutil
import sys
import subprocess as subp

def do_powerpoint(filename):
   """run external copy of self to do powerpoint stuff"""
   # sys.executable is the python.exe you are using, __file__ is the
   # path to this module's source and filename you pass in
   return subp.call([sys.executable, __file__, filename])

def _do_powerpoint(filename):
    rundate = "Quote_{:%d%m%Y_%H%M%S%f}".format(datetime.now())
    pythoncom.CoInitialize()
    APPLICATION = win32com.client.DispatchEx("PowerPoint.Application")
    APPLICATION.Visible = True # I think False is better so you dont see it pop up
    path_ppt = shutil.copy(filename, "D:/{0}.pptx".format(rundate))
    PRESENTATION = APPLICATION.Presentations.Open(path_ppt)
    Slide1 = PRESENTATION.Slides(1)
    Shape1 = Slide1.Shapes(1)
    print(Shape1.AlternativeText)
    for shape in Slide1.Shapes:
        if shape.AlternativeText:
            print(shape.AlternativeText)
        if shape.HasTextFrame:
            shape.TextFrame.TextRange.Replace(FindWhat="#abc",ReplaceWhat="THAILAND", WholeWords=False)
        if shape.AlternativeText == "1":
            shape.Fill.UserPicture("D:/1.jpg")
        if shape.AlternativeText == "2":
            shape.Fill.UserPicture("D:/2.jpg")
        if shape.AlternativeText == "3":
            shape.Fill.UserPicture("D:/3.jpg")
    PATH_TO_PDF = "{0}{1}{2}".format(r'd:/',rundate,'.pdf')
    PRESENTATION.SaveAs(PATH_TO_PDF, 32)
    PRESENTATION.Close()
    APPLICATION.Quit()
    os.remove(path_ppt)

if __name__ == "__main__":
    _do_powerpoint(sys.argv[1]) # will raise error if no parameters
</code>```

Now, in your main code, import powerpointer and call powerpointer.do_powerpoint(filename) as needed. It will run its own module as a script and you will only have 1 application object in that instance.

Body:
I have been trying to create multiple pdf files using DispatchEx but when I try to test my code, it creates only first pdf file while all other requests fail with strange errors. What am I doing wrong and/or how can I effectively handle multiple clients calls simultaneously to generate their respective pdf files they request?

Here is that part of my code:

            rundate = "Quote_{:%d%m%Y_%H%M%S%f}".format(datetime.now())
            pythoncom.CoInitialize()
            FILENAME = "D:/packages/abc.pptx"
            APPLICATION = win32com.client.DispatchEx("PowerPoint.Application")
            APPLICATION.Visible = True
            path_ppt = shutil.copy(FILENAME, "D:/{0}.pptx".format(rundate))
            PRESENTATION = APPLICATION.Presentations.Open(path_ppt)
            Slide1 = PRESENTATION.Slides(1)
            Shape1 = Slide1.Shapes(1)
            print(Shape1.AlternativeText)
            for shape in Slide1.Shapes:
                if shape.AlternativeText:
                    print(shape.AlternativeText)
                if shape.HasTextFrame:
                    shape.TextFrame.TextRange.Replace(FindWhat="#abc",ReplaceWhat="THAILAND", WholeWords=False)
                if shape.AlternativeText == "1":
                    shape.Fill.UserPicture("D:/1.jpg")
                if shape.AlternativeText == "2":
                    shape.Fill.UserPicture("D:/2.jpg")
                if shape.AlternativeText == "3":
                    shape.Fill.UserPicture("D:/3.jpg")
            PATH_TO_PDF = "{0}{1}{2}".format(r'd:/',rundate,'.pdf')
            PRESENTATION.SaveAs(PATH_TO_PDF, 32)
            APPLICATION.Quit()
            PRESENTATION.Close()
            PRESENTATION =  None
            APPLICATION = None
            os.remove(path_ppt)

PS - The code successfully creates as many ppt copies (using shutil) as requests sent to it, but the win32com gives error when multiple requests are made in short interval of time, like shape.AlternativeText not found, object does not exist etc.

Body:
You may be able to solve the APPLICATION exit problem by running this code in a separate process. (Ignoring the risk of using a hard coded file name when simultaneous calls).

Create another module in your project package

powerpointer.py

import shutil
import sys
import subprocess as subp

def do_powerpoint(filename):
   """run external copy of self to do powerpoint stuff"""
   # sys.executable is the python.exe you are using, __file__ is the
   # path to this module's source and filename you pass in
   return subp.call([sys.executable, __file__, filename])

def _do_powerpoint(filename):
    rundate = "Quote_{:%d%m%Y_%H%M%S%f}".format(datetime.now())
    pythoncom.CoInitialize()
    APPLICATION = win32com.client.DispatchEx("PowerPoint.Application")
    APPLICATION.Visible = True # I think False is better so you dont see it pop up
    path_ppt = shutil.copy(filename, "D:/{0}.pptx".format(rundate))
    PRESENTATION = APPLICATION.Presentations.Open(path_ppt)
    Slide1 = PRESENTATION.Slides(1)
    Shape1 = Slide1.Shapes(1)
    print(Shape1.AlternativeText)
    for shape in Slide1.Shapes:
        if shape.AlternativeText:
            print(shape.AlternativeText)
        if shape.HasTextFrame:
            shape.TextFrame.TextRange.Replace(FindWhat="#abc",ReplaceWhat="THAILAND", WholeWords=False)
        if shape.AlternativeText == "1":
            shape.Fill.UserPicture("D:/1.jpg")
        if shape.AlternativeText == "2":
            shape.Fill.UserPicture("D:/2.jpg")
        if shape.AlternativeText == "3":
            shape.Fill.UserPicture("D:/3.jpg")
    PATH_TO_PDF = "{0}{1}{2}".format(r'd:/',rundate,'.pdf')
    PRESENTATION.SaveAs(PATH_TO_PDF, 32)
    PRESENTATION.Close()
    APPLICATION.Quit()
    os.remove(path_ppt)

if __name__ == "__main__":
    _do_powerpoint(sys.argv[1]) # will raise error if no parameters

Now, in your main code, import powerpointer and call powerpointer.do_powerpoint(filename) as needed. It will run its own module as a script and you will only have 1 application object in that instance.