问:
CSV file upload from buffer to S3
I am trying to upload content taken out of a model in Django as a csv file. I don't want to save the file locally, but keep it in the buffer and upload to s3. Currently, this code does not error as is, and uploads the file properly, however, the file is empty.

```<code>file_name='some_file.csv'
fields = [list_of_fields]
header = [header_fields]

buff =  io.StringIO()
writer = csv.writer(buff, dialect='excel', delimiter=',')
writer.writerow(header)
for value in some_queryset:
    row = []
    for field in fields:
        # filling in the row
    writer.writerow(row)

# Upload to s3
client = boto3.client('s3')
bucket = 'some_bucket_name'
date_time = datetime.datetime.now()
date = date_time.date()
time = date_time.time()
dt = '{year}_{month}_{day}__{hour}_{minute}_{second}'.format(
    day=date.day,
    hour=time.hour,
    minute=time.minute,
    month=date.month,
    second=time.second,
    year=date.year,
)
key = 'some_name_{0}.csv'.format(dt)

client.upload_fileobj(buff, bucket, key)
</code>```

If I take the buffer's content, it is definitely writing it:

```<code>content = buff.getvalue()
content.encode('utf-8')
print("content: {0}".format(content)) # prints the csv content
</code>```

EDIT: I am doing a similar thing with a zip file, created in a buffer:

```<code>with zipfile.ZipFile(buff, 'w') as archive:
</code>```

Writing to the archive (adding pdf files that I am generating), and once I am done, I execute this: buff.seek(0) which seems to be necessary. If I do a similar thing above, it will error out: Unicode-objects must be encoded before hashing

答:
As explained here using the method put_object rather than upload_fileobj would just do the job right with io.STRINGIO object buffer.

So here, to match the initial example:

```<code>client = boto3.client('s3')
client.upload_fileobj(buff2, bucket, key)
</code>```

would become

```<code>client = boto3.client('s3')
client.put_object(Body=buff2, Bucket=bucket, Key=key, ContentType='application/vnd.ms-excel')
</code>```

Title: CSV file upload from buffer to S3

Body:
I am trying to upload content taken out of a model in Django as a csv file. I don't want to save the file locally, but keep it in the buffer and upload to s3. Currently, this code does not error as is, and uploads the file properly, however, the file is empty.

file_name='some_file.csv'
fields = [list_of_fields]
header = [header_fields]

buff =  io.StringIO()
writer = csv.writer(buff, dialect='excel', delimiter=',')
writer.writerow(header)
for value in some_queryset:
    row = []
    for field in fields:
        # filling in the row
    writer.writerow(row)

# Upload to s3
client = boto3.client('s3')
bucket = 'some_bucket_name'
date_time = datetime.datetime.now()
date = date_time.date()
time = date_time.time()
dt = '{year}_{month}_{day}__{hour}_{minute}_{second}'.format(
    day=date.day,
    hour=time.hour,
    minute=time.minute,
    month=date.month,
    second=time.second,
    year=date.year,
)
key = 'some_name_{0}.csv'.format(dt)

client.upload_fileobj(buff, bucket, key)

If I take the buffer's content, it is definitely writing it:

content = buff.getvalue()
content.encode('utf-8')
print("content: {0}".format(content)) # prints the csv content

EDIT: I am doing a similar thing with a zip file, created in a buffer:

with zipfile.ZipFile(buff, 'w') as archive:

Writing to the archive (adding pdf files that I am generating), and once I am done, I execute this: buff.seek(0) which seems to be necessary. If I do a similar thing above, it will error out: Unicode-objects must be encoded before hashing

Body:
As explained here using the method put_object rather than upload_fileobj would just do the job right with io.STRINGIO object buffer.

So here, to match the initial example:

client = boto3.client('s3')
client.upload_fileobj(buff2, bucket, key)

would become

client = boto3.client('s3')
client.put_object(Body=buff2, Bucket=bucket, Key=key, ContentType='application/vnd.ms-excel')


来源: stackexchange

问:
Change email address based on drop-down selection
I have a contact form with the following fields:

Name

Email

Number

Department

Message

"Department" is a drop down selection with the seven following options

Audio Engineering

Graphic Design

Music Production

Photography

Videography

Web Development

Other

I have been trying to set it up in such a way where the email address that the data is being sent to, changes based on the user's drop-down selection. For example, if the user selects Option 1, "Audio Engineering", the email will be sent to "audio@email.com". If the user selects Option 2, "Graphic Design", the email will be sent to "graphics@email.com" and so on, upon submission of the form. However, my current code returns an error.

This is my HTML.

```<code><form method="post" action="contact.php" name="contactform" id="contactform">

      <fieldset id="contact_form">
          <label for="name">
              <input type="text" name="name" id="name" placeholder="ENTER YOUR NAME">
          </label>

          <label for="email">
              <input type="email" name="email" id="email" placeholder="ENTER YOUR EMAIL">
          </label>

          <label for="phone">
              <input type="text" name="phone" id="phone" placeholder="PHONE NUMBER">
          </label>

          <label for="department">
              <select name="department" id="department" class="cs-select cs-skin-border" required>
                  <option value="" disabled selected>DEPARTMENT</option>
                  <option value="audio">Audio Engineering</option>
                  <option value="graphics">Graphic Design</option>
                  <option value="music">Music Production</option>
                  <option value="photography">Photography</option>
                  <option value="videography">Videography</option>
                  <option value="development">Web Development</option>
                  <option value="other">Other</option>
              </select>
          </label>

          <label for="comments">
              <textarea name="comments" id="comments" placeholder="ENTER YOUR MESSAGE"></textarea>
          </label>

          <input type="submit" class="submit btn btn-default btn-black" id="submit" value="Submit">
      </fieldset>

</form>
</code>```

This is the snippet of my PHP where I use if statements to change emails based on selection.

```<code><?php

$name       = $_POST['name'];
$email      = $_POST['email'];
$phone      = $_POST['phone'];
$dept       = $_POST['department'];
$comments   = $_POST['comments'];

if(trim($name) == '') {
    echo '<div class="error_message" style="color: #de493e; font-weight: 700;">Please enter your name. Don\'t be shy!</div>';
    exit();
} else if(trim($email) == '') {
    echo '<div class="error_message" style="color: #de493e; font-weight: 700;">Please enter your email address, so we can get back to you!</div>';
    exit();
} else if(!isEmail($email)) {
    echo '<div class="error_message" style="color: #de493e; font-weight: 700;">Invalid e-mail address, try again!</div>';
    exit();
} else if(trim($comments) == '') {
    echo '<div class="error_message" style="color: #de493e; font-weight: 700;">You forgot to enter your message!</div>';
    exit();
}

if($dept == "audio") {
    $address = "audio@email.com";
} else if ($dept == "graphics") {
    $address = "graphics@email.com";
} else if ($dept == "music") {
    $address = "music@email.com";
} else if ($dept == "photography") {
    $address = "photography@email.com";
} else if ($dept == "videography") {
    $address = "videography@email.com";
} else if ($dept == "development") {
    $address = "development@email.com";
} else if ($dept == "other") {
    $address = "admin@email.com";
}

if(mail($address, $received_subject, $message, $header)) {

    // Email has sent successfully, echo a success page.

    echo "<h2>Email Sent Successfully.</h2>";
    echo "<p>Thank you <strong>$name</strong>, your message has been sent to us.</p>";
    echo "<p>We will get back to you within 24 hours!</p>";

} else {

    echo '<h2>ERROR!</h2>';

}

?>
</code>```

This unfortunately returns "ERROR!" and i'm not sure why.

I would also like to return an error message if no selection is made.

答:
Passed param to mail function. </p>

