问:
How to Stop Duplicating items in java combo box
well I am making a POS system for a stationary shop, the client need to enter the photocopy sales details to his system so what I did was I entered the paper format size color and price respectively to MySQL database. for example

A4 single side B/W $1
A4 double side B/w $2
A4 single side color $3
A4 double color $4

now the problem is when I a populate the combo box with a column the data will be duplicated

for example
A4
A4
A4
A4

that is because I entered 4 times the A4 to database,what I need to do is when I click the combo box I should only show 1 A4

I connected the combo box with database

```<code>   try {

        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/photocopy","root","");

        String sql="SELECT * FROM `prices`";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        ResultSet rs =pstmt.executeQuery();

        while(rs.next()){

        String pathayo = rs.getString("color");

        jComboBox3.addItem(pathayo);

        }

    } catch (Exception e) {
    }
</code>```

I need to show only A4 once not 4 times

check this images plz

check this images plz

答:
Here is root cause. You have 4 columns, however, you retrieve only 1 column 4 times.  Use below as example.

while (rs.next()) {
            String coffeeName = rs.getString("COF_NAME");
            int supplierID = rs.getInt("SUP_ID");
            float price = rs.getFloat("PRICE");
        }
```

<p>In your case, fixing is very simple:</p>

<pre class="lang-java prettyprint-override"><code>String pathayo = null;
while(rs.next()){
   pathayo = rs.getString("color");
}
if(pathayo != null) jComboBox3.addItem(pathayo);
</code>```

Body:
well I am making a POS system for a stationary shop, the client need to enter the photocopy sales details to his system so what I did was I entered the paper format size color and price respectively to MySQL database. for example

A4 single side B/W $1
A4 double side B/w $2
A4 single side color $3
A4 double color $4

now the problem is when I a populate the combo box with a column the data will be duplicated

for example
A4
A4
A4
A4

that is because I entered 4 times the A4 to database,what I need to do is when I click the combo box I should only show 1 A4

I connected the combo box with database

   try {

        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/photocopy","root","");

        String sql="SELECT * FROM `prices`";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        ResultSet rs =pstmt.executeQuery();

        while(rs.next()){

        String pathayo = rs.getString("color");

        jComboBox3.addItem(pathayo);

        }

    } catch (Exception e) {
    }

I need to show only A4 once not 4 times

check this images plz

check this images plz

Body:
Here is root cause. You have 4 columns, however, you retrieve only 1 column 4 times.  Use below as example.

while (rs.next()) {
            String coffeeName = rs.getString("COF_NAME");
            int supplierID = rs.getInt("SUP_ID");
            float price = rs.getFloat("PRICE");
        }

In your case, fixing is very simple:

String pathayo = null;
while(rs.next()){
   pathayo = rs.getString("color");
}
if(pathayo != null) jComboBox3.addItem(pathayo);


来源: stackexchange

问:
How to list files that can be imported from within cypher-shell?
How can I run common Terminal commands (or equivalent command) such as ls for listing importable files from within Cypher-shell?

答: cypher-shell just provides a way to execute Cypher queries from the command line.  It is not a general-purpose shell, like say bash, and does not provide any way to directly access the filesystem.

ContentLicense: CC BY-SA 4.0


问:
Validate number as a UK mobile number only using libphonenumber-for-php
I am using libphonenumber-for-php to write a validation class that will check if a number is a UK mobile number. Anything else will fail.

```<code>public function validate(){
    $phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();
    $carrierMapper = \libphonenumber\PhoneNumberToCarrierMapper::getInstance();

    foreach ($this->phoneNumbers as $number){
        try {
            $phoneNumberObject = $phoneUtil->parse($number, 'GB');
        }catch (NumberParseException $e){
            echo $e;
        }

        $valid = $phoneUtil->isValidNumber($phoneNumberObject);
        $type = $phoneUtil->getNumberType($phoneNumberObject);
        $carrier = $carrierMapper->getNameForNumber($phoneNumberObject, 'en');
    }
}
</code>```

Is this all that is required? I check if it is a valid number then check if it is of the mobile number type. Is there anything else I should do to be 100% certain the passed in number is a Valid UK mobile number?

答: I think the method for getting a carrier is getDescriptionForNumber. I am not a complete PHP programmer, but I use this library in Python and C and then I got the same error because of that method. </p>

Body:
I am using libphonenumber-for-php to write a validation class that will check if a number is a UK mobile number. Anything else will fail.

public function validate(){
    $phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();
    $carrierMapper = \libphonenumber\PhoneNumberToCarrierMapper::getInstance();

    foreach ($this->phoneNumbers as $number){
        try {
            $phoneNumberObject = $phoneUtil->parse($number, 'GB');
        }catch (NumberParseException $e){
            echo $e;
        }

        $valid = $phoneUtil->isValidNumber($phoneNumberObject);
        $type = $phoneUtil->getNumberType($phoneNumberObject);
        $carrier = $carrierMapper->getNameForNumber($phoneNumberObject, 'en');
    }
}

Is this all that is required? I check if it is a valid number then check if it is of the mobile number type. Is there anything else I should do to be 100% certain the passed in number is a Valid UK mobile number?


问:
Is there a way to filter a mongo database by the number of occurrences of specific value?
For example if I have a database like

```<code>Number OtherStuff
1      stuff
2      stuffalso
1      morestuff
1      otherstuff
2      stuff2
3      stuff3
4      stuff4
</code>```

is there a way to get back just those entries matching 'Number' < 4 and there are more than 2 instances? So in this case just those with 'Number' == 1 since there are 3 of them.

Something like db.find({Number: {$lt: 4}, somethingelsehere})

答:
You can run $match to check if Number is less than 4 and then run $group to check how many instances each group has. You can also run $unwind and $replaceRoot to get back original shape of your data:

```<code>db.col.aggregate([
    { $match: { Number: { $lt: 4 } } },
    {
        $group: {
            _id: "$Number",
            documents: { $push: "$$ROOT" },
            count: { $sum: 1 }
        }
    },
    {
        $match: { count: { $gt: 2 } }
    },
    {
        $unwind: "$documents"
    },
    {
        $replaceRoot: { newRoot: "$documents" }
    }
])
</code>```

Body:
For example if I have a database like

Number OtherStuff
1      stuff
2      stuffalso
1      morestuff
1      otherstuff
2      stuff2
3      stuff3
4      stuff4

is there a way to get back just those entries matching 'Number' < 4 and there are more than 2 instances? So in this case just those with 'Number' == 1 since there are 3 of them.

Something like db.find({Number: {$lt: 4}, somethingelsehere})

Body:
You can run $match to check if Number is less than 4 and then run $group to check how many instances each group has. You can also run $unwind and $replaceRoot to get back original shape of your data:

db.col.aggregate([
    { $match: { Number: { $lt: 4 } } },
    {
        $group: {
            _id: "$Number",
            documents: { $push: "$$ROOT" },
            count: { $sum: 1 }
        }
    },
    {
        $match: { count: { $gt: 2 } }
    },
    {
        $unwind: "$documents"
    },
    {
        $replaceRoot: { newRoot: "$documents" }
    }
])


问:
What happens if I do not delete a dynamically created variable?
I am a beginner in C++.I was wondering what will happen if I do not delete memory
allocated using new operator.Why is it considered a bad practice?I have heard that even if I do not free dynamically allocated memory the OS will free it sooner or later.Can this practice crash the application or cause any bugs or is
it just discouraged?</p>
```<code>#include <iostream>
using namespace std;
int main()
{
   int* arr = new int[10];

   arr = new int[5];//initializing again with new
}
</code>```

答:
It is definitely a memory leak and a very very very bad practice.

First, you don't want to take system resource like memory, abandon it but not release it.

Second, your code works because you are only creating memory leak of 10 integers. If it was a commercial application and this bug was in code or many parts of the code and it gets executed over and over, it could cause a nasty un-deterministic crashes.

You can simulate this by wrapping your code in large loop like 10k iterations. Try it without deleting the memory and than with deleting it. You will see the difference. The one without deleting will crash at some point when the memory is exhausted.

Body:
I am a beginner in C++.I was wondering what will happen if I do not delete memory
allocated using new operator.Why is it considered a bad practice?I have heard that even if I do not free dynamically allocated memory the OS will free it sooner or later.Can this practice crash the application or cause any bugs or is
it just discouraged?

#include <iostream>
using namespace std;
int main()
{
   int* arr = new int[10];

   arr = new int[5];//initializing again with new
}


问:
Nifi putMongo upsert example
I'm struggling to find any examples that show how to use the upsert (or update for that matter) functionality in the putMongo NiFi processor.

I'd be grateful if someone could provide me with an example that I can then tailor to my own needs.

Specifically, given a flowfile containing a single JSON document, pull a single value from the document, filtering on that value, then upserting using a subset of the other available attributes and fields in the document.

What I'd love to do is similar to a SQL merge where an insert could follow one path and an update can follow another but I don't think the functionality allows that.

Thanks

答:
pull a single value from the document

The update query key parameter should do the job for you. By default, it uses _id, but you can specify a different key to use for finding a document to update. Additionally, you can specify a query using the update query configuration parameter.

Title: Nifi putMongo upsert example


问:
Can SSIS put command to compute on Vertica(ELT)
I have some questions about SSIS and Vertica.

Can SSIS send or put command to compute or transform data on Vertica target server(ELT not ETL) ?

Can SSIS connect to Unix/Linux for call a Shell Script?

Thanks and Best Regards,

答:
What research have you done on this? Did you check the vendor's website for SSIS connection managers (click here)?

It might be possible. You can execute PowerShell scripts, call applications, etc. via the Execute Process task.


问:
Deploy code from gitlab on ec2 WITHOUT.gitlab-ci.yml file
I am using gitlab as repository and want to push my code on ec2 whenever any commit is done on gitlab.
 The gitlab CD/CI documentation states that I have to add a file .gitlab-ci.yml  at the root directory of my repo.
 This is actually a problem for me because, I want project repo to have only code and not any configuration related info like build and deploy etc.
 Also when anybody clones the repo, they would have access to location where my code is pushed/deployed on ec2.
 Is there any work around for this problem ?

答:
You'll need to use a gitlab-ci.yml filke to deploy your application. The file provides instructions and a pipeline "infrastructure" which, if properly configured,  will build, test and automatically deploy your code.

If you are worried about leaking credentials, you should use the built-in instance variables to mask your important bits, like a "$SERVERNAME" or "$DB_PASSWORD" for instance.

Lastly, you can use the power of gitignore, in order to not publish all of your credentials or sensitive bits to your projects' servers or instances.


问:
Scraping and parsing Google search results using Python
I asked a question on realizing a general idea to crawl and save webpages.
Part of the original question is: how to crawl and save a lot of "About" pages from the Internet.

