问:
Mongoose is saying I have 46 records, mongoDB says I have zero?
The following test script says I have 46 records:

```<code>var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var DealSchema = new Schema({
  title : String,
});

var Deal = mongoose.model('Deal', DealSchema);

mongoose.connect('mongodb://localhost/dealsite');
mongoose.connection.on("open", function(){
  console.log("Mongoose connected");
  Deal.count({}, function( err, count){
    console.log( "Records:", count );
  })
});
</code>```

output:

```<code>$ node testmongo.js
Mongoose connected
Records: 46
</code>```

While if I try to read the cords using the mongo shell I get a different story:

```<code>$ mongo localhost/dealsite
MongoDB shell version: 1.4.4
url: localhost/dealsite
connecting to: localhost/dealsite
type "exit" to exit
type "help" for help
> db.dealsite.count()
0
> db.dealsite.Deal.count()
0
</code>```

Where are my records hiding?

答:
you missed the statement :

```<code>"use Deal"    [ use DATABASE_NAME ]
</code>```

before doing

```<code>db.dealsite.count()
</code>```

Body:
The following test script says I have 46 records:

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var DealSchema = new Schema({
  title : String,
});

var Deal = mongoose.model('Deal', DealSchema);

mongoose.connect('mongodb://localhost/dealsite');
mongoose.connection.on("open", function(){
  console.log("Mongoose connected");
  Deal.count({}, function( err, count){
    console.log( "Records:", count );
  })
});

output:

$ node testmongo.js
Mongoose connected
Records: 46

While if I try to read the cords using the mongo shell I get a different story:

$ mongo localhost/dealsite
MongoDB shell version: 1.4.4
url: localhost/dealsite
connecting to: localhost/dealsite
type "exit" to exit
type "help" for help
> db.dealsite.count()
0
> db.dealsite.Deal.count()
0

Where are my records hiding?

Body:
you missed the statement :

"use Deal"    [ use DATABASE_NAME ]

before doing

db.dealsite.count()


来源: stackexchange

问:
Get MAC address of host inside a docker container
I'm looking for an efficient way to get the MAC address of host inside a docker container. The docker container will not run with host network enabled and I don't want to supply the MAC address as an ENV variable. There would be a program ( preferably C++ or Python code ) that runs inside the docker container. The program would write the MAC address to a file. The MAC address will be the true MAC address of the host's network device. The docker will have a Ubuntu operating system. Any ways of achieving this? </p>

答:
Try this

```<code>ifconfig -a | grep -Po 'HWaddr \K.*$') > /path/you/choose/host_mac_address
</code>```

When running you docker run

```<code>    docker run -v /path/you/choose:/app container
</code>```

Inside your app just need to open the file located /app/host_mac_address

Make all of this better when you got the idea

All of this will be better using an ENV variable (but you dont want this solution)

ContentLicense: CC BY-SA 4.0

Body:
Try this

ifconfig -a | grep -Po 'HWaddr \K.*$') > /path/you/choose/host_mac_address

When running you docker run

    docker run -v /path/you/choose:/app container

Inside your app just need to open the file located /app/host_mac_address

Make all of this better when you got the idea

All of this will be better using an ENV variable (but you dont want this solution)


问:
Retrieve logged user information from cloud foundry web application
We developed a web application using SAP Web-IDE Full Stack; we need to retrieve the details of the user logged into application (as defined in SAP Cloud Platform Identity Authentication Administration), for example display name and assigned groups.
We tried the userapi/currentUser API, but it seems to work only on NEO environment, for this reason is working fine while debugging in Web-IDE, but we get a 404 error when deploying the app on Cloud Foundry.
Do we need to add a new destination to make userapi work also on CF? Or is there some kind of similar solution available on Cloud Foundry?</p>

答:
In SAP Cloud Foundry if you develop a MTA using XSUAA service to manage User Authentication and Admistration, defined for example in the mta.yaml,

```<code>...
resources:
  - name: uaa_myapp
  parameters:
    path: ./xs-security.json
    service-plan: application
    service: xsuaa
  type: org.cloudfoundry.managed-service
...
</code>```

you can use the UAA API published from XSUAA service self to manage user authentication and authorization (e.g.: retrieve user info, groups assigned, password management etc..). also in the case the application is federated with another IDP.

To consume this API for example to retrieve user info you need to:

Determine the XSUAA endpoint bound to your app (SCP Cockpit > XSUAA service detail > take the value url)

Create a destination (xsuaa_api_destination) of type OAuth2TokenExchange bound to your app with url url took before, and fill OAuth2 authentication parameters with the data contained in XSUAA service detail (step 1).

From your app execute the call xsuaa_api_destination/userinfo, for example using an ajax if you are using JS.

You can find other info in Account and Authentication Service of the Cloud Foundry Environment SAP doc.

Body:
In SAP Cloud Foundry if you develop a MTA using XSUAA service to manage User Authentication and Admistration, defined for example in the mta.yaml,

...
resources:
  - name: uaa_myapp
  parameters:
    path: ./xs-security.json
    service-plan: application
    service: xsuaa
  type: org.cloudfoundry.managed-service
...

you can use the UAA API published from XSUAA service self to manage user authentication and authorization (e.g.: retrieve user info, groups assigned, password management etc..). also in the case the application is federated with another IDP.

To consume this API for example to retrieve user info you need to:

Determine the XSUAA endpoint bound to your app (SCP Cockpit > XSUAA service detail > take the value url)

Create a destination (xsuaa_api_destination) of type OAuth2TokenExchange bound to your app with url url took before, and fill OAuth2 authentication parameters with the data contained in XSUAA service detail (step 1).

From your app execute the call xsuaa_api_destination/userinfo, for example using an ajax if you are using JS.

You can find other info in Account and Authentication Service of the Cloud Foundry Environment SAP doc.


问:
How to use PostgreSQL varchar column value in IN query
In PostgreSQL database we have a column with varchar value in which values are stored like this [1,2,3,4,5]
I need to check that in a function with In clause.
For example,

```<code>--Some SQL Query with many joins
AND OtherTable.PhoneNumber NOT IN((myTable.PhoneNumberJson));
</code>```

I tried passing the values in various ways using BLIMIT, RegExReplace and type casting the values but still getting the error.
How to convert the varchar object["1,2,3,4,5"]  list to integer number and use it inside the IN clause.

答:
In Postgres, you can use the ? operator to check if a jsonb array contains a given value:

```<code>AND myTable.PhoneNumberJson ? OtherTable.PhoneNumber
</code>```

Please note that this requires PhoneNumberJson to be of jsonb datatype. If it's a json, then you can cast first:

```<code>AND myTable.PhoneNumberJson::jsonb ? OtherTable.PhoneNumber
</code>```

Body:
In PostgreSQL database we have a column with varchar value in which values are stored like this [1,2,3,4,5]
I need to check that in a function with In clause.
For example,

--Some SQL Query with many joins
AND OtherTable.PhoneNumber NOT IN((myTable.PhoneNumberJson));

I tried passing the values in various ways using BLIMIT, RegExReplace and type casting the values but still getting the error.
How to convert the varchar object["1,2,3,4,5"]  list to integer number and use it inside the IN clause.

Body:
In Postgres, you can use the ? operator to check if a jsonb array contains a given value:

AND myTable.PhoneNumberJson ? OtherTable.PhoneNumber

Please note that this requires PhoneNumberJson to be of jsonb datatype. If it's a json, then you can cast first:

AND myTable.PhoneNumberJson::jsonb ? OtherTable.PhoneNumber


问:
Position footer always on viewport bottom
I have a footer that contain the user name. I want to show it always on the bottom of the viewport. Like a fixed bottom bar but only on my sidebar.

I use the function

```<code>function setFooterStyle() {
    var docHeight = $(window).height();
    var footerHeight = $('#footer').outerHeight();
    var footerTop = $('#footer').position().top + footerHeight;

    $('#footer').css('margin-top', (docHeight - footerTop) + 'px');

    $('#footer').removeClass('invisible');
}
</code>```

this inside:

```<code>$( function () {
    setFooterStyle();
    window.onresize = setFooterStyle;
}
</code>```

But because I use a sidebar I thing the margin-top will place the footer the amount of pixel under the sidebar and not under the page top. So it is somewhere at the bottom of the document and I have to scroll to see.

Any idea what I do wrong to keep the text always on the bottom of the viewport, while resize ans while scroll?

答:
The general term for what you are trying to do is "Sticky Footer". The trick is to make a wrapper div for your content above the footer that takes up 100% of the height of the viewport, then to use negative margins on the footer to move it up the same amount as the height of the footer. Then the footer is always at the bottom of the viewport. Then you need to add padding to the bottom of the content so that it never gets covered by the footer, now that the footer is not taking up space in the regular flow of the layout.

html, body {
  height: 100%;
  margin: 0;
}
.content {
  min-height: 100%;
}
.content-inside {
  padding: 20px;
  padding-bottom: 50px;
}
.footer {
  height: 50px;
  margin-top: -50px;
}```

https://css-tricks.com/couple-takes-sticky-footer/

Body:
I have a footer that contain the user name. I want to show it always on the bottom of the viewport. Like a fixed bottom bar but only on my sidebar.

I use the function

function setFooterStyle() {
    var docHeight = $(window).height();
    var footerHeight = $('#footer').outerHeight();
    var footerTop = $('#footer').position().top + footerHeight;

    $('#footer').css('margin-top', (docHeight - footerTop) + 'px');

    $('#footer').removeClass('invisible');
}

this inside:

$( function () {
    setFooterStyle();
    window.onresize = setFooterStyle;
}

But because I use a sidebar I thing the margin-top will place the footer the amount of pixel under the sidebar and not under the page top. So it is somewhere at the bottom of the document and I have to scroll to see.

Any idea what I do wrong to keep the text always on the bottom of the viewport, while resize ans while scroll?

Body:
The general term for what you are trying to do is "Sticky Footer". The trick is to make a wrapper div for your content above the footer that takes up 100% of the height of the viewport, then to use negative margins on the footer to move it up the same amount as the height of the footer. Then the footer is always at the bottom of the viewport. Then you need to add padding to the bottom of the content so that it never gets covered by the footer, now that the footer is not taking up space in the regular flow of the layout.

html, body {
  height: 100%;
  margin: 0;
}
.content {
  min-height: 100%;
}
.content-inside {
  padding: 20px;
  padding-bottom: 50px;
}
.footer {
  height: 50px;
  margin-top: -50px;
}

https://css-tricks.com/couple-takes-sticky-footer/


问:
How to base the width of the rest of the elements on the width of the title?
I have some centered divs that have a title and text below the title. The title is centered but the text is aligned on the left and starts from where the title starts. I used inline-block to make the div adjust in size based on the content. However, if the text is longer than the title, the container adjusts its width based on the text, not the title, so then the text appears wider than the title. How do I keep the width based on the title, not the text? I've included my code below as well as a badly drawn image to better understand what happens.

HTML and CSS:

.projects {
  width: 30vw;
  left: 10vw;
  right: 10vw;
  margin: 50px auto 0 auto;
  text-align: center;
}

.pContent {
  display: inline-block;
  margin-bottom: 10px;
}

.pInfo {
  text-align: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="projects">
  <h2>My Projects:</h2>
  <div class="pContent">
    <h3 id="p1" class="pTitle">Project Title</h3>
    <div id="p1Info" class="pInfo">
      <p class="desc">This is a project description Lorem Ipsum Dolor</p>
      <p class="demo">View a demo of the project.</p>
    </div>
  </div>
  <br>
  <div class="pContent">
    <h3 id="p2" class="pTitle">Another Project Title</h3>
    <div id="p2Info" class="pInfo">
      <p class="desc">This is a project</p>
      <p class="demo">View.</p>
    </div>
  </div>
</div></code>```