```<code>$name       = $_POST['name'];
$email      = $_POST['email'];
$phone      = $_POST['phone'];
$dept       = $_POST['department'];
$comments   = $_POST['comments'];

if(trim($name) == '') {
    echo '<div class="error_message" style="color: #de493e; font-weight: 700;">Please enter your name. Don\'t be shy!</div>';
    exit();
} else if(trim($email) == '') {
    echo '<div class="error_message" style="color: #de493e; font-weight: 700;">Please enter your email address, so we can get back to you!</div>';
    exit();
} else if(!isEmail($email)) {
    echo '<div class="error_message" style="color: #de493e; font-weight: 700;">Invalid e-mail address, try again!</div>';
    exit();
} else if(trim($comments) == '') {
    echo '<div class="error_message" style="color: #de493e; font-weight: 700;">You forgot to enter your message!</div>';
    exit();
}

if($dept == "audio") {
    $address = "audio@email.com";
} else if ($dept == "graphics") {
    $address = "graphics@email.com";
} else if ($dept == "music") {
    $address = "music@email.com";
} else if ($dept == "photography") {
    $address = "photography@email.com";
} else if ($dept == "videography") {
    $address = "videography@email.com";
} else if ($dept == "development") {
    $address = "development@email.com";
} else if ($dept == "other") {
    $address = "admin@email.com";
}

$message = "First line of text\nSecond line of text";
$received_subject = "My subject";
if(mail($address, $received_subject, $message)) {

    // Email has sent successfully, echo a success page.

    echo "<h2>Email Sent Successfully.</h2>";
    echo "<p>Thank you <strong>$name</strong>, your message has been sent to us.</p>";
    echo "<p>We will get back to you within 24 hours!</p>";

} else {

    echo '<h2>ERROR!</h2>';

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a contact form with the following fields:

Name

Email

Number

Department

Message

"Department" is a drop down selection with the seven following options

Audio Engineering

Graphic Design

Music Production

Photography

Videography

Web Development

Other

I have been trying to set it up in such a way where the email address that the data is being sent to, changes based on the user's drop-down selection. For example, if the user selects Option 1, "Audio Engineering", the email will be sent to "audio@email.com". If the user selects Option 2, "Graphic Design", the email will be sent to "graphics@email.com" and so on, upon submission of the form. However, my current code returns an error.

This is my HTML.

<form method="post" action="contact.php" name="contactform" id="contactform">

      <fieldset id="contact_form">

              <input type="text" name="name" id="name" placeholder="ENTER YOUR NAME">

              <input type="email" name="email" id="email" placeholder="ENTER YOUR EMAIL">

              <input type="text" name="phone" id="phone" placeholder="PHONE NUMBER">

              <select name="department" id="department" class="cs-select cs-skin-border" required>
                  <option value="" disabled selected>DEPARTMENT</option>
                  <option value="audio">Audio Engineering</option>
                  <option value="graphics">Graphic Design</option>
                  <option value="music">Music Production</option>
                  <option value="photography">Photography</option>
                  <option value="videography">Videography</option>
                  <option value="development">Web Development</option>
                  <option value="other">Other</option>
              </select>

              <textarea name="comments" id="comments" placeholder="ENTER YOUR MESSAGE"></textarea>

          <input type="submit" class="submit btn btn-default btn-black" id="submit" value="Submit">
      </fieldset>

</form>

This is the snippet of my PHP where I use if statements to change emails based on selection.

<?php

$name       = $_POST['name'];
$email      = $_POST['email'];
$phone      = $_POST['phone'];
$dept       = $_POST['department'];
$comments   = $_POST['comments'];

if(trim($name) == '') {
    echo '
Please enter your name. Don\'t be shy!
';
    exit();
} else if(trim($email) == '') {
    echo '
Please enter your email address, so we can get back to you!
';
    exit();
} else if(!isEmail($email)) {
    echo '
Invalid e-mail address, try again!
';
    exit();
} else if(trim($comments) == '') {
    echo '
You forgot to enter your message!
';
    exit();
}

if($dept == "audio") {
    $address = "audio@email.com";
} else if ($dept == "graphics") {
    $address = "graphics@email.com";
} else if ($dept == "music") {
    $address = "music@email.com";
} else if ($dept == "photography") {
    $address = "photography@email.com";
} else if ($dept == "videography") {
    $address = "videography@email.com";
} else if ($dept == "development") {
    $address = "development@email.com";
} else if ($dept == "other") {
    $address = "admin@email.com";
}

if(mail($address, $received_subject, $message, $header)) {

    // Email has sent successfully, echo a success page.

    echo "
Email Sent Successfully.
";
    echo "
Thank you $name, your message has been sent to us.
";
    echo "
We will get back to you within 24 hours!
";

} else {

    echo '
ERROR!
';

}

?>

This unfortunately returns "ERROR!" and i'm not sure why.

I would also like to return an error message if no selection is made.

Body:
Passed param to mail function.

$name       = $_POST['name'];
$email      = $_POST['email'];
$phone      = $_POST['phone'];
$dept       = $_POST['department'];
$comments   = $_POST['comments'];

if(trim($name) == '') {
    echo '<div class="error_message" style="color: #de493e; font-weight: 700;">Please enter your name. Don\'t be shy!</div>';
    exit();
} else if(trim($email) == '') {
    echo '<div class="error_message" style="color: #de493e; font-weight: 700;">Please enter your email address, so we can get back to you!</div>';
    exit();
} else if(!isEmail($email)) {
    echo '<div class="error_message" style="color: #de493e; font-weight: 700;">Invalid e-mail address, try again!</div>';
    exit();
} else if(trim($comments) == '') {
    echo '<div class="error_message" style="color: #de493e; font-weight: 700;">You forgot to enter your message!</div>';
    exit();
}

if($dept == "audio") {
    $address = "audio@email.com";
} else if ($dept == "graphics") {
    $address = "graphics@email.com";
} else if ($dept == "music") {
    $address = "music@email.com";
} else if ($dept == "photography") {
    $address = "photography@email.com";
} else if ($dept == "videography") {
    $address = "videography@email.com";
} else if ($dept == "development") {
    $address = "development@email.com";
} else if ($dept == "other") {
    $address = "admin@email.com";
}

$message = "First line of text\nSecond line of text";
$received_subject = "My subject";
if(mail($address, $received_subject, $message)) {

    // Email has sent successfully, echo a success page.

    echo "<h2>Email Sent Successfully.</h2>";
    echo "<p>Thank you <strong>$name</strong>, your message has been sent to us.</p>";
    echo "<p>We will get back to you within 24 hours!</p>";

} else {

    echo '<h2>ERROR!</h2>';

}


问:
CachedNetworkImage image does not change with same name
I'm using https://pub.dev/packages/cached_network_image for display network image.

I came across with curious issue. Here I'm setting my profile image and url of profile image will be same, Only image will be changed.

Suppose if, First time I upload profile image then I will get url like "https://xx.yyy/user/profileAvatar" First time all works fine. But when I change profile image second time I will get same url as above with new image. But issue is here CachedNetworkImage can't able to load my new image.

Need your guidance to solve this issue.

PS. : I know, If I delete previous image from cache directory before uploading second one it will solve my issue.

UPDATED:

OMG, Same things even doesn't work with Image.network too.

答:
So for me calling MyCache.evict(key), deleting the image from disk and calling setState() did nothing. But if I also call MyImageDownloader.evict(key) before calling setState() that will trigger a new download which should get the new image for the same key.

The thing is that you have to evict and/or delete the image from everywhere including the class that is extending ImageProvider which in my case is MyImageDownloader.

If everything else is done and still you are not receiving the new image, then call the "not recommended" PaintingBinding.instance.imageCache.evict(key)

There are a couple of libraries out there and all have their own special ingredients. So try to experiment with the one that is working better for you. The idea is that you evict from any of the libraries' cache, delete from the disk, and call evict from whatever class is extending the ImageProvider.


问:
You are trying to add a non-nullable field 'owner' to product without a default
You are trying to add a non-nullable field 'owner' to product without a default; we can't do that (the database needs something to populate existing rows</p>

答:
Put in null=True, It will make your model field accept null values and also gives them null if you don't give them a value.

E.g:

```<code>owner = models.CharField(max_length=255, null=True)
</code>```

OR

you can put in a default for your model field

```<code>owner = models.CharField(max_length=255, default='Some String')
</code>```

Body:
Put in null=True, It will make your model field accept null values and also gives them null if you don't give them a value.

E.g:

owner = models.CharField(max_length=255, null=True)

OR

you can put in a default for your model field

owner = models.CharField(max_length=255, default='Some String')


问:
Error : in my query i am using multiple variables in c#
i am not getting what is the issue in the query probably i am not following the correct way to put the string and char sign , i am inserting the data in c# to local host with where clause please check the query and Error i am getting

Here is the query

```<code>String insertQuery = "insert into exam_add (id,session_id,Title,From_date,To_date,class_id,is_Post,is_Lock) select '"+id+ ",s.session,'" + title.Text+",'"+ from.Value.Date.ToString("yyyy-MM-dd")+",'"+to.Value.Date.ToString("yyyy-MM-dd")+ ", c.class_name,'"+x+",'"+x+" from year_session s, classes c where s.id = '1' and c.id='" + cls + "'";
</code>```

Exception image
here the image for exception i am getting after run this query

答:
I recommend use SQLparameters to avoid sql injection but your error is you forgot to close the single quotes it shoud be like this '"+cls + "'

```<code> String insertQuery = "insert into exam_add (id,session_id,Title,From_date,To_date,class_id,is_Post,is_Lock) select '" + id + "','"+s.session+"','" + title.Text + "','" + from.Value.Date.ToString("yyyy-MM-dd") + "','" + to.Value.Date.ToString("yyyy-MM-dd")+"' , '"+c.class_name+"','" + x + "','" + x + "' from year_session s, classes c where s.id = '1' and c.id='" + cls + "'";
</code>```

I don't know why you need that on select columns. and  you provided insufficient information and code on your question.

Body:
i am not getting what is the issue in the query probably i am not following the correct way to put the string and char sign , i am inserting the data in c# to local host with where clause please check the query and Error i am getting

Here is the query

String insertQuery = "insert into exam_add (id,session_id,Title,From_date,To_date,class_id,is_Post,is_Lock) select '"+id+ ",s.session,'" + title.Text+",'"+ from.Value.Date.ToString("yyyy-MM-dd")+",'"+to.Value.Date.ToString("yyyy-MM-dd")+ ", c.class_name,'"+x+",'"+x+" from year_session s, classes c where s.id = '1' and c.id='" + cls + "'";

Exception image
here the image for exception i am getting after run this query

Body:
I recommend use SQLparameters to avoid sql injection but your error is you forgot to close the single quotes it shoud be like this '"+cls + "'

 String insertQuery = "insert into exam_add (id,session_id,Title,From_date,To_date,class_id,is_Post,is_Lock) select '" + id + "','"+s.session+"','" + title.Text + "','" + from.Value.Date.ToString("yyyy-MM-dd") + "','" + to.Value.Date.ToString("yyyy-MM-dd")+"' , '"+c.class_name+"','" + x + "','" + x + "' from year_session s, classes c where s.id = '1' and c.id='" + cls + "'";

I don't know why you need that on select columns. and  you provided insufficient information and code on your question.


问:
Where do I call my function so it successfully updates my UI?
I have written the following function to ensure my user fills in a textField before being able to continue.

```<code>func validateFields() -> String {

    if textfield.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" {
        return "Please fill in textField"
    }

    return "A-OK."
}

 func updateUI() {
    let verdict = validateFields()

    if verdict == "A-OK." {
        self.buttonOne.alpha = 1
    }
}

override func viewDidLoad() {
    super.viewDidLoad()

     updateUI()
}
</code>```

However, once the textField has been filled in, the above code fails to update the UI. I know I am missing out on something trivial here, I just cannot wrap my head around what. I'd really appreciate the help.

答:
Use text textFieldDidEndEditing, textFieldDidBeginEditing, textFieldShouldReturn, etc. according to your requirement.

But I think delegate "textFieldShouldReturn" works fine with your requirement.

You just need to add you function updateUI() in this delegate.

Body:
I have written the following function to ensure my user fills in a textField before being able to continue.

func validateFields() -> String {

    if textfield.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" {
        return "Please fill in textField"
    }

    return "A-OK."
}

 func updateUI() {
    let verdict = validateFields()

    if verdict == "A-OK." {
        self.buttonOne.alpha = 1
    }
}

override func viewDidLoad() {
    super.viewDidLoad()

     updateUI()
}

However, once the textField has been filled in, the above code fails to update the UI. I know I am missing out on something trivial here, I just cannot wrap my head around what. I'd really appreciate the help.


问:
How to change from a HTTP POST request to HTTPS POST request?
I right now have an HTTP POST request using this layout:

```<code>private static readonly HttpClient client = new HttpClient();

var values = new Dictionary<string, string>
{
   { "thing1", "hello" },
   { "thing2", "world" }
};

var content = new FormUrlEncodedContent(values);

var response = await client.PostAsync("https://www.example.com/recepticle.aspx", content); //It's not the URL I'm using.

var responseString = await response.Content.ReadAsStringAsync();
</code>```

I want to set a password(textbox) on a website using a POST request with C#. I tried with the above layout, but it doesn't set it. So I think it's because I'm using an HTTP request instead of an HTTPS request(Do you think I'm right?). My problem is, I don't know how to send it as an HTTPS request. I need a way to make it HTTPS.

I should probably clarify that I'm sending the following things:

```<code>Password, - Not in the textbox
Password again, - Not in the textbox
question index, - In the textbox
answer for the question, - In the textbox
terms_of_service. - Not in the textbox
</code>```

So I guess the website does process my request but doesn't care about some things in it. Maybe it's the cookies?

Thank you in advance.

答: Apperantly the website did process and got the things I sent him but it never sent them back to me, because security. </p>

Body:
I right now have an HTTP POST request using this layout:

private static readonly HttpClient client = new HttpClient();

var values = new Dictionary<string, string>
{
   { "thing1", "hello" },
   { "thing2", "world" }
};

var content = new FormUrlEncodedContent(values);

var response = await client.PostAsync("https://www.example.com/recepticle.aspx", content); //It's not the URL I'm using.

var responseString = await response.Content.ReadAsStringAsync();

I want to set a password(textbox) on a website using a POST request with C#. I tried with the above layout, but it doesn't set it. So I think it's because I'm using an HTTP request instead of an HTTPS request(Do you think I'm right?). My problem is, I don't know how to send it as an HTTPS request. I need a way to make it HTTPS.

I should probably clarify that I'm sending the following things:

Password, - Not in the textbox
Password again, - Not in the textbox
question index, - In the textbox
answer for the question, - In the textbox
terms_of_service. - Not in the textbox

So I guess the website does process my request but doesn't care about some things in it. Maybe it's the cookies?

Thank you in advance.


问:
i want to add the following from a list but the result only concatinates

Sample value of n is 5

```<code>    n = input("Enter a No: ")
    n = "{0}+{0}{0}+{0}{0}{0}".format(n)
    n = n.split("+")
    a=n[0]
    b=n[1]
    c=n[2]
    n = (a + b + c)
    print(n)