With some further research, I got some choices to go ahead with both on scraping and parsing (listed at the bottom).

Today, I ran into another Ruby discussion about how to scrape from Google search results. This provides a great alternative for my problem which will save all the effort on the crawling part.

The new question are: in Python, to scrape Google search results for a given keyword, in this case "About", and finally get the links for further parsing.
What are the best choices of methods and libraries to go ahead with? (in measure of easy-to-learn and easy-to-implement).

p.s. in this website, the exactly same thing is implemented, but closed and ask for money for more results. I'd prefer to do it myself if no open-source available and learn more Python in the meanwhile.

Oh, btw, advices for parsing the links from search results would be nice, if any. Still, easy-to-learn and easy-to-implement. Just started learning Python. :P

Final update, problem solved. Code using xgoogle, please read note in the section below in order to make xgoogle working.

```<code>import time, random
from xgoogle.search import GoogleSearch, SearchError

f = open('a.txt','wb')

for i in range(0,2):
    wt = random.uniform(2, 5)
    gs = GoogleSearch("about")
    gs.results_per_page = 10
    gs.page = i
    results = gs.get_results()
    #Try not to annnoy Google, with a random short wait
    time.sleep(wt)
    print 'This is the %dth iteration and waited %f seconds' % (i, wt)
    for res in results:
        f.write(res.url.encode("utf8"))
        f.write("\n")

print "Done"
f.close()
</code>```

Note on xgoogle (below answered by Mike Pennington):
The latest version from it's Github does not work by default already, due to changes in Google search results probably. These two replies (a b) on the home page of the tool give a solution and it is currently still working with this tweak. But maybe some other day it may stop working again due to Google's change/block.

Resources known so far:

For scraping, Scrapy seems to be a popular choice and a webapp called ScraperWiki is very interesting and there is another project extract it's library for offline/local usage. Mechanize was brought up quite several times in different discussions too.

For parsing HTML, BeautifulSoup seems to be the one of the most
popular choices. Of course. lxml too.

答:
Another option to scrape Google search results using Python is the one by ZenSERP.

I like the API-first approach which is easy to use and the JSON results are easily integrated into our solution.

Here is an example for a curl request:

```<code>curl "https://app.zenserp.com/api/search" -F "q=Pied Piper" -F "location=United States" -F "search_engine=google.com" -F "language=English" -H "apikey: APIKEY"
</code>```

And the response:

```<code>{
  "q": "Pied Piper",
  "domain": "google.com",
  "location": "United States",
  "language": "English",
  "url": "https://www.google.com/search?q=Pied%20Piper&num=100&hl=en&gl=US&gws_rd=cr&ie=UTF-8&oe=UTF-8&uule=w+CAIQIFISCQs2MuSEtepUEUK33kOSuTsc",
  "total_results": 17100000,
  "auto_correct": "",
  "auto_correct_type": "",
  "results": []
}
</code>```

A Python code for example:

```<code>import requests

headers = {
    'apikey': 'APIKEY',
}

params = (
    ('q', 'Pied Piper'),
    ('location', 'United States'),
    ('search_engine', 'google.com'),
    ('language', 'English'),
)

response = requests.get('https://app.zenserp.com/api/search', headers=headers, params=params)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I asked a question on realizing a general idea to crawl and save webpages.
Part of the original question is: how to crawl and save a lot of "About" pages from the Internet.

With some further research, I got some choices to go ahead with both on scraping and parsing (listed at the bottom).

Today, I ran into another Ruby discussion about how to scrape from Google search results. This provides a great alternative for my problem which will save all the effort on the crawling part.

The new question are: in Python, to scrape Google search results for a given keyword, in this case "About", and finally get the links for further parsing.
What are the best choices of methods and libraries to go ahead with? (in measure of easy-to-learn and easy-to-implement).

p.s. in this website, the exactly same thing is implemented, but closed and ask for money for more results. I'd prefer to do it myself if no open-source available and learn more Python in the meanwhile.

Oh, btw, advices for parsing the links from search results would be nice, if any. Still, easy-to-learn and easy-to-implement. Just started learning Python. :P

Final update, problem solved. Code using xgoogle, please read note in the section below in order to make xgoogle working.

import time, random
from xgoogle.search import GoogleSearch, SearchError

f = open('a.txt','wb')

for i in range(0,2):
    wt = random.uniform(2, 5)
    gs = GoogleSearch("about")
    gs.results_per_page = 10
    gs.page = i
    results = gs.get_results()
    #Try not to annnoy Google, with a random short wait
    time.sleep(wt)
    print 'This is the %dth iteration and waited %f seconds' % (i, wt)
    for res in results:
        f.write(res.url.encode("utf8"))
        f.write("\n")

print "Done"
f.close()

Note on xgoogle (below answered by Mike Pennington):
The latest version from it's Github does not work by default already, due to changes in Google search results probably. These two replies (a b) on the home page of the tool give a solution and it is currently still working with this tweak. But maybe some other day it may stop working again due to Google's change/block.

Resources known so far:

For scraping, Scrapy seems to be a popular choice and a webapp called ScraperWiki is very interesting and there is another project extract it's library for offline/local usage. Mechanize was brought up quite several times in different discussions too.

For parsing HTML, BeautifulSoup seems to be the one of the most
popular choices. Of course. lxml too.

Body:
Another option to scrape Google search results using Python is the one by ZenSERP.

I like the API-first approach which is easy to use and the JSON results are easily integrated into our solution.

Here is an example for a curl request:

curl "https://app.zenserp.com/api/search" -F "q=Pied Piper" -F "location=United States" -F "search_engine=google.com" -F "language=English" -H "apikey: APIKEY"

And the response:

{
  "q": "Pied Piper",
  "domain": "google.com",
  "location": "United States",
  "language": "English",
  "url": "https://www.google.com/search?q=Pied%20Piper&num=100&hl=en&gl=US&gws_rd=cr&ie=UTF-8&oe=UTF-8&uule=w+CAIQIFISCQs2MuSEtepUEUK33kOSuTsc",
  "total_results": 17100000,
  "auto_correct": "",
  "auto_correct_type": "",
  "results": []
}

A Python code for example:

import requests

headers = {
    'apikey': 'APIKEY',
}

params = (
    ('q', 'Pied Piper'),
    ('location', 'United States'),
    ('search_engine', 'google.com'),
    ('language', 'English'),
)

response = requests.get('https://app.zenserp.com/api/search', headers=headers, params=params)


问:
Spring - How to add a session attribute only once per session
In my Spring Boot application I add the user name as a custom session attribute. I did this so in the Tomcat manager I can see who is currently using the app:

I implemented javax.servlet.Filter to add the user name. But is this the recommended way to do that? After all, the attribute gets added on every single request. Does Spring provide a callback which is executed only once per session?

答:
Once you add an attribute to HttpSession , that attribute will keep existing in the session provided that the session does not expiry or you do not remove it from the session. So I don't see the point of implementing a Filter to add an attribute to the HttpSession for every request as this attribute is already exist in the session since you add it.

Besides , what you are doing is already done by Spring Security (p.s. in the SecurityContextPersistenceFilter) and I would not do it one more time by myself. Actually that session attribute SPRING_SECURITY_CONTEXT is the same object as we use SecurityContextHolder.getContext() to access the current login user information.

That means if the Authentication object that is set into the SecurityContextHolder has its toString() implemented to print the username (such as this), you could also see the username in the SPRING_SECURITY_CONTEXT session attribute in Tomcat Manager.


问:
Flex: How to create an Image control from a flash.display.Bitmap?
I need to create an Image control from a Bitmap because I have an ItemRedender to use in a List control.

I'm trying to show a list of images (Bitmaps) in a List control and I couldn't by now.

答:
you can use a bitmap as an image just by creating a new image and setting the source of the image to the bitmap. You can do it like this:</p>

```<code>var _image:Image = new Image();
_image.source = yourBitmap;
</code>```

Body:
you can use a bitmap as an image just by creating a new image and setting the source of the image to the bitmap. You can do it like this:

var _image:Image = new Image();
_image.source = yourBitmap;


问:
How to delete cookie MEAN stack?
I try to delete a cookie of my Node API in my Angular client (MEAN stack) but it doesn't work.

I have on Node side a controller and a router, and on my Angular I subscribe the service.

// router node

```<code>authRouter.get('/logout', this.passport.authenticate('jwt', {
  session: false
}), (req, res) => {
  logout()
    .then(apiResponse => sendApiSuccessResponse(res, Vocabulary.request.success, apiResponse))
    .catch(apiResponse => sendApiErrorResponse(res, Vocabulary.request.error, apiResponse));
});
</code>```

// controller node

```<code>const logout = (res) => {
  res.cookie(process.env.COOKIE_NAME, '', {
    maxAge: -1,
    httpOnly: true
  });
};
</code>```

// service angular

```<code>public logout(): Observable < any > {
  // GET '/auth/logout'
  console.log('logout service ok');
  return this.HttpClient.get(`${environment.apiUrl}/auth/logout`)
}
</code>```

// component angular call logout

```<code>public logout = () => {
  return this.AuthService.logout()
};

ngOnInit() {
  this.logout();
};
</code>```

Do you think the code is OK ?

答: Try cookies.set('process.env.COOKIE_NAME', {maxAge: Date.now()});

Title: How to delete cookie MEAN stack?

Body:
I try to delete a cookie of my Node API in my Angular client (MEAN stack) but it doesn't work.

I have on Node side a controller and a router, and on my Angular I subscribe the service.

// router node

authRouter.get('/logout', this.passport.authenticate('jwt', {
  session: false
}), (req, res) => {
  logout()
    .then(apiResponse => sendApiSuccessResponse(res, Vocabulary.request.success, apiResponse))
    .catch(apiResponse => sendApiErrorResponse(res, Vocabulary.request.error, apiResponse));
});

// controller node

const logout = (res) => {
  res.cookie(process.env.COOKIE_NAME, '', {
    maxAge: -1,
    httpOnly: true
  });
};

// service angular

public logout(): Observable < any > {
  // GET '/auth/logout'
  console.log('logout service ok');
  return this.HttpClient.get(`${environment.apiUrl}/auth/logout`)
}

// component angular call logout

public logout = () => {
  return this.AuthService.logout()
};

ngOnInit() {
  this.logout();
};

Do you think the code is OK ?


问:
using passed arguments in bash script
I am passing two date values to a script and trying to use those in a CURL POST command as below:

```<code>starttime=$1
endtime=$2

for apps in $(cat testapps.txt)
do
    curl -X POST -H "Content-type: application/vnd.appd.cntrl+json;v=1" -d '{"name": "This is a test","timeRange": {"startTimeMillis":"$1","endTimeMillis":"$2"}, "affects": {"type": "APP"}}'