Here's an image of what I want and what actually happens.

答: How about adding padding-left and padding-right to your container</p>

Body:
I have some centered divs that have a title and text below the title. The title is centered but the text is aligned on the left and starts from where the title starts. I used inline-block to make the div adjust in size based on the content. However, if the text is longer than the title, the container adjusts its width based on the text, not the title, so then the text appears wider than the title. How do I keep the width based on the title, not the text? I've included my code below as well as a badly drawn image to better understand what happens.

HTML and CSS:

.projects {
  width: 30vw;
  left: 10vw;
  right: 10vw;
  margin: 50px auto 0 auto;
  text-align: center;
}

.pContent {
  display: inline-block;
  margin-bottom: 10px;
}

.pInfo {
  text-align: left;
}

My Projects:

Project Title

This is a project description Lorem Ipsum Dolor

View a demo of the project.

Another Project Title

This is a project

View.

Here's an image of what I want and what actually happens.


问:
How to avoid string repetition
I have two different string String A="example"; String B="example";
if concat both the string i am getting examplexample. Is there any possibility to avoid repetition of string with same name..??

答:
The Strings are not different, the same String object is assigned to two different variables ("two pointers to the same memory address").

Consider dumping all strings to a Set before concatenating, this avoids duplicates in the concatenated sequence:

```<code>Set<String> strings = new HashSet<String>();
StringBuilder resultBuilder = new StringBuilder();
for (String s:getAllStrings()) {  // some magic to get all your strings
   if (strings.contains(s))
       continue;                  // has been added already
   resultBuilder.append(s);       // concatenate
   strings.add(s);                // put string to set
}
String result = resultBuilder.toString();
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to avoid string repetition

Body:
The Strings are not different, the same String object is assigned to two different variables ("two pointers to the same memory address").

Consider dumping all strings to a Set before concatenating, this avoids duplicates in the concatenated sequence:

Set<String> strings = new HashSet<String>();
StringBuilder resultBuilder = new StringBuilder();
for (String s:getAllStrings()) {  // some magic to get all your strings
   if (strings.contains(s))
       continue;                  // has been added already
   resultBuilder.append(s);       // concatenate
   strings.add(s);                // put string to set
}
String result = resultBuilder.toString();


问:
Firebase Notifications not being delivered if sent other than firebase console
I am facing a really strange issue, the notifications sent from the Firebase Console are being delivered properly so it means the project is configured and certificates are correct, but when I send notification from the app it doesn't work. I am using the following method to send notifications.

```<code>func sendPushNotification(to token: String, title: String, body: String, Type: String) {

        let urlString = "https://fcm.googleapis.com/fcm/send"
        let url = NSURL(string: urlString)!
        let paramString: [String : Any] =
            [
                "message" :[
                    "to" : token,
                    "notification" : ["title" : title, "body" : body],
                    "data" : ["notification_type": Type]
                ],
                "to" : token
            ]

        print(paramString)
        let request = NSMutableURLRequest(url: url as URL)
        request.httpMethod = "POST"
        request.httpBody = try? JSONSerialization.data(withJSONObject:paramString, options: [.prettyPrinted])
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue("key=AAAApQ9EAjg:XXXX", forHTTPHeaderField: "Authorization")
        let task =  URLSession.shared.dataTask(with: request as URLRequest)  { (data, response, error) in
            do {
                if let jsonData = data {
                    if let jsonDataDict  = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: AnyObject] {
                        NSLog("Received data:\n\(jsonDataDict))")
                    }
                }
            } catch let err as NSError {
                print(err.debugDescription)
            }
        }
        task.resume()

    }
</code>```

I have also tried sending through curl with the following method

```<code><?php
/**
 * Created by PhpStorm.
 * User: ussaidiqbal
 * Date: 2020-02-17
 * Time: 19:45
 */

$url = "https://fcm.googleapis.com/fcm/send";
$token = "eMIK6wGOTUUutqp62vEIr-:XXXXXX";
$serverKey = 'AIzaSyCJFUydXXXXXXXXXX';
$title = "Title";
$body = "Body of the message";
$notification = array('title' =>$title , 'text' => $body, 'sound' => 'default', 'badge' => '1');
$arrayToSend = array('to' => $token, 'notification' => $notification,'priority'=>'high');
$json = json_encode($arrayToSend);
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: key='. $serverKey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST,

    "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