</code>```

Expected Result : 615

答:
Here, how you should do it:

```<code>n = input("Enter a No: ")
n = "{0}+{0}{0}+{0}{0}{0}".format(n)
n = list(map(int, n.split("+")))
print(sum(n))
</code>```

I have used map to convert a list of string to a list of int and sum to sum all the elements of the list. I assume you need to sum all the elements of your list. If you want to sum only first three elements, then:

```<code>a=n[0]
b=n[1]
c=n[2]
n = (a + b + c)
print(n)
</code>```

Note: If you are using latest version of Python, then n = map(int, n) will return a TypeError: 'map' object is not subscriptable. You need to explicitly convert object returned by map to a list.

Body:
Sample value of n is 5

    n = input("Enter a No: ")
    n = "{0}+{0}{0}+{0}{0}{0}".format(n)
    n = n.split("+")
    a=n[0]
    b=n[1]
    c=n[2]
    n = (a + b + c)
    print(n)

Expected Result : 615

Body:
Here, how you should do it:

n = input("Enter a No: ")
n = "{0}+{0}{0}+{0}{0}{0}".format(n)
n = list(map(int, n.split("+")))
print(sum(n))

I have used map to convert a list of string to a list of int and sum to sum all the elements of the list. I assume you need to sum all the elements of your list. If you want to sum only first three elements, then:

a=n[0]
b=n[1]
c=n[2]
n = (a + b + c)
print(n)

Note: If you are using latest version of Python, then n = map(int, n) will return a TypeError: 'map' object is not subscriptable. You need to explicitly convert object returned by map to a list.


问:
How to sum float numbers in the format hours and minutes?
How to sum float numbers in the format hours and minutes?

Those. if  calculate two such numbers 0.35+3.45 then it should be = 4.20, not 3.80

var arr = [0.15, 0.2, 3.45, 0.4, 2, 0.3, 5.2, 1, 1.4, 1.1, 2.4, 1, 3.4]

var sum = 0.0;

arr.forEach(function(item) {
  console.log(sum);
  sum += parseFloat(item);
});```
</div>
</div>
</p>

<p>The result should be like this:</p>

```0
0.15
0.35
4.20
5.0
7.0
7.30
12.50
13.50
15.30
16.40
19.20
20.20
```

答:
You have to convert them to hours and minutes first

var arr = [0.15, 0.2, 3.45, 0.4, 2, 0.3, 5.2, 1, 1.4, 1.1, 2.4, 1, 3.4];

function add(arr) {
  var hm = arr
    .map(v => [Math.floor(v), (v % 1).toFixed(2) * 100])  // Map the array to values having [hours, minutes]
    .reduce((t, v) => { //  reduce the array of [h, m] to a single object having total hours and minutes
      t = {
        h: t.h + v[0],
        m: t.m + v[1]
      };
      return t;
    }, {
      h: 0,
      m: 0
    });

  // final result would be =
  // total hours from above
  // + hours from total minutes (retrived using Math.floor(hm.m / 60))
  // + minutes (after converting it to be a decimal part)
  return (parseFloat(hm.h + Math.floor(hm.m / 60)) + parseFloat(((hm.m % 60) / 100).toFixed(2))).toFixed(2);
}

// adding `arr` array
console.log(add(arr));

// adding 0.35+3.45
console.log(add([0.35, 3.45]));```

Body:
How to sum float numbers in the format hours and minutes?

Those. if  calculate two such numbers 0.35+3.45 then it should be = 4.20, not 3.80

var arr = [0.15, 0.2, 3.45, 0.4, 2, 0.3, 5.2, 1, 1.4, 1.1, 2.4, 1, 3.4]

var sum = 0.0;

arr.forEach(function(item) {
  console.log(sum);
  sum += parseFloat(item);
});

The result should be like this:

0
0.15
0.35
4.20
5.0
7.0
7.30
12.50
13.50
15.30
16.40
19.20
20.20


问:
Redirect based on browser language in Gatsby
I am building a site based on Gatsby. The english content is accessible with "/" and the german content with "/de". This is handled by the following plugin: https://github.com/angeloocana/gatsby-plugin-i18n.

Now I would like to detect the browser language and redirect the user to either "/" or "/de". What I understood so far is that it's not easy to get this behaviour with Gatsby, as Gatsby renders and builds the routing on the server-side.

What's the best way to detect the language of a user and redirect to either "/" or "/de"

答:
You need to do something like this

UPDATE: {replace: true} was added to support browsers like Firefox. Read the comments below this answer for a better context on when to use {replace: true}. Thanks to  Frederik Baetens for the heads up.

```<code>import React, { useEffect } from "react";
import { navigate } from "gatsby";

const getRedirectLanguage = () => {
  if (typeof navigator === `undefined`) {
    return "en";
  }

  const lang = navigator && navigator.language && navigator.language.split("-")[0];
  if (!lang) return "en";

  switch (lang) {
    case "ja":
      return "ja";
    default:
      return "en";
  }
};

const IndexPage = () => {
  useEffect(() => {
    const urlLang = getRedirectLanguage();

    navigate(`/${urlLang}/`, {replace: true});
  }, []);

  return null;
};

export default IndexPage;
</code>```

Credits to https://github.com/gatsbyjs/gatsby/issues/21548

Body:
You need to do something like this

UPDATE: {replace: true} was added to support browsers like Firefox. Read the comments below this answer for a better context on when to use {replace: true}. Thanks to  Frederik Baetens for the heads up.

import React, { useEffect } from "react";
import { navigate } from "gatsby";

const getRedirectLanguage = () => {
  if (typeof navigator === `undefined`) {
    return "en";
  }

  const lang = navigator && navigator.language && navigator.language.split("-")[0];
  if (!lang) return "en";

  switch (lang) {
    case "ja":
      return "ja";
    default:
      return "en";
  }
};

const IndexPage = () => {
  useEffect(() => {
    const urlLang = getRedirectLanguage();

    navigate(`/${urlLang}/`, {replace: true});
  }, []);

  return null;
};

export default IndexPage;

Credits to https://github.com/gatsbyjs/gatsby/issues/21548


问:
How to use two different github accounts with SSH and Red Hat 7?
I know that are a lot of questions like this one, but no answer was able to solve this problem for redhat. I had a MACOS with two accounts with no big deal, but on Red Hat it just doesn't work.

I have 2 accounts

```<code>https://github.com/USER1/REPOSITORY_A.git
https://github.com/USER2/REPOSITORY_B.git
</code>```

The earlier setup I had been to create an SSH key used for USER1 one on:

```<code>~/.ssh/id_rsa.pub
</code>```

and the second USER2 on:

```<code>~/.ssh/USER2/id_rsa.pub
</code>```

Added the ssh keys like:

```<code>ssh-add ~/.ssh/id_rsa
ssh-add ~/.ssh/USER2/id_rsa
</code>```

I had to add each key its own account SSH keys on github. And than I had to set up my config like this:

```<code>vi ~/.ssh/config

Host github.com
    Hostname ssh.github.com
    Port 443
    AddKeysToAgent yes
    IdentityFile ~/.ssh/id_rsa
    User git

Host user2-github.com
    HostName github.com
    AddKeysToAgent yes
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/user2/id_rsa
    User git

Host *
    AddKeysToAgent yes
    IdentityFile ~/.ssh/id_rsa
</code>```

and than I had to set up the USER2 local repository a remote host like:

```<code>git remote set-url origin git@user2-github.com:user2/REPOSITORY_B.git
</code>```

On MACOS everything worked like a charm, but on redhat, when I try to push on the local (USER2) repository, it tries to use "USER1" credentials... I can't find a solution, so I think I need your help...

How to use two different github accounts with SSH and Red Hat 7?

答:
Firsrt, on RedHat, do check the remote URL used:

```<code>git remote -v
</code>```

If you see https:// in there, no amount of SSH tweaking would help: SSH keys would be ignored. git config credential.helper might show you a credential cache in place, which would have cached USER1 credentials (username/password)

Secong, make sure your URL is user2-github.com:user2/REPOSITORY_B.git (no need for git@, since the user git is specified in the SSH config file)

Body:
I know that are a lot of questions like this one, but no answer was able to solve this problem for redhat. I had a MACOS with two accounts with no big deal, but on Red Hat it just doesn't work.

I have 2 accounts

https://github.com/USER1/REPOSITORY_A.git
https://github.com/USER2/REPOSITORY_B.git

The earlier setup I had been to create an SSH key used for USER1 one on:

~/.ssh/id_rsa.pub

and the second USER2 on:

~/.ssh/USER2/id_rsa.pub

Added the ssh keys like:

ssh-add ~/.ssh/id_rsa
ssh-add ~/.ssh/USER2/id_rsa

I had to add each key its own account SSH keys on github. And than I had to set up my config like this:

vi ~/.ssh/config

Host github.com
    Hostname ssh.github.com
    Port 443
    AddKeysToAgent yes
    IdentityFile ~/.ssh/id_rsa
    User git

Host user2-github.com
    HostName github.com
    AddKeysToAgent yes
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/user2/id_rsa
    User git

Host *
    AddKeysToAgent yes
    IdentityFile ~/.ssh/id_rsa

and than I had to set up the USER2 local repository a remote host like:

git remote set-url origin git@user2-github.com:user2/REPOSITORY_B.git

On MACOS everything worked like a charm, but on redhat, when I try to push on the local (USER2) repository, it tries to use "USER1" credentials... I can't find a solution, so I think I need your help...

How to use two different github accounts with SSH and Red Hat 7?

Body:
Firsrt, on RedHat, do check the remote URL used:

git remote -v

If you see https:// in there, no amount of SSH tweaking would help: SSH keys would be ignored. git config credential.helper might show you a credential cache in place, which would have cached USER1 credentials (username/password)

Secong, make sure your URL is user2-github.com:user2/REPOSITORY_B.git (no need for git@, since the user git is specified in the SSH config file)


问:
Why My test Binaries are getting copied into TestResults\<somepath>\out folder?
I am facing this unusual behavior from my Visual Studio where all of a sudden my test binaries(mytestsolution.dll) and the dependency binaries which are added in reference, are getting copied into  TestResults\\Out folder from my Bin folder and starts executing from there?

This results in my tests getting failed as my GetExecutionAssembly() is giving the path of the Out Folder instead of Bin folder where some of the dependent binaries exist?

Could any one please help me how to stop this?

答:
Little too late to the party but here what I just learned from my experiment

Env: net45, VS2017, Microsoft.VisualStudio.QualityTools.UnitTestFramework

When my TestMethod has DeploymentItemAttribute, it executes from TestResults\....\Out folder. When I remove DeploymentItemAttribute it executes from bin\debug.

ContentLicense: CC BY-SA 3.0


问:
Confusion over class resolution in Oracle java stored procedures
I'm trying to use a third-party java library within oracle.  The library seems compatible with the same 1.4 version of the jvm that our Oracle 10g server hosts, since it runs fine outside of Oracle, so I feel like I should be able to get this to work.  This library ends up making SOAP-based http requests, and I get class resolution errors when I run in Oracle.

Here's a line that shows the difference:

```<code>Class msgfact = Class.forName("com.sun.xml.messaging.saaj.soap.MessageFactoryImpl");
</code>```

I tried to register these libraries into Oracle with the loadjava utility, and I got what I thought was a successful result:

```
C:\>loadjava -verbose -schema MYUSER -user MYUSER/MYPWD@dbinstance -force saaj-impl.jar
```

It looks like everything gets loaded, and I can see this MessageFactoryImpl class in that list.  But then I try to run this line of code from Oracle SQL (inside another class I wrote and loaded with loadjava), this line throws a ClassNotFoundException (java.lang.ClassNotFoundException: com/sun/xml/messaging/saaj/soap/MessageFactoryImpl).

Then I went back and tried to add the "-resolve" switch at the loadjava command line.  It acts like these saaj classes are getting registered, but they aren't resolving properly.

How can I successfully get these saaj classes into Oracle,  or if for some reason Oracle already has these loaded, how can I convince my own code to successfully use the existing class?

FWIW, I already took the steps to make sure that the appropriate socket permissions were granted and my code can successfully make a generic http request to the target url.  It just has trouble using the library's SOAP stack to make it happen.

EDIT:
Here is a sample of my loadjava result.  This seems to be showing exactly what's failing, but I'm confused as to why these particular classes aren't being resolved when they seem to be handled properly in the pre-resolution steps.  I've eliminated about 80% of the file here, but there are other classes that show the same class resolution issues.

```
arguments: '-verbose' '-schema' 'MYSCHEMA' '-user' 'MYSCHEMA/MYSCHEMA@actest' '-resolve' '-force' 'saaj-impl.jar'
[snip]
creating : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/EnvelopeFactory
loading  : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/EnvelopeFactory
creating : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/GifDataContentHandler
loading  : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/GifDataContentHandler
creating : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/JpegDataContentHandler
loading  : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/JpegDataContentHandler
creating : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageFactoryImpl
loading  : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageFactoryImpl
creating : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl
loading  : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl
[snip]
resolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/AttachmentPartImpl
resolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/Envelope
resolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/EnvelopeFactory
errors   : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/EnvelopeFactory
    ORA-29534: referenced object MYSCHEMA.com/sun/xml/messaging/saaj/soap/SOAPPartImpl could not be resolved
resolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/GifDataContentHandler
resolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/JpegDataContentHandler
resolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageFactoryImpl
errors   : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageFactoryImpl
    ORA-29534: referenced object MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl could not be resolved
errors   : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl
    ORA-29534: referenced object MYSCHEMA.com/sun/xml/messaging/saaj/soap/impl/EnvelopeImpl could not be resolved
errors   : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl$1
    ORA-29534: referenced object MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl could not be resolved
skipping : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl$2
[snip]
The following operations failed
    class MYSCHEMA.com/sun/xml/messaging/saaj/soap/EnvelopeFactory: resolution
    class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageFactoryImpl: resolution
    class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl: resolution
    class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl$1: resolution
[snip]
exiting  : Failures occurred during processing
```

答:
First of all, verify outside of Oracle that the class you are looking for is actually in that jar file.  I expect it is, but it doesn't hurt to check.

Then, I would check what classes have been loaded and whether they have valid statuses.

```<code>SELECT object_name, dbms_java.longname(object_name), status
  FROM user_objects
  WHERE object_type='JAVA CLASS'
  ORDER BY 1
</code>```

You might want to limit this somewhat if there are a lot of classes, e.g.:

```<code>WHERE dbms_java.longname(object_name) LIKE '%MessageFactoryImpl'
</code>```

If the class is not there, or it is there with the wrong package name, then the problem is with the loadjava command.

If the class is there but its status is INVALID, then check USER_ERRORS to see what the errors are.  I don't recall if I've done dynamic class loading within Oracle, but I recall that static linking would give errors that implied a class didn't exist when it really existed but had errors.

New info after loadjava output posted

The loadjava output seems inconsistent with your attempt to find the class in the database.  If it is being loaded but not resolved, it should still be listed, but with an INVALID status.

I got the JAR and tried it myself in an empty schema.  The class loads but is invalid as expected:

```<code>dev> select object_name, dbms_java.longname(object_name),status
  2  from user_objects
  3  where object_name like '%MessageFactoryImpl';

OBJECT_NAME
--------------------------------------------------------------------------------
DBMS_JAVA.LONGNAME(OBJECT_NAME)
--------------------------------------------------------------------------------
STATUS
-------
/3e484eb0_MessageFactoryImpl
com/sun/xml/messaging/saaj/soap/MessageFactoryImpl
INVALID
</code>```

I then checked what the error were on the class:

```<code>dev> alter java class "com/sun/xml/messaging/saaj/soap/MessageFactoryImpl" resolve;
dev> /

Warning: Java altered with compilation errors.

dev> show error
Errors for JAVA CLASS "/3e484eb0_MessageFactoryImpl":

LINE/COL ERROR
-------- -----------------------------------------------------------------
0/0      ORA-29521: referenced name javax/xml/soap/MessageFactory could
         not be found

0/0      ORA-29521: referenced name javax/xml/soap/SOAPMessage could not
         be found

0/0      ORA-29521: referenced name javax/xml/soap/MimeHeaders could not
         be found

0/0      ORA-29521: referenced name javax/xml/soap/SOAPException could not
         be found
</code>```

(These errors would also be listed in USER_ERRORS, assuming resolution was attempted at least once.)

So clearly this class references classes from the base SOAP library.  You would have to load that too -- have you done that?

FYI, when I write some code to do the Class.forName() call, I do get the ClassNotFoundException.  Which may seem counter-intuitive since the class object does exist in the schema.  However, an invalid class doesn't really "exist" from the point of view of the class loader in Oracle; and in order for the class to be valid Oracle has to be able to resolve all of its references to other classes.

OwnerDisplayName: Chris Farmer

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to use a third-party java library within oracle.  The library seems compatible with the same 1.4 version of the jvm that our Oracle 10g server hosts, since it runs fine outside of Oracle, so I feel like I should be able to get this to work.  This library ends up making SOAP-based http requests, and I get class resolution errors when I run in Oracle.

Here's a line that shows the difference:

Class msgfact = Class.forName("com.sun.xml.messaging.saaj.soap.MessageFactoryImpl");

I tried to register these libraries into Oracle with the loadjava utility, and I got what I thought was a successful result:

C:\>loadjava -verbose -schema MYUSER -user MYUSER/MYPWD@dbinstance -force saaj-impl.jar

It looks like everything gets loaded, and I can see this MessageFactoryImpl class in that list.  But then I try to run this line of code from Oracle SQL (inside another class I wrote and loaded with loadjava), this line throws a ClassNotFoundException (java.lang.ClassNotFoundException: com/sun/xml/messaging/saaj/soap/MessageFactoryImpl).

Then I went back and tried to add the "-resolve" switch at the loadjava command line.  It acts like these saaj classes are getting registered, but they aren't resolving properly.

How can I successfully get these saaj classes into Oracle,  or if for some reason Oracle already has these loaded, how can I convince my own code to successfully use the existing class?

FWIW, I already took the steps to make sure that the appropriate socket permissions were granted and my code can successfully make a generic http request to the target url.  It just has trouble using the library's SOAP stack to make it happen.

EDIT:
Here is a sample of my loadjava result.  This seems to be showing exactly what's failing, but I'm confused as to why these particular classes aren't being resolved when they seem to be handled properly in the pre-resolution steps.  I've eliminated about 80% of the file here, but there are other classes that show the same class resolution issues.

arguments: '-verbose' '-schema' 'MYSCHEMA' '-user' 'MYSCHEMA/MYSCHEMA@actest' '-resolve' '-force' 'saaj-impl.jar'
[snip]
creating : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/EnvelopeFactory
loading  : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/EnvelopeFactory
creating : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/GifDataContentHandler
loading  : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/GifDataContentHandler
creating : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/JpegDataContentHandler
loading  : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/JpegDataContentHandler
creating : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageFactoryImpl
loading  : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageFactoryImpl
creating : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl
loading  : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl
[snip]
resolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/AttachmentPartImpl
resolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/Envelope
resolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/EnvelopeFactory
errors   : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/EnvelopeFactory
    ORA-29534: referenced object MYSCHEMA.com/sun/xml/messaging/saaj/soap/SOAPPartImpl could not be resolved
resolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/GifDataContentHandler
resolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/JpegDataContentHandler
resolving: class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageFactoryImpl
errors   : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageFactoryImpl
    ORA-29534: referenced object MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl could not be resolved
errors   : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl
    ORA-29534: referenced object MYSCHEMA.com/sun/xml/messaging/saaj/soap/impl/EnvelopeImpl could not be resolved
errors   : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl$1
    ORA-29534: referenced object MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl could not be resolved
skipping : class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl$2
[snip]
The following operations failed
    class MYSCHEMA.com/sun/xml/messaging/saaj/soap/EnvelopeFactory: resolution
    class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageFactoryImpl: resolution
    class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl: resolution
    class MYSCHEMA.com/sun/xml/messaging/saaj/soap/MessageImpl$1: resolution
[snip]
exiting  : Failures occurred during processing

LastEditorDisplayName: Chris Farmer

Body:
First of all, verify outside of Oracle that the class you are looking for is actually in that jar file.  I expect it is, but it doesn't hurt to check.

Then, I would check what classes have been loaded and whether they have valid statuses.

SELECT object_name, dbms_java.longname(object_name), status
  FROM user_objects
  WHERE object_type='JAVA CLASS'
  ORDER BY 1

You might want to limit this somewhat if there are a lot of classes, e.g.:

WHERE dbms_java.longname(object_name) LIKE '%MessageFactoryImpl'

If the class is not there, or it is there with the wrong package name, then the problem is with the loadjava command.

If the class is there but its status is INVALID, then check USER_ERRORS to see what the errors are.  I don't recall if I've done dynamic class loading within Oracle, but I recall that static linking would give errors that implied a class didn't exist when it really existed but had errors.

New info after loadjava output posted

The loadjava output seems inconsistent with your attempt to find the class in the database.  If it is being loaded but not resolved, it should still be listed, but with an INVALID status.

I got the JAR and tried it myself in an empty schema.  The class loads but is invalid as expected:

dev> select object_name, dbms_java.longname(object_name),status
  2  from user_objects
  3  where object_name like '%MessageFactoryImpl';

OBJECT_NAME
--------------------------------------------------------------------------------
DBMS_JAVA.LONGNAME(OBJECT_NAME)
--------------------------------------------------------------------------------
STATUS
-------
/3e484eb0_MessageFactoryImpl
com/sun/xml/messaging/saaj/soap/MessageFactoryImpl
INVALID

I then checked what the error were on the class:

dev> alter java class "com/sun/xml/messaging/saaj/soap/MessageFactoryImpl" resolve;
dev> /

Warning: Java altered with compilation errors.

dev> show error
Errors for JAVA CLASS "/3e484eb0_MessageFactoryImpl":

LINE/COL ERROR
-------- -----------------------------------------------------------------
0/0      ORA-29521: referenced name javax/xml/soap/MessageFactory could
         not be found

0/0      ORA-29521: referenced name javax/xml/soap/SOAPMessage could not
         be found

0/0      ORA-29521: referenced name javax/xml/soap/MimeHeaders could not
         be found

0/0      ORA-29521: referenced name javax/xml/soap/SOAPException could not
         be found

(These errors would also be listed in USER_ERRORS, assuming resolution was attempted at least once.)

So clearly this class references classes from the base SOAP library.  You would have to load that too -- have you done that?

FYI, when I write some code to do the Class.forName() call, I do get the ClassNotFoundException.  Which may seem counter-intuitive since the class object does exist in the schema.  However, an invalid class doesn't really "exist" from the point of view of the class loader in Oracle; and in order for the class to be valid Oracle has to be able to resolve all of its references to other classes.

OwnerDisplayName: Dave Costa

LastEditorDisplayName: Dave Costa


问:
Fill 3 tables in a Dataset
I've been reading a lot about this but I haven't come across any solutions. I have a dataset with 3 tables. How can I fill these 3 tables in the dataset?
Is it possible using only one sql query with many joins?</p>

答:
```<code>select * from tableA where <condition>