</code>```

It is giving me 500 internal server error.

If I replace the $1 and $2 value with the date/time as below, it works fine.

```<code>curl -X POST -H "Content-type: application/vnd.appd.cntrl+json;v=1" -d '{"name": "This is a test","timeRange": {"startTimeMillis":"2019-05-28T15:00:00-0400","endTimeMillis":"2019-05-28T16:00:00-0400"}, "affects": {"type": "APP"}}'
</code>```

Am I missing anything?

答:
First, Dont Read Lines With For.</p>

```<code>while read apps
do args=(
    -X POST
    -H "Content-type: application/vnd.appd.cntrl+json;v=1"
    -d '{ "name":"This is a test",
          "timeRange": {
              "startTimeMillis": "'"$1"'",
              "endTimeMillis": "'"$2"'" },
          "affects": {"type": "APP"}}'
   )
   # don't you need a URL here?
   curl "${args[@]}" "$apps" # added $apps, assuming that was missing...
done < testapps.txt
</code>```

Title: using passed arguments in bash script

Body:
I am passing two date values to a script and trying to use those in a CURL POST command as below:

starttime=$1
endtime=$2

for apps in $(cat testapps.txt)
do
    curl -X POST -H "Content-type: application/vnd.appd.cntrl+json;v=1" -d '{"name": "This is a test","timeRange": {"startTimeMillis":"$1","endTimeMillis":"$2"}, "affects": {"type": "APP"}}'

It is giving me 500 internal server error.

If I replace the $1 and $2 value with the date/time as below, it works fine.

curl -X POST -H "Content-type: application/vnd.appd.cntrl+json;v=1" -d '{"name": "This is a test","timeRange": {"startTimeMillis":"2019-05-28T15:00:00-0400","endTimeMillis":"2019-05-28T16:00:00-0400"}, "affects": {"type": "APP"}}'

Am I missing anything?

Body:
First, Dont Read Lines With For.

while read apps
do args=(
    -X POST
    -H "Content-type: application/vnd.appd.cntrl+json;v=1"
    -d '{ "name":"This is a test",
          "timeRange": {
              "startTimeMillis": "'"$1"'",
              "endTimeMillis": "'"$2"'" },
          "affects": {"type": "APP"}}'
   )
   # don't you need a URL here?
   curl "${args[@]}" "$apps" # added $apps, assuming that was missing...
done < testapps.txt


问:
Find all packages that depend on a specific one
Is it possible to scan all the packages on CRAN in order to find all those that are dependent on a specific package?

I have found out how to do that but only on the packages I have installed and that is not what I want.

答:
You can do (with a package randomly picked from CRAN):

```<code>tools::package_dependencies(package = "ABHgenotypeR")

$ABHgenotypeR
[1] "ggplot2"  "reshape2" "utils"
</code>```

If you need the reverse dependencies, you can do:

```<code>tools::package_dependencies(package = "ABHgenotypeR",
                            reverse = TRUE)

$ABHgenotypeR
character(0)
</code>```

From documentation:

For given packages which are not found in the db, NULL entries are
  returned, as opposed to character(0) entries which indicate no
  dependencies.

And you can do it for multiple packages simultaneously:

```<code>packages <- c("ABHgenotypeR", "accelerometry", "ACNE")
tools::package_dependencies(package = packages)

$ABHgenotypeR
[1] "ggplot2"  "reshape2" "utils"

$accelerometry
[1] "Rcpp"   "dvmisc"

$ACNE
[1] "aroma.affymetrix" "MASS"             "R.methodsS3"      "R.oo"             "R.utils"
[6] "matrixStats"      "R.filesets"       "aroma.core"
</code>```

Body:
You can do (with a package randomly picked from CRAN):

tools::package_dependencies(package = "ABHgenotypeR")

$ABHgenotypeR
[1] "ggplot2"  "reshape2" "utils"

If you need the reverse dependencies, you can do:

tools::package_dependencies(package = "ABHgenotypeR",
                            reverse = TRUE)

$ABHgenotypeR
character(0)

From documentation:

For given packages which are not found in the db, NULL entries are
  returned, as opposed to character(0) entries which indicate no
  dependencies.

And you can do it for multiple packages simultaneously:

packages <- c("ABHgenotypeR", "accelerometry", "ACNE")
tools::package_dependencies(package = packages)

$ABHgenotypeR
[1] "ggplot2"  "reshape2" "utils"

$accelerometry
[1] "Rcpp"   "dvmisc"

$ACNE
[1] "aroma.affymetrix" "MASS"             "R.methodsS3"      "R.oo"             "R.utils"
[6] "matrixStats"      "R.filesets"       "aroma.core"


问:
Thin wrapper for read_xlsx function works with defaults, but not with custom file location
I'm creating a simple little time-saver wrapper function that pre-fills out some standard file locations, etc. for importing an Excel file using readxl::read_xlsx.  It works exactly as expected with the defaults, however, when I try to use it at the console with a different file location I get the following error.

Error in read_space_program(path = "inst/extdata/space_program.xlsx") :
  unused argument (path = "inst/extdata/space_program.xlsx")

I've tried adding , ..., as suggested on StackOverflow by those with similar error messages, to extend the arguments but it does not fix the problem.  This is the code I am running:

read_space_program <-
    function(file_location = "inst/extdata/space_program.xlsx",
             sheet_name = "Program",
             skip_rows = 5, ...) {
        readxl::read_xlsx(
            path = file_location,
            sheet = sheet_name,
            col_names = TRUE,
            skip = skip_rows
        ) # first five rows skipped to allow for project information
    }
```

Without uploading the entire .xlsx file, suffice to say that I use this particular file all the time and it is not the source of the problem.  It loads fine with this exact code when I run it like this: read_space_program(), however when I test it by feeding the exact same file location into it at the console with this: read_space_program(file_location = "inst/extdata/space_program.xlsx"), I get the error above.  This error probably has something to do with something basic, I'm pretty sure, but cannot figure it out.  Any help is appreciated.

答: This was caused by an artifact of development in my environment.  Cleaning the environment allowed the code to run.</p>

Body:
I'm creating a simple little time-saver wrapper function that pre-fills out some standard file locations, etc. for importing an Excel file using readxl::read_xlsx.  It works exactly as expected with the defaults, however, when I try to use it at the console with a different file location I get the following error.

Error in read_space_program(path = "inst/extdata/space_program.xlsx") :
  unused argument (path = "inst/extdata/space_program.xlsx")

I've tried adding , ..., as suggested on StackOverflow by those with similar error messages, to extend the arguments but it does not fix the problem.  This is the code I am running:

read_space_program <-
    function(file_location = "inst/extdata/space_program.xlsx",
             sheet_name = "Program",
             skip_rows = 5, ...) {
        readxl::read_xlsx(
            path = file_location,
            sheet = sheet_name,
            col_names = TRUE,
            skip = skip_rows
        ) # first five rows skipped to allow for project information
    }

Without uploading the entire .xlsx file, suffice to say that I use this particular file all the time and it is not the source of the problem.  It loads fine with this exact code when I run it like this: read_space_program(), however when I test it by feeding the exact same file location into it at the console with this: read_space_program(file_location = "inst/extdata/space_program.xlsx"), I get the error above.  This error probably has something to do with something basic, I'm pretty sure, but cannot figure it out.  Any help is appreciated.


问:
Pass Reference in Class
I am totally confused. In this example which is part of my class, I have:

```<code>public:
        typedef DoubleLinkedNode<DataType> Node;
private:
            const DataType* fValue;
            Node* fNext;
            Node* fPrevious;
            DoubleLinkedNode(): fValue((const DataType*)0){
                fNext = (Node*)0;
                fPrevious = (Node*)0;
            }
</code>```

Which means fValue is a const DataType* , now I want to apply/define data type like string or int to fValue by this part:

```<code>    DoubleLinkedNode( const DataType& aValue ){

        std::cout << "  --  "  << aValue << std::endl;
    }
</code>```

I am confused , what exactly I must write there and why? How can I define aValue to my fValue ?!
(note: The std::cout << "  --  "  << aValue << std::endl; is just for test)

答:
Since fValue is a pointer, and DoubleLinkedNode() takes an object by reference, you need to dereference the pointer, like this:

```<code>DoubleLinkedNode(*fValue);
</code>```

Title: Pass Reference in Class

Body:
I am totally confused. In this example which is part of my class, I have:

public:
        typedef DoubleLinkedNode<DataType> Node;
private:
            const DataType* fValue;
            Node* fNext;
            Node* fPrevious;
            DoubleLinkedNode(): fValue((const DataType*)0){
                fNext = (Node*)0;
                fPrevious = (Node*)0;
            }

Which means fValue is a const DataType* , now I want to apply/define data type like string or int to fValue by this part:

    DoubleLinkedNode( const DataType& aValue ){

        std::cout << "  --  "  << aValue << std::endl;
    }

I am confused , what exactly I must write there and why? How can I define aValue to my fValue ?!
(note: The std::cout << "  --  "  << aValue << std::endl; is just for test)

Body:
Since fValue is a pointer, and DoubleLinkedNode() takes an object by reference, you need to dereference the pointer, like this:

DoubleLinkedNode(*fValue);


问:
ReactJS- downloading a pdf file "Failed - no file"
I have written a React Component to download a pdf file using the achor tag of the file. I'm getting an error Failed- No file.

```<code>import React from 'react'

const Links = ()=>
        <div className='github-link'>
             <a href="https://github.com/" rel='noopener noreferrer'  alt="github link"
     target='_blank'><strong>View my GitHub here!</strong></a>
     <a href="../resume/resume.pdf" download><strong>Download my Resume!</strong></a>
        </div>

export default Links

</code>```

I have my resume pdf in my src directory inside a directory called resume. The file I want to download is called resume.pdf

Thanks for any help!

答:
Easy fix is to put the pdf file in your public folder and set href="resume.pdf".

You can also create a folder named resume in your public and put the pdf file inside your resume folder.

```<code><a href="/resume/resume.pdf" download><strong>Download my Resume!</strong></a>
</code>```

Body:
I have written a React Component to download a pdf file using the achor tag of the file. I'm getting an error Failed- No file.

import React from 'react'

const Links = ()=>

             View my GitHub here!
     Download my Resume!

export default Links

I have my resume pdf in my src directory inside a directory called resume. The file I want to download is called resume.pdf

Thanks for any help!

Body:
Easy fix is to put the pdf file in your public folder and set href="resume.pdf".

You can also create a folder named resume in your public and put the pdf file inside your resume folder.

<a href="/resume/resume.pdf" download><strong>Download my Resume!</strong></a>