//Send the request
$response = curl_exec($ch);
//Close request
if ($response === FALSE) {
    die('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);
</code>```

I also have tried to send through PostMan using the following payload

```<code>{
    "notification":{
        "title": "XXXXX",
        "body": "XXXXX"
    },
  "to": "XXXXXXX"
}
</code>```

This is the response of the request

```<code>{
    "multicast_id": 36126XXXXXXXX,
    "success": 1,
    "failure": 0,
    "canonical_ids": 0,
    "results": [
        {
            "message_id": "0:1581960379105057~~~~~~~~~~"
        }
    ]
}
</code>```

None of the above method seems to be working, What am I doing wrong?
I have tried both the Legacy server key and Server key but no luck. Has anyone ever faced such an issue?

答:
I think also that your paramString has the wrong properties. Try that: </p>

```<code>        let paramString: [String : Any] = [
            "to" : token,
            "notification" : ["title" : title, "text" : body],
            "time_to_live" : 60000,
            "sound" : "default"
        ]
</code>```

Body:
I am facing a really strange issue, the notifications sent from the Firebase Console are being delivered properly so it means the project is configured and certificates are correct, but when I send notification from the app it doesn't work. I am using the following method to send notifications.

func sendPushNotification(to token: String, title: String, body: String, Type: String) {

        let urlString = "https://fcm.googleapis.com/fcm/send"
        let url = NSURL(string: urlString)!
        let paramString: [String : Any] =
            [
                "message" :[
                    "to" : token,
                    "notification" : ["title" : title, "body" : body],
                    "data" : ["notification_type": Type]
                ],
                "to" : token
            ]

        print(paramString)
        let request = NSMutableURLRequest(url: url as URL)
        request.httpMethod = "POST"
        request.httpBody = try? JSONSerialization.data(withJSONObject:paramString, options: [.prettyPrinted])
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue("key=AAAApQ9EAjg:XXXX", forHTTPHeaderField: "Authorization")
        let task =  URLSession.shared.dataTask(with: request as URLRequest)  { (data, response, error) in
            do {
                if let jsonData = data {
                    if let jsonDataDict  = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: AnyObject] {
                        NSLog("Received data:\n\(jsonDataDict))")
                    }
                }
            } catch let err as NSError {
                print(err.debugDescription)
            }
        }
        task.resume()

    }

I have also tried sending through curl with the following method

<?php
/**
 * Created by PhpStorm.
 * User: ussaidiqbal
 * Date: 2020-02-17
 * Time: 19:45
 */

$url = "https://fcm.googleapis.com/fcm/send";
$token = "eMIK6wGOTUUutqp62vEIr-:XXXXXX";
$serverKey = 'AIzaSyCJFUydXXXXXXXXXX';
$title = "Title";
$body = "Body of the message";
$notification = array('title' =>$title , 'text' => $body, 'sound' => 'default', 'badge' => '1');
$arrayToSend = array('to' => $token, 'notification' => $notification,'priority'=>'high');
$json = json_encode($arrayToSend);
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: key='. $serverKey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST,

    "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
//Send the request
$response = curl_exec($ch);
//Close request
if ($response === FALSE) {
    die('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);

I also have tried to send through PostMan using the following payload

{
    "notification":{
        "title": "XXXXX",
        "body": "XXXXX"
    },
  "to": "XXXXXXX"
}

This is the response of the request

{
    "multicast_id": 36126XXXXXXXX,
    "success": 1,
    "failure": 0,
    "canonical_ids": 0,
    "results": [
        {
            "message_id": "0:1581960379105057~~~~~~~~~~"
        }
    ]
}

None of the above method seems to be working, What am I doing wrong?
I have tried both the Legacy server key and Server key but no luck. Has anyone ever faced such an issue?

Body:
I think also that your paramString has the wrong properties. Try that:

        let paramString: [String : Any] = [
            "to" : token,
            "notification" : ["title" : title, "text" : body],
            "time_to_live" : 60000,
            "sound" : "default"
        ]


问:
Unable to edit and write information to a new file using Awk and Sed
As part of my homework, I need to take a row containing address information from a text file.

Like This.

```<code>2 GO MOBILITY / CALEX EXPRESS^58 PITTSTON AVENUE^^PITTSTON^PA^18640^570-603-1042
</code>```

Then format the file to look like this.

```<code>Company Name: 2 GO MOBILITY / CALEX EXPRESS
Company Phone Number: 570-603-1042
Company Address: 58 PITTSTON AVENUE, PITTSTON, PA, 18640
\n (blank line)
</code>```

Then append the address to a file called PA_595.txt within the directory ./basefolder/PA.

If a different state is listed then the information should appear in the file in the appropriate folder.

I need to use AWK and SED to do this.

```<code>awk -v FS=^ '{print $1,$2,$3,$4,$5,$6,$7}' "./data/595.txt" | sed i\ " Company Name: $1 \n Company Address: $2,$3,$4,$5 \n Company Phone Number: $6" | tee "./$2/$5/${5}_595.txt"
</code>```

I'm getting

```<code>PERFORMANCE MOBILITY 1640 WEST 7th AVE  EUGENE OR 97402 541-393-8474
Company Name:
Company Addess: ,,,
Company Phone Number:
</code>```

I need

```<code>Company Name:PERFORMANCE MOBILITY
Company Phone Number:541-393-8474
Company Address: 1640 WEST 7th AVE, EUGENE, OR, 97402
</code>```

The awk portion of the code works.  I'm pretty sure the issue is that sed isn't seeing the field names from awk.

I've made progress since last night.  I changed my code to .

```<code>file_name=$1
i=0

while IFS=^ read company_name address1 address2 city state zip phone
do
    ((i++))

echo "./$2/$state/${state}_595.txt"

sed -e "i\ Company Name:$company_name \n Company Phone Number:$phone \n Company Addess: $address1, $city, $state, $zip \n " | tee "./$2/$state/${state}_595.txt"

done < $file_name
</code>```

The problem is that it shows each address as it shows in the txt file.  But then it shows it properly underneath.

>
PERFORMANCE MOBILITY^1640 WEST 7th AVE^^EUGENE^OR^97402^541-393-8474
 Company Name:2 GO MOBILITY / CALEX EXPRESS
 Company Phone Number:570-603-1042
 Company Addess: 58 PITTSTON AVENUE, PITTSTON, PA, 18640

However, the formatting is incorrect in the txt file and all address go to the same txt file.

Company Name:2 GO MOBILITY / CALEX EXPRESS
   Company Phone Number:570-603-1042

Company Addess: 58 PITTSTON AVENUE, PITTSTON, PA, 18640

A & J MOBILITY^3058 HELSAN DR^^RICHFIELD^WI^53716^262-623-6236
 Company Name:2 GO MOBILITY / CALEX EXPRESS
 Company Phone Number:570-603-1042

Company Addess: 58 PITTSTON AVENUE, PITTSTON, PA, 18640

A TO Z MOBILITY AND MEDICAL EQUIPMENT, INC.^P.O. BOX 99^^SOMONAUK^IL^60552^815-495-3423
 Company Name:2 GO MOBILITY / CALEX EXPRESS
 Company Phone Number:570-603-1042

I'm not sure why.

The last response got me almost all the way there.  I'm just left seeing one error.

>
tee: /CA_595.txt: Permission denied

I've checked the folder and file permissions and they are all 775.

I'm using this command when creating the .txt file

```<code>cstates=($(awk -v FS=^ '{print $5}' "$1"))

for i in "${cstates[@]}"
do

    :

if [[ ! -f "./$2/$i/${i}_595.txt" ]]; then

    echo "Making ${i}_595.txt File"
    touch "./$2/$i/${i}_595.txt"
    chmod a+x "./$2/$i/${i}_595.txt"
    else echo "File ${i}_595.txt already exists"

fi
done
</code>```

Or if I just use this command.

```<code>file_name="$1"

while IFS=^ read -r company_name address1 address2 city state zip phone
do

# sed " a\ Company Name:$company_name \n Company Phone Number:$phone \n Company Addess: $address1, $city, $state, $zip \n " | tee -a "./$2/$state/${state}_595.txt"

printf "Company Name: %s\nCompany Address: %s%s, %s, %s, %s\nCompany Phone Number: %s\n\n" \
      "${company_name}" "${address1}" "${address2}" "${city}" "${state}" "${zip}" "${phone}" | tee -a "${outputdir}/${state}_595.txt" > /dev/null

done < $file_name
</code>```

The file and folder permission look ok and it shows me as having ownership of the files and folders.

答:
When you don't have the requirement of writing data to different files, the next command would work:

```<code>   awk -v FS=^ '{
      printf ("Company Name: %s\nCompany Address: %s%s, %s, %s, %s\nCompany Phone Number: %s\n\n",
        $1,$2,$3,$4,$5,$6,$7)
      }' "./data/595.txt"
</code>```

When you want to send parts to different directories, you should print it inside awk to both the file and stdout. Look out for spaces in the name of the dir.

Using a loop is also possible. You can use tee -a (a=append) inside the loop.

```<code>file_name="$1" # Quote, look out for spaces.
i=0
# use read with option -r
while IFS=^ read -r company_name address1 address2 city state zip phone
do
   # Not used: ((i++))
   outputdir="./$2/$state"
   mkdir -p "${outputdir}"
   printf "Company Name: %s\nCompany Address: %s%s, %s, %s, %s\nCompany Phone Number: %s\n\n" \
      "${company_name}" "${address1}" "${address2}" "${city}" "${state}" "${zip}" "${phone}" | tee -a "${outputdir}/${state}_595.txt"
done < "${file_name}"
</code>```

When you don't need to see the complete output in your commandline, you can replace tee -a by >>.

Body:
As part of my homework, I need to take a row containing address information from a text file.

Like This.

2 GO MOBILITY / CALEX EXPRESS^58 PITTSTON AVENUE^^PITTSTON^PA^18640^570-603-1042

Then format the file to look like this.

Company Name: 2 GO MOBILITY / CALEX EXPRESS
Company Phone Number: 570-603-1042
Company Address: 58 PITTSTON AVENUE, PITTSTON, PA, 18640
\n (blank line)

Then append the address to a file called PA_595.txt within the directory ./basefolder/PA.

If a different state is listed then the information should appear in the file in the appropriate folder.

I need to use AWK and SED to do this.

awk -v FS=^ '{print $1,$2,$3,$4,$5,$6,$7}' "./data/595.txt" | sed i\ " Company Name: $1 \n Company Address: $2,$3,$4,$5 \n Company Phone Number: $6" | tee "./$2/$5/${5}_595.txt"

I'm getting

PERFORMANCE MOBILITY 1640 WEST 7th AVE  EUGENE OR 97402 541-393-8474
Company Name:
Company Addess: ,,,
Company Phone Number:

I need

Company Name:PERFORMANCE MOBILITY
Company Phone Number:541-393-8474
Company Address: 1640 WEST 7th AVE, EUGENE, OR, 97402

The awk portion of the code works.  I'm pretty sure the issue is that sed isn't seeing the field names from awk.

I've made progress since last night.  I changed my code to .

file_name=$1
i=0

while IFS=^ read company_name address1 address2 city state zip phone
do
    ((i++))

echo "./$2/$state/${state}_595.txt"

sed -e "i\ Company Name:$company_name \n Company Phone Number:$phone \n Company Addess: $address1, $city, $state, $zip \n " | tee "./$2/$state/${state}_595.txt"

done < $file_name

The problem is that it shows each address as it shows in the txt file.  But then it shows it properly underneath.

>
PERFORMANCE MOBILITY^1640 WEST 7th AVE^^EUGENE^OR^97402^541-393-8474
 Company Name:2 GO MOBILITY / CALEX EXPRESS
 Company Phone Number:570-603-1042
 Company Addess: 58 PITTSTON AVENUE, PITTSTON, PA, 18640

However, the formatting is incorrect in the txt file and all address go to the same txt file.

Company Name:2 GO MOBILITY / CALEX EXPRESS
   Company Phone Number:570-603-1042

Company Addess: 58 PITTSTON AVENUE, PITTSTON, PA, 18640

A & J MOBILITY^3058 HELSAN DR^^RICHFIELD^WI^53716^262-623-6236
 Company Name:2 GO MOBILITY / CALEX EXPRESS
 Company Phone Number:570-603-1042

Company Addess: 58 PITTSTON AVENUE, PITTSTON, PA, 18640

A TO Z MOBILITY AND MEDICAL EQUIPMENT, INC.^P.O. BOX 99^^SOMONAUK^IL^60552^815-495-3423
 Company Name:2 GO MOBILITY / CALEX EXPRESS
 Company Phone Number:570-603-1042

I'm not sure why.

The last response got me almost all the way there.  I'm just left seeing one error.

>
tee: /CA_595.txt: Permission denied

I've checked the folder and file permissions and they are all 775.

I'm using this command when creating the .txt file

cstates=($(awk -v FS=^ '{print $5}' "$1"))

for i in "${cstates[@]}"
do

    :

if [[ ! -f "./$2/$i/${i}_595.txt" ]]; then

    echo "Making ${i}_595.txt File"
    touch "./$2/$i/${i}_595.txt"
    chmod a+x "./$2/$i/${i}_595.txt"
    else echo "File ${i}_595.txt already exists"

fi
done

Or if I just use this command.

file_name="$1"

while IFS=^ read -r company_name address1 address2 city state zip phone
do

# sed " a\ Company Name:$company_name \n Company Phone Number:$phone \n Company Addess: $address1, $city, $state, $zip \n " | tee -a "./$2/$state/${state}_595.txt"

printf "Company Name: %s\nCompany Address: %s%s, %s, %s, %s\nCompany Phone Number: %s\n\n" \
      "${company_name}" "${address1}" "${address2}" "${city}" "${state}" "${zip}" "${phone}" | tee -a "${outputdir}/${state}_595.txt" > /dev/null

done < $file_name

The file and folder permission look ok and it shows me as having ownership of the files and folders.

Body:
When you don't have the requirement of writing data to different files, the next command would work:

   awk -v FS=^ '{
      printf ("Company Name: %s\nCompany Address: %s%s, %s, %s, %s\nCompany Phone Number: %s\n\n",
        $1,$2,$3,$4,$5,$6,$7)
      }' "./data/595.txt"

When you want to send parts to different directories, you should print it inside awk to both the file and stdout. Look out for spaces in the name of the dir.

Using a loop is also possible. You can use tee -a (a=append) inside the loop.

file_name="$1" # Quote, look out for spaces.
i=0
# use read with option -r
while IFS=^ read -r company_name address1 address2 city state zip phone
do
   # Not used: ((i++))
   outputdir="./$2/$state"
   mkdir -p "${outputdir}"
   printf "Company Name: %s\nCompany Address: %s%s, %s, %s, %s\nCompany Phone Number: %s\n\n" \
      "${company_name}" "${address1}" "${address2}" "${city}" "${state}" "${zip}" "${phone}" | tee -a "${outputdir}/${state}_595.txt"
done < "${file_name}"

When you don't need to see the complete output in your commandline, you can replace tee -a by >>.


问:
Avoiding [weak self] for simple operations?
For short-running operations, is it acceptable to avoid [weak self]? For example, URLSession will retain the closure from dataTask(with:completion:):

```<code>final class ViewController: UIViewController {
  let label = UILabel()

  override func viewDidLoad() {
    super.viewDidLoad()
    URLSession.shared.dataTask(with: url) { data, response, error in
      guard let data = data else { return }
      let decodedString = String(bytes: data, encoding: .utf8)

      DispatchQueue.main.async {
        self.label.text = decodedString
      }
    }.resume()
  }
}
</code>```

In this case, the closure captures self strongly, which means even if this ViewController is held in memory by the closure. URLSession will hold the closure until the data task is complete, which means the life cycle of the ViewController can potentially be extended until dataTask completes.

In this situation, should we use capture lists to avoid this behavior? Is my reasoning correct that there's no reference cycle here?

答:
Is my reasoning correct that there's no reference cycle here?

There is no reference cycle here. ViewController is not retaining the dataTask completion handler. You can think of this as iOS keeping a strong reference to both the view controller and the completion handler, and the completion handler also keeping a strong reference to the view controller. There is no strong reference from the view controller back to the completion handler, or to any chain of objects with a reference to the completion handler, so you are cycle-free. Look for this same pattern in UIView.animate, where you are again sending closures to iOS instead of storing them locally.

For short-running operations, is it acceptable to avoid [weak self]?

The duration of the work is not a factor. The two pertinent questions are:

Does a cycle of references exist?

Will the cycle of references be broken?

Take this example:

```<code>class BadVC: UIViewController {
    private lazy var cycleMaker: () -> Void = { print(self) }

    override func loadView() {
        view = UIView()
        cycleMaker()
    }
}
</code>```

BadVC here manages to create a reference cycle that will never be broken as soon as it loads its view. The fact that cycleMaker() will execute in nanoseconds does not save us from a memory leak.

Pragmatically, there is a third question:

Does this code avoid permanent reference cycles in a way that is difficult to understand, easy to break, or unreliable, so reference cycles are likely to emerge in the future due to misuse or modification?

You can break reference cycles manually. For example:

```<code>class StillBadVC: UIViewController {
    private lazy var cycleMaker: () -> Void = { print(self) }

    override func loadView() {
        view = UIView()
        cycleMaker()
    }

    func breakCycle() {
        cycleMaker = { }
    }
}
</code>```

Here, we are in danger because StillBadVC has a strong reference to cycleMaker and cycleMaker captures a strong reference to StillBadVC. The cycle will be broken as long as someone remembers to call breakCycle(), at which point the view controller will remove its strong reference to cycleMaker, allowing cycleMaker to deallocate. However, the cycle will not be broken if someone forgets to call breakCycle(). Calling a method called breakCycle() is not usually a part of the contract for using a view controller, so we would expect StillBadVC to result in memory leaks in practice.

Body:
For short-running operations, is it acceptable to avoid [weak self]? For example, URLSession will retain the closure from dataTask(with:completion:):

final class ViewController: UIViewController {
  let label = UILabel()

  override func viewDidLoad() {
    super.viewDidLoad()
    URLSession.shared.dataTask(with: url) { data, response, error in
      guard let data = data else { return }
      let decodedString = String(bytes: data, encoding: .utf8)

      DispatchQueue.main.async {
        self.label.text = decodedString
      }
    }.resume()
  }
}

In this case, the closure captures self strongly, which means even if this ViewController is held in memory by the closure. URLSession will hold the closure until the data task is complete, which means the life cycle of the ViewController can potentially be extended until dataTask completes.

In this situation, should we use capture lists to avoid this behavior? Is my reasoning correct that there's no reference cycle here?

Body:
Is my reasoning correct that there's no reference cycle here?

There is no reference cycle here. ViewController is not retaining the dataTask completion handler. You can think of this as iOS keeping a strong reference to both the view controller and the completion handler, and the completion handler also keeping a strong reference to the view controller. There is no strong reference from the view controller back to the completion handler, or to any chain of objects with a reference to the completion handler, so you are cycle-free. Look for this same pattern in UIView.animate, where you are again sending closures to iOS instead of storing them locally.

For short-running operations, is it acceptable to avoid [weak self]?

The duration of the work is not a factor. The two pertinent questions are:

Does a cycle of references exist?

Will the cycle of references be broken?

Take this example:

class BadVC: UIViewController {
    private lazy var cycleMaker: () -> Void = { print(self) }

    override func loadView() {
        view = UIView()
        cycleMaker()
    }
}

BadVC here manages to create a reference cycle that will never be broken as soon as it loads its view. The fact that cycleMaker() will execute in nanoseconds does not save us from a memory leak.

Pragmatically, there is a third question:

Does this code avoid permanent reference cycles in a way that is difficult to understand, easy to break, or unreliable, so reference cycles are likely to emerge in the future due to misuse or modification?

You can break reference cycles manually. For example:

class StillBadVC: UIViewController {
    private lazy var cycleMaker: () -> Void = { print(self) }

    override func loadView() {
        view = UIView()
        cycleMaker()
    }

    func breakCycle() {
        cycleMaker = { }
    }
}

Here, we are in danger because StillBadVC has a strong reference to cycleMaker and cycleMaker captures a strong reference to StillBadVC. The cycle will be broken as long as someone remembers to call breakCycle(), at which point the view controller will remove its strong reference to cycleMaker, allowing cycleMaker to deallocate. However, the cycle will not be broken if someone forgets to call breakCycle(). Calling a method called breakCycle() is not usually a part of the contract for using a view controller, so we would expect StillBadVC to result in memory leaks in practice.


问:
Using re.compile function to parse a gcode file line by line in Python
I'm parsing a gcode file (located in f_path) line by line, searching for a given string. That string ("M622") appears a single text in the whole text file, whose structure is like this one:

GCODE FILE

```<code>M622; arm the Lasers
M610 S0 A80 B0 C0 ; allocate feeders
T0 ; set active extruder
G92 E0 ; set active extruder to 0
G28 XY ; home X and Y
G28 X ; home x
G90 ; absolute
G0 F3000 X35 Y5 S255 ; edge of plate
G92 X0 Y0 Z-2 ; local home
G0 Z0 ; drop Z
</code>```

In the end, I want the code to return the line number where the string was found.

CODE

```<code>rgx_start = re.compile(r'M622') # String to be searched: "M622"
with open (f_path, 'rt') as txtfile:
    line = txtfile.readline()
    line_i = 0  # Counter of each line in the original text file
    hdr_start = 0 # Variable to store the line number where the header starts
    while line:  # Reading each line as a string
        while rgx_start.search(line) != None: # No "M622" is found => move to the next line
            line_i += 1 # The line counter is set to the next line
        hdr_start = line_i # When "M622" is found

print('First line: ',hdr_start)
</code>```

As I run the code above, I enter in an infinite loop. Any suggestions?

答:
you could do:</p>

```<code>import re
rgx_start = re.compile(r'M622')
with open('gt.dat','r') as textfile:
   for i,line in enumerate(textfile.readlines()):
       if  rgx_start.search(line):
           line = i
           break  # since you said that it appears once
print(line)
</code>```

Body:
I'm parsing a gcode file (located in f_path) line by line, searching for a given string. That string ("M622") appears a single text in the whole text file, whose structure is like this one:

GCODE FILE

M622; arm the Lasers
M610 S0 A80 B0 C0 ; allocate feeders
T0 ; set active extruder
G92 E0 ; set active extruder to 0
G28 XY ; home X and Y
G28 X ; home x
G90 ; absolute
G0 F3000 X35 Y5 S255 ; edge of plate
G92 X0 Y0 Z-2 ; local home
G0 Z0 ; drop Z

In the end, I want the code to return the line number where the string was found.

CODE

rgx_start = re.compile(r'M622') # String to be searched: "M622"
with open (f_path, 'rt') as txtfile:
    line = txtfile.readline()
    line_i = 0  # Counter of each line in the original text file
    hdr_start = 0 # Variable to store the line number where the header starts
    while line:  # Reading each line as a string
        while rgx_start.search(line) != None: # No "M622" is found => move to the next line
            line_i += 1 # The line counter is set to the next line
        hdr_start = line_i # When "M622" is found

print('First line: ',hdr_start)

As I run the code above, I enter in an infinite loop. Any suggestions?

Body:
you could do:

import re
rgx_start = re.compile(r'M622')
with open('gt.dat','r') as textfile:
   for i,line in enumerate(textfile.readlines()):
       if  rgx_start.search(line):
           line = i
           break  # since you said that it appears once
print(line)


问:
Detecting length of overlap between two strings
```<code>int overlap(const char *s1, const char *s2){
    int i = 0;
    while (s1[i] && s2[i] && s1[i] == s2[i])
        i++;
    return i;
}
</code>```

This returns the length of the substring overlap between the two strings it takes as input. However, if the two strings are:

```<code>abcdefg
1234efg
</code>```

it returns an overlap of 0 because it can only read overlaps that start at the beginning of the strings, can someone modify or help me to make it so that it can read overlaps no mantter where they are in the strings?

答:
well i have thought this question again.
i think you want an overlap at the same index in each string.
pay attention to the character '\0' in the end of each string.

so we can write the codes as the following:

```<code>int overlap(const char *s1, const char *s2){
    int i = 0;
    while (*s1 != '\0' && *s2 != '\0') {
        if (*s1++ == *s2++) i++;
    }
    return i;
}
</code>```

for "abcdefg" and "1234efg", it will return 3.

Body:
int overlap(const char *s1, const char *s2){
    int i = 0;
    while (s1[i] && s2[i] && s1[i] == s2[i])
        i++;
    return i;
}

This returns the length of the substring overlap between the two strings it takes as input. However, if the two strings are:

abcdefg
1234efg

it returns an overlap of 0 because it can only read overlaps that start at the beginning of the strings, can someone modify or help me to make it so that it can read overlaps no mantter where they are in the strings?

Body:
well i have thought this question again.
i think you want an overlap at the same index in each string.
pay attention to the character '\0' in the end of each string.

so we can write the codes as the following:

int overlap(const char *s1, const char *s2){
    int i = 0;
    while (*s1 != '\0' && *s2 != '\0') {
        if (*s1++ == *s2++) i++;
    }
    return i;
}

for "abcdefg" and "1234efg", it will return 3.


问:
Force second div to appear under the third div in html
I use a WordPress template in which there are three main divisions

```<code><div class="sidebar-right"></div>
<div class="sidebar-left"></div>
<div class="sidebar-middle"></div>
</code>```

using float:right it arranges the divisions as three columns. However in mobile version the left sidebar disappears. I tried to display it, but it then appears between the right sidebar and middle, while I want it to be under the middle! Can I achieve this goal by changing CSS? or should I reorder them in the template?

答:
By using CSS order property it is possible.

#container {
  display: flex;
  flex-direction: column;
  text-align: center;
}

.sidebar-right,
.sidebar-left,
.sidebar-middle {
  width: 100%;
}

.sidebar-right {
  order: 1;
}

.sidebar-left {
  order: 3;
}

.sidebar-middle {
  order: 2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <div class="sidebar-right">One</div>
  <div class="sidebar-left">Two</div>
  <div class="sidebar-middle">Three</div>
</div></code>```

For larger displays, you can use media quires. For example, if the device width is greater than 1024 means you can set the flex-direction: unset;

#container {
  display: flex;
  flex-direction: column;
}