select * from tableB where <condition>

select * from tableC where <condition>
</code>```

will return three tables (DataSet)

Title: Fill 3 tables in a Dataset

Body:
select * from tableA where <condition>

select * from tableB where <condition>

select * from tableC where <condition>

will return three tables (DataSet)


问:
Sonarqube SonarScanner ignores Javascript files in a React project
I have a ReactJS Javascript project workspace in Windows 10 OS for which I wanted to use SonarScanner to run code analysis. I have setup and verified that SonarScanner is running correctly. I also set the "sonar.host.url" in SonarScanner/conf/sonar-scanner.properties file. I can see the results of the scan everytime I run.

I then added the "sonar-project.properties" file in my workspace. These are the settings in the "sonar-project.properties" file:

```<code>sonar-project.properties
# must be unique in a given SonarQube instance
sonar.projectKey=Project1

# --- optional properties ---

# defaults to project key
sonar.projectName=React Webapp
# defaults to 'not provided'
#sonar.projectVersion=1.0

# Path is relative to the sonar-project.properties file. Defaults to .
sonar.projectBaseDir=C:/code/model-group-webapp
sonar.sources=src

# Encoding of the source code. Default is default system encoding
#sonar.sourceEncoding=UTF-8
</code>```

I then ran the sonar-scanner command like this "$sonar-scanner -X".

I can see in the logs that the Javascript files are read, but the files are indexed with language "null".

```<code>13:56:46.764 INFO: Source paths: src
13:56:46.765 INFO: Source encoding: windows-1252, default locale: en_US
13:56:46.768 INFO: Index files
13:56:46.794 DEBUG: 'src/App.js' indexed with language 'null'
13:56:46.796 DEBUG: 'src/App.test.js' indexed with language 'null'
13:56:46.796 DEBUG: 'src/config/config.js' indexed with language 'null'
13:56:46.798 DEBUG: 'src/EditPanel.js' indexed with language 'null'
13:56:46.800 DEBUG: 'src/Filter.js' indexed with language 'null'
13:56:46.800 DEBUG: 'src/index.css' indexed with language 'null'
13:56:46.805 DEBUG: 'src/index.js' indexed with language 'null'
13:56:46.805 DEBUG: 'src/logo.svg' indexed with language 'null'
13:56:46.810 DEBUG: 'src/serviceWorker.js' indexed with language 'null'
</code>```

I also noticed that Javascript was not in the available languages in the logs. It only showed Java:

```<code>14:29:42.889 INFO: Load project repositories (done) | time=125ms
14:29:42.990 DEBUG: Available languages:
14:29:42.993 DEBUG:   * Java => "java"
</code>```

In the Sonarqube server, the project shows 0 errors and vulnerabilities, with no source code.

What is the missing configuration here?

答:
If you are running from jenkins,
add the srs path of your code files,</p>

```<code>sonar.language=js (optional)
sonar.sources=./src/main/TestApp
</code>```

Body:
I have a ReactJS Javascript project workspace in Windows 10 OS for which I wanted to use SonarScanner to run code analysis. I have setup and verified that SonarScanner is running correctly. I also set the "sonar.host.url" in SonarScanner/conf/sonar-scanner.properties file. I can see the results of the scan everytime I run.

I then added the "sonar-project.properties" file in my workspace. These are the settings in the "sonar-project.properties" file:

sonar-project.properties
# must be unique in a given SonarQube instance
sonar.projectKey=Project1

# --- optional properties ---

# defaults to project key
sonar.projectName=React Webapp
# defaults to 'not provided'
#sonar.projectVersion=1.0

# Path is relative to the sonar-project.properties file. Defaults to .
sonar.projectBaseDir=C:/code/model-group-webapp
sonar.sources=src

# Encoding of the source code. Default is default system encoding
#sonar.sourceEncoding=UTF-8

I then ran the sonar-scanner command like this "$sonar-scanner -X".

I can see in the logs that the Javascript files are read, but the files are indexed with language "null".

13:56:46.764 INFO: Source paths: src
13:56:46.765 INFO: Source encoding: windows-1252, default locale: en_US
13:56:46.768 INFO: Index files
13:56:46.794 DEBUG: 'src/App.js' indexed with language 'null'
13:56:46.796 DEBUG: 'src/App.test.js' indexed with language 'null'
13:56:46.796 DEBUG: 'src/config/config.js' indexed with language 'null'
13:56:46.798 DEBUG: 'src/EditPanel.js' indexed with language 'null'
13:56:46.800 DEBUG: 'src/Filter.js' indexed with language 'null'
13:56:46.800 DEBUG: 'src/index.css' indexed with language 'null'
13:56:46.805 DEBUG: 'src/index.js' indexed with language 'null'
13:56:46.805 DEBUG: 'src/logo.svg' indexed with language 'null'
13:56:46.810 DEBUG: 'src/serviceWorker.js' indexed with language 'null'

I also noticed that Javascript was not in the available languages in the logs. It only showed Java:

14:29:42.889 INFO: Load project repositories (done) | time=125ms
14:29:42.990 DEBUG: Available languages:
14:29:42.993 DEBUG:   * Java => "java"

In the Sonarqube server, the project shows 0 errors and vulnerabilities, with no source code.

What is the missing configuration here?

Body:
If you are running from jenkins,
add the srs path of your code files,

sonar.language=js (optional)
sonar.sources=./src/main/TestApp


问:
Making an outbound connection
I've recently been tinkering around with the python socket module and I have come across an issue.
Here is my python server side script (im using python3.8.2)

```<code>import socket

#defin socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 0))
s.listen(5)
while True:
    clientsocket, address = s.accept()
    print(f"connection from client has been established")
    clientsocket.send(bytes("welcome to the server!", "utf-8"))

</code>```

My server side script runs fine, however when i run the client script

```<code>import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(127.0.0.1), 0))
msg = s.recv(1024)
print(msg.decode("utf-8"))
</code>```

i get the following:

```<code>File "client.py", line 3
    s.connect((socket.gethostname(127.0.0.1), 0))
                                       ^
SyntaxError: invalid syntax
</code>```

I've tried changing the IP to my computer host name  and gives the following:

```<code>raceback (most recent call last):
  File "client.py", line 3, in <module>
    s.connect(socket.gethostname((LAPTOP-XXXXXXX), 0))
NameError: name 'LAPTOP' is not defined
</code>```

答:
In the /etc/hosts file content, You will have an IP address mapping with '127.0.1.1' to your hostname. This will cause the name resolution to get 127.0.1.1. Just comment this line. So  Every one in your LAN can receive the data when they connect with your ip (192.168.1.*). Used threading to manage multiple Clients.

Here's the Server and Client Code:
Server Code:

```<code>import socket
import os
from threading import Thread
import threading
import time
import datetime

def listener(client, address):
    print ("Accepted connection from: ", address)
    with clients_lock:
        clients.add(client)
    try:
        while True:
            client.send(a)
            time.sleep(2)

    finally:
        with clients_lock:
            clients.remove(client)
            client.close()

clients = set()
clients_lock = threading.Lock()

host = socket.getfqdn()  # it gets ip of lan
port = 10016

s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host,port))
s.listen(3)
th = []
print ("Server is listening for connections...")
while True:
    client, address = s.accept()
    timestamp = datetime.datetime.now().strftime("%b %d %Y,%a, %I:%M:%S %p")
    a = ("Hi Steven!!!" + timestamp).encode()
    th.append(Thread(target=listener, args = (client,address)).start())
s.close()
</code>```

Client Code:

```<code>import socket
import os
import time

s = socket.socket()
host = '192.168.1.43' #my server ip
port = 10016
print(host)
print(port)

s.connect((host, port))
while True:
    print((s.recv(1024)).decode())
s.close()
</code>```

Output:

```<code>(base) paulsteven@smackcoders:~$ python server.py
Server is listening for connections...
Accepted connection from:  ('192.168.1.43', 38716)