问:
puppeteer issue on CentOs 7 problem after exactly 30 minutes
i have a script that use node js and puppeteer, the script run wonderful on my windows 10 for as long as i dont close it from command line, when i`m using it .

on my VPS it is working for exactly 30 minute , i tried few times and all the time it is exactly 30 minutes, the node js is still functioning but no data is received after 30 minutes, i`m scraping web socket just for the info .

i have tried any args on launch but nothing is keep the connection alive.

答:
finally i found a solution :)
i guess the sites checking your activity and if you are not active for 30 minutes then they closing any connection that is open , so with puppeteer you can use mouse movement and that is the solution , i put movement in interval and all are fine now, if someone have that issue then just use this method and all are good.</p>


答: If you don't care about doing it programmatically, the easiest way is to look at the corresponding CRAN web page (i.e. https://CRAN.R-project.org/package=PKGNAME) and look at the "Reverse depends:", "Reverse imports:", and "Reverse suggests:" sections.

Title: Find all packages that depend on a specific one

Body:
Is it possible to scan all the packages on CRAN in order to find all those that are dependent on a specific package?

I have found out how to do that but only on the packages I have installed and that is not what I want.


问:
Summation of each column by selected few specific rows - in R
I have started learning R recently. For one of my codes, I have been trying to debug this issue for quite a while.

I have the data which looks like this:

```<code>dd
    [,1]       [,2]   [,3]
[1,] "Category" "A"    "B"
[2,] "ONE"      "23"   "45"
[3,] "TWO"      "234"  "23"
[4,] "THREE"    "565"  "324"
[5,] "FOUR"     "676"  "343"
[6,] "FIVE"     "1231" "544"
</code>```

I want to add rows: ONE, THREE and FIVE (in Category) for each of the columns. Therefore, the output will look like:

```<code>sum  1819   913
</code>```

I have tried to use rowSums and sum. I get error every time I use this. One of the most common error is shown below.

```<code>sum = rowSums(subset(dd, CATEGORY == 'ONE', 'THREE', 'FIVE'))
Error in rowSums(subset(spread_DNT_TXN, CATEGORY == "Invoiced")) :
  'x' must be numeric
</code>```

I am looking for how I can perform this function. I am unable to find it anywhere.

Thanks in advance!

答:
We can do this in base R.  Note that the OP's dataset is a matrix and matrix can hold only a single class.  If there is one character element, the whole matrix will be converted to character class.  Here, for some reason, the headers are the first row, along with the fact that first column is character.  One option would be to subset the numeric columns, convert the type, and then select the rows of interest for rowSums

```<code>m1 <- matrix(as.numeric(dd[-1, 2:3]), ncol = 2)
i1 <- dd[-1, 1] %in% c("ONE", "THREE", "FIVE")
rowSums(m1[i1, ])
#[1]   68  889 1775
</code>```

Or if it needs to be column wise sum

```<code>colSums(m1[i1, ])
#[1] 1819  913
</code>```

data

```<code>dd <- cbind(c("Category", "ONE", "TWO", "THREE", "FOUR", "FIVE"),
    c("A", 23, 234, 565, 676, 1231), c("B", 45, 23, 324, 343, 544))
</code>```

Body:
I have started learning R recently. For one of my codes, I have been trying to debug this issue for quite a while.

I have the data which looks like this:

dd
    [,1]       [,2]   [,3]
[1,] "Category" "A"    "B"
[2,] "ONE"      "23"   "45"
[3,] "TWO"      "234"  "23"
[4,] "THREE"    "565"  "324"
[5,] "FOUR"     "676"  "343"
[6,] "FIVE"     "1231" "544"

I want to add rows: ONE, THREE and FIVE (in Category) for each of the columns. Therefore, the output will look like:

sum  1819   913

I have tried to use rowSums and sum. I get error every time I use this. One of the most common error is shown below.

sum = rowSums(subset(dd, CATEGORY == 'ONE', 'THREE', 'FIVE'))
Error in rowSums(subset(spread_DNT_TXN, CATEGORY == "Invoiced")) :
  'x' must be numeric

I am looking for how I can perform this function. I am unable to find it anywhere.

Thanks in advance!

Body:
We can do this in base R.  Note that the OP's dataset is a matrix and matrix can hold only a single class.  If there is one character element, the whole matrix will be converted to character class.  Here, for some reason, the headers are the first row, along with the fact that first column is character.  One option would be to subset the numeric columns, convert the type, and then select the rows of interest for rowSums

m1 <- matrix(as.numeric(dd[-1, 2:3]), ncol = 2)
i1 <- dd[-1, 1] %in% c("ONE", "THREE", "FIVE")
rowSums(m1[i1, ])
#[1]   68  889 1775

Or if it needs to be column wise sum

colSums(m1[i1, ])
#[1] 1819  913

data

dd <- cbind(c("Category", "ONE", "TWO", "THREE", "FOUR", "FIVE"),
    c("A", 23, 234, 565, 676, 1231), c("B", 45, 23, 324, 343, 544))


问:
Persist apache nifi flow.xml.gz file in docker volume
How can I persist the  flow.xml.gz file in nifi docker container?

I am using a docker-compose file, it is giving me errors such as not finding certain files.

Didi you encounter the same issue?

Thanks

```<code>    version: "3.3"
services:
  nifi:
    image: apache/nifi
    volumes:
      - /home/ubuntu/nifi/conf:/opt/nifi/nifi-current/conf
      #- ./flow/flow.xml.gz:/opt/nifi/nifi-current/conf/flow.xml.gz
    ports:
      - "8080:8080"
</code>```

答:
Apparently NiFi doesn't allow you to only persist the flow.xml.gz file, it gives error and the container shuts.

You need to persist the whole /opt/nifi/nifi-current/conf/ folder

Body:
How can I persist the  flow.xml.gz file in nifi docker container?

I am using a docker-compose file, it is giving me errors such as not finding certain files.

Didi you encounter the same issue?

Thanks

    version: "3.3"
services:
  nifi:
    image: apache/nifi
    volumes:
      - /home/ubuntu/nifi/conf:/opt/nifi/nifi-current/conf
      #- ./flow/flow.xml.gz:/opt/nifi/nifi-current/conf/flow.xml.gz
    ports:
      - "8080:8080"


问:
Figuring out an array using powershell
I'm trying to create an array that will remove files from the destination path and then copy from the source path to the destination path. I've created a .txt document on the build server with a list of files with their relative path. When I run the below block of code it's removing all contents in folder B and copy Folder A(without any contents) to Folder B.

This is what I'm running

```<code>$files = get-content "C:\files.txt"
foreach ($filepath in $files)
{
    $source = '\\Server1\Folder A' + $filepath
    $dest = '\\Server2\Folder B' + $filepath
    foreach ($removefile in $dest)
    {
       rd $removefile -recurse -force
    }
    foreach ($addfile in $source)
    {
        cp $addfile -destination $dest
    }
}
</code>```

Soda,

I've tried your suggestion but it's trying to remove from/copy to the incorrect directory.

Code:

```<code>$targetList = Get-Content "C:\MCSfiles.txt"

foreach ($target in $targetList) {

    $destPath = Join-Path "\\Server2\MCSWebTest" $target
    $destFiles = Get-ChildItem $destPath

    foreach ($file in $destFiles) {
       Remove-Item $file -Recurse -Force
    }

    $sourcePath = Join-Path "\\Server1\WebSites\McsWeb2" $target
    $sourceFiles = Get-ChildItem $sourcePath

    foreach ($file in $sourceFiles) {
        Copy-Item $file -Destination $destPath
    }
}
</code>```

Error:

Remove-Item : Cannot find path 'C:\Program Files (x86)\Jenkins\jobs\MCSTest\workspace\App_Code' because it does not exist.
  At C:\Users\SVC-VI~1\AppData\Local\Temp\jenkins5893875881898738781.ps1:9 >char:1
  9
  +        Remove-Item <<<<  $file -Recurse -Force
     + CategoryInfo          : ObjectNotFound: (C:\Program >File...kspace\App_Co
    de:String) [Remove-Item], ItemNotFoundException
     + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.Remov
    eItemCommand

Copy-Item : Cannot find path 'C:\Program Files (x86)\Jenkins\jobs\MCSTest\works
  pace\App_Code' because it does not exist.
  At C:\Users\SVC-VI~1\AppData\Local\Temp\jenkins5893875881898738781.ps1:16 >char:
  18
  +         Copy-Item <<<<  $file -Destination $destPath
     + CategoryInfo          : ObjectNotFound: (C:\Program >File...kspace\App_Co
    de:String) [Copy-Item], ItemNotFoundException
     + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.CopyI
    temCommand

Soda,

Neither of the suggestions work. It's still removing everything in the destination directory and adding the source directory folder to the destination directory without files.  I'm a little lost here.

答:
The issue is you are trying to loop too many times. The outer loop processes the files one at a time. There should be no inner loop. Also, you aren't validating the file exists before issuing a deletion.</p>

```<code>$files = Get-Content "C:\test.txt"
$source_base="C:\TEMP\source\"
$dest_base="C:\TEMP\dest\"

foreach ($filepath in $files)
{
    $source = $source_base + $filepath
    $dest = $dest_base + $filepath

    if(Test-Path $dest) {rd $dest -recurse -force}
    cp $source -destination $dest
}
</code>```

Title: Figuring out an array using powershell

Body:
I'm trying to create an array that will remove files from the destination path and then copy from the source path to the destination path. I've created a .txt document on the build server with a list of files with their relative path. When I run the below block of code it's removing all contents in folder B and copy Folder A(without any contents) to Folder B.

This is what I'm running

$files = get-content "C:\files.txt"
foreach ($filepath in $files)
{
    $source = '\\Server1\Folder A' + $filepath
    $dest = '\\Server2\Folder B' + $filepath
    foreach ($removefile in $dest)
    {
       rd $removefile -recurse -force
    }
    foreach ($addfile in $source)
    {
        cp $addfile -destination $dest
    }
}

Soda,

I've tried your suggestion but it's trying to remove from/copy to the incorrect directory.

Code:

$targetList = Get-Content "C:\MCSfiles.txt"

foreach ($target in $targetList) {

    $destPath = Join-Path "\\Server2\MCSWebTest" $target
    $destFiles = Get-ChildItem $destPath

    foreach ($file in $destFiles) {
       Remove-Item $file -Recurse -Force
    }

    $sourcePath = Join-Path "\\Server1\WebSites\McsWeb2" $target
    $sourceFiles = Get-ChildItem $sourcePath

    foreach ($file in $sourceFiles) {
        Copy-Item $file -Destination $destPath
    }
}

Error:

Remove-Item : Cannot find path 'C:\Program Files (x86)\Jenkins\jobs\MCSTest\workspace\App_Code' because it does not exist.
  At C:\Users\SVC-VI~1\AppData\Local\Temp\jenkins5893875881898738781.ps1:9 >char:1
  9
  +        Remove-Item <<<<  $file -Recurse -Force
     + CategoryInfo          : ObjectNotFound: (C:\Program >File...kspace\App_Co
    de:String) [Remove-Item], ItemNotFoundException
     + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.Remov
    eItemCommand

Copy-Item : Cannot find path 'C:\Program Files (x86)\Jenkins\jobs\MCSTest\works
  pace\App_Code' because it does not exist.
  At C:\Users\SVC-VI~1\AppData\Local\Temp\jenkins5893875881898738781.ps1:16 >char:
  18
  +         Copy-Item <<<<  $file -Destination $destPath
     + CategoryInfo          : ObjectNotFound: (C:\Program >File...kspace\App_Co
    de:String) [Copy-Item], ItemNotFoundException
     + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.CopyI
    temCommand

Soda,

Neither of the suggestions work. It's still removing everything in the destination directory and adding the source directory folder to the destination directory without files.  I'm a little lost here.

Body:
The issue is you are trying to loop too many times. The outer loop processes the files one at a time. There should be no inner loop. Also, you aren't validating the file exists before issuing a deletion.

$files = Get-Content "C:\test.txt"
$source_base="C:\TEMP\source\"
$dest_base="C:\TEMP\dest\"

foreach ($filepath in $files)
{
    $source = $source_base + $filepath
    $dest = $dest_base + $filepath

    if(Test-Path $dest) {rd $dest -recurse -force}
    cp $source -destination $dest
}


问:
How can i prevent this negative white space in my website from appearing?
I have been working on fixing this problem for a while, my website at some pages that has less or few content, or if it's shown in a big screen, it shows white space right under the footer.

"as shown here (https://imgur.com/ATR59Ts)"

i tried using height:100% but it doesn't work if the screen is small, because if i put the height:100% in body{} it will cause elements inside the body to overlap over the body and cause white space.

"as shown here (https://imgur.com/3fWTNZE)"

i have no idea what else to tinker with to prevent this white space.

i tried to add height:100% in body,html (doesn't work on small screens when i add more element in my divs.

```<code>body, html{
    margin: 0;
    padding: 0;
    width: 100%;
    /* height: 100%; */
    /* overflow: scroll; */
}
</code>```

i expected the result to make the body always at 100% on all possible screens, but the element would overflow over the body and cause white spaces.

答: Looks like content in the container is smaller than screen size? Then you may use min-height:100vh in main container style. This will make its minimum size equals to windows size. Example at Codepen

Body:
I have been working on fixing this problem for a while, my website at some pages that has less or few content, or if it's shown in a big screen, it shows white space right under the footer.

"as shown here (https://imgur.com/ATR59Ts)"

i tried using height:100% but it doesn't work if the screen is small, because if i put the height:100% in body{} it will cause elements inside the body to overlap over the body and cause white space.

"as shown here (https://imgur.com/3fWTNZE)"

i have no idea what else to tinker with to prevent this white space.

i tried to add height:100% in body,html (doesn't work on small screens when i add more element in my divs.

body, html{
    margin: 0;
    padding: 0;
    width: 100%;
    /* height: 100%; */
    /* overflow: scroll; */
}

i expected the result to make the body always at 100% on all possible screens, but the element would overflow over the body and cause white spaces.


问:
How can I make a REST controller conditional on the environment?
We have a use case where we want a set of endpoints to be enabled in every environment except the production environment.  Rather than implementing a custom security implementation for this use case, our idea was to use a variation of Spring's Conditional annotation to only enable the controller in non-production environments.

Our initial attempt was to use @ConditionalOnExpression by injecting a dynamic system property that specifies the type of environment (eg. dev, test, prod, etc.) and to match that property against a regular expression, but we have not been able to get the SpEL expressions to resolve properly in a way that suits our needs.

@RestController
@ConditionalOnExpression("${property.name} matches ^((?!prod).)*$")
public class TestDataController
```

<p>We have also considered using @ConditionalOnProperty, but there seems to be no way to allow this property to accept multiple valid values.</p>

<pre class="lang-java prettyprint-override"><code>@RestController
@ConditionalOnProperty(
        value = "property.name",
        havingValue = "value1" or "value2",
        matchIfMissing = true)
public class TestDataController
</code>```

Our last attempt was to write a custom class extending Spring's Conditional class to suit our needs.  This works for now, but it is relying on Java file I/O, which we would like to avoid if possible.

Any ideas?

UPDATE 29 May 19

We were able to use the following solution to solve our problem:

Define a custom conditional in the following way:

public class NotInProductionCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        final String env = context.getEnvironment().getProperty("property.name");
        if (env == null || env.isEmpty()) {
            return true;
        }
        return !env.contains("prod");
    }
}
```

<ol start="2">
<li>Use the custom condition on our controller:</li>
</ol>

<pre class="lang-java prettyprint-override"><code>@RestController
@Conditional(NotInProductionCondition.class)
public class TestDataController
</code>```

答:
You can use @Profile annotation to instantiate a bean depending on a profile set in your environment.

```<code>@RestController
@Profile("!prod")
class MyController {
  ...
}
</code>```

If you don't use profiles in your environment you most likely using some type of environment variable to specify the environment name, I suppose. You can make it a spring profile like this

```<code>spring.profiles.active = ${environmentName}
</code>```

Body:
We have a use case where we want a set of endpoints to be enabled in every environment except the production environment.  Rather than implementing a custom security implementation for this use case, our idea was to use a variation of Spring's Conditional annotation to only enable the controller in non-production environments.

Our initial attempt was to use @ConditionalOnExpression by injecting a dynamic system property that specifies the type of environment (eg. dev, test, prod, etc.) and to match that property against a regular expression, but we have not been able to get the SpEL expressions to resolve properly in a way that suits our needs.

@RestController
@ConditionalOnExpression("${property.name} matches ^((?!prod).)*$")
public class TestDataController

We have also considered using @ConditionalOnProperty, but there seems to be no way to allow this property to accept multiple valid values.

@RestController
@ConditionalOnProperty(
        value = "property.name",
        havingValue = "value1" or "value2",
        matchIfMissing = true)
public class TestDataController

Our last attempt was to write a custom class extending Spring's Conditional class to suit our needs.  This works for now, but it is relying on Java file I/O, which we would like to avoid if possible.

Any ideas?

UPDATE 29 May 19

We were able to use the following solution to solve our problem:

Define a custom conditional in the following way:

public class NotInProductionCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        final String env = context.getEnvironment().getProperty("property.name");
        if (env == null || env.isEmpty()) {
            return true;
        }
        return !env.contains("prod");
    }
}

Use the custom condition on our controller:

@RestController
@Conditional(NotInProductionCondition.class)
public class TestDataController

Body:
You can use @Profile annotation to instantiate a bean depending on a profile set in your environment.

@RestController
@Profile("!prod")
class MyController {
  ...
}

If you don't use profiles in your environment you most likely using some type of environment variable to specify the environment name, I suppose. You can make it a spring profile like this

spring.profiles.active = ${environmentName}


问:
regex to match character in specific position
I need to come up with a regex to look for only letters A, F or E on the position 9 of a given text. I am really new with regex, did some searching and couldn't find any similar response. what i have so far is:

```<code>/^.{9}A/
</code>```

This command seems to work to find letter A on the space nine, but how can I add the other 2 letters to the regex?

答:
This way can also solve the problem

```<code>/^.{8}A|^.{8}F|^.{8}E/;
</code>```

you have to use 8 instead of 9 if you want to match the character on the 9th position

Body:
I need to come up with a regex to look for only letters A, F or E on the position 9 of a given text. I am really new with regex, did some searching and couldn't find any similar response. what i have so far is:

/^.{9}A/

This command seems to work to find letter A on the space nine, but how can I add the other 2 letters to the regex?

Body:
This way can also solve the problem

/^.{8}A|^.{8}F|^.{8}E/;

you have to use 8 instead of 9 if you want to match the character on the 9th position


答:
Basically there are two layout files which are required to be created, one is activity_main.xml and another one is the layout that shows each item in the RecyclerView. Consider the name of the layout file to be layout_r.xml.

activity_main.xml

```<code><LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
    <RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"    <!--This can be changed to wrap_content or match_parent, even though match_parent makes single view on the screen-->
        android:layout_height="wrap_content">
    </RecyclerView>
</LinearLayout>
</code>```

layout_r.xml

```<code><LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
    <TextView
        android:id="@+id/tvText"
        android:text="Add text here"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <!--............And rest of the views..............-->

</LinearLayout>
</code>```

Title: RecyclerView show many items and make current item in center

Body:
Like this.

Show three items at screen, but left and right item show only edge

When index = 0, show first item at center

When index = n, show current item at center

|-----------------------------------|
|                                   |
|                                   |
|         |---------------|    |----|
|         |               |    |    |
|         |               |    |    |
|         |               |    |    |
|         |               |    |    |
|         |       1       |    |  2 |
|         |               |    |    |
|         |               |    |    |
|         |               |    |    |
|         |               |    |    |
|         |---------------|    |----|
|                                   |
|                                   |
|-----------------------------------|

|-----------------------------------|
|                                   |
|                                   |
|----|    |---------------|    |----|
|    |    |               |    |    |
|    |    |               |    |    |
|    |    |               |    |    |
|    |    |               |    |    |
|  1 |    |       2       |    |  3 |
|    |    |               |    |    |
|    |    |               |    |    |
|    |    |               |    |    |
|    |    |               |    |    |
|----|    |---------------|    |----|
|                                   |
|                                   |
|-----------------------------------|

I have try SnapHelper, but I don't known how

Body:
Basically there are two layout files which are required to be created, one is activity_main.xml and another one is the layout that shows each item in the RecyclerView. Consider the name of the layout file to be layout_r.xml.

activity_main.xml

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
    <RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"    <!--This can be changed to wrap_content or match_parent, even though match_parent makes single view on the screen-->
        android:layout_height="wrap_content">
    </RecyclerView>
</LinearLayout>

layout_r.xml

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
    <TextView
        android:id="@+id/tvText"
        android:text="Add text here"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <!--............And rest of the views..............-->

</LinearLayout>


问:
Python: sqlite3.OperationalError: near "<": syntax error (updating sqlite3 field with html source code)
I would like to change all the occurence of sometext (matching all case combination like sometext, SOMETEXT, SOmeTExt) in the note field of the table itemNotes of a sqlite.

Because sqlite doesn't support case insensitive update (I already ask 2 question here and here ), I am using python and regex.