.sidebar-right,
.sidebar-left,
.sidebar-middle {
  width: 33.33%;
  float: left;
}

.sidebar-right {
  order: 1;
}

.sidebar-left {
  order: 3;
}

.sidebar-middle {
  order: 2;
}

@media screen and (min-width: 1024px) {
  #container {
    flex-direction: unset;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <div class="sidebar-right">One</div>
  <div class="sidebar-left">Two</div>
  <div class="sidebar-middle">Three</div>
</div></code>```

Body:
I use a WordPress template in which there are three main divisions

using float:right it arranges the divisions as three columns. However in mobile version the left sidebar disappears. I tried to display it, but it then appears between the right sidebar and middle, while I want it to be under the middle! Can I achieve this goal by changing CSS? or should I reorder them in the template?

Body:
By using CSS order property it is possible.

#container {
  display: flex;
  flex-direction: column;
  text-align: center;
}

.sidebar-right,
.sidebar-left,
.sidebar-middle {
  width: 100%;
}

.sidebar-right {
  order: 1;
}

.sidebar-left {
  order: 3;
}

.sidebar-middle {
  order: 2;
}

<div id="container">
  <div class="sidebar-right">One</div>
  <div class="sidebar-left">Two</div>
  <div class="sidebar-middle">Three</div>
</div>

For larger displays, you can use media quires. For example, if the device width is greater than 1024 means you can set the flex-direction: unset;

#container {
  display: flex;
  flex-direction: column;
}

.sidebar-right,
.sidebar-left,
.sidebar-middle {
  width: 33.33%;
  float: left;
}

.sidebar-right {
  order: 1;
}

.sidebar-left {
  order: 3;
}

.sidebar-middle {
  order: 2;
}

@media screen and (min-width: 1024px) {
  #container {
    flex-direction: unset;
  }
}

<div id="container">
  <div class="sidebar-right">One</div>
  <div class="sidebar-left">Two</div>
  <div class="sidebar-middle">Three</div>
</div>


问:
What's wrong with my JS code for a command prompt?
This was working earlier, and then stopped. No idea why. It should function like this: enter a command into the textbox that is matched with an if statement, and execute the command. The form keeps refreshing after you press enter, so I don't think the "event.preventDefault();" at the end of my JS code is working.

HTML

```<code><form id="command-form" autocomplete="off">
    <img src="img/tint.png" alt="tint-img" id="tint-img" class="CMP">
    <input type="text" placeholder="Enter Command" class="CMP" id="command-box">
    <img id="x-icon" src="img/x-icon.png" alt="x-icon" class="goto-command-console bottom-left-navigation-item" onclick="toggleCMP();">
    <input type="submit" style="display: none;" onclick="checkCommand();">
</form>
</code>```

JavaScript

```<code>function checkCommand() {
    var commandInput = document.getElementById("command-box");
    var form = document.getElementById("command-form");

    if ( commandInput.value === "help" ) {
        window.open("html/commandhelp.html");
    }
    if ( commandInput.value === "windows" ) {
        changeStyle('css/windows-xp.css');
    }
    if ( commandInput.value === "explicit pass:3XPL1C1T" ) {
        changeStyle('css/explicit.css');
        playMusic('other/audio/moaning.mp3');
    }

    form.reset();
    event.preventDefault();
}
</code>```

Edits

A nice gentleman in the comments solved the problem, go check out his answer below. However, my method works too. In an earlier function, I did this:

```<code>function playMusic(url-to-mp3) {
    new Audio(url-to-mp3).play();
}
</code>```

I wasn't even thinking about the dashes in the function object. Both methods work great, and thank you for your help. Sorry for wasting your time.

答:
It works:

function checkCommand(event) {
 event.preventDefault();

    var commandInput = document.getElementById("command-box");
    var form = document.getElementById("command-form");

    if ( commandInput.value === "help" ) {
        window.open("html/commandhelp.html");
    }
    if ( commandInput.value === "windows" ) {
        changeStyle('css/windows-xp.css');
    }
    if ( commandInput.value === "explicit pass:3XPL1C1T" ) {
        changeStyle('css/explicit.css');
        playMusic('other/audio/moaning.mp3');
    }

    form.reset();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="command-form" onsubmit="return checkCommand(event)" autocomplete="off">
    <img src="img/tint.png" alt="tint-img" id="tint-img" class="CMP">
    <input type="text" placeholder="Enter Command" class="CMP" id="command-box">
    <img id="x-icon" src="img/x-icon.png" alt="x-icon" class="goto-command-console bottom-left-navigation-item" onclick="toggleCMP();">
    <button type="submit">Send me</button>
</form></code>```

Body:
This was working earlier, and then stopped. No idea why. It should function like this: enter a command into the textbox that is matched with an if statement, and execute the command. The form keeps refreshing after you press enter, so I don't think the "event.preventDefault();" at the end of my JS code is working.

HTML

<form id="command-form" autocomplete="off">

    <input type="text" placeholder="Enter Command" class="CMP" id="command-box">

    <input type="submit" style="display: none;" onclick="checkCommand();">
</form>

JavaScript

function checkCommand() {
    var commandInput = document.getElementById("command-box");
    var form = document.getElementById("command-form");

    if ( commandInput.value === "help" ) {
        window.open("html/commandhelp.html");
    }
    if ( commandInput.value === "windows" ) {
        changeStyle('css/windows-xp.css');
    }
    if ( commandInput.value === "explicit pass:3XPL1C1T" ) {
        changeStyle('css/explicit.css');
        playMusic('other/audio/moaning.mp3');
    }

    form.reset();
    event.preventDefault();
}

Edits

A nice gentleman in the comments solved the problem, go check out his answer below. However, my method works too. In an earlier function, I did this:

function playMusic(url-to-mp3) {
    new Audio(url-to-mp3).play();
}

I wasn't even thinking about the dashes in the function object. Both methods work great, and thank you for your help. Sorry for wasting your time.

Body:
It works:

function checkCommand(event) {
 event.preventDefault();

    var commandInput = document.getElementById("command-box");
    var form = document.getElementById("command-form");

    if ( commandInput.value === "help" ) {
        window.open("html/commandhelp.html");
    }
    if ( commandInput.value === "windows" ) {
        changeStyle('css/windows-xp.css');
    }
    if ( commandInput.value === "explicit pass:3XPL1C1T" ) {
        changeStyle('css/explicit.css');
        playMusic('other/audio/moaning.mp3');
    }

    form.reset();
}

<form id="command-form" onsubmit="return checkCommand(event)" autocomplete="off">
    <img src="img/tint.png" alt="tint-img" id="tint-img" class="CMP">
    <input type="text" placeholder="Enter Command" class="CMP" id="command-box">
    <img id="x-icon" src="img/x-icon.png" alt="x-icon" class="goto-command-console bottom-left-navigation-item" onclick="toggleCMP();">
    <button type="submit">Send me</button>
</form>


问:
My code doesn't calculate min and max numbers
I'm trying to write a code which will show the highest, lowest, the difference of them and the average of inputted 30 numbers.
But its not working and is showing the same result for both min and max numbers. Here is the code.</p>

```<code>public class aa {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int[] daystemp = new int[30];
        int i = 0;
        int dayHot = 0;
        int dayCold = 0;
        while(i < daystemp.length){
            daystemp[i] = input.nextInt();
            i++;
        }
        int maxTemp = daystemp[0];
        while (i < daystemp.length) {
            if (daystemp[i] > maxTemp) {
                maxTemp = daystemp[i];
                dayHot = i + 1;
                i++;
            }
        }
        System.out.println(maxTemp);
        int minTemp = daystemp[0];
        while (i < daystemp.length) {
            if (daystemp[i] < minTemp) {
                minTemp = daystemp[i];
                dayCold = i + 1;
                i++;
            }
        }
        System.out.println(minTemp);
        int diff = maxTemp - minTemp;
        System.out.println("The difference between them is"+diff);
        double sum = 0;
        while(i < daystemp.length) {
            sum += daystemp[i];
            i++;
        }
        double average = sum / daystemp.length;
        System.out.println("Average was"+average);
    }
}
</code>```

答:
A few notes about this solution:

By declaring the cumulative total double, no casting is required.
Because Java knows you want to convert int to double automatically if you assign an int to a declared double. Similary the fact that you want to express a result as double is implied when dividing a double by an int, such as when the average is taken. That avoids a cast also. If you had two ints and you wanted to produce a double you'd need to cast one or more of them, or in cases like a print statement where the compiler can't deduce the optimal type for the parameter, you'd need to explicitly cast to covert an int value to a double.

Not sure what OS you're running this on. The ideal situation would be to make it work on all platforms without requiring people type a magic word to end input (because how tacky). The easiest way to end input is to use the OS-specific end of input (end of file) key combination, and for Linux it's CTRL/D, which is how I explained it in the prompt. On another OS with a different end of input sequence you could just change the prompt. The trickiest would be if it is supposed to be truly portable Java. In that case I'd personally investigate how I could figure out the OS and/or End of File character or key combination on the current OS and modify the prompt to indicate to end input with whatever that is. That would be a bit of and advanced assignment but a very cool result.

Example illustrates use of a named constant to determine the array and is used limit the amount of input (and could be used to limit loop count of for loops accessing the array).

By setting the min and max to very high and low values respectively (notice the LOW value assigned to max and HIGH value assigned to min, those ensure the first legit temp entered will set the min and max and things will go from there).

Temperature Maximum, Minimum, Average and Difference Calculator

```<code>import java.util.Scanner;

  public class TemperatureStats {

    final static int MAX_DAYS = 31;

    public static void main(String[] args) {

        int[] dayTemps = new int[MAX_DAYS];
        double cumulativeTemp = 0.0;
        int minTemp = 1000, maxTemp = -1000;

        Scanner input = new Scanner(System.in);

        System.out.println("Enter temps for up to 1 month of days (end with CTRL/D):");
        int entryCount = 0;
        while (input.hasNextInt() && entryCount < MAX_DAYS)
            dayTemps[entryCount++] = input.nextInt();

        /* Find min, max, cumulative total */
        for (int i = 0; i < entryCount; i++) {
            int temp = dayTemps[i];
            if (temp < minTemp)
                minTemp = temp;
            if (temp > maxTemp)
                maxTemp = temp;
            cumulativeTemp += temp;
        }

        System.out.println("High temp. = " + maxTemp);
        System.out.println("Low temp.  = " + minTemp);
        System.out.println("Difference = " + (maxTemp - minTemp));
        System.out.println("Avg temp.  = " + cumulativeTemp / entryCount);
    }
}
</code>```

Body:
I'm trying to write a code which will show the highest, lowest, the difference of them and the average of inputted 30 numbers.
But its not working and is showing the same result for both min and max numbers. Here is the code.

public class aa {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int[] daystemp = new int[30];
        int i = 0;
        int dayHot = 0;
        int dayCold = 0;
        while(i < daystemp.length){
            daystemp[i] = input.nextInt();
            i++;
        }
        int maxTemp = daystemp[0];
        while (i < daystemp.length) {
            if (daystemp[i] > maxTemp) {
                maxTemp = daystemp[i];
                dayHot = i + 1;
                i++;
            }
        }
        System.out.println(maxTemp);
        int minTemp = daystemp[0];
        while (i < daystemp.length) {
            if (daystemp[i] < minTemp) {
                minTemp = daystemp[i];
                dayCold = i + 1;
                i++;
            }
        }
        System.out.println(minTemp);
        int diff = maxTemp - minTemp;
        System.out.println("The difference between them is"+diff);
        double sum = 0;
        while(i < daystemp.length) {
            sum += daystemp[i];
            i++;
        }
        double average = sum / daystemp.length;
        System.out.println("Average was"+average);
    }
}