(base) paulsteven@smackcoders:~$ python client.py
192.168.1.43
10016
Hi Steven!!!Feb 19 2020,Wed, 11:13:17 AM
Hi Steven!!!Feb 19 2020,Wed, 11:13:17 AM
Hi Steven!!!Feb 19 2020,Wed, 11:13:17 AM
</code>```

Title: Making an outbound connection

Body:
I've recently been tinkering around with the python socket module and I have come across an issue.
Here is my python server side script (im using python3.8.2)

import socket

#defin socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 0))
s.listen(5)
while True:
    clientsocket, address = s.accept()
    print(f"connection from client has been established")
    clientsocket.send(bytes("welcome to the server!", "utf-8"))

My server side script runs fine, however when i run the client script

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(127.0.0.1), 0))
msg = s.recv(1024)
print(msg.decode("utf-8"))

i get the following:

File "client.py", line 3
    s.connect((socket.gethostname(127.0.0.1), 0))
                                       ^
SyntaxError: invalid syntax

I've tried changing the IP to my computer host name  and gives the following:

raceback (most recent call last):
  File "client.py", line 3, in <module>
    s.connect(socket.gethostname((LAPTOP-XXXXXXX), 0))
NameError: name 'LAPTOP' is not defined

Body:
In the /etc/hosts file content, You will have an IP address mapping with '127.0.1.1' to your hostname. This will cause the name resolution to get 127.0.1.1. Just comment this line. So  Every one in your LAN can receive the data when they connect with your ip (192.168.1.*). Used threading to manage multiple Clients.

Here's the Server and Client Code:
Server Code:

import socket
import os
from threading import Thread
import threading
import time
import datetime

def listener(client, address):
    print ("Accepted connection from: ", address)
    with clients_lock:
        clients.add(client)
    try:
        while True:
            client.send(a)
            time.sleep(2)

    finally:
        with clients_lock:
            clients.remove(client)
            client.close()

clients = set()
clients_lock = threading.Lock()

host = socket.getfqdn()  # it gets ip of lan
port = 10016

s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host,port))
s.listen(3)
th = []
print ("Server is listening for connections...")
while True:
    client, address = s.accept()
    timestamp = datetime.datetime.now().strftime("%b %d %Y,%a, %I:%M:%S %p")
    a = ("Hi Steven!!!" + timestamp).encode()
    th.append(Thread(target=listener, args = (client,address)).start())
s.close()

Client Code:

import socket
import os
import time

s = socket.socket()
host = '192.168.1.43' #my server ip
port = 10016
print(host)
print(port)

s.connect((host, port))
while True:
    print((s.recv(1024)).decode())
s.close()

Output:

(base) paulsteven@smackcoders:~$ python server.py
Server is listening for connections...
Accepted connection from:  ('192.168.1.43', 38716)

(base) paulsteven@smackcoders:~$ python client.py
192.168.1.43
10016
Hi Steven!!!Feb 19 2020,Wed, 11:13:17 AM
Hi Steven!!!Feb 19 2020,Wed, 11:13:17 AM
Hi Steven!!!Feb 19 2020,Wed, 11:13:17 AM


问:
Java Jsoup Submitting a form
I am trying to figure out how to submit a form using Jsoup.
On Xfinity's website, I am trying to input an address and get back the resulting page after clicking on "Show me deals" from the url below:

https://www.xfinity.com/learn/offers

Here is my current code:

```<code>    public String getISP() throws IOException {
    Connection.Response addressFormResponse = Jsoup.connect("https://www.xfinity.com/learn/offers")
            .data("Address.SingleStreetAddress", address)
            .method(Connection.Method.POST)
            .execute();

    Document doc = addressFormResponse.parse();

    System.out.println(doc.title());
    System.out.println(doc.location());
    if (doc.location().contains("Active Address")) {
        return "Comcast XFinity";
    }
    return "Cannot find an ISP";
}
</code>```

The current code only returns the same webpage, how would I get back the resulting page?

答: Jsoup is a HTML parser library, it provides functionality for extracting and manipulating data on HTML page. If you need traverse websites, submit forms, click elements, it's better to use another tools, like selenium, HTTP client (which are often used for automated test of web applications) or web crawler libraries like crawler4j.</p>

Title: Java Jsoup Submitting a form

Body:
I am trying to figure out how to submit a form using Jsoup.
On Xfinity's website, I am trying to input an address and get back the resulting page after clicking on "Show me deals" from the url below:

https://www.xfinity.com/learn/offers

Here is my current code:

    public String getISP() throws IOException {
    Connection.Response addressFormResponse = Jsoup.connect("https://www.xfinity.com/learn/offers")
            .data("Address.SingleStreetAddress", address)
            .method(Connection.Method.POST)
            .execute();

    Document doc = addressFormResponse.parse();

    System.out.println(doc.title());
    System.out.println(doc.location());
    if (doc.location().contains("Active Address")) {
        return "Comcast XFinity";
    }
    return "Cannot find an ISP";
}

The current code only returns the same webpage, how would I get back the resulting page?


问:
Can't install tensorflow with pip or anaconda
Does anyone know how to properly install tensorflow on Windows?

I'm currently using Python 3.7 (also tried with 3.6) and every time I get the same "Could not find a version that satisfies the requirement tensorflow-gpu (from versions: )
No matching distribution found for tensorflow-gpu" error

I tried installing using pip and anaconda, both don't work for me.

Found a solution, seems like Tensorflow doesn't support versions of python after 3.6.4. This is the version I'm currently using and it works.

答:
As of Feb 2020, Tensorflow is not supported for Python 3.8+

To make it work install a virtualenv w/ Python 3.7 from here: https://www.python.org/downloads/windows/


问:
Inner Join with similar IDs
I have two tables, say:

```<code>Table 1

id, name, place
1, a, b
2, c, d
3, e, f

Table 2

id,text
1, hello
1, bye
1, what
2, tired
</code>```

Desired Output

```<code>id, name, place, text
1, a, b, hello or bye or what (any one of the three)
2, c, d, tired
</code>```

I have seen a lot of posts but I couldn't find anything similar. I am new to SQL/Postgresql. I am doing it in PostgreSQL.

答:
You could use DISTINCT ON here and arbitrarily just take the alphabetically lowest text from the second table:

```<code>SELECT DISTINCT ON (t1.id) t1.id, t1.name, t1.place, t2.text
FROM Table1 t1
INNER JOIN Table2 t2
    ON t1.id = t2.id
ORDER BY
    t1.id,
    t2.text;
</code>```

Demo

Title: Inner Join with similar IDs

Body:
I have two tables, say:

Table 1

id, name, place
1, a, b
2, c, d
3, e, f

Table 2

id,text
1, hello
1, bye
1, what
2, tired

Desired Output

id, name, place, text
1, a, b, hello or bye or what (any one of the three)
2, c, d, tired

I have seen a lot of posts but I couldn't find anything similar. I am new to SQL/Postgresql. I am doing it in PostgreSQL.

Body:
You could use DISTINCT ON here and arbitrarily just take the alphabetically lowest text from the second table:

SELECT DISTINCT ON (t1.id) t1.id, t1.name, t1.place, t2.text
FROM Table1 t1
INNER JOIN Table2 t2
    ON t1.id = t2.id
ORDER BY
    t1.id,
    t2.text;

Demo


问:
How to format numbers floats with comma and dot
I have the following data that I need to format:

```<code>  Ativo        high       close
 HTMX11       169.8       169.8
 KNHY11       116.0       116.0
 FAED11       272.3       272.3
 FLRP11     1579.92     1579.92
 FVPQ11       215.5       215.5
</code>```

Need to convert 1579.92 to 1.579,92

not a problem, since I can do with:

```<code>import pandas as pd
import locale
locale.setlocale (locale.LC_ALL, 'pt_br.utf-8')
pd.set_option ('display.float_format', lambda x: locale.format ('%. 2f', x, grouping = True))
</code>```

but when I need to convert the column to a string and add some letters, numbers are kept only with commas:

I need complete formatting.

```<code>df['close'] = '$' + df['close'].astype()
df['close']
</code>```

Results in:

```<code>Fechamento
  R$ 169,8
  R$ 116,0
  R$ 272,3
R$ 1579,92
  R$ 215,5
</code>```

desired output:

```<code>R$ 1.579,92
</code>```

答:
As you've noticed, the display option only affects the display. So you need to do an explicit conversion, possibly using locale.format(), if you want to actually convert the column to a string.

The locale methods are also somewhat limited in what they can do, so I'd recommend using the Babel module for internationalization and localization. Babel has a richer API and it actually ships localization data you can use (so you don't need to depend on it being available in your O.S.) It also includes data about currencies, so it can do that conversion for you as well.

You can install Babel with:

```<code>pip install Babel
</code>```

And then you can convert your columns to use Brazilian Real currency with:

```<code>from babel.numbers import format_currency

df['close'] = df['close'].apply(
    lambda v: format_currency(v, 'BRL', locale='pt_BR'),
)
</code>```

Or, to convert both "high" and "close" together:

```<code>df[['high', 'close']] = df[['high', 'close']].applymap(
    lambda v: format_currency(v, 'BRL', locale='pt_BR'),
)
</code>```

If you're generating HTML from the DataFrame (for example, in a Jupyter notebook), you can use the Styling API to apply the format only when rendering the DataFrame, keeping the underlying data as floats and not strings:

```<code>df.style.format(
    lambda v: format_currency(v, 'BRL', locale='pt_BR'),
    subset=['high', 'close'],
)
</code>```

Body:
I have the following data that I need to format:

  Ativo        high       close
 HTMX11       169.8       169.8
 KNHY11       116.0       116.0
 FAED11       272.3       272.3
 FLRP11     1579.92     1579.92
 FVPQ11       215.5       215.5

Need to convert 1579.92 to 1.579,92

not a problem, since I can do with:

import pandas as pd
import locale
locale.setlocale (locale.LC_ALL, 'pt_br.utf-8')
pd.set_option ('display.float_format', lambda x: locale.format ('%. 2f', x, grouping = True))

but when I need to convert the column to a string and add some letters, numbers are kept only with commas:

I need complete formatting.

df['close'] = '$' + df['close'].astype()
df['close']

Results in:

Fechamento
  R$ 169,8
  R$ 116,0
  R$ 272,3
R$ 1579,92
  R$ 215,5

desired output:

R$ 1.579,92

Body:
As you've noticed, the display option only affects the display. So you need to do an explicit conversion, possibly using locale.format(), if you want to actually convert the column to a string.

The locale methods are also somewhat limited in what they can do, so I'd recommend using the Babel module for internationalization and localization. Babel has a richer API and it actually ships localization data you can use (so you don't need to depend on it being available in your O.S.) It also includes data about currencies, so it can do that conversion for you as well.

You can install Babel with:

pip install Babel

And then you can convert your columns to use Brazilian Real currency with:

from babel.numbers import format_currency

df['close'] = df['close'].apply(
    lambda v: format_currency(v, 'BRL', locale='pt_BR'),
)

Or, to convert both "high" and "close" together:

df[['high', 'close']] = df[['high', 'close']].applymap(
    lambda v: format_currency(v, 'BRL', locale='pt_BR'),
)

If you're generating HTML from the DataFrame (for example, in a Jupyter notebook), you can use the Styling API to apply the format only when rendering the DataFrame, keeping the underlying data as floats and not strings:

df.style.format(
    lambda v: format_currency(v, 'BRL', locale='pt_BR'),
    subset=['high', 'close'],
)


问:
Read Image pixels, row by row
I've been working on a project that requires my code to get pixel data of an image and reconstruct it (in another form) however when I try to create an image using the pixel data, it turns out that all the pixels are on the same row.

Here's my code

pixels = (image.getdata())

img_array = np.array(pixels, dtype=np.uint8)

img = Image.fromarray(img_array)
img.save('testrgb.png')
```

<p>How do I read the image's pixels line by line and arrange them in different lists depending on their rows?</p>

<p><strong>EDIT</strong> I was able to achieve the desired result by using the following code</p>

<pre class="lang-py prettyprint-override"><code>pixels = list(image.getdata())
print(pixels[0][0])
pixels2 = []
for i in range(0, height):
    pixels2.append(pixels[i * width:(i + 1) * width])

#for pixel_value in pixels:
    #print(pixel_value)

img_array = array = np.array(pixels2, dtype=np.uint8)

img = Image.fromarray(array)
img.save('maps/testrgb.png')
</code>```

答:
From the documentation on getdata:

Returns the contents of this image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on.

If you want to have a NumPy array representation of the actual image, use np.array on image directly:

import numpy as np
from PIL import Image

# Open image with Pillow
image = Image.open('path/to/your/image.png')

# Convert Pillow image to NumPy array
img_array = np.array(image, dtype=np.uint8)

# ... do some operation on NumPy array (copy rows to lists, etc.) ...

# Convert NumPy array back to Pillow image
img = Image.fromarray(img_array)

# Save image with Pillow
img.save('testrgb.png')
```