But I get this error : sqlite3.OperationalError: near "<": syntax error matching line of cursor.execute(f'REPLACE

I dont' have a <in my code so I think it's coming from the note field which contains html source code.

Here is my code:

```<code>keyword ="sometext"
replacement_word="abc"

# load sqlite3
db = sqlite3.connect(path_to_sqlite)
cursor = db.cursor()

# search for all therm
cursor.execute(f'SELECT * FROM itemNotes  WHERE note like "%{keyword}%"')
print("\nfetch one:")
# itemID_list = cursor.fetchone()

# pour chacun des result, change
for row in cursor.fetchall():
    # print(each)
    row_regex = re.compile(re.escape(keyword), re.IGNORECASE)
    row_regex_replaced = row_regex.sub(replacement_word, row[2])

    rowindex = row[0]
    cursor.execute(
        f'REPLACE INTO itemNotes (note) VALUES ({row_regex_replaced}) where itemID = {rowindex}')
</code>```

After looking up "sql injection", this is what I came up with :

```<code>sql = "REPLACE INTO itemNotes (note) VALUES (?) where itemID = (?)"
data = (row_regex_replaced, rowindex,)
cursor.execute(sql, data)
</code>```

But now I am getting this error : sqlite3.OperationalError: near "where": syntax error

答:
From the sqlite doc:

The REPLACE command is an alias for the "INSERT OR REPLACE" variant of
  the INSERT command.

An INSERT doesn't have a WHERE clause. The query needs to be written as a "regular" INSERT, and the system will "decide" whether to replace. Something like INSERT into itemNotes (itemID,note) VALUES (?,?). (NB the order of the data list in the above example would need to change).

Body:
I would like to change all the occurence of sometext (matching all case combination like sometext, SOMETEXT, SOmeTExt) in the note field of the table itemNotes of a sqlite.

Because sqlite doesn't support case insensitive update (I already ask 2 question here and here ), I am using python and regex.

But I get this error : sqlite3.OperationalError: near "<": syntax error matching line of cursor.execute(f'REPLACE

I dont' have a <in my code so I think it's coming from the note field which contains html source code.

Here is my code:

keyword ="sometext"
replacement_word="abc"

# load sqlite3
db = sqlite3.connect(path_to_sqlite)
cursor = db.cursor()

# search for all therm
cursor.execute(f'SELECT * FROM itemNotes  WHERE note like "%{keyword}%"')
print("\nfetch one:")
# itemID_list = cursor.fetchone()

# pour chacun des result, change
for row in cursor.fetchall():
    # print(each)
    row_regex = re.compile(re.escape(keyword), re.IGNORECASE)
    row_regex_replaced = row_regex.sub(replacement_word, row[2])

    rowindex = row[0]
    cursor.execute(
        f'REPLACE INTO itemNotes (note) VALUES ({row_regex_replaced}) where itemID = {rowindex}')

After looking up "sql injection", this is what I came up with :

sql = "REPLACE INTO itemNotes (note) VALUES (?) where itemID = (?)"
data = (row_regex_replaced, rowindex,)
cursor.execute(sql, data)

But now I am getting this error : sqlite3.OperationalError: near "where": syntax error


问:
Trying to convert XML values into map
I have seen a lot of similar problems that keep getting me partway there, but I end up starting to have to build recursive solutions on top which I'm trying to avoid.

I have an XML file I want to convert into a map.

The structure is unknown except for one thing

```<code><items>
<item>
{section to be converted to map}
</item>
<item>
{section to be converted to map}
</item>
</items>
</code>```

All the solutions I've seen seem to be converting the entire thing into map, or parse through each attribute/value manually.

I'm wondering if there's a method to say...

Jump into items, jump into each item, convert each item to map, then I can process each map individually.

I am streaming through a potentially large file, so don't want to hold the entire thing in memory, just one item at a time.

I have tried to use xmleventreader to do this, but get jammed up in a recursive nightmare. The item was for the event reader to find individual items, and them on those individual items to have them process, but not finding any documentation on how to capture what's between each value so it can be processed as an XML later.

```<code>private void parseItemList(MultipartFile file) {
    XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
    try {
        XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(file.getInputStream());
        processItems(xmlEventReader);
    } catch (FileNotFoundException | XMLStreamException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code>```

The idea would be to convert:

```<code><items>
<item>
<id>1</id>
<value>4</value>
</item>
<item>
<id>2</id>
<attributes>
<value>5</value>
</attributes>
</item>
</items>
</code>```

into

```<code>{id: 1, value: 4}
{id: 2, attributes{value: 5}}
</code>```

and so on, where I can process and push each map individually before moving onto the next. If there's a library that handles this easily, I'd love to be pointed in that direction.

答: Your map definition looks like JSON and it would be easiest to just convert your XML into JSON</p>

Title: Trying to convert XML values into map

Body:
I have seen a lot of similar problems that keep getting me partway there, but I end up starting to have to build recursive solutions on top which I'm trying to avoid.

I have an XML file I want to convert into a map.

The structure is unknown except for one thing

<items>
<item>
{section to be converted to map}
</item>
<item>
{section to be converted to map}
</item>
</items>

All the solutions I've seen seem to be converting the entire thing into map, or parse through each attribute/value manually.

I'm wondering if there's a method to say...

Jump into items, jump into each item, convert each item to map, then I can process each map individually.

I am streaming through a potentially large file, so don't want to hold the entire thing in memory, just one item at a time.

I have tried to use xmleventreader to do this, but get jammed up in a recursive nightmare. The item was for the event reader to find individual items, and them on those individual items to have them process, but not finding any documentation on how to capture what's between each value so it can be processed as an XML later.

private void parseItemList(MultipartFile file) {
    XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
    try {
        XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(file.getInputStream());
        processItems(xmlEventReader);
    } catch (FileNotFoundException | XMLStreamException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

The idea would be to convert:

<items>
<item>
<id>1</id>
<value>4</value>
</item>
<item>
<id>2</id>
<attributes>
<value>5</value>
</attributes>
</item>
</items>

into

{id: 1, value: 4}
{id: 2, attributes{value: 5}}

and so on, where I can process and push each map individually before moving onto the next. If there's a library that handles this easily, I'd love to be pointed in that direction.


问:
How to make tkinter button interact with my script?
I am new to coding and trying to figure this out and I cannot, and I can't seem to find any videos on youtube that shows this either.

Essentially what i want to do is have a loop running, and be able to click a button and it change a variable in the loop.  For instance:

```<code>from tkinter import *
import time

root = Tk()
x = 0

def changeVariable():
    x = x + 5

button1 = Button(root, text="add 5", command=changeVariable)
button1.pack()

while True:
    root.mainloop()
    while x > 0:
        print("X is greater than 0")
        x = x - 1
        time.sleep(1)
    else:
        print("Please click the button")
        time.sleep(1)
</code>```

I have tried all sorts of things and i cannot get the button to change the value of X in my while loop. Can someone please explain how to do this or link a video/guide that does a good job explaining this to a novice?

Thanks

答:
You cannot put code after the mainloop. You do not need root.mainloop as there is a forever loop already in your code. You can just remove root.mainloop and your code should work.

Edit: Another issue is that x is not defined globally. At the beginning of the changeVariable function, add the code global x.

The final issue is that you use time.sleep(). You don't want to use a time.sleep as the button could be pressed while everything is frozen. See edit 2 for a fix.

Edit 2:

You can use the tkinter after method. The after method can be applied to any tkinter object. In this case, we will apply it to root. This is the basic syntax: root.after(milliseconds, function_to_execute_after_wait). The function to execute is optional. In your case, instead of time.sleep(1), you should use root.after(1000). Make sure to add a root.update() after your root.after(1000).

You can also use += or -= for changing variables. Instead of x = x + 5, you can use x += 5. Instead of x = x - 1, you can use x -= 1.

Final Code:

from tkinter import *

root = Tk()
x = 0

def changeVariable():
    global x
    x += 5

button1 = Button(root, text="add 5", command=changeVariable)
button1.pack()

while True:
    while x > 0:
        print("X is greater than 0")
        x -= 1
        root.after(1000)
        root.update()
    else:
        print("Please click the button")
        root.after(1000)
        root.update()
```

Body:
I am new to coding and trying to figure this out and I cannot, and I can't seem to find any videos on youtube that shows this either.

Essentially what i want to do is have a loop running, and be able to click a button and it change a variable in the loop.  For instance:

from tkinter import *
import time

root = Tk()
x = 0

def changeVariable():
    x = x + 5

button1 = Button(root, text="add 5", command=changeVariable)
button1.pack()

while True:
    root.mainloop()
    while x > 0:
        print("X is greater than 0")
        x = x - 1
        time.sleep(1)
    else:
        print("Please click the button")
        time.sleep(1)

I have tried all sorts of things and i cannot get the button to change the value of X in my while loop. Can someone please explain how to do this or link a video/guide that does a good job explaining this to a novice?

Thanks


问:
How to check if cell data exist in two different dataframes rows
I have two files. They already sorted by first column.
I need some how check if row data from first file equals (or exist) to the same row in second file.
If data not exist (meaning new value or was changed) I would like to update both files with " ".

Example

old

```<code>col1 col2 col3 col4

val1 val2 val3 val4
val5 val6 val7 val8
</code>```

new

```<code>col1 col2 col3 col4
val1 val2 val3 val4
val9 val5 val6 val7
</code>```

Result

old_updated

```<code>col1 col2 col3 col4 col5
val1 val2 val3 val4 nan
     val5 val6 val7 val8
</code>```

new_updated

```<code>col1 col2 col3 col4 col5
val1 val2 val3 val4
val9 val5 val6 val7
</code>```

I already tried isin for series

答:
Here's a start using pandas merge with the indicator flag set to True. This will add a column telling you what the source of that row is.

```<code>dfnew = pd.DataFrame([["x","y","z","t"], ["a","s","b","e"]],
                     columns=("col1","col2","col3","col4"))
dfold = pd.DataFrame([["x","y","z","t"],["d","a","b","t"]],
                     columns=("col1","col2","col3","col4"))

df_merge = pd.merge(dfnew, dfold, how="outer", indicator=True)
>>>
  col1 col2 col3 col4      _merge
0    x    y    z    t        both
1    a    s    b    e   left_only
2    d    a    b    t  right_only
</code>```

With an outer join you'll see everything. You can do a how="left" if you only want the dfnew rows represented.

From here you can mask on the _merge column etc, as you see fit. Your use case isn't clear so this should get you going.

Body:
I have two files. They already sorted by first column.
I need some how check if row data from first file equals (or exist) to the same row in second file.
If data not exist (meaning new value or was changed) I would like to update both files with " ".

Example

old

col1 col2 col3 col4

val1 val2 val3 val4
val5 val6 val7 val8

new

col1 col2 col3 col4
val1 val2 val3 val4
val9 val5 val6 val7

Result

old_updated

col1 col2 col3 col4 col5
val1 val2 val3 val4 nan
     val5 val6 val7 val8

new_updated

col1 col2 col3 col4 col5
val1 val2 val3 val4
val9 val5 val6 val7

I already tried isin for series

Body:
Here's a start using pandas merge with the indicator flag set to True. This will add a column telling you what the source of that row is.

dfnew = pd.DataFrame([["x","y","z","t"], ["a","s","b","e"]],
                     columns=("col1","col2","col3","col4"))
dfold = pd.DataFrame([["x","y","z","t"],["d","a","b","t"]],
                     columns=("col1","col2","col3","col4"))

df_merge = pd.merge(dfnew, dfold, how="outer", indicator=True)
>>>
  col1 col2 col3 col4      _merge
0    x    y    z    t        both
1    a    s    b    e   left_only
2    d    a    b    t  right_only

With an outer join you'll see everything. You can do a how="left" if you only want the dfnew rows represented.

From here you can mask on the _merge column etc, as you see fit. Your use case isn't clear so this should get you going.


问:
Git - How to handle changes in locally renamed files when pulling from a parent repo

Question

I'm having issues pulling a parent repository into a fork and properly resolving conflicts.
It appears that if a file is renamed in the fork and is modified by both the parent and the fork, git only treats it as being deleted by us.

This happens when I use git pull /path/to/parent master and git merge upstream/master (with upstream configured).

How can I use git such that I am prompted to resolve the conflict on the renamed file instead of having git assume the file was deleted by us?

Setup

Here is a setup to demonstrate the issue I'm having. This can be done locally or in an online managed system (I'm experiencing this in Azure DevOps / VSTS).

I've duplicated most of the steps below in GitHub with these two repos:

parent - https://github.com/Daniel-Khodabakhsh/TestForkPull

fork - https://github.com/Daniel-H-K/TestForkPull

You can clone the fork and do a git pull https://github.com/Daniel-Khodabakhsh/TestForkPull.git master to see the issue.

Manual steps:

Create a small project with files with arbitrary text named A.txt, B.txt, and C.txt in a repo path /path/to/parent.

Create a fork of this repo by copying it to /path/to/fork and switch to this path.

In this new fork repo, rename the files in the following way and commit. I did it with the OS instead of using git mv but this shouldn't matter because of how git works.

```<code>A.txt → X.txt
B.txt → Y.txt
C.txt → Z.txt
</code>```

Verify git recognises the rename by running git diff --name-status HEAD~1 and noticing the 'R' indicating a detected rename.

```<code>$ git diff --name-status HEAD~1
R100    A.txt   X.txt
R100    B.txt   Y.txt
R100    C.txt   Z.txt
</code>```

In the parent repo, make modifications to the contents of files A.txt and B.txt.

In the fork repo, make modifications to the contents of files Y.txt and Z.txt.

Up to here, you'd have the following files in both repos:

```<code>A.txt → X.txt - Modified in parent
B.txt → Y.txt - Modified in both
C.txt → Z.txt - Modified in fork
</code>```

"pull" the parent repo into the fork by running git pull /path/to/parent master from the fork path. You will get the following output:

```<code>$ git pull /path/to/parent/ master
remote: Enumerating objects: 7, done.
remote: Counting objects: 100% (7/7), done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 4 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (4/4), done.
From D:/path/to/parent
 * branch            master     -> FETCH_HEAD
CONFLICT (modify/delete): B.txt deleted in HEAD and modified in ba146eba53bd7d51c9977238d9d62b56f7a984f7. Version ba146eba53bd7d51c9977238d9d62b56f7a984f7 of B.txt left in tree.
Automatic merge failed; fix conflicts and then commit the result.
</code>```

```<code>$ git status
On branch master
You have unmerged paths.
  (fix conflicts and run "git commit")
  (use "git merge --abort" to abort the merge)

Changes to be committed:

        modified:   X.txt

Unmerged paths:
  (use "git add/rm <file>..." as appropriate to mark resolution)

        deleted by us:   B.txt
</code>```

Here X.txt correctly only shows the modification from the parent repo, Z.txt is correctly untouched with changes from the fork repo, but Y.txt (B.txt) is not properly shown as in conflict, but rather, shown as only being deleted by us.

答:
It appears that if a file is renamed in the fork and is modified by both the parent and the fork, git only treats it as being deleted by us.

Note that git doesn't track file renames or moves. This means that when a file is moved on on branch and modified on another branch, you will get merge conflicts as you have seen.

How can I use git such that I am prompted to resolve the conflict on the renamed file instead of having git assume the file was deleted by us?

You have to manually make the modifications in the moved version of the file.

Body:
Question

I'm having issues pulling a parent repository into a fork and properly resolving conflicts.
It appears that if a file is renamed in the fork and is modified by both the parent and the fork, git only treats it as being deleted by us.

This happens when I use git pull /path/to/parent master and git merge upstream/master (with upstream configured).

How can I use git such that I am prompted to resolve the conflict on the renamed file instead of having git assume the file was deleted by us?

Setup

Here is a setup to demonstrate the issue I'm having. This can be done locally or in an online managed system (I'm experiencing this in Azure DevOps / VSTS).

I've duplicated most of the steps below in GitHub with these two repos:

parent - https://github.com/Daniel-Khodabakhsh/TestForkPull

fork - https://github.com/Daniel-H-K/TestForkPull

You can clone the fork and do a git pull https://github.com/Daniel-Khodabakhsh/TestForkPull.git master to see the issue.

Manual steps:

Create a small project with files with arbitrary text named A.txt, B.txt, and C.txt in a repo path /path/to/parent.

Create a fork of this repo by copying it to /path/to/fork and switch to this path.

In this new fork repo, rename the files in the following way and commit. I did it with the OS instead of using git mv but this shouldn't matter because of how git works.

A.txt → X.txt
B.txt → Y.txt
C.txt → Z.txt

Verify git recognises the rename by running git diff --name-status HEAD~1 and noticing the 'R' indicating a detected rename.

$ git diff --name-status HEAD~1
R100    A.txt   X.txt
R100    B.txt   Y.txt
R100    C.txt   Z.txt

In the parent repo, make modifications to the contents of files A.txt and B.txt.

In the fork repo, make modifications to the contents of files Y.txt and Z.txt.

Up to here, you'd have the following files in both repos:

A.txt → X.txt - Modified in parent
B.txt → Y.txt - Modified in both
C.txt → Z.txt - Modified in fork

"pull" the parent repo into the fork by running git pull /path/to/parent master from the fork path. You will get the following output:

$ git pull /path/to/parent/ master
remote: Enumerating objects: 7, done.
remote: Counting objects: 100% (7/7), done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 4 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (4/4), done.
From D:/path/to/parent
 * branch            master     -> FETCH_HEAD
CONFLICT (modify/delete): B.txt deleted in HEAD and modified in ba146eba53bd7d51c9977238d9d62b56f7a984f7. Version ba146eba53bd7d51c9977238d9d62b56f7a984f7 of B.txt left in tree.
Automatic merge failed; fix conflicts and then commit the result.

$ git status
On branch master
You have unmerged paths.
  (fix conflicts and run "git commit")
  (use "git merge --abort" to abort the merge)

Changes to be committed:

        modified:   X.txt

Unmerged paths:
  (use "git add/rm <file>..." as appropriate to mark resolution)

        deleted by us:   B.txt

Here X.txt correctly only shows the modification from the parent repo, Z.txt is correctly untouched with changes from the fork repo, but Y.txt (B.txt) is not properly shown as in conflict, but rather, shown as only being deleted by us.


问:
Ktor HttpClient is hang in runBlocking
I am validating App Store recipes in a server-side Kotlin using with Ktor's HttpClient (Ktor version is 1.2.1). Here is my code so far:

```<code>class AppStoreClient(
        val url: String,
        val password: String,
        val excludeOldTransactions: Boolean = true
) {
    private val objectMapper = ObjectMapperFactory.defaultObjectMapper()
    private val client = HttpClient(Apache /* tried with CIO as well */) {
        install(JsonFeature) {
            serializer = JacksonSerializer()
        }
    }

    suspend fun validate(receipt: String): VerifyReceiptResponse {
        val post = client.post<String> {
            url(this@AppStoreClient.url)
            contentType(ContentType.Application.Json)
            accept(ContentType.Application.Json)
            body = VerifyReceiptRequest(
                    receipt,
                    password,
                    excludeOldTransactions
            )
        }

        // client.close()

        // Apple does not send Content-Type header ¯\_(ツ)_/¯
        // So Ktor's deserialization is not working here and
        // I have to manually deserialize the response.
        return objectMapper.readValue(post)
    }
}
</code>```

And here I'm testing it:

```<code>fun main() = runBlocking {
    val client = AppStoreClient("https://sandbox.itunes.apple.com/verifyReceipt", "<password>")

    println(client.validate("<recipe1>"))
    // println(client.validate("<recipe2>"))
    // println(client.validate("<recipe3>"))
}
</code>```

I got all the responses (one or three) in the output, but then my app just hangs and never quits the main method. Looks like runBlocking is still waiting for something, like client.close. Indeed, if I close the client after the first request, the app successfully ends, but that will force me to create the client on each separate validation request. Client's pipeline configuration seems to be time-consuming and AppStoreClient is meant to be a long-lived object, so I thought the client can share its lifecycle (probably even dependency-injected).

Is the io.ktor.client.HttpClient a long-lived object that can be re-used for multiple requests or should I create a new one for each request?

If yes, what am I doing wrong with it, so the runBlocking hangs?

P.S. The code works with Ktor 1.1.1! Is it a bug?

P.P.S. This code hangs as well:

```<code>fun main() {
    val client = AppStoreClient("...", "...")

    runBlocking {
        println(client.validate("..."))
        println(client.validate("..."))
        println(client.validate("..."))
    }

    runBlocking {
        println(client.validate("..."))
        println(client.validate("..."))
        println(client.validate("..."))
    }
}
</code>```

So I might seriously consider closing the client.

答:
Is the io.ktor.client.HttpClient a long-lived object that can be re-used for multiple requests or should I create a new one for each request?

Yes, it's recommended to use single HttpClient, since some resources (like thread-pool in case of ApacheHttpClient) allocated under the hood, and there are no reasons to create new client each time.

If yes, what am I doing wrong with it, so the runBlocking hangs?

Your problem with closing client, not with coroutines itself, consider this example which also "hangs":

```<code>fun main() {
    val client = HttpAsyncClients.createDefault().also {
        it.start()
    }
}
</code>```

So in my practice, closing client responsibility of developer, like this:

```<code>fun main() {
    val client = HttpAsyncClients.createDefault().also {
        it.start()
    }

    client.close() // we're good now

}
</code>```

Or using Runtime.addShutodownHook in more complex applications.

P.S. The code works with Ktor 1.1.1! Is it a bug?

I think this is real question, what 1.1.1 do, that 1.2.1 don't (or visa-versa)

UPD.

According Ktor Client documentation, you should close client manually:

```<code>suspend fun sequentialRequests() {
    val client = HttpClient()

    // Get the content of an URL.
    val firstBytes = client.get<ByteArray>("https://127.0.0.1:8080/a")

    // Once the previous request is done, get the content of an URL.
    val secondBytes = client.get<ByteArray>("https://127.0.0.1:8080/b")

    client.close()
}
</code>```

Title: Ktor HttpClient is hang in runBlocking

Body:
I am validating App Store recipes in a server-side Kotlin using with Ktor's HttpClient (Ktor version is 1.2.1). Here is my code so far:

class AppStoreClient(
        val url: String,
        val password: String,
        val excludeOldTransactions: Boolean = true
) {
    private val objectMapper = ObjectMapperFactory.defaultObjectMapper()
    private val client = HttpClient(Apache /* tried with CIO as well */) {
        install(JsonFeature) {
            serializer = JacksonSerializer()
        }
    }

    suspend fun validate(receipt: String): VerifyReceiptResponse {
        val post = client.post<String> {
            url(this@AppStoreClient.url)
            contentType(ContentType.Application.Json)
            accept(ContentType.Application.Json)
            body = VerifyReceiptRequest(
                    receipt,
                    password,
                    excludeOldTransactions
            )
        }

        // client.close()

        // Apple does not send Content-Type header ¯\_(ツ)_/¯
        // So Ktor's deserialization is not working here and
        // I have to manually deserialize the response.
        return objectMapper.readValue(post)
    }
}

And here I'm testing it:

fun main() = runBlocking {
    val client = AppStoreClient("https://sandbox.itunes.apple.com/verifyReceipt", "<password>")

    println(client.validate("<recipe1>"))
    // println(client.validate("<recipe2>"))
    // println(client.validate("<recipe3>"))
}

I got all the responses (one or three) in the output, but then my app just hangs and never quits the main method. Looks like runBlocking is still waiting for something, like client.close. Indeed, if I close the client after the first request, the app successfully ends, but that will force me to create the client on each separate validation request. Client's pipeline configuration seems to be time-consuming and AppStoreClient is meant to be a long-lived object, so I thought the client can share its lifecycle (probably even dependency-injected).

Is the io.ktor.client.HttpClient a long-lived object that can be re-used for multiple requests or should I create a new one for each request?

If yes, what am I doing wrong with it, so the runBlocking hangs?

P.S. The code works with Ktor 1.1.1! Is it a bug?

P.P.S. This code hangs as well:

fun main() {
    val client = AppStoreClient("...", "...")

    runBlocking {
        println(client.validate("..."))
        println(client.validate("..."))
        println(client.validate("..."))
    }

    runBlocking {
        println(client.validate("..."))
        println(client.validate("..."))
        println(client.validate("..."))
    }
}

So I might seriously consider closing the client.

Body:
Is the io.ktor.client.HttpClient a long-lived object that can be re-used for multiple requests or should I create a new one for each request?

Yes, it's recommended to use single HttpClient, since some resources (like thread-pool in case of ApacheHttpClient) allocated under the hood, and there are no reasons to create new client each time.

If yes, what am I doing wrong with it, so the runBlocking hangs?

Your problem with closing client, not with coroutines itself, consider this example which also "hangs":

fun main() {
    val client = HttpAsyncClients.createDefault().also {
        it.start()
    }
}

So in my practice, closing client responsibility of developer, like this:

fun main() {
    val client = HttpAsyncClients.createDefault().also {
        it.start()
    }

    client.close() // we're good now

}

Or using Runtime.addShutodownHook in more complex applications.

P.S. The code works with Ktor 1.1.1! Is it a bug?

I think this is real question, what 1.1.1 do, that 1.2.1 don't (or visa-versa)

UPD.

According Ktor Client documentation, you should close client manually:

suspend fun sequentialRequests() {
    val client = HttpClient()

    // Get the content of an URL.
    val firstBytes = client.get<ByteArray>("https://127.0.0.1:8080/a")

    // Once the previous request is done, get the content of an URL.
    val secondBytes = client.get<ByteArray>("https://127.0.0.1:8080/b")

    client.close()
}


问:
Facebook database design?
I have always wondered how Facebook designed the friend <-> user relation.

I figure the user table is something like this:

```<code>user_email PK
user_id PK
password
</code>```

I figure the table with user's data (sex, age etc connected via user email I would assume).

How does it connect all the friends to this user?

Something like this?

```<code>user_id
friend_id_1
friend_id_2
friend_id_3
friend_id_N
</code>```

Probably not. Because the number of users is unknown and will expand.

答:
Its a type of graph database:
http://components.neo4j.org/neo4j-examples/1.2-SNAPSHOT/social-network.html

Its not related to Relational databases.

Google for graph databases.

Title: Facebook database design?

Body:
I have always wondered how Facebook designed the friend <-> user relation.

I figure the user table is something like this:

user_email PK
user_id PK
password

I figure the table with user's data (sex, age etc connected via user email I would assume).

How does it connect all the friends to this user?

Something like this?

user_id
friend_id_1
friend_id_2
friend_id_3
friend_id_N

Probably not. Because the number of users is unknown and will expand.


问:
MongoDb Aggregation $count to display 0
I have a collections with 7 Subjects.

6 Subjects with credit value of 3

1 Subject with credit value of 6.

I have to find the total number of subjects that have credit value of more than 6.

How to i make it print 0?

```<code>db.Subject.aggregate([{$match:{"subject.prerequisite":{$gt:6}}},
                      {$count:"Total"}])
</code>```

Expected: Total : 0

Actual: Nothing

答:
As your $match returns no documents MongoDB simply stops processing further pipeline stages which is a bit counterintuitive in this case since you expect $count to always return the number of documents, even if it's 0.

If you want to get total value anyway you can take advantage of $facet operator, try:

```<code>db.Subject.aggregate([
    {
        $facet: {
            matched: [ {$match:{"subject.prerequisite":{$gt:6}}} ]
        }
    },
    {
        $project: {
            Total: { $size: "$matched" }
        }
    }
])
</code>```

Title: MongoDb Aggregation $count to display 0

Body:
I have a collections with 7 Subjects.

6 Subjects with credit value of 3

1 Subject with credit value of 6.

I have to find the total number of subjects that have credit value of more than 6.

How to i make it print 0?

db.Subject.aggregate([{$match:{"subject.prerequisite":{$gt:6}}},
                      {$count:"Total"}])

Expected: Total : 0

Actual: Nothing

Body:
As your $match returns no documents MongoDB simply stops processing further pipeline stages which is a bit counterintuitive in this case since you expect $count to always return the number of documents, even if it's 0.

If you want to get total value anyway you can take advantage of $facet operator, try:

db.Subject.aggregate([
    {
        $facet: {
            matched: [ {$match:{"subject.prerequisite":{$gt:6}}} ]
        }
    },
    {
        $project: {
            Total: { $size: "$matched" }
        }
    }
])


问:
Python Decorator - printing description instead of name
I have the below decorator function for printing response times. Is there a way to pass description of the decorator when decorating another function with this decorator? For eg: I want to print "calling service xyz" instead of function name "call_service_xyz"</p>

```<code> def timer(func):
        """Print the runtime of the decorated function"""
        @functools.wraps(func)
        def wrapper_timer(*args, **kwargs):
            start_time = time.perf_counter()    # 1
            value = func(*args, **kwargs)
            end_time = time.perf_counter()      # 2
            run_time = end_time - start_time    # 3
            logger.info(f"Finished {func.__name__!r} in {run_time:.4f} secs")
            return value
        return wrapper_timer

@timer("call service xyz")
def call_service_xyz():
</code>```

答:
You could print the docstring to act as the description of the function:

```<code> def timer(func):
    """Print the runtime of the decorated function"""
    @functools.wraps(func)
    def wrapper_timer(*args, **kwargs):
        start_time = time.perf_counter()    # 1
        value = func(*args, **kwargs)
        end_time = time.perf_counter()      # 2
        run_time = end_time - start_time    # 3
        logger.info(f"{desc} Finished in {run_time:.4f} secs")
        return value
    return wrapper_timer

@timer
def call_service_xyz():
    """Call service xyz."""
    # ^^ this is the docstring which is
    # assigned to .__doc__
</code>```

Alternatively, if you wish to pass the description into timer you need to create another layer to the decorator which accepts arguments:

```<code>def timer(desc):
    def decorator(func):
        @functools.wraps(func)
        def wrapper_timer(*args, **kw):
            start_time = time.perf_counter()
            value = func(*args, **kw)
            end_time = time.perf_counter()
            run_time = end_time - start_time
            logger.info(f"{func.__doc__!r} Finished in {run_time:.4f} secs")
            return value
        return wrapper_timer
    return decorator
</code>```

Now use as you describe in your question:

```<code>@timer('call service xyz')
def xyz():
    ...
</code>```

Body:
I have the below decorator function for printing response times. Is there a way to pass description of the decorator when decorating another function with this decorator? For eg: I want to print "calling service xyz" instead of function name "call_service_xyz"

 def timer(func):
        """Print the runtime of the decorated function"""
        @functools.wraps(func)
        def wrapper_timer(*args, **kwargs):
            start_time = time.perf_counter()    # 1
            value = func(*args, **kwargs)
            end_time = time.perf_counter()      # 2
            run_time = end_time - start_time    # 3
            logger.info(f"Finished {func.__name__!r} in {run_time:.4f} secs")
            return value
        return wrapper_timer

@timer("call service xyz")
def call_service_xyz():

Body:
You could print the docstring to act as the description of the function:

 def timer(func):
    """Print the runtime of the decorated function"""
    @functools.wraps(func)
    def wrapper_timer(*args, **kwargs):
        start_time = time.perf_counter()    # 1
        value = func(*args, **kwargs)
        end_time = time.perf_counter()      # 2
        run_time = end_time - start_time    # 3
        logger.info(f"{desc} Finished in {run_time:.4f} secs")
        return value
    return wrapper_timer

@timer
def call_service_xyz():
    """Call service xyz."""
    # ^^ this is the docstring which is
    # assigned to .__doc__

Alternatively, if you wish to pass the description into timer you need to create another layer to the decorator which accepts arguments:

def timer(desc):
    def decorator(func):
        @functools.wraps(func)
        def wrapper_timer(*args, **kw):
            start_time = time.perf_counter()
            value = func(*args, **kw)
            end_time = time.perf_counter()
            run_time = end_time - start_time
            logger.info(f"{func.__doc__!r} Finished in {run_time:.4f} secs")
            return value
        return wrapper_timer
    return decorator

Now use as you describe in your question:

@timer('call service xyz')
def xyz():
    ...