Body:
A few notes about this solution:

By declaring the cumulative total double, no casting is required.
Because Java knows you want to convert int to double automatically if you assign an int to a declared double. Similary the fact that you want to express a result as double is implied when dividing a double by an int, such as when the average is taken. That avoids a cast also. If you had two ints and you wanted to produce a double you'd need to cast one or more of them, or in cases like a print statement where the compiler can't deduce the optimal type for the parameter, you'd need to explicitly cast to covert an int value to a double.

Not sure what OS you're running this on. The ideal situation would be to make it work on all platforms without requiring people type a magic word to end input (because how tacky). The easiest way to end input is to use the OS-specific end of input (end of file) key combination, and for Linux it's CTRL/D, which is how I explained it in the prompt. On another OS with a different end of input sequence you could just change the prompt. The trickiest would be if it is supposed to be truly portable Java. In that case I'd personally investigate how I could figure out the OS and/or End of File character or key combination on the current OS and modify the prompt to indicate to end input with whatever that is. That would be a bit of and advanced assignment but a very cool result.

Example illustrates use of a named constant to determine the array and is used limit the amount of input (and could be used to limit loop count of for loops accessing the array).

By setting the min and max to very high and low values respectively (notice the LOW value assigned to max and HIGH value assigned to min, those ensure the first legit temp entered will set the min and max and things will go from there).

Temperature Maximum, Minimum, Average and Difference Calculator