<p>Hope that helps!</p>

<pre class="lang-none prettyprint-override"><code>----------------------------------------
System information
----------------------------------------
Platform:    Windows-10-10.0.16299-SP0
Python:      3.8.1
NumPy:       1.18.1
Pillow:      7.0.0
----------------------------------------
</code>```

Title: Read Image pixels, row by row

Body:
I've been working on a project that requires my code to get pixel data of an image and reconstruct it (in another form) however when I try to create an image using the pixel data, it turns out that all the pixels are on the same row.

Here's my code

pixels = (image.getdata())

img_array = np.array(pixels, dtype=np.uint8)

img = Image.fromarray(img_array)
img.save('testrgb.png')

How do I read the image's pixels line by line and arrange them in different lists depending on their rows?

EDIT I was able to achieve the desired result by using the following code

pixels = list(image.getdata())
print(pixels[0][0])
pixels2 = []
for i in range(0, height):
    pixels2.append(pixels[i * width:(i + 1) * width])

#for pixel_value in pixels:
    #print(pixel_value)

img_array = array = np.array(pixels2, dtype=np.uint8)

img = Image.fromarray(array)
img.save('maps/testrgb.png')

Body:
From the documentation on getdata:

Returns the contents of this image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on.

If you want to have a NumPy array representation of the actual image, use np.array on image directly:

import numpy as np
from PIL import Image

# Open image with Pillow
image = Image.open('path/to/your/image.png')

# Convert Pillow image to NumPy array
img_array = np.array(image, dtype=np.uint8)

# ... do some operation on NumPy array (copy rows to lists, etc.) ...

# Convert NumPy array back to Pillow image
img = Image.fromarray(img_array)

# Save image with Pillow
img.save('testrgb.png')

Hope that helps!

----------------------------------------
System information
----------------------------------------
Platform:    Windows-10-10.0.16299-SP0
Python:      3.8.1
NumPy:       1.18.1
Pillow:      7.0.0
----------------------------------------


问:
Volley error response bytes does not convert from bytes to string
```<code>CustomStringRequest customStringRequest = new CustomStringRequest(requestMethod.ordinal(), serverUrl,
            result -> {
                Log.d(TAG, "headers: " + result.headers);
                Log.d(TAG, "response: " + result.response);
                createTaskItem(result);
            },
            error -> {
                Log.d(TAG, "error: " + error);
            })
</code>```

error is in JSON string, I tried to get error like this:

```<code>new String(error.networkResponse.data, "utf-8");
new String(error.networkResponse.data);
</code>```

none of the above method works, i always get empty string, don't know why :(

as you can see bytes in picture, the error response is actually this:

```<code>   {
  "error": [
    "Wrong Credentials!"
  ],
  "email_exists": false
}
</code>```

I am using:

```<code>implementation 'com.android.volley:volley:1.1.1'
</code>```

答:
oh, i was just evaluating error response in debug mode
new String(error.networkResponse.data, "UTF-8");
and it returns empty string in result.
I just tried to print error response and it worked!. Thanks.

Body:
CustomStringRequest customStringRequest = new CustomStringRequest(requestMethod.ordinal(), serverUrl,
            result -> {
                Log.d(TAG, "headers: " + result.headers);
                Log.d(TAG, "response: " + result.response);
                createTaskItem(result);
            },
            error -> {
                Log.d(TAG, "error: " + error);
            })

error is in JSON string, I tried to get error like this:

new String(error.networkResponse.data, "utf-8");
new String(error.networkResponse.data);

none of the above method works, i always get empty string, don't know why :(

as you can see bytes in picture, the error response is actually this:

   {
  "error": [
    "Wrong Credentials!"
  ],
  "email_exists": false
}

I am using:

implementation 'com.android.volley:volley:1.1.1'


问:
MySQL query to find all URLs that are substring of other URLs
I have a MySQL field URL of type Varchar.

Is it possible with one MySQL query to return all records where the string value URL is a substring of another record URL value, and display both the substrings and full strings records?

答: In general, the answer is "Yes", using the INSTR() or LOCATE() functions. But it depends on how your URLS are stored.  Things like "http://", subdomains, and such can give you many false positives or false negatives. Not false in the sense that INSTR() is broken, but false in the sense that it won't do what you might want it to.</p>


问:
SQL Server combine data
I have 2 tables, one containing an ID number and a DateTime (MAIN TABLE). The other table has an ID, LocationName and DateTime (Location table).

The DateTime in the main table is a frequent capture of automated signals. The DateTime in the location table is when an object has been moved to a new location. Both the IDs are the primary key and link.

What I'm trying to do is produce just one table showing when the location changes occur, showing ID, DateTime from the main table and LocationName from the location table.

I have been trying for hours but can't seem to do it...

Below is an example of the tables and the end result..

Any help would be grateful.

Thanks

```<code>MAIN TABLE           Location Table

ID DateTime          ID DateTime         Location
-----------------    ----------------------------
1  20200101 12:00    1  20200101 11:45   Loc 1
1  20200101 13:00    1  20200101 13:45   Loc 2
1  20200101 14:00    2  20200101 15:15   Loc 1
2  20200101 15:00    2  20200101 17:30   Loc 2
2  20200101 17:00
</code>```

To show the table as:

```<code>ID DateTime       Location
---------------------------
1  20200101 12:00 Loc 1
1  20200101 13:00 Loc 2
1  20200101 14:00 Loc 2
2  20200101 15:00 Loc 1
2  20200101 17:00 Loc 2
</code>```

答:
```<code>  SELECT MAIN.ID,MAIN.DATETIME,Location.LOC
FROM MAIN
left  JOIN Location
ON Location.ID = MAIN.ID and MAIN.DATETIME=Location.DATETIME
GROUP BY Location.ID,MAIN.ID,MAIN.DATETIME,Location.LOC;
</code>```

That is a Output Generate either change the data in your Main Table

Title: SQL Server combine data

Body:
I have 2 tables, one containing an ID number and a DateTime (MAIN TABLE). The other table has an ID, LocationName and DateTime (Location table).

The DateTime in the main table is a frequent capture of automated signals. The DateTime in the location table is when an object has been moved to a new location. Both the IDs are the primary key and link.

What I'm trying to do is produce just one table showing when the location changes occur, showing ID, DateTime from the main table and LocationName from the location table.

I have been trying for hours but can't seem to do it...

Below is an example of the tables and the end result..

Any help would be grateful.

Thanks

MAIN TABLE           Location Table

ID DateTime          ID DateTime         Location
-----------------    ----------------------------
1  20200101 12:00    1  20200101 11:45   Loc 1
1  20200101 13:00    1  20200101 13:45   Loc 2
1  20200101 14:00    2  20200101 15:15   Loc 1
2  20200101 15:00    2  20200101 17:30   Loc 2
2  20200101 17:00

To show the table as:

ID DateTime       Location
---------------------------
1  20200101 12:00 Loc 1
1  20200101 13:00 Loc 2
1  20200101 14:00 Loc 2
2  20200101 15:00 Loc 1
2  20200101 17:00 Loc 2

Body:
  SELECT MAIN.ID,MAIN.DATETIME,Location.LOC
FROM MAIN
left  JOIN Location
ON Location.ID = MAIN.ID and MAIN.DATETIME=Location.DATETIME
GROUP BY Location.ID,MAIN.ID,MAIN.DATETIME,Location.LOC;

That is a Output Generate either change the data in your Main Table


问:
Azure Pipelines Conditional and Persistent Variables
I'm trying to setup an Azure Pipeline that automatically updates version numbers based on which branch is being built. Given a master branch, a develop branch, and a version in the form {major.minor.patch.build} I want to achieve the following:

Whenever the pipeline is triggered by master:

patch is incremented by 1

build is reset to 0

Whenever the pipeline is triggered by develop:

build is incremented by 1

An example of what I expect the version numbers to look like after multiple runs assuming a starting version of 1.0.0.0:

Run 1 on develop: 1.0.0.1

Run 2 on develop: 1.0.0.2

Run 3 on master: 1.0.1.0

Run 4 on master: 1.0.2.0

Run 5 on develop: 1.0.2.1

Run 6 on develop: 1.0.2.2

Run 7 on master: 1.0.3.0

My first thought was to use a counter for the patch and build values but there doesn't seem to be a way of conditionally incrementing them or resetting the counter. My next thought was to use a couple script tasks that execute conditionally based on the branch, such as:

```<code>    #Update build
    - powershell: echo "##vso[task.setvariable variable=version.build;isOutput=true]$(version.build + 1)"
      condition: eq(variables['Build.SourceBranch'], 'refs/heads/develop')

    #Reset build number
    - powershell: echo "##vso[task.setvariable variable=version.build;isOutput=true]0"
      condition: eq(variables['Build.SourceBranch'], 'refs/heads/master')

    #Update patch
    - powershell: echo "##vso[task.setvariable variable=version.patch;isOutput=true]$(version.patch + 1)"
      condition: eq(variables['Build.SourceBranch'], 'refs/heads/master')
</code>```

However that approach isn't persistent across runs (not to mention $(version.patch + 1) doesn't work. I can't find any information on how to actually increment a variable in this way). My last idea was to have a version file in the repository and use that but I really don't want to have to go down that route.

Is there a way to achieve what I'm looking for using Pipelines or am I barking up the wrong tree trying to go about it this way?

Edit
I should have mentioned in the question that at this point I have a pipeline setup that builds my application but does nothing with versioning. What I'm looking for at this point is a way to dynamically update a few persistent variables/values (specifically patch and build).

答:
So there is a counter variable that is available that can handle some of what you want.

Using it I was able to partially get it to work with what you are after.

```<code>trigger:
- master

pool:
  vmImage: 'ubuntu-latest'

variables:
  major: 1
  minor: 0
  # define b as a counter with the prefix as variable a, and seed as 100.
  #patch: $[counter(variables['major'], 1)]

  ${{ if eq( variables['Build.SourceBranchName'], 'master') }}:
    patch: $[counter(variables['major'], 1)]
    build: 0

  ${{ if eq( variables['Build.SourceBranchName'], 'develop') }}:
    build: $[counter(variables['major'], 1)]
    #patch: ?

name: $(major).$(minor).$(patch).$(build)

steps:
    - bash: echo $(major).$(minor).$(patch).$(build)
</code>```

But as far as I see there is not a good way to get the current $(patch) counter variable when a build runs on develop. Side note I would be interested to know how to get at the custom counter values. You could likely use the API and go grab the Buildnumber from the last run and pull the patch number and reuse it, but that leads into this question you asked.

Is there a way to achieve what I'm looking for using Pipelines or am I
  barking up the wrong tree trying to go about it this way?

I would argue to change your approach. If you are crafting custom versioning schemes with powershell or yaml, at that point I would say versioning is important enough for you to use GitVersion or some equivalent. There is a learning curve to get started, but one of the default out of the box GitVersion modes would likely serve your purpose.

There is a pipeline task here that will handle computing a version for you, if you just add it to your pipeline.

```<code>- task: GitVersion@5
  inputs:
    runtime: 'core'
    configFilePath: 'GitVersion.yml'