import java.util.Scanner;

  public class TemperatureStats {

    final static int MAX_DAYS = 31;

    public static void main(String[] args) {

        int[] dayTemps = new int[MAX_DAYS];
        double cumulativeTemp = 0.0;
        int minTemp = 1000, maxTemp = -1000;

        Scanner input = new Scanner(System.in);

        System.out.println("Enter temps for up to 1 month of days (end with CTRL/D):");
        int entryCount = 0;
        while (input.hasNextInt() && entryCount < MAX_DAYS)
            dayTemps[entryCount++] = input.nextInt();

        /* Find min, max, cumulative total */
        for (int i = 0; i < entryCount; i++) {
            int temp = dayTemps[i];
            if (temp < minTemp)
                minTemp = temp;
            if (temp > maxTemp)
                maxTemp = temp;
            cumulativeTemp += temp;
        }

        System.out.println("High temp. = " + maxTemp);
        System.out.println("Low temp.  = " + minTemp);
        System.out.println("Difference = " + (maxTemp - minTemp));
        System.out.println("Avg temp.  = " + cumulativeTemp / entryCount);
    }
}


答: Add word-break: break-word (or break-all) to .pContent

Title: How to base the width of the rest of the elements on the width of the title?

Body:
I have some centered divs that have a title and text below the title. The title is centered but the text is aligned on the left and starts from where the title starts. I used inline-block to make the div adjust in size based on the content. However, if the text is longer than the title, the container adjusts its width based on the text, not the title, so then the text appears wider than the title. How do I keep the width based on the title, not the text? I've included my code below as well as a badly drawn image to better understand what happens.

HTML and CSS:

.projects {
  width: 30vw;
  left: 10vw;
  right: 10vw;
  margin: 50px auto 0 auto;
  text-align: center;
}

.pContent {
  display: inline-block;
  margin-bottom: 10px;
}

.pInfo {
  text-align: left;
}

My Projects:

Project Title

This is a project description Lorem Ipsum Dolor

View a demo of the project.

Another Project Title

This is a project

View.

Here's an image of what I want and what actually happens.


答:
You need to set "max-width:325px;" and "width:100%;" of ".p1Info" div. Try below snippet. Just replace ".p1Info" class in CSS, rest CSS will be the same - </p>

```<code>   .pInfo {
        text-align: left;
        max-width: 325px;
        width: 100%;
    }
</code>```

Body:
You need to set "max-width:325px;" and "width:100%;" of ".p1Info" div. Try below snippet. Just replace ".p1Info" class in CSS, rest CSS will be the same -

   .pInfo {
        text-align: left;
        max-width: 325px;
        width: 100%;
    }


问:
Convert entire column from integer to datetime using SQL
I have a table with an entire column that contains integers. I know that these integers were previously datetime values. I want to update all values in this column to be datetimes. There are 1000+ plus rows. I've altered this column from an INT to varchar since all the errors I received didn't like me going from an INT to DATETIME but I am having the same issue with the varchar data type.

Example values in the column: 43873, 40706, 43873, ect

I have tried the following queries:

```<code>UPDATE WORKER SET INT_TIME = DATEFROMPARTS(INT_TIME,1,1);

UPDATE WORKER SET INT_TIME = CONVERT(datetime,INT_TIME,107);
</code>```

I receive errors like

Conversion failed when converting date and/or time from character
  string.

INT_TIME is the column I am trying to update all values to a datetime:

答:
You can use dateadd() function :

```<code>select dateadd(day, t.int_time, 0) as joining_date
from tabel t;
</code>```

You can use update statement to update , before that you need to alter table definition also :

```<code>alter table worker
    alter column int_time DATETIME

update worker
      set int_time = dateadd(day, t.int_time, 0)
</code>```

0 have a default date 1900-01-01 00:00:00.000

Body:
I have a table with an entire column that contains integers. I know that these integers were previously datetime values. I want to update all values in this column to be datetimes. There are 1000+ plus rows. I've altered this column from an INT to varchar since all the errors I received didn't like me going from an INT to DATETIME but I am having the same issue with the varchar data type.

Example values in the column: 43873, 40706, 43873, ect

I have tried the following queries:

UPDATE WORKER SET INT_TIME = DATEFROMPARTS(INT_TIME,1,1);

UPDATE WORKER SET INT_TIME = CONVERT(datetime,INT_TIME,107);

I receive errors like

Conversion failed when converting date and/or time from character
  string.

INT_TIME is the column I am trying to update all values to a datetime:

Body:
You can use dateadd() function :

select dateadd(day, t.int_time, 0) as joining_date
from tabel t;

You can use update statement to update , before that you need to alter table definition also :

alter table worker
    alter column int_time DATETIME

update worker
      set int_time = dateadd(day, t.int_time, 0)

0 have a default date 1900-01-01 00:00:00.000


问:
Pre load background images in jQuery
I'm having trouble pre loading background images. This is my attempt but still seems to not be working - ie. there is still a delay seeing the image when i call showAjaxLoader("#mytarget"). Does anybody have any suggestions?

CSS:

```<code>div.entryform-ajax-loader {
    background-image:url(../images/preloader-entry-form.gif);
}
</code>```

Script:

```<code>var ajax_loader = $('<div />').attr('class', 'entryform-ajax-loader');

function showAjaxLoader(target)
{
    $(target).append(ajax_loader);
}

function hideAjaxLoader(target)
{
    ajax_loader.remove();
</code>```

答:
Add a div to your head which has the source as your image, in this case, image will be loaded before the actual page loads. </p>

```<code><div style="display:none">
<img src="../images/preloader-entry-form.gif">
</div>
</code>```

Title: Pre load background images in jQuery

Body:
I'm having trouble pre loading background images. This is my attempt but still seems to not be working - ie. there is still a delay seeing the image when i call showAjaxLoader("#mytarget"). Does anybody have any suggestions?

CSS:

div.entryform-ajax-loader {
    background-image:url(../images/preloader-entry-form.gif);
}

Script:

var ajax_loader = $('
').attr('class', 'entryform-ajax-loader');

function showAjaxLoader(target)
{
    $(target).append(ajax_loader);
}

function hideAjaxLoader(target)
{
    ajax_loader.remove();

Body:
Add a div to your head which has the source as your image, in this case, image will be loaded before the actual page loads.

<div style="display:none">
<img src="../images/preloader-entry-form.gif">
</div>


问:
numpy loadtxt incrementally to preserve memory?
I have a numpy array that is quite large, about a gigabyte or so.  It takes a long time to compute the values that go into the array, so once it's built, I serialize it with np.savetxt.  However, the conversion from an array of floats (which are 64bits each) to a file with strings representing those floats (which are 8bits*len(float_2_string_conversion) > 64bits) creates a file that is much larger than the original array.  I think that perhaps, np.loadtxt loads in all of the string content and then does a conversion to float all in one go.  Thus, the memory footprint of np.loadtxt is significantly larger than the original array.

In any case, I cannot load my array back into memory, because np.loadtxt is not very memory-polite.  Is there a convenient way to load a numpy-created csv back into memory that is not so memory hungry?

Note: this question seems to bring up this exact issue, but there does not seem to be any solution, merely an acknowledgement that this is a problem.

答:
If you use np.load() you can set a memmap parameter. I have not used it cannot vouch for its performance.

https://docs.scipy.org/doc/numpy/reference/generated/numpy.load.html?highlight=memmap


问:
JsPrettier in Sublime 3 does not single quote className
I´m using Sublime Text 3 with JSPrettier to format Javascript and JSX code.

I have the following set in my JSPrettier configuration:

```<code>// If true, will use single instead of double quotes
"singleQuote": true
</code>```

Even with that, when formatting the code JSPrettier still insists on putting double quote on className and other JSX properties, like:

```<code><div className="uxm-details-header-buttons">
</code>```

or

```<code><Icon name="refresh" />
</code>```

I really expected everything with single quote, keeping double ones for special cases.

Any hint on how to solve that ?

答:
In Sublime Text 3 this can be achieved by modifying the user preferences section of the package. (    Preferences > Package Settings > JSPrettier)</p>

```<code>{
"prettier_options":
  {
  "singleQuote": true
  }
}
</code>```

Body:
I´m using Sublime Text 3 with JSPrettier to format Javascript and JSX code.

I have the following set in my JSPrettier configuration:

// If true, will use single instead of double quotes
"singleQuote": true

Even with that, when formatting the code JSPrettier still insists on putting double quote on className and other JSX properties, like:

or

<Icon name="refresh" />

I really expected everything with single quote, keeping double ones for special cases.

Any hint on how to solve that ?

Body:
In Sublime Text 3 this can be achieved by modifying the user preferences section of the package. (    Preferences > Package Settings > JSPrettier)

{
"prettier_options":
  {
  "singleQuote": true
  }
}


问:
Summarising a data frame in R by 2 elements
I have a large dataset that includes information for multiple sequences, detailing their sequence ID, country of origin, clade, host and many other things. Each country has multiple different sequences and some countries contain sequences from multiple different clades. Is there a way to know the number of different clades for each different country, without having to test each country one by one (there are too many to realistically enter by hand)?</p>

答:
Assuming, your dataframe df has columns like 'country' and 'clade' then you can run:

```<code>aggregate(data=df, clade ~ country, FUN=function(x) length(unique(x)))
</code>```

Body:
Assuming, your dataframe df has columns like 'country' and 'clade' then you can run:

aggregate(data=df, clade ~ country, FUN=function(x) length(unique(x)))


问:
Should I use Static class for Database connectivity in C#.net?
I have a class which contain all the database connection activities. What i want to know is should i make this class as static then i can call anywhere without creating it.
but the application runs in different pcs in same network in same time.

OR ELSE

should i create a normal class that can be use in other classes by inheriting it?

答:
You should consider the fact that making classes static make them hard to unit test.

Here are two links that discuss the topic:
Is static universally “evil” for unit testing and if so why does resharper recommend it?

Static Methods are Death to Testability

Basically making things static also makes them hard to isolate and remove dependencies in.


问:
Netty unit testing: How to test invocations on the Channel object that is part of the passed ChannelHandlerContext?
Part of the behavior of a ChannelHandler implementation is that it should send a response after receiving a message. However, the passed ChannelHandlerContext does seem to create an internal Channel instance that is not equal to the EmbeddedChannel instance used in the unit test. So, it is not possible to test from outside that a response has actually been written to the channel.

Here is some code to clarify the problem:

```<code>public class EchoHandler extends SimpleChannelInboundHandler<Object>
{
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception
    {
        ctx.channel().writeAndFlush(msg);
    }
}

@Test
public void aTest() throws Exception
{
    EchoHandler handler = new EchoHandler();
    EmbeddedChannel channel = spy(new EmbeddedChannel(handler));
    Object anObject = new Object();
    channel.writeInbound(anObject);
    verify(channel, times(1)).writeAndFlush(eq(anObject)); // will fail
}
</code>```

答:
As simple as it gets:</p>

```<code>public class EchoHandlerTest {

    static class EchoHandler extends ChannelInboundHandlerAdapter {

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ctx.channel().writeAndFlush(msg);
        }
    }

    @Test
    public void aTest() throws Exception {
        EmbeddedChannel channel = new EmbeddedChannel(new EchoHandler());
        Object anObject = new Object();
        channel.writeInbound(anObject);
        assertThat(channel.readOutbound(), is(anObject));
    }
}
</code>```

Body:
Part of the behavior of a ChannelHandler implementation is that it should send a response after receiving a message. However, the passed ChannelHandlerContext does seem to create an internal Channel instance that is not equal to the EmbeddedChannel instance used in the unit test. So, it is not possible to test from outside that a response has actually been written to the channel.

Here is some code to clarify the problem:

public class EchoHandler extends SimpleChannelInboundHandler<Object>
{
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception
    {
        ctx.channel().writeAndFlush(msg);
    }
}

@Test
public void aTest() throws Exception
{
    EchoHandler handler = new EchoHandler();
    EmbeddedChannel channel = spy(new EmbeddedChannel(handler));
    Object anObject = new Object();
    channel.writeInbound(anObject);
    verify(channel, times(1)).writeAndFlush(eq(anObject)); // will fail
}

Body:
As simple as it gets:

public class EchoHandlerTest {

    static class EchoHandler extends ChannelInboundHandlerAdapter {

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ctx.channel().writeAndFlush(msg);
        }
    }

    @Test
    public void aTest() throws Exception {
        EmbeddedChannel channel = new EmbeddedChannel(new EchoHandler());
        Object anObject = new Object();
        channel.writeInbound(anObject);
        assertThat(channel.readOutbound(), is(anObject));
    }
}


问:
How to protect the /metrics, /health and /openapi endpoints in Quarkus?
Quarkus use the /metrics endpoint to provide metrics data, the /health endpoint to provide the application status (UP or DOWN) and the /openapi endpoint to provide information about the available endpoints. This endpoints are defined by the Eclipse Microprofile Specifications.

By default this endpoints are public. I want protect this endpoints to only authenticated and authorized users can access.

How to protect this endpoints using Quarkus?

I want that the applications returns 403 for unauthorized users.

To authenticate I want use a basic authentication or a JWT token.

Is possible create a filter to this endpoints?

答:
This configuration should help:

```<code>quarkus.http.auth.permission.public.paths=/health/*,/metrics/*,/openapi/*
quarkus.http.auth.permission.public.policy=authenticated
</code>```

You can start from the basic authentication as recommended here.

HTH

Body:
This configuration should help:

quarkus.http.auth.permission.public.paths=/health/*,/metrics/*,/openapi/*
quarkus.http.auth.permission.public.policy=authenticated

You can start from the basic authentication as recommended here.

HTH


问:
Why is WebElement the same using for each loop Selenium?
I'm trying to get  elements using for each loop, but I'm gettting always the same first element.

Firstly, I'm searching for an element by id.

```<code>WebElement tableId = driver.findElement(By.id("tablepress-6"));
</code>```

Then I'm going to find tr elements by tagName.

```<code> List<WebElement> trElements = tableId.findElements(By.tagName("tr"));
</code>```

And finally using for each loop, I'm trying to get td elements with required fields:

```<code>List<Journal> journalList = new ArrayList<>();
    //...
    for (WebElement element : trElements) {
    String title = element.findElement(By.xpath("//*[@id=\"tablepress-6\"]/tbody/tr/td[3]")).getText();
    //String title = element.findElement(By.xpath("//table[@id='tablepress-6']/tbody/tr/td/a")).getText();
    String city = ...;
    journalList.add(new Journal(title, city));
    }
</code>```

As a result I'm getting:

```<code>Journal{title='Low Temperature Physics', city='...'}
Journal{title='Low Temperature Physics', city='...'}
Journal{title='Low Temperature Physics', city='...'}
Journal{title='Low Temperature Physics', city='...'}
</code>```

Instead of the expected:

```<code>Journal{title='Low Temperature Physics', city='...'}
Journal{title='Ukrainian Journal of Physical Optics', city='...'}
Journal{title='Theoretical and Experimental Chemistry', city='...'}
Journal{title='Kinematics and Physics of Celestial Bodies', city='...'}
</code>```

Here's my HTML code:

```<code><table id=tablepress-6 class="tablepress tablepress-id-6">
    <thead>
        <tr class="row-1 odd">
            <th class=column-1>Sci</th>
            <th class=column-2>Subject area (SJR)</th>
            <th class=column-3>Назва наукового журналу</th>
            <th class=column-4>ISSN (Print&El)</th>
            <th class=column-5>Scopus(SNIP)</th>
            <th class=column-6>WOS_Core</th>
            <th class=column-7>Місто</th>
            <th class=column-8>Шифри 2015</th>
        </tr>
    </thead>
    <tbody class=row-hover>
        <tr class="row-2 even">
            <td class=column-1>П</td>
            <td class=column-2>Physics and astronomy</td>
            <td class=column-3><a href="http://ltp.aip.org/" target=_blank rel="nofollow noopener noreferrer">Low Temperature Physics</a></td>
            <td class=column-4>1063-777X
                <br/> 1090-6517
                <br/>
            </td>
            <td class=column-5><a href="https://www.scopus.com/sourceid/13789" target=_blank rel="nofollow noopener noreferrer">0,617</a>
                <br/> 1997-2019
            </td>
            <td class=column-6><a href="http://ip-science.thomsonreuters.com/cgi-bin/jrnlst/jlresults.cgi?PC=MASTER&ISSN=1063-777X" target=_blank rel="nofollow noopener noreferrer">SCIE (0,860)</a>
                <br/> 1997-2019
            </td>
            <td class=column-7>Харків /
                <br/> Нью-Йорк
            </td>
            <td class=column-8>10; 13</td>
        </tr>
        <tr class="row-3 odd">
            <td class=column-1>П</td>
            <td class=column-2>Physics and astronomy</td>
            <td class=column-3><a href="http://www.ifo.lviv.ua/journal/" target=_blank rel="nofollow noopener noreferrer">Ukrainian Journal of Physical Optics</a>
                <br/> Український журнал фізичної оптики</td>
            <td class=column-4>1609-1833
                <br/> 1816-2002
                <br/>
            </td>
            <td class=column-5><a href="https://www.scopus.com/sourceid/11400153315" target=_blank rel="nofollow noopener noreferrer">0,593</a>
                <br/> 2000-2019
            </td>
            <td class=column-6><a href="http://ip-science.thomsonreuters.com/cgi-bin/jrnlst/jlresults.cgi?PC=MASTER&ISSN=1609-1833" target=_blank rel="nofollow noopener noreferrer">SCIE (0,488)</a>
                <br/> 2008-2019
            </td>
            <td class=column-7>Київ</td>
            <td class=column-8>10</td>
        </tr>
        <tr class="row-4 even">
            <td class=column-1>П</td>
            <td class=column-2>Chemistry</td>
            <td class=column-3><a href="http://link.springer.com/journal/11237" target=_blank rel="nofollow noopener noreferrer">Theoretical and Experimental Chemistry</a></td>
            <td class=column-4>0040-5760
                <br/> 1573-935X
                <br/>
            </td>
            <td class=column-5><a href="https://www.scopus.com/sourceid/21969" target=_blank rel="nofollow noopener noreferrer">0,198</a>
                <br/> 1967-2019
            </td>
            <td class=column-6><a href="http://ip-science.thomsonreuters.com/cgi-bin/jrnlst/jlresults.cgi?PC=MASTER&ISSN=0040-5760" target=_blank rel="nofollow noopener noreferrer">SCIE (0,878)</a>
                <br/> 2008-2019
            </td>
            <td class=column-7>Київ /
                <br/> Нью-Йорк
            </td>
            <td class=column-8>10; 16</td>
        </tr>
        <tr class="row-5 odd">
            <td class=column-1>П</td>
            <td class=column-2>Earth and planetary sciences; Physics and Astronomy</td>
            <td class=column-3><a href="http://www.allertonpress.com/journals/kin.htm" target=_blank rel="nofollow noopener noreferrer">Kinematics and Physics of Celestial Bodies</a>
                <br/> Кінематика і фізика небесних тіл</td>
            <td class=column-4>0884-5913
                <br/> 1934-8401
                <br/>
            </td>
            <td class=column-5><a href="https://www.scopus.com/sourceid/19700173017" target=_blank rel="nofollow noopener noreferrer">0,432</a>
                <br/> 2009-2019
            </td>
            <td class=column-6><a href="http://ip-science.thomsonreuters.com/cgi-bin/jrnlst/jlresults.cgi?PC=MASTER&ISSN=0884-5913" target=_blank rel="nofollow noopener noreferrer">SCIE (0,654)</a>
                <br/> 2008-2019
            </td>
            <td class=column-7>Київ /
                <br/> Нью-Йорк
            </td>
            <td class=column-8>10</td>
        </tr>
        <tr class="row-6 even">
            <td class=column-1>П</td>
            <td class=column-2>Biochemistry, genetics and molecular biology; Medicine</td>
            <td class=column-3><a href="https://link.springer.com/journal/11956" target=_blank rel="nofollow noopener noreferrer">Cytology and Genetics</a>
                <br/> Цитологія і генетика</td>
            <td class=column-4>0564-3783
                <br/> 0095-4527
                <br/>
            </td>
            <td class=column-5><a href="https://www.scopus.com/sourceid/19061" target=_blank rel="nofollow noopener noreferrer">0,229</a>
                <br/> 2009-2019
            </td>
            <td class=column-6><a href="http://ip-science.thomsonreuters.com/cgi-bin/jrnlst/jlresults.cgi?PC=MASTER&ISSN=0095-4527" target=_blank rel="nofollow noopener noreferrer">SCIE (0,239)</a>
                <br/> 2007-2019
            </td>
            <td class=column-7>Київ /
                <br/> Нью-Йорк
            </td>
            <td class=column-8>09; 22</td>
        </tr>
     //...
    </tbody>
</table>
</code>```

Am I missing something here? Thanks in advance.

答:
Alternatively You can do that in a single xpath statement.

```<code>List<WebElement> Elements = driver.findElements(By.xpath("//table[@id='tablepress-6']/tbody//tr//td[3]/a"));

 List<Journal> journalList = new ArrayList<>();

    for (WebElement element : Elements) {
    String title = element.getText();

    String city = ...;
    journalList.add(new Journal(title, city));
    }
</code>```

Body:
I'm trying to get  elements using for each loop, but I'm gettting always the same first element.

Firstly, I'm searching for an element by id.

WebElement tableId = driver.findElement(By.id("tablepress-6"));

Then I'm going to find tr elements by tagName.

 List<WebElement> trElements = tableId.findElements(By.tagName("tr"));

And finally using for each loop, I'm trying to get td elements with required fields:

List<Journal> journalList = new ArrayList<>();
    //...
    for (WebElement element : trElements) {
    String title = element.findElement(By.xpath("//*[@id=\"tablepress-6\"]/tbody/tr/td[3]")).getText();
    //String title = element.findElement(By.xpath("//table[@id='tablepress-6']/tbody/tr/td/a")).getText();
    String city = ...;
    journalList.add(new Journal(title, city));
    }

As a result I'm getting:

Journal{title='Low Temperature Physics', city='...'}
Journal{title='Low Temperature Physics', city='...'}
Journal{title='Low Temperature Physics', city='...'}
Journal{title='Low Temperature Physics', city='...'}

Instead of the expected:

Journal{title='Low Temperature Physics', city='...'}
Journal{title='Ukrainian Journal of Physical Optics', city='...'}
Journal{title='Theoretical and Experimental Chemistry', city='...'}
Journal{title='Kinematics and Physics of Celestial Bodies', city='...'}

Here's my HTML code:

            Sci
            Subject area (SJR)
            Назва наукового журналу
            ISSN (Print&El)
            Scopus(SNIP)
            WOS_Core
            Місто
            Шифри 2015

            П
            Physics and astronomy
            Low Temperature Physics
            1063-777X

 1090-6517

            0,617

 1997-2019

            SCIE (0,860)

 1997-2019

            Харків /

 Нью-Йорк

            10; 13

            П
            Physics and astronomy
            Ukrainian Journal of Physical Optics

 Український журнал фізичної оптики
            1609-1833

 1816-2002

            0,593

 2000-2019

            SCIE (0,488)

 2008-2019

            Київ
            10

            П
            Chemistry
            Theoretical and Experimental Chemistry
            0040-5760

 1573-935X

            0,198

 1967-2019

            SCIE (0,878)

 2008-2019

            Київ /

 Нью-Йорк

            10; 16

            П
            Earth and planetary sciences; Physics and Astronomy
            Kinematics and Physics of Celestial Bodies

 Кінематика і фізика небесних тіл
            0884-5913

 1934-8401

            0,432

 2009-2019

            SCIE (0,654)

 2008-2019

            Київ /

 Нью-Йорк

            10

            П
            Biochemistry, genetics and molecular biology; Medicine
            Cytology and Genetics

 Цитологія і генетика
            0564-3783

 0095-4527

            0,229

 2009-2019

            SCIE (0,239)

 2007-2019

            Київ /

 Нью-Йорк

            09; 22

     //...

Am I missing something here? Thanks in advance.

Body:
Alternatively You can do that in a single xpath statement.

List<WebElement> Elements = driver.findElements(By.xpath("//table[@id='tablepress-6']/tbody//tr//td[3]/a"));

 List<Journal> journalList = new ArrayList<>();

    for (WebElement element : Elements) {
    String title = element.getText();

    String city = ...;
    journalList.add(new Journal(title, city));
    }


问:
javascript find all the object in an array and convert it into an array to array
I have a list of array with object in it like address and details

Input

```<code>var arr = [
    {id: 1, name: "abc", address: {street: "some text1", pin: 879888, state: "my-state1"}, details: {section: "A", roll: 12, branch:"CSE"}},
    {id: 2, name: "xyz", address: {street: "some text2", pin: 879887, state: "my-state2"}, details: {section: "B", roll: 13, branch:"IT"}}
]
</code>```

I want to iterate on this array and convert all the inner object so that it will look something like below

Expected Result

```<code>var arr = [
    {id: 1, name: "abc", street: "some text1", pin: 879888, state: "my-state1", section: "A", roll: 12, branch: "CSE"},
    {id: 2, name: "xyz", street: "some text2", pin: 879887, state: "my-state2", section: "B", roll: 13, branch: "IT"}
]
</code>```

答:
You can iterate over the array using Array.map, destructure address, details and combine the rest of the properties into a new object using destructuring assignment.

Then merge every object into a single object using Object.assign()

const result = arr.map(({ address, details, ...rest }) =>
  Object.assign(rest, address, details));
```

Body:
I have a list of array with object in it like address and details

Input

var arr = [
    {id: 1, name: "abc", address: {street: "some text1", pin: 879888, state: "my-state1"}, details: {section: "A", roll: 12, branch:"CSE"}},
    {id: 2, name: "xyz", address: {street: "some text2", pin: 879887, state: "my-state2"}, details: {section: "B", roll: 13, branch:"IT"}}
]

I want to iterate on this array and convert all the inner object so that it will look something like below

Expected Result

var arr = [
    {id: 1, name: "abc", street: "some text1", pin: 879888, state: "my-state1", section: "A", roll: 12, branch: "CSE"},
    {id: 2, name: "xyz", street: "some text2", pin: 879887, state: "my-state2", section: "B", roll: 13, branch: "IT"}
]


问:
how to fetch huge data size efficiently?
I have an API endpoint which I reverse-engineered. I use it to search for a name and it returns no more than 100 entities at one request. But there's about 1.3M+ of these entities that I want to fetch.

Here's a sample of an entity from response:

```<code>{
 "name":"COMPANY NAME",
 "regNo":"100-H",
 "newRegNo":"191101000018",
 "type":"Company"
}
</code>```

I can search by either name or regNo. there's no minimum character limit for searching. I thought of search by alphabetically but since it returns no more than 100 entities at once i cannot fetch the rest. So, I tried to fetch it by regNo. regNo can be from 1 up to 1000000.

here's the script that I wrote to fetch all entities by their regNo:

const test = async () => {
  const data = {};
  try {
    const requests = [];
    // since it returns no more than 100 entities at once it adds 100
    // to the search query on every loop

    for (let i = 100; i < 10000; i += 100) {
      requests.push(fetchData(i));
    }
    const result = await Promise.all(requests);

    result.forEach(res => {
      res.entityList.forEach(entity => {
        data[entity.regNo] = entity;
      });
    });

    // You can ignore this part
    fs.writeFile("data.json", JSON.stringify(data), err => {
      console.log(err);
    });
    console.log(Object.keys(data).length);
  } catch (err) {
    console.log(err);
  }
};
```

<p>It took about 15 seconds to fetch 9100 entities ( made 100 loops )
And every <code>regNo</code> has one letter suffix like this <code>11000-H</code></p>

<p>If I fetch 100 it would return something like this:</p>

```entityList: [
    {
      name: "COMPANY NAME",
      regNo: '100-H',
      newRegNo: '191101000018',
      type: 'Company'
    },
    {
      name: "COMPANY NAME",
      regNo: '1000-V',
      newRegNo: '193901000021',
      type: 'Company'
    },
    {
      name: "COMPANY NAME",
      regNo: '10000-T',
      newRegNo: '197001000604',
      type: 'Company'
    },
    {
      name: "COMPANY NAME",
      regNo: '100000-D',
      newRegNo: '198301004377',
      type: 'Company'
    },
    {
      name: "COMPANY NAME",
      regNo: '1000001-W',
      newRegNo: '201001012078',
      type: 'Company'
    },
    {
      name: "COMPANY NAME",
      regNo: '1000002-K',
      newRegNo: null,
      type: 'Company'
    },
    {
      name: "COMPANY NAME",
      regNo: '1000003-U',
      newRegNo: '201001012079',
      type: 'Company'
    },
    {
      name: "COMPANY NAME",
      regNo: '1000004-V',
      newRegNo: '201001012080',
      type: 'Company'
    },
    {
      name: "COMPANY NAME",
      regNo: '1000005-D',
      newRegNo: '201001012081',
      type: 'Company'
    },
    {
      name: "COMPANY NAME",
      regNo: '1000006-A',
      newRegNo: '201001012082',
      type: 'Company'
    },
 .......
```

As you can see it does not return entities from 0 to 99. I am assuming that the highest regNo is 1000000-suffixLetter and if I can fetch from 100 to 1000000 in a loop I would fetch about 1M entities. BUT here's the trick regNo has a suffix letter. Let's suppose that if I fetch 100 it returs from 100-A to 199-A. But there's other entities like 100-B, 100-C, etc

how can I fetch 1.3M+ entities efficiently without loss of data ?

答:
OK it looks like you're looking at like 250 MB of data and that request round-trips are taking about 15 ms. Assuming you have 100 Mbps download speed the theoretical max speed you can do this at is 20 seconds.

Since most of the time involved here seems to be waiting for the network round trips, you could try massively parallelizing this. Instead of having one thread looping, you can loop and create many threads. Up to some point, I'd expect you to get nearly proportional speedup from doing this since you have almost no compute time here, almost exclusively I/O. Past that point, you might begin to exhaust available network resources and get bottlenecked that way again. However, your system should be able to handle many independent requests simultaneously.

Given that your single-threaded program takes ~15 ms per request, and there are potentially ~1.3M requests, you'd be looking at about 195,000 seconds running this way. Use a single other thread and I'd be surprised if you didn't see something around 100,000 seconds. Use four threads and you might get around 50,000 seconds. You might need to experiment with a smaller range and toggle the number of threads until you see your best throughput.

Note: it's possible that the site you're accessing already has (or may quickly install if you start doing the above) rate-limiters to throttle high-volume traffic from single sources. Consider whether the API you're calling can handle this much traffic before you start using it this way.

Body:
I have an API endpoint which I reverse-engineered. I use it to search for a name and it returns no more than 100 entities at one request. But there's about 1.3M+ of these entities that I want to fetch.

Here's a sample of an entity from response:

{
 "name":"COMPANY NAME",
 "regNo":"100-H",
 "newRegNo":"191101000018",
 "type":"Company"
}

I can search by either name or regNo. there's no minimum character limit for searching. I thought of search by alphabetically but since it returns no more than 100 entities at once i cannot fetch the rest. So, I tried to fetch it by regNo. regNo can be from 1 up to 1000000.

here's the script that I wrote to fetch all entities by their regNo:

const test = async () => {
  const data = {};
  try {
    const requests = [];
    // since it returns no more than 100 entities at once it adds 100
    // to the search query on every loop

    for (let i = 100; i < 10000; i += 100) {
      requests.push(fetchData(i));
    }
    const result = await Promise.all(requests);

    result.forEach(res => {
      res.entityList.forEach(entity => {
        data[entity.regNo] = entity;
      });
    });

    // You can ignore this part
    fs.writeFile("data.json", JSON.stringify(data), err => {
      console.log(err);
    });
    console.log(Object.keys(data).length);
  } catch (err) {
    console.log(err);
  }
};

It took about 15 seconds to fetch 9100 entities ( made 100 loops )
And every regNo has one letter suffix like this 11000-H

If I fetch 100 it would return something like this:

entityList: [
    {
      name: "COMPANY NAME",
      regNo: '100-H',
      newRegNo: '191101000018',
      type: 'Company'
    },
    {
      name: "COMPANY NAME",
      regNo: '1000-V',
      newRegNo: '193901000021',
      type: 'Company'
    },
    {
      name: "COMPANY NAME",
      regNo: '10000-T',
      newRegNo: '197001000604',
      type: 'Company'
    },
    {
      name: "COMPANY NAME",
      regNo: '100000-D',
      newRegNo: '198301004377',
      type: 'Company'
    },
    {
      name: "COMPANY NAME",
      regNo: '1000001-W',
      newRegNo: '201001012078',
      type: 'Company'
    },
    {
      name: "COMPANY NAME",
      regNo: '1000002-K',
      newRegNo: null,
      type: 'Company'
    },
    {
      name: "COMPANY NAME",
      regNo: '1000003-U',
      newRegNo: '201001012079',
      type: 'Company'
    },
    {
      name: "COMPANY NAME",
      regNo: '1000004-V',
      newRegNo: '201001012080',
      type: 'Company'
    },
    {
      name: "COMPANY NAME",
      regNo: '1000005-D',
      newRegNo: '201001012081',
      type: 'Company'
    },
    {
      name: "COMPANY NAME",
      regNo: '1000006-A',
      newRegNo: '201001012082',
      type: 'Company'
    },
 .......

As you can see it does not return entities from 0 to 99. I am assuming that the highest regNo is 1000000-suffixLetter and if I can fetch from 100 to 1000000 in a loop I would fetch about 1M entities. BUT here's the trick regNo has a suffix letter. Let's suppose that if I fetch 100 it returs from 100-A to 199-A. But there's other entities like 100-B, 100-C, etc

how can I fetch 1.3M+ entities efficiently without loss of data ?