</code>```

Better to supply a GitVersion.yml, which is the scheme or instruction set for how to do the versioning.

There is a chocolatey package that you can install to experiment with locally. If you run GitVersion init in the root of your repo it will walk you though some versioning options, and create the GitVersion.yml for you.

```<code>mode: Mainline
branches:
  master:
    tag: ''
    regex: master
    increment: minor
  develop:
    tag: ''
    regex: develop
    increment: patch
ignore:
  sha: []
merge-message-formats: {}
</code>```

As an example the above stock mainline mode gives me:

Body:
I'm trying to setup an Azure Pipeline that automatically updates version numbers based on which branch is being built. Given a master branch, a develop branch, and a version in the form {major.minor.patch.build} I want to achieve the following:

Whenever the pipeline is triggered by master:

patch is incremented by 1

build is reset to 0

Whenever the pipeline is triggered by develop:

build is incremented by 1

An example of what I expect the version numbers to look like after multiple runs assuming a starting version of 1.0.0.0:

Run 1 on develop: 1.0.0.1

Run 2 on develop: 1.0.0.2

Run 3 on master: 1.0.1.0

Run 4 on master: 1.0.2.0

Run 5 on develop: 1.0.2.1

Run 6 on develop: 1.0.2.2

Run 7 on master: 1.0.3.0

My first thought was to use a counter for the patch and build values but there doesn't seem to be a way of conditionally incrementing them or resetting the counter. My next thought was to use a couple script tasks that execute conditionally based on the branch, such as:

    #Update build
    - powershell: echo "##vso[task.setvariable variable=version.build;isOutput=true]$(version.build + 1)"
      condition: eq(variables['Build.SourceBranch'], 'refs/heads/develop')

    #Reset build number
    - powershell: echo "##vso[task.setvariable variable=version.build;isOutput=true]0"
      condition: eq(variables['Build.SourceBranch'], 'refs/heads/master')

    #Update patch
    - powershell: echo "##vso[task.setvariable variable=version.patch;isOutput=true]$(version.patch + 1)"
      condition: eq(variables['Build.SourceBranch'], 'refs/heads/master')

However that approach isn't persistent across runs (not to mention $(version.patch + 1) doesn't work. I can't find any information on how to actually increment a variable in this way). My last idea was to have a version file in the repository and use that but I really don't want to have to go down that route.

Is there a way to achieve what I'm looking for using Pipelines or am I barking up the wrong tree trying to go about it this way?

Edit
I should have mentioned in the question that at this point I have a pipeline setup that builds my application but does nothing with versioning. What I'm looking for at this point is a way to dynamically update a few persistent variables/values (specifically patch and build).

Body:
So there is a counter variable that is available that can handle some of what you want.

Using it I was able to partially get it to work with what you are after.

trigger:
- master

pool:
  vmImage: 'ubuntu-latest'

variables:
  major: 1
  minor: 0
  # define b as a counter with the prefix as variable a, and seed as 100.
  #patch: $[counter(variables['major'], 1)]

  ${{ if eq( variables['Build.SourceBranchName'], 'master') }}:
    patch: $[counter(variables['major'], 1)]
    build: 0

  ${{ if eq( variables['Build.SourceBranchName'], 'develop') }}:
    build: $[counter(variables['major'], 1)]
    #patch: ?

name: $(major).$(minor).$(patch).$(build)

steps:
    - bash: echo $(major).$(minor).$(patch).$(build)

But as far as I see there is not a good way to get the current $(patch) counter variable when a build runs on develop. Side note I would be interested to know how to get at the custom counter values. You could likely use the API and go grab the Buildnumber from the last run and pull the patch number and reuse it, but that leads into this question you asked.

Is there a way to achieve what I'm looking for using Pipelines or am I
  barking up the wrong tree trying to go about it this way?

I would argue to change your approach. If you are crafting custom versioning schemes with powershell or yaml, at that point I would say versioning is important enough for you to use GitVersion or some equivalent. There is a learning curve to get started, but one of the default out of the box GitVersion modes would likely serve your purpose.

There is a pipeline task here that will handle computing a version for you, if you just add it to your pipeline.

- task: GitVersion@5
  inputs:
    runtime: 'core'
    configFilePath: 'GitVersion.yml'

Better to supply a GitVersion.yml, which is the scheme or instruction set for how to do the versioning.

There is a chocolatey package that you can install to experiment with locally. If you run GitVersion init in the root of your repo it will walk you though some versioning options, and create the GitVersion.yml for you.

mode: Mainline
branches:
  master:
    tag: ''
    regex: master
    increment: minor
  develop:
    tag: ''
    regex: develop
    increment: patch
ignore:
  sha: []
merge-message-formats: {}

As an example the above stock mainline mode gives me:


问:
React Native: Refreshing gets stuck while scrolling in nesting FlatLists in Androdid
While using a horizontal FlatList with other vertical FlatList as items there seems to be an issue with the refreshing. This happens when refreshing is enabled on the vertical lists but not on the horizontal container list. It is actually possible to refresh each individual list if you are very carful and only scrolls vertically (this is very hard). But at once you scrolls sideways the refreshing gets stuck.

React Native nested FlatLists

Issue in Android. Works in iOS

Attempts
I have tried replacing the wrapping FlatList with a ScollView with the same result. I am fully aware of that it is possible to disable refreshing of the individual list and enable it on the containing FlatList but that is not very appropriate in my case.

I have also tried the upvoted answers on this similar question but it didn't solve it.

Example:

```<code> <FlatList
            horizontal={true}
            pagingEnabled={true}
            data={[{key: 'a'}, {key: 'b'}]}
            renderItem={({item}) =>
                <FlatList
                    style={{width: 400}}
                    ref="scrollView"
                    horizontal={false}
                    refreshing={false}
                    onRefresh={() => {}}
                    data={[{key: 'c'}, {key: 'd'}]}
                    renderItem={({item}) =>  <Text>{item.key}</Text>}
                />
            }
        />
</code>```

Does anyone have a solution to this?

答:
i created a component based on what i understood from ur question,
make second flat list width as u want and put the height as '100%' so it will com full screen, so that it behaves like paging 2 flat lists... Hope it works for u

Here is the code
Snack URL

```<code>import React, {Component} from 'react';
import {
  View,
  Text,
  Image,
  TouchableOpacity,
  FlatList,
  Dimensions,
} from 'react-native';

const { width } = Dimensions.get('window');
export default class App extends Component {
  render() {
    return (
      <View style={{ flex: 1 }}>
        <FlatList
          horizontal
          pagingEnabled
          data={[{ key: 'a' }, { key: 'b' }]}
          renderItem={({ item }) => (
            <FlatList
              style={{ width, height: '100%' }}
              // ref="scrollView"
              horizontal={false}
              refreshing={false}
              onRefresh={() => {}}
              data={[{ key: 'c' }, { key: 'd' }, { key: 'f' }, { key: 'h' }]}
              renderItem={({ item }) => (
                <Text style={{ paddingVertical: 40 }}>{item.key}</Text>
              )}
            />
          )}
        />
      </View>
    );
  }
}
</code>```

Body:
While using a horizontal FlatList with other vertical FlatList as items there seems to be an issue with the refreshing. This happens when refreshing is enabled on the vertical lists but not on the horizontal container list. It is actually possible to refresh each individual list if you are very carful and only scrolls vertically (this is very hard). But at once you scrolls sideways the refreshing gets stuck.

React Native nested FlatLists

Issue in Android. Works in iOS

Attempts
I have tried replacing the wrapping FlatList with a ScollView with the same result. I am fully aware of that it is possible to disable refreshing of the individual list and enable it on the containing FlatList but that is not very appropriate in my case.

I have also tried the upvoted answers on this similar question but it didn't solve it.

Example:

 <FlatList
            horizontal={true}
            pagingEnabled={true}
            data={[{key: 'a'}, {key: 'b'}]}
            renderItem={({item}) =>
                <FlatList
                    style={{width: 400}}
                    ref="scrollView"
                    horizontal={false}
                    refreshing={false}
                    onRefresh={() => {}}
                    data={[{key: 'c'}, {key: 'd'}]}
                    renderItem={({item}) =>  <Text>{item.key}</Text>}
                />
            }
        />

Does anyone have a solution to this?

Body:
i created a component based on what i understood from ur question,
make second flat list width as u want and put the height as '100%' so it will com full screen, so that it behaves like paging 2 flat lists... Hope it works for u

Here is the code
Snack URL

import React, {Component} from 'react';
import {
  View,
  Text,
  Image,
  TouchableOpacity,
  FlatList,
  Dimensions,
} from 'react-native';

const { width } = Dimensions.get('window');
export default class App extends Component {
  render() {
    return (
      <View style={{ flex: 1 }}>
        <FlatList
          horizontal
          pagingEnabled
          data={[{ key: 'a' }, { key: 'b' }]}
          renderItem={({ item }) => (
            <FlatList
              style={{ width, height: '100%' }}
              // ref="scrollView"
              horizontal={false}
              refreshing={false}
              onRefresh={() => {}}
              data={[{ key: 'c' }, { key: 'd' }, { key: 'f' }, { key: 'h' }]}
              renderItem={({ item }) => (
                <Text style={{ paddingVertical: 40 }}>{item.key}</Text>
              )}
            />
          )}
        />
      </View>
    );
  }
}


问:
How to sum float numbers in the format hours and minutes?
How to sum float numbers in the format hours and minutes?

Those. if  calculate two such numbers 0.35+3.45 then it should be = 4.20, not 3.80

var arr = [0.15, 0.2, 3.45, 0.4, 2, 0.3, 5.2, 1, 1.4, 1.1, 2.4, 1, 3.4]

var sum = 0.0;

arr.forEach(function(item) {
  console.log(sum);
  sum += parseFloat(item);
});```
</div>
</div>
</p>

<p>The result should be like this:</p>

```0
0.15
0.35
4.20
5.0
7.0
7.30
12.50
13.50
15.30
16.40
19.20
20.20
```

答:
Here you go, implementation in Javascript ES6.
I looped each element, and splits hours, minutes by .,
checked if minutes is non-existing else assign 0
count the total of hours and minutes and applied necessary computation.

const resultObj = [0.35, 3.45].reduce((a, e) => {
  const [hours, minutes] = e.toString().split('.');
  a.h += +hours;
  a.m += (+(minutes.padEnd(2, 0)) || 0);
  return a;
}, {h: 0, m: 0});

const result = resultObj.h + Math.floor(resultObj.m / 60) + ((resultObj.m % 60) / 100);
console.log(result);```

Body:
How to sum float numbers in the format hours and minutes?

Those. if  calculate two such numbers 0.35+3.45 then it should be = 4.20, not 3.80

var arr = [0.15, 0.2, 3.45, 0.4, 2, 0.3, 5.2, 1, 1.4, 1.1, 2.4, 1, 3.4]

var sum = 0.0;

arr.forEach(function(item) {
  console.log(sum);
  sum += parseFloat(item);
});

The result should be like this:

0
0.15
0.35
4.20
5.0
7.0
7.30
12.50
13.50
15.30
16.40
19.20
20.20