问:
How to find number in list which has the biggest number of prime?
I want to write a program that receives 10 entries and at the end it should print the number that has the greatest number of prime factors along with the number of its prime factors in the output. And, if some of the inputs have the same condition, the program will print the biggest one.

The code that I wrote executed all conditions except the final condition.
How should I write a code for a case where two numbers have the same numbers of prime factors (when I want the bigger number to be my output)?
For example both 678 and 84 have 3 prime factors . The output of my code is 84, while I want the output to be 678 (the bigger number).

input:
  123
  43
  54
  12
  76
  84
  98
  678
  543
  231

  Correct output:
  678 3

  but my output:
  84 3

```<code>a = [0,0,0,0,0,0,0,0,0,0]
#a = [123,43,54,12,76,84,98,678,543,231]
b = [0,0,0,0,0,0,0,0,0,0]

def is_first (number):
    Prime_number= 0
    for m in range(1, (number //2)+1, 1):
        if number % m == 0:
                Prime_number += 1
    if    Prime_number > 1:
        is_prime = 0
    else:
        is_prime = 1
    return is_prime

for i in range(0,10,1):
    a[i] = input()

for j in a:
    numbers= 0
    for k in range(2, int(j)//2, 1):
        if int(j) % k == 0:
            if is_first (k) == 1:
                numbers += 1
    b[a.index(j)] = numbers

index_of_same = [i for i, e in enumerate(b) if e == max(b)]
n = []
for t in index_of_same:
    n.append(a[t])

print(str(max(n))+ ' ' + str(max(b)))
</code>```

答:
When you append the numbers that have the highest number of prime factors to the list n,  you are storing them as strings and not integers. Hence when you do the max() function on n, which holds 84,678 and 231, 84 is returned. I would suggest you to convert the numbers using int(), when storing into n and then perform the max()function on it. Just tweak your code as under:

```<code>for t in index_of_same:
    n.append(int(a[t]))
</code>```

Body:
I want to write a program that receives 10 entries and at the end it should print the number that has the greatest number of prime factors along with the number of its prime factors in the output. And, if some of the inputs have the same condition, the program will print the biggest one.

The code that I wrote executed all conditions except the final condition.
How should I write a code for a case where two numbers have the same numbers of prime factors (when I want the bigger number to be my output)?
For example both 678 and 84 have 3 prime factors . The output of my code is 84, while I want the output to be 678 (the bigger number).

input:
  123
  43
  54
  12
  76
  84
  98
  678
  543
  231

  Correct output:
  678 3

  but my output:
  84 3

a = [0,0,0,0,0,0,0,0,0,0]
#a = [123,43,54,12,76,84,98,678,543,231]
b = [0,0,0,0,0,0,0,0,0,0]

def is_first (number):
    Prime_number= 0
    for m in range(1, (number //2)+1, 1):
        if number % m == 0:
                Prime_number += 1
    if    Prime_number > 1:
        is_prime = 0
    else:
        is_prime = 1
    return is_prime

for i in range(0,10,1):
    a[i] = input()

for j in a:
    numbers= 0
    for k in range(2, int(j)//2, 1):
        if int(j) % k == 0:
            if is_first (k) == 1:
                numbers += 1
    b[a.index(j)] = numbers

index_of_same = [i for i, e in enumerate(b) if e == max(b)]
n = []
for t in index_of_same:
    n.append(a[t])

print(str(max(n))+ ' ' + str(max(b)))

Body:
When you append the numbers that have the highest number of prime factors to the list n,  you are storing them as strings and not integers. Hence when you do the max() function on n, which holds 84,678 and 231, 84 is returned. I would suggest you to convert the numbers using int(), when storing into n and then perform the max()function on it. Just tweak your code as under:

for t in index_of_same:
    n.append(int(a[t]))


来源: stackexchange

答:
Your code is cumbersome IMO, so I'd like to suggest a simpler version:</p>

```<code>def getNumOfFactors(n):
    num = 0
    factor = 1
    while n > 1:
        factor += 1
        if n % factor == 0:
            num += 1
            n /= factor
            while n % factor == 0:
                n /= factor
    return num

def getMaxValue(values):
    factors = [getNumOfFactors(n) for n in values]
    tuples = zip(factors,values)
    sorted_tuples = sorted([tuple for tuple in tuples],key=lambda x: x[0])
    max_tuples = [tuple for tuple in sorted_tuples if tuple[0] == sorted_tuples[-1][0]]
    sorted_max_tuples = sorted([tuple for tuple in max_tuples],key=lambda x: x[1])
    return sorted_max_tuples[-1]

maxValue = getMaxValue([123,43,54,12,76,84,98,678,543,231])
print(maxValue)
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to find number in list which has the biggest number of prime?

Body:
Your code is cumbersome IMO, so I'd like to suggest a simpler version:

def getNumOfFactors(n):
    num = 0
    factor = 1
    while n > 1:
        factor += 1
        if n % factor == 0:
            num += 1
            n /= factor
            while n % factor == 0:
                n /= factor
    return num

def getMaxValue(values):
    factors = [getNumOfFactors(n) for n in values]
    tuples = zip(factors,values)
    sorted_tuples = sorted([tuple for tuple in tuples],key=lambda x: x[0])
    max_tuples = [tuple for tuple in sorted_tuples if tuple[0] == sorted_tuples[-1][0]]
    sorted_max_tuples = sorted([tuple for tuple in max_tuples],key=lambda x: x[1])
    return sorted_max_tuples[-1]

maxValue = getMaxValue([123,43,54,12,76,84,98,678,543,231])
print(maxValue)


问:
How to insert data using insertMany() with DataType NumberDecimal in mongodb?
I have collection with field price that is of the DataType Decimal. When I use insertMany, how to set it to store in decimal type ?

```<code>let data=[{id:'1', price:10}, {id:'2', price:20}]
insertMany(data)
</code>```

I user meteor and mongo node driver.

答:
To insert multiple document in MongoDB collection you can use the insert method of MongoDB driver for nodejs. Meteor provides rawCollection method to access to the the Collection object corresponding to the collection from the MongoDB driver module which is wrapped by Mongo.Collection.

In your case the query will be like this:

```<code>let data=[{id:'1', price:10}, {id:'2', price:20}]
CollectionName.rawCollection().insert(data);
</code>```

Body:
I have collection with field price that is of the DataType Decimal. When I use insertMany, how to set it to store in decimal type ?

let data=[{id:'1', price:10}, {id:'2', price:20}]
insertMany(data)

I user meteor and mongo node driver.

Body:
To insert multiple document in MongoDB collection you can use the insert method of MongoDB driver for nodejs. Meteor provides rawCollection method to access to the the Collection object corresponding to the collection from the MongoDB driver module which is wrapped by Mongo.Collection.

In your case the query will be like this:

let data=[{id:'1', price:10}, {id:'2', price:20}]
CollectionName.rawCollection().insert(data);


问:
How do I install opencv using pip?
I need to install cv2 for a script that has been written for me. I tried  pip install cv2 and pip install open_cv and got the same problem - a warning message from dist.py and complains about zlib being not found. No cv2 installed. I also tried pyopenvc and pip install opencv-python.

So, I went to the opencv site and downloaded the relevant exe. Ran it - generated a heap of subdirectories and a make file and stuff.

What do I do now?

答:
Everybody struggles initially while installing OpenCV. OpenCV requires a lot of dependencies in the backend. The best way to start with OpenCV is, install it in a virtual environment. I suggest that you use the Python Anaconda distribution and create a virtual environment using it. Then inside the virtual environment, you can install OpenCV using this command:</p>
```<code>conda install -c conda-forge opencv
</code>```

Title: How do I install opencv using pip?

Body:
Everybody struggles initially while installing OpenCV. OpenCV requires a lot of dependencies in the backend. The best way to start with OpenCV is, install it in a virtual environment. I suggest that you use the Python Anaconda distribution and create a virtual environment using it. Then inside the virtual environment, you can install OpenCV using this command:

conda install -c conda-forge opencv


问:
Excessive drop shadow in UITableView
Here is a screenshot:

If you look at the top cell, there is an excessive drop shadow while the one at the bottom has the intended drop shadow effect. The excessive ones disappears and becomes normal after scrolling it out of screen then coming back to it. I can not figure out what is going on with this.

Here is my drop shadow code in the tableview cell class :

```<code>override func layoutSubviews() {
    super.layoutSubviews()
    let shadowPath = UIBezierPath(rect: containerView.bounds)
    containerView.layer.masksToBounds = false
    containerView.layer.shadowColor = UIColor.black.cgColor
    containerView.layer.shadowOffset = CGSize(width: 0, height: 0.1)
    containerView.layer.shadowOpacity = 0.2
    containerView.layer.shadowPath = shadowPath.cgPath
  }
</code>```

Please help and Thank you!

答: I figured this out. basically, I was using containerView.bounds for shadow path but the layer was drawn way too big because the cell started off big then shrunk based on device. The solution is to use constants. Anticipate the height and width and use CGRect. </p>

Title: Excessive drop shadow in UITableView

Body:
Here is a screenshot:

If you look at the top cell, there is an excessive drop shadow while the one at the bottom has the intended drop shadow effect. The excessive ones disappears and becomes normal after scrolling it out of screen then coming back to it. I can not figure out what is going on with this.

Here is my drop shadow code in the tableview cell class :

override func layoutSubviews() {
    super.layoutSubviews()
    let shadowPath = UIBezierPath(rect: containerView.bounds)
    containerView.layer.masksToBounds = false
    containerView.layer.shadowColor = UIColor.black.cgColor
    containerView.layer.shadowOffset = CGSize(width: 0, height: 0.1)
    containerView.layer.shadowOpacity = 0.2
    containerView.layer.shadowPath = shadowPath.cgPath
  }

Please help and Thank you!


问:
Prevent users from login to same system using different browsers (IE and FF)
We have a web application where users can login.

Now what we want is that the same user should not be able to login using different browsers.

Basically currently a user using two different browsers (IE and FF) can log in to the same account at the same time.  When you hit the login button, is it possible to invalidate all other logins for that account.

What is the best possible approach to do this?

PS: We are using Struts, Spring and Hibernate in our web application.

Thanks !

答:
Doing this on server-side is your best bet. You can keep tract of logged-in users in your application context.

Well, a little hint. Make use of a Servlet Filter, say AuthFilter, and make validation, may be isAlreadyLoggedIn(), over there beside other validations like username/password etc.. Now after having this check in place, you either -- that it depends what you want to do with the user trying to log in, show the message that "user already logged-in", or you can let the user log-in and invalidate the previous session. As discussed here.

ContentLicense: CC BY-SA 3.0


问:
Why am I getting more lines added to my arraylist from a file I am reading?
The file only consists of 4 lines and and when I add my nextLine() in the for loop, I get an error  "Exception in thread "main" java.util.NoSuchElementException: No line found" but if I put it before the for loop or if I add it before the for loop it stores 8 classes.

Moving the nextLine around before and after the for loop and also in it, as well as changing what x equals in the for loop

```<code>public static void main(String args[]) {
        WLS client = new WLS();
        print("WLS Status: " + client.status());
        client.checkFileSize();
        print("Login Lines: " + loginLines);
        client.getLogins();
        print("Logins Stored: " + loginList.size());
    }

public void getLogins() {
            String[] parsedLogin;
            if(active) {
                try {
                    print("Gathering info from file: " + inputFile + ".txt");
                    file = new Scanner(new File(inputFile + ".txt"));
                    while(file.hasNextLine()) {
                        parsedLogin = file.nextLine().split(" ");
                        file.nextLine();
                        for(int x = 0; x < logins.length; x++) {
                            logins[x] = new Logins(parsedLogin[0], parsedLogin[1], parsedLogin[2]);
                            loginList.add(logins[x]);//#TODO Storing 8 for some reason file.nextLine(); is causing a breakage NEED TO FIX!!
                            file.nextLine();
                        }
                    }
                } catch(FileNotFoundException e) { print("File not found"); }
            } else { print("Activate WLS to proceed"); }
        }
</code>```

I expect the output to be:

```<code>WLS Activated
WLS Status: true
Enter database name: (Do NOT include extension! i.e. '.txt')
database
Login Lines: 4
Gathering info from file: database.txt
Logins Stored: 4
</code>```

But the actual output is:

```<code>WLS Activated
WLS Status: true
Enter database name: (Do NOT include extension! i.e. '.txt')
database
Login Lines: 4
Gathering info from file: database.txt
Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Unknown Source)
    at Main$WLS.getLogins(Main.java:59)
    at Main.main(Main.java:17)
</code>```

答:
you placed the reading of next line inside the wrong loop.
you have two loops: first to read the lines and the second on the split line.
the first loop determines the sequence of reading lines</p>

```<code>file = new Scanner(new File(inputFile + ".txt"));
while(file.hasNextLine()) {
    parsedLogin = file.nextLine().split(" ");  // only place to read line
    for(int x = 0; x < logins.length; x++) {
        logins[x] = new Logins(parsedLogin[0], parsedLogin[1], parsedLogin[2]);
        loginList.add(logins[x]);//#TODO Storing 8 for some reason file.nextLine(); is causing a breakage NEED TO FIX!!
    }
}
</code>```

Body:
The file only consists of 4 lines and and when I add my nextLine() in the for loop, I get an error  "Exception in thread "main" java.util.NoSuchElementException: No line found" but if I put it before the for loop or if I add it before the for loop it stores 8 classes.

Moving the nextLine around before and after the for loop and also in it, as well as changing what x equals in the for loop

public static void main(String args[]) {
        WLS client = new WLS();
        print("WLS Status: " + client.status());
        client.checkFileSize();
        print("Login Lines: " + loginLines);
        client.getLogins();
        print("Logins Stored: " + loginList.size());
    }

public void getLogins() {
            String[] parsedLogin;
            if(active) {
                try {
                    print("Gathering info from file: " + inputFile + ".txt");
                    file = new Scanner(new File(inputFile + ".txt"));
                    while(file.hasNextLine()) {
                        parsedLogin = file.nextLine().split(" ");
                        file.nextLine();
                        for(int x = 0; x < logins.length; x++) {
                            logins[x] = new Logins(parsedLogin[0], parsedLogin[1], parsedLogin[2]);
                            loginList.add(logins[x]);//#TODO Storing 8 for some reason file.nextLine(); is causing a breakage NEED TO FIX!!
                            file.nextLine();
                        }
                    }
                } catch(FileNotFoundException e) { print("File not found"); }
            } else { print("Activate WLS to proceed"); }
        }

I expect the output to be:

WLS Activated
WLS Status: true
Enter database name: (Do NOT include extension! i.e. '.txt')
database
Login Lines: 4
Gathering info from file: database.txt
Logins Stored: 4

But the actual output is:

WLS Activated
WLS Status: true
Enter database name: (Do NOT include extension! i.e. '.txt')
database
Login Lines: 4
Gathering info from file: database.txt
Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Unknown Source)
    at Main$WLS.getLogins(Main.java:59)
    at Main.main(Main.java:17)

Body:
you placed the reading of next line inside the wrong loop.
you have two loops: first to read the lines and the second on the split line.
the first loop determines the sequence of reading lines

file = new Scanner(new File(inputFile + ".txt"));
while(file.hasNextLine()) {
    parsedLogin = file.nextLine().split(" ");  // only place to read line
    for(int x = 0; x < logins.length; x++) {
        logins[x] = new Logins(parsedLogin[0], parsedLogin[1], parsedLogin[2]);
        loginList.add(logins[x]);//#TODO Storing 8 for some reason file.nextLine(); is causing a breakage NEED TO FIX!!
    }
}


问:
Debugger break command in VS Code?
In Visual Studio (C#) there is a command

```<code>System.Diagnostics.Debugger.Break();
</code>```

that lets you automatically hop into the debugger even without setting a breakpoint.  Is there such a thing for VS Code?  I'd especially like it for rust.  I tried just writing "let x = 1/0" but that just crashes the program.

I'm using the cppvsdbg debugger for windows.

答:
Looking through what David Cullen suggested in the comments leads to a few options:

std::intrinsics::breakpoint This needs nightly rust.

The breakpoint crate This doesn't even compile but it would have been nice.

The WinApi this is rather OS specific but it works for my case.  The OS dependency can at least probably be mitigated using conditional compilation.  To use the library, add:

```
[dependencies.winapi]
version = "0.3.7"
features = ["debugapi"]
```

to Cargo.toml and call it using

```<code>unsafe {
    winapi::um::debugapi::DebugBreak();
}
</code>```

However it turns out that even this approach doesn't work across crates, it just crashes.

Title: Debugger break command in VS Code?

Body:
In Visual Studio (C#) there is a command

System.Diagnostics.Debugger.Break();

that lets you automatically hop into the debugger even without setting a breakpoint.  Is there such a thing for VS Code?  I'd especially like it for rust.  I tried just writing "let x = 1/0" but that just crashes the program.

I'm using the cppvsdbg debugger for windows.

Body:
Looking through what David Cullen suggested in the comments leads to a few options:

std::intrinsics::breakpoint This needs nightly rust.

The breakpoint crate This doesn't even compile but it would have been nice.

The WinApi this is rather OS specific but it works for my case.  The OS dependency can at least probably be mitigated using conditional compilation.  To use the library, add:

[dependencies.winapi]
version = "0.3.7"
features = ["debugapi"]

to Cargo.toml and call it using

unsafe {
    winapi::um::debugapi::DebugBreak();
}

However it turns out that even this approach doesn't work across crates, it just crashes.


问:
Can I map entity field names to alias column names in TypeORM?
I am in the process of migrating from Rails to NestJs with TypeORM.
For historical reasons, table names and column names in Rails are snaked_cased - I don't want to copy this nuisance to our NestJs/React side.

Can I create entity fields in NestJS (typeorm) called firstName but are mapped to a column named first_name in my DB?

My table

+-------------+--------------+----------------------------+
|                      system_users                       |
+-------------+--------------+----------------------------+
| id          | int(11)      | PRIMARY KEY AUTO_INCREMENT |
| first_name  | varchar(100) |                            |
| last_name   | varcahr(100) |                            |
+-------------+--------------+----------------------------+
```
<p>My User Entity Class</p>
<pre class="lang-js prettyprint-override"><code>import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

@Entity({ name: 'system_users' })
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ length: 255 })
  first_name: string; // <-- I WANT THIS TO BE firstName (camelCased)

  @Column({ length: 255 })
  last_name: string;  // <-- I WANT THIS TO BE lastName (camelCased)
}
</code>```

答:
I finally found what I was looking for in the documentation. The @Column attribute receives many properties, one of them is name which can define the column name associated with the field.

My updated entity:

@Entity({ name: 'system_users' })
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ length: 255, name: "first_name" })
  firstName: string;

  @Column({ length: 255, name: "last_name" })
  lastName: string;
}
```

Body:
I am in the process of migrating from Rails to NestJs with TypeORM.
For historical reasons, table names and column names in Rails are snaked_cased - I don't want to copy this nuisance to our NestJs/React side.

Can I create entity fields in NestJS (typeorm) called firstName but are mapped to a column named first_name in my DB?

My table

+-------------+--------------+----------------------------+
|                      system_users                       |
+-------------+--------------+----------------------------+
| id          | int(11)      | PRIMARY KEY AUTO_INCREMENT |
| first_name  | varchar(100) |                            |
| last_name   | varcahr(100) |                            |
+-------------+--------------+----------------------------+

My User Entity Class

import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

@Entity({ name: 'system_users' })
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ length: 255 })
  first_name: string; // <-- I WANT THIS TO BE firstName (camelCased)

  @Column({ length: 255 })
  last_name: string;  // <-- I WANT THIS TO BE lastName (camelCased)
}


问:
Remove li from a dynamic list using blade and Jquery
I have a dynamically populated list. On clicking on the Approve/reject button, an AJAX call happens. If the response is 1, the li should be hidden from the UI.

Below is my code. The remove() option doesn't seem to work. Can't figure out a way.

Approve.blade.php

```<code><ul>
   @foreach($pendlist as $pend)
   <li id="{{$pend->id}}">
      <div class="list-box-listing">
         <div class="list-box-listing-img"><a href="#"><img src="images/listing-item-01.jpg" alt=""></a></div>
         <div class="list-box-listing-content">
            <div class="inner">
               <h3><a href="#">{{$pend->title}}</a></h3>
               <span>{{$pend->address}}, {{$pend->locality}}, {{$pend->city}}</span>
               <div class="star-rating" data-rating="3.5">
                  <div class="rating-counter">(12 reviews)</div>
                  <input type="hidden" value="{{$pend->id}}" id="propid">
               </div>
            </div>
         </div>
      </div>
      <div class="buttons-to-right">
         <a href="#" class="button gray reject" id="reject"><i class="sl sl-icon-close"></i> Reject</a>
         <a href="#" class="button gray approve" id="approve"><i class="sl sl-icon-check"></i> Approve</a>
      </div>
   </li>
   @endforeach
</ul>
</code>```

jQuery:

```<code>$('#approve').click(function() {
      $.ajax({
        type: "POST",
        url: "{{ url('/api/approve') }}",
        async: true,
        data: {
          id: $('#propid').val(),
          status: 1
        },
        success: function(result) {
          let id = $('#propid').val();
          if (result == 1) {
            $(this).remove();
          }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          alert(errorThrown);
          $("#loader").hide();
        }
      });
</code>```

I have tried:

```<code>$(this).closest('li').remove()
</code>```

But that also doesn't seem to work.

答:
Use parent withclosest . Hold your scope of  this on variable.

$('.approve').click(function() {
  let $this = this;
  //Your ajex call
  $($this).parent().closest('li').remove();

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li>
    <div class="list-box-listing">
      other stuff
    </div>
    <div class="buttons-to-right">
      id}}"><i class="sl sl-icon-close"></i> Reject
      id}}"><i class="sl sl-icon-check"></i> Approve
    </div>
  </li>
</ul></code>```

Body:
I have a dynamically populated list. On clicking on the Approve/reject button, an AJAX call happens. If the response is 1, the li should be hidden from the UI.

Below is my code. The remove() option doesn't seem to work. Can't figure out a way.

Approve.blade.php

   @foreach($pendlist as $pend)

id}}">

{{$pend->title}}

               {{$pend->address}}, {{$pend->locality}}, {{$pend->city}}

(12 reviews)

                  <input type="hidden" value="{{$pend->id}}" id="propid">

          Reject
          Approve

   @endforeach

jQuery:

$('#approve').click(function() {
      $.ajax({
        type: "POST",
        url: "{{ url('/api/approve') }}",
        async: true,
        data: {
          id: $('#propid').val(),
          status: 1
        },
        success: function(result) {
          let id = $('#propid').val();
          if (result == 1) {
            $(this).remove();
          }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          alert(errorThrown);
          $("#loader").hide();
        }
      });

I have tried:

$(this).closest('li').remove()

But that also doesn't seem to work.

Body:
Use parent withclosest . Hold your scope of  this on variable.

$('.approve').click(function() {
  let $this = this;
  //Your ajex call
  $($this).parent().closest('li').remove();

});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li>
    <div class="list-box-listing">
      other stuff
    </div>
    <div class="buttons-to-right">
      <a href="#" class="button gray reject" id="{{$pend->id}}"><i class="sl sl-icon-close"></i> Reject</a>
      <a href="#" class="button gray approve" id="{{$pend->id}}"><i class="sl sl-icon-check"></i> Approve</a>
    </div>
  </li>
</ul>


问:
SQL Passing Table Date for Date
Wondering how I can pass the RECEIVEDDATETIME to the statement below. What am I missing in my SQL statement?

I added an inner join to my CALENDAR table and TESTDATA table to pass the T.RECEIVEDDATETIME as the date from the original example thanks to Mark Barinstein.

This statement gets the C.WORKDATE from my tblCalendar, but I need to have the T.RECEIVEDDATETIME to pass to get my desired "DUEDATE".

I created a "tblCalendar" because I read that it was easier to reference a Calendar for true workdays...to exclude weekends and holidays and to account for leap years. Unsure if this is the best practice, but seemed straight forward to not code for exceptions. So I created the tblCalendar that includes ALL DATEs from 2017 until 2050 and holidays. The data below only represents partially January 2019 as I haven't found a way to attach a table here:

```<code>tblCalendar (partial)
DATE        NUMDAYOFWK       DAYOFWK      HOLIDAY
01/01/2019    3              Tuesday      YES
01/02/2019    4              Wednesday
01/03/2019    5              Thursday
01/04/2019    6              Friday
01/05/2019    7              Saturday
01/06/2019    1              Sunday
01/07/2019    2              Monday
01/08/2019    3              Tuesday
01/09/2019    4              Wednesday
01/10/2019    5              Thursday
01/11/2019    6              Friday
01/12/2019    7              Saturday
01/13/2019    1              Sunday
01/14/2019    2              Monday
01/15/2019    3              Tuesday
01/16/2019    4              Wednesday
01/17/2019    5              Thursday
01/18/2019    6                  Friday
01/19/2019    7              Saturday
01/20/2019    1              Sunday
01/21/2019    2              Monday       YES
</code>```

The tblTestData table holds the core data where I reference all fields needed for my reports.

```<code>tblTestData Columns (partial) - DeliveryDays would reference the 2nd parameter BusDayAdd that was noted in the previous SQL.

ID                  RECEIVEDDATE       DeliveryDays     Address
T-20190116-255      01/16/2019          2             1234 Address
T-20190117-255      01/17/2019          2             3657 Address
T-20190118-222      01/18/2019          2             9999 Address
T-20190119-255      01/19/2019          2
T-20190120-255      01/20/2019
T-20190121-255      01/21/2019
T-20190303-1        03/03/2019
</code>```

The Desired end results would look like the following taking into account the RECEIVEDDATETIME in my tblTestData and reference the tblCalendar table to exclude weekends and holidays to give the correct due date.

```<code>ID              RECEIVEDDATE            DeliveryDays    DueDate    Address
T-20190116-255  1/16/2019                2             1/18/2019     1234 Address
T-20190117-255  1/17/2019   2   1/22/2019   3657 Address
T-20190118-222  1/18/2019   2   1/23/2019   9999 Address
T-20190119-255  1/19/2019   2   1/23/2019   10000 Address
T-20190120-255  1/20/2019   2   1/23/2019   10001 Address
T-20190121-255  1/21/2019   2   1/23/2019   10002 Address
T-20190121-256  1/22/2019   2   1/24/2019   10003 Address
T-20190303-1    3/3/2019    3   3/6/2019    10004 Address
T-20190121-257  3/15/2019   7   3/26/2019   10005 Address
</code>```

I have tried various statements by rewriting the code to wrap the SQL string to pass the table "RECEIVEDDATETIME", but each time the "DUEDATE" comes back {NULL}.

```<code>SELECT T.ID, VARCHAR_format(T.RECEIVEDDATETIME, 'MM/DD/YYYY') RECDATE,

(select VARCHAR_FORMAT(WORKDATE,'MM/DD/YYYY') DUEDATE

from

(Select
WORKDATE, T.RECEIVEDDATETIME,
sum(case when C.HOLIDAY='YES' or C.NUMDAYOFWK in (7,1) then 0 else 1 end) over  (order by C.WORKDATE) BUSDAYADD

from tblCALENDAR C

--ADDED INNER JOIN TO GET T.RECEIVEDDATETIME TO FEED AUTOMATICALLY FROM TESTDATA TABLE

INNER JOIN TESTDATA T
      ON
VARCHAR_FORMAT(C.WORKDATE, 'MM/DD/YYYY') = VARCHAR_FORMAT(T.RECEIVEDDATETIME,'MM/DD/YYYY')

where C.WORKDATE > VARCHAR_FORMAT(T.RECEIVEDDATETIME,'MM/DD/YYYY')) -- 1-st PARAMETER TO CAPTURE RECEIVEDDATETIME

WHERE BUSDAYADD = ? -- 2-nd parameter to add the number of days needed to be added to RECEIVEDDATETIME

order by WORKDATE --3rd Parameter
fetch first 1 row only)

FROM TESTDATA T
WHERE ID = 'T-20190303-1'
</code>```

When I run the SQL, I get {NULL} for my results for DUEDATE:

```<code>ID              RECDATE     DUEDATE
T-20190303-1    03/03/2019  {NULL}
</code>```

The results should be:

```<code> ID             RECDATE     DUEDATE
 T-20190303-1   03/03/2019  03/05/2019
</code>```

Any help is appreciated.

答:
The SELECT of the DUEDATE is

```<code>INNER JOIN TESTDATA T
   ON VARCHAR_FORMAT(C.WORKDATE, 'MM/DD/YYYY') = VARCHAR_FORMAT(T.RECEIVEDDATETIME,'MM/DD/YYYY')
where C.WORKDATE > VARCHAR_FORMAT(T.RECEIVEDDATETIME,'MM/DD/YYYY'))
</code>```

This means you join on the Equality and then restrict to Workdate > Receiveddatetime
that might be the problem...

Title: SQL Passing Table Date for Date

Body:
Wondering how I can pass the RECEIVEDDATETIME to the statement below. What am I missing in my SQL statement?

I added an inner join to my CALENDAR table and TESTDATA table to pass the T.RECEIVEDDATETIME as the date from the original example thanks to Mark Barinstein.

This statement gets the C.WORKDATE from my tblCalendar, but I need to have the T.RECEIVEDDATETIME to pass to get my desired "DUEDATE".

I created a "tblCalendar" because I read that it was easier to reference a Calendar for true workdays...to exclude weekends and holidays and to account for leap years. Unsure if this is the best practice, but seemed straight forward to not code for exceptions. So I created the tblCalendar that includes ALL DATEs from 2017 until 2050 and holidays. The data below only represents partially January 2019 as I haven't found a way to attach a table here:

tblCalendar (partial)
DATE        NUMDAYOFWK       DAYOFWK      HOLIDAY
01/01/2019    3              Tuesday      YES
01/02/2019    4              Wednesday
01/03/2019    5              Thursday
01/04/2019    6              Friday
01/05/2019    7              Saturday
01/06/2019    1              Sunday
01/07/2019    2              Monday
01/08/2019    3              Tuesday
01/09/2019    4              Wednesday
01/10/2019    5              Thursday
01/11/2019    6              Friday
01/12/2019    7              Saturday
01/13/2019    1              Sunday
01/14/2019    2              Monday
01/15/2019    3              Tuesday
01/16/2019    4              Wednesday
01/17/2019    5              Thursday
01/18/2019    6                  Friday
01/19/2019    7              Saturday
01/20/2019    1              Sunday
01/21/2019    2              Monday       YES

The tblTestData table holds the core data where I reference all fields needed for my reports.

tblTestData Columns (partial) - DeliveryDays would reference the 2nd parameter BusDayAdd that was noted in the previous SQL.

ID                  RECEIVEDDATE       DeliveryDays     Address
T-20190116-255      01/16/2019          2             1234 Address
T-20190117-255      01/17/2019          2             3657 Address
T-20190118-222      01/18/2019          2             9999 Address
T-20190119-255      01/19/2019          2
T-20190120-255      01/20/2019
T-20190121-255      01/21/2019
T-20190303-1        03/03/2019

The Desired end results would look like the following taking into account the RECEIVEDDATETIME in my tblTestData and reference the tblCalendar table to exclude weekends and holidays to give the correct due date.

ID              RECEIVEDDATE            DeliveryDays    DueDate    Address
T-20190116-255  1/16/2019                2             1/18/2019     1234 Address
T-20190117-255  1/17/2019   2   1/22/2019   3657 Address
T-20190118-222  1/18/2019   2   1/23/2019   9999 Address
T-20190119-255  1/19/2019   2   1/23/2019   10000 Address
T-20190120-255  1/20/2019   2   1/23/2019   10001 Address
T-20190121-255  1/21/2019   2   1/23/2019   10002 Address
T-20190121-256  1/22/2019   2   1/24/2019   10003 Address
T-20190303-1    3/3/2019    3   3/6/2019    10004 Address
T-20190121-257  3/15/2019   7   3/26/2019   10005 Address

I have tried various statements by rewriting the code to wrap the SQL string to pass the table "RECEIVEDDATETIME", but each time the "DUEDATE" comes back {NULL}.

SELECT T.ID, VARCHAR_format(T.RECEIVEDDATETIME, 'MM/DD/YYYY') RECDATE,

(select VARCHAR_FORMAT(WORKDATE,'MM/DD/YYYY') DUEDATE

from

(Select
WORKDATE, T.RECEIVEDDATETIME,
sum(case when C.HOLIDAY='YES' or C.NUMDAYOFWK in (7,1) then 0 else 1 end) over  (order by C.WORKDATE) BUSDAYADD

from tblCALENDAR C

--ADDED INNER JOIN TO GET T.RECEIVEDDATETIME TO FEED AUTOMATICALLY FROM TESTDATA TABLE

INNER JOIN TESTDATA T
      ON
VARCHAR_FORMAT(C.WORKDATE, 'MM/DD/YYYY') = VARCHAR_FORMAT(T.RECEIVEDDATETIME,'MM/DD/YYYY')

where C.WORKDATE > VARCHAR_FORMAT(T.RECEIVEDDATETIME,'MM/DD/YYYY')) -- 1-st PARAMETER TO CAPTURE RECEIVEDDATETIME

WHERE BUSDAYADD = ? -- 2-nd parameter to add the number of days needed to be added to RECEIVEDDATETIME

order by WORKDATE --3rd Parameter
fetch first 1 row only)

FROM TESTDATA T
WHERE ID = 'T-20190303-1'

When I run the SQL, I get {NULL} for my results for DUEDATE:

ID              RECDATE     DUEDATE
T-20190303-1    03/03/2019  {NULL}

The results should be:

 ID             RECDATE     DUEDATE
 T-20190303-1   03/03/2019  03/05/2019

Any help is appreciated.

Body:
The SELECT of the DUEDATE is

INNER JOIN TESTDATA T
   ON VARCHAR_FORMAT(C.WORKDATE, 'MM/DD/YYYY') = VARCHAR_FORMAT(T.RECEIVEDDATETIME,'MM/DD/YYYY')
where C.WORKDATE > VARCHAR_FORMAT(T.RECEIVEDDATETIME,'MM/DD/YYYY'))

This means you join on the Equality and then restrict to Workdate > Receiveddatetime
that might be the problem...


问:
How to post Faker collection in Laravel testing?
I have a test case where the user will be allowed to create/post multiple items at once. Please take a look at my test:

/**
 * Test multiple item creation.
 *
 * @return void
 */
public function testMultipleCreation()
{
    $token = Test::generateToken();
    $user = Test::getAuthenticatedUser();
    $stall = factory(Stall::class)->make()->toArray();
    $item = factory(Item::class, 5)->make()->toArray();
    dump($item);

    $user->addStall($stall);
    $response = $this->withHeaders(['Authorization' => 'Bearer ' . $token]);
    $response = $response->json('POST', route('items.store', $item));
    $response->assertStatus(200);

    // $this->assertDatabaseHas('items', $item);
}
```

<p>and here is the controller:</p>

<pre class="lang-php prettyprint-override"><code>/**
 * Store a newly created resource in storage.
 *
 * @param  \App\Http\Requests\StoreItem  $request
 * @return \App\Helpers\ResponseMessage
 */
public function store(StoreItem $request)
{
    if (is_array($request)) {
        $this->createMultiple($request);
    }

    $item = auth()->user()->addItem(
        $request->validated()
    );

    return ResponseMessage::created('item', $item);
}

/**
 * Create multiple items.
 *
 * @param array $items
 * @return void
 */
protected function createMultiple($items)
{
    $itemCollection = [];

    foreach ($items as $item) {
        $itemCollection[] = auth()->user()->addItem(
            $item->validated()
        );
    }

    return ResponseMessage::created('items', $itemCollection);
}
</code>```

It works fine if I post it as $item = factory(Item::class)->make()->toArray();, but if I make it more than 1 factory item, it fails and throws this error:

1) Tests\Unit\ItemTest::testMultipleCreation
  ErrorException: Array to string conversion

ERRORS!
  Tests: 9, Assertions: 20, Errors: 1.

答:
Problem is likely here

```<code>$response = $response->json('POST', route('items.store', $item));
</code>```

Since $item is an Array, it doesn't know how to convert it.
Probably you meant

```<code>$response = $response->json('POST', route('items.store'), $item);
</code>```

Body:
I have a test case where the user will be allowed to create/post multiple items at once. Please take a look at my test:

/**
 * Test multiple item creation.
 *
 * @return void
 */
public function testMultipleCreation()
{
    $token = Test::generateToken();
    $user = Test::getAuthenticatedUser();
    $stall = factory(Stall::class)->make()->toArray();
    $item = factory(Item::class, 5)->make()->toArray();
    dump($item);

    $user->addStall($stall);
    $response = $this->withHeaders(['Authorization' => 'Bearer ' . $token]);
    $response = $response->json('POST', route('items.store', $item));
    $response->assertStatus(200);

    // $this->assertDatabaseHas('items', $item);
}

and here is the controller:

/**
 * Store a newly created resource in storage.
 *
 * @param  \App\Http\Requests\StoreItem  $request
 * @return \App\Helpers\ResponseMessage
 */
public function store(StoreItem $request)
{
    if (is_array($request)) {
        $this->createMultiple($request);
    }

    $item = auth()->user()->addItem(
        $request->validated()
    );

    return ResponseMessage::created('item', $item);
}

/**
 * Create multiple items.
 *
 * @param array $items
 * @return void
 */
protected function createMultiple($items)
{
    $itemCollection = [];

    foreach ($items as $item) {
        $itemCollection[] = auth()->user()->addItem(
            $item->validated()
        );
    }

    return ResponseMessage::created('items', $itemCollection);
}

It works fine if I post it as $item = factory(Item::class)->make()->toArray();, but if I make it more than 1 factory item, it fails and throws this error:

1) Tests\Unit\ItemTest::testMultipleCreation
  ErrorException: Array to string conversion

ERRORS!
  Tests: 9, Assertions: 20, Errors: 1.

Body:
Problem is likely here

$response = $response->json('POST', route('items.store', $item));

Since $item is an Array, it doesn't know how to convert it.
Probably you meant

$response = $response->json('POST', route('items.store'), $item);


问:
Click event not triggering for every iteration of for loop
I want to automate this page to generate exam results. I want to generate exam results from one particular date to some other particular date. On clicking the submit button, the page generates another page in a new tab.

Manually clicking 10 times will generate 10 tabs. But see the following code:

```<code>for(let i=0;i<10;i++)
{
document.querySelector('#reg1').click();
console.log(`clicked ${i}th time`)
}
</code>```

I want to trigger a click 10 times and it should generate 10 tabs accordingly. But the problem is that the click works only works on the 10th iteration and spawns 1 tab only. Help me.
see

Edit:
@Jesse
See my utility full code:

```<code>var dateFrom=new Date('2017-01')
var dateTo=new Date('2019-01')
for(var i=dateFrom;i<dateTo;i.setMonth(i.getMonth()+1))
{
    // console.log(`${i.getFullYear()}-${i.getMonth()}`);
    // var dd=`${i.getFullYear()}-${i.getMonth()}`;
    var dd=new Date(i).toISOString().substr(0,7);
    console.log(dd);
    document.querySelector("input#picker.form-control").value=dd;
    var type='Supplementary'
    document.querySelector("select#result_type.form-control.form-email.selectoption").value=type;
    document.querySelector('#reg1').click();

}
</code>```

答:
I just figured out that my browser's popup blocker is stopping the subsequent tabs from being opened.

Try turning off your popup blocker. I was able to trigger the behavior you're after with mine off.

It works when you click it because it's a user interaction, so the blocker assumes it's something you're actively trying to do. If you trigger it programmatically, repeatedly, it gets blocked. This makes sense given that one of your browser's popup blocker's primary functions is to prevent sites from trapping you in infinite popup hell.

Body:
I want to automate this page to generate exam results. I want to generate exam results from one particular date to some other particular date. On clicking the submit button, the page generates another page in a new tab.

Manually clicking 10 times will generate 10 tabs. But see the following code:

for(let i=0;i<10;i++)
{
document.querySelector('#reg1').click();
console.log(`clicked ${i}th time`)
}

I want to trigger a click 10 times and it should generate 10 tabs accordingly. But the problem is that the click works only works on the 10th iteration and spawns 1 tab only. Help me.
see

Edit:
@Jesse
See my utility full code:

var dateFrom=new Date('2017-01')
var dateTo=new Date('2019-01')
for(var i=dateFrom;i<dateTo;i.setMonth(i.getMonth()+1))
{
    // console.log(`${i.getFullYear()}-${i.getMonth()}`);
    // var dd=`${i.getFullYear()}-${i.getMonth()}`;
    var dd=new Date(i).toISOString().substr(0,7);
    console.log(dd);
    document.querySelector("input#picker.form-control").value=dd;
    var type='Supplementary'
    document.querySelector("select#result_type.form-control.form-email.selectoption").value=type;
    document.querySelector('#reg1').click();

}


问:
Multiprocessing pool not taking list of strings to create individual process
I am trying to write a multiprocessing application where i have list of companies for which individual processes needs to be triggered from a process pool.

I have a function which takes 3 args out of which 1 being self, and the second being a list and third being a company code.
I am trying to process the function as a process for each company code.
I initially had problem with the self variable, which gives 'pickle' error, which for now i am overcoming by passing None.
I have used 'Partial' to multiple arguments problem in multiprocessing, after which i am getting an error "TypeError: can only concatenate str (not "list") to str" when adding a company_list as iterable to my map.

```<code>def processing_saved_search_per_company(self, saved_search_list, each_cpy):
    print("Company Key : " + each_cpy)
    print("Saved Search List : " + saved_search_list)

def process(self):
        saved_search_list =[]
        company_list = APICall.fetch_onboarded_companies_from_customer_csv(self)
        saved_search_list_file = os.path.join(code_dir_path, "resources\\saved_search_template.txt")
        try:
            with open(saved_search_list_file, "r") as ss_file_pointer:
                saved_search_list = ss_file_pointer.readlines()
        except IOError as ie:
            print(f"Error Occurred while accessing the Saved Search file reason being :-: {ie}")

        final_ss_list = []
        p=Pool(processes=4)

        #for each_cpy in company_list:
        print("Company List : "+str(company_list))

        func = partial(APICall.processing_saved_search_per_company,None,saved_search_list)
        p.map(func, company_list)
        p.close()
</code>```

I need the creation of a pool of process which runs like,

p1= processing_saved_search_per_company(self,saved_search_list,"company 1")

p2 = processing_saved_search_per_company(self,saved_search_list,"company 2")

p3 = processing_saved_search_per_company(self,saved_search_list,"company 3")

but getting an error as,

TypeError: can only concatenate str (not "list") to str

Requesting help on this issue.

Thanks,
Shahid

答:
Found an workaround to this problem, like passing the Company list as well as part of the partial function and then the array of numbers to the length of Company list to my below function, which would now take index as a new parameter at the end.

processing_saved_search_per_company(self, saved_search_list, companies_list,index):

With the index now coming from the below map, I am able to run the above function for the specific company, without any hassle.

func = partial(APICall.processing_saved_search_per_company,None,saved_search_list, company_list)
  Index_values =[X for X in range(0,len(companies_list))]
  p.map(func, index_values)
  p.close()
  p.join()

Thanks

Body:
I am trying to write a multiprocessing application where i have list of companies for which individual processes needs to be triggered from a process pool.

I have a function which takes 3 args out of which 1 being self, and the second being a list and third being a company code.
I am trying to process the function as a process for each company code.
I initially had problem with the self variable, which gives 'pickle' error, which for now i am overcoming by passing None.
I have used 'Partial' to multiple arguments problem in multiprocessing, after which i am getting an error "TypeError: can only concatenate str (not "list") to str" when adding a company_list as iterable to my map.

def processing_saved_search_per_company(self, saved_search_list, each_cpy):
    print("Company Key : " + each_cpy)
    print("Saved Search List : " + saved_search_list)

def process(self):
        saved_search_list =[]
        company_list = APICall.fetch_onboarded_companies_from_customer_csv(self)
        saved_search_list_file = os.path.join(code_dir_path, "resources\\saved_search_template.txt")
        try:
            with open(saved_search_list_file, "r") as ss_file_pointer:
                saved_search_list = ss_file_pointer.readlines()
        except IOError as ie:
            print(f"Error Occurred while accessing the Saved Search file reason being :-: {ie}")

        final_ss_list = []
        p=Pool(processes=4)

        #for each_cpy in company_list:
        print("Company List : "+str(company_list))

        func = partial(APICall.processing_saved_search_per_company,None,saved_search_list)
        p.map(func, company_list)
        p.close()

I need the creation of a pool of process which runs like,

p1= processing_saved_search_per_company(self,saved_search_list,"company 1")

p2 = processing_saved_search_per_company(self,saved_search_list,"company 2")

p3 = processing_saved_search_per_company(self,saved_search_list,"company 3")

but getting an error as,

TypeError: can only concatenate str (not "list") to str

Requesting help on this issue.

Thanks,
Shahid


问:
How does indirect manipulation of dynamically allocated string literals truly work in C?
As it stands, I know that dynamically allocated string literals cannot be changed during run-time, otherwise you will hit a segmentation fault.

This is due to the fact that dynamically allocated string literals are stored, from what I saw in the assembly code, in the .rodata segment, placing these literals in what I interpret as read only memory.

So in theory this should never work on what I hope is in every modern C compiler:

#include <stdio.h>
#include <stdlib.h>

int
main( void )
{
  char *p = ( char * )malloc( 10 * sizeof( char ) );
  if ( p == NULL )
  {
    puts( "Bad memory allocation error!" );
    return( EXIT_FAILURE );
  }
  else
  {
    p = "literal";
    printf( "%s\n", p );
    p[0] = 't'; // <-- This should cause a segmentation fault!
    printf( "%s\n", p ); // <-- This should never reach execution!
  }
  return( EXIT_SUCCESS );
}
```

<p>However, upon studying how <code>tolower()</code> and <code>toupper()</code> work. I find it rather difficult to understand how these two simple functions are able to do what I thought for a long while was impossible. Here's what I mean:</p>

<pre class="lang-c prettyprint-override"><code>#include <stdio.h>

int
tolowercase( int c )
{
  return ( c >= 'A' && c <= 'Z' ) ? ( c + 32) : ( c );
}

int
retstrlen( char *str )
{
  int len = 0;
  while( *str != '\0' ) { len++; str++; }
  return( len );
}

int
main( int argc, char **argv )
{
  for( int i = 0; i < argc; i++ )
  {
    for( int j = 0; j < retstrlen( argv[i] ); j++ )
    {
      argv[i][j] = tolowercase( argv[i][j] );
      printf( "%c", argv[i][j] );
    }
    printf( "\n" );
  }
  return 0;
}
</code>```

How does the source code defined in my custom tolower() function not cause a segmentation fault as it normally would through manipulating dynamically allocated string literals?

My only hypothesis that I can draw is that since tolowercase() has a parameter of int, and a return type of int, then the compiler performs a type conversion which indirectly manipulates **argv.

I am pretty sure I am on the right track about this, yet I could have gotten my whole terminology wrong here, so what is really happening to **argv?

答:
Two points:

p[0] = 't'; // <-- This should cause a segmentation fault! is not guaranteed, the only thing which is guaranteed is to invoke undefined behavior.

For string literals, from C11, chapter §6.4.5

[...] If the program attempts to modify such an array, the behavior is
  undefined.

Regarding "How does the source code defined in my custom tolower() function not cause a segmentation fault as it normally would through manipulating dynamically allocated string literals?"

Quoting C11, chapter §5.1.2.2.1

The parameters argc and argv and the strings pointed to by the argv array shall
  be modifiable by the program, and retain their last-stored values between program
  startup and program termination.

So, they are not string literals, they are perfectly modifiable.

Body:
As it stands, I know that dynamically allocated string literals cannot be changed during run-time, otherwise you will hit a segmentation fault.

This is due to the fact that dynamically allocated string literals are stored, from what I saw in the assembly code, in the .rodata segment, placing these literals in what I interpret as read only memory.

So in theory this should never work on what I hope is in every modern C compiler:

#include <stdio.h>
#include <stdlib.h>

int
main( void )
{
  char *p = ( char * )malloc( 10 * sizeof( char ) );
  if ( p == NULL )
  {
    puts( "Bad memory allocation error!" );
    return( EXIT_FAILURE );
  }
  else
  {
    p = "literal";
    printf( "%s\n", p );
    p[0] = 't'; // <-- This should cause a segmentation fault!
    printf( "%s\n", p ); // <-- This should never reach execution!
  }
  return( EXIT_SUCCESS );
}

However, upon studying how tolower() and toupper() work. I find it rather difficult to understand how these two simple functions are able to do what I thought for a long while was impossible. Here's what I mean:

#include <stdio.h>

int
tolowercase( int c )
{
  return ( c >= 'A' && c <= 'Z' ) ? ( c + 32) : ( c );
}

int
retstrlen( char *str )
{
  int len = 0;
  while( *str != '\0' ) { len++; str++; }
  return( len );
}

int
main( int argc, char **argv )
{
  for( int i = 0; i < argc; i++ )
  {
    for( int j = 0; j < retstrlen( argv[i] ); j++ )
    {
      argv[i][j] = tolowercase( argv[i][j] );
      printf( "%c", argv[i][j] );
    }
    printf( "\n" );
  }
  return 0;
}

How does the source code defined in my custom tolower() function not cause a segmentation fault as it normally would through manipulating dynamically allocated string literals?

My only hypothesis that I can draw is that since tolowercase() has a parameter of int, and a return type of int, then the compiler performs a type conversion which indirectly manipulates **argv.

I am pretty sure I am on the right track about this, yet I could have gotten my whole terminology wrong here, so what is really happening to **argv?


问:
If condition is not checked multiple times inside a while loop
I am trying to find the number of times a number is shifted from its original sequence. I swap the number in ascending order and I count the number of swaps; if the count is >3 I break from the loop.

But so far when I check the numbers the first iteration only the if condition executes and after that it doesn't check for the condition. I am trying to understand why the if condition isn't executing.

```<code> def minimumBribes(q):
       x=q.copy()
       lis=[]
       i=0
       j=0
       count=0
       flag=0
       while i< len(q):
           k=j+1
           a=q[j]
           b=q[k]
           print(a,b)
           if a>b:
             print(a>b)
             x.pop(x.index(a))
             x.insert(x.index(b),a)

             print(x)
             flag+=1
             if flag>3:
                print('Too chaotic')
                break
             else:
                j+=1
           i+=1
       print(count)

if __name__ == '__main__':
    t = int(input())

    for t_itr in range(t):
        n = int(input())

        q = list(map(int, input().rstrip().split()))

        minimumBribes(q)
</code>```

答:
I walked through your code with a debugger and the if-Statement is never entered if the first item in your list is greater than the second.

Say your list looks like this:

```<code>q = [1, 2, 4, 3, 8, 7, 6, 0, 10]
</code>```

Then the first iteration of the while loop would look like that:

```<code>k = j + 1 # k = 1
a = q[j] # a = 1
b = q[k] # b = 2
print(a, b) # 1, 2
if a > b: # false
    ...
</code>```

Since your j is only increased inside the if-Statement, the values for a and b never change.

Also: I could not figure out why you need the variables t, n and lis. Are they used in another part of your code? If so, please remove them from your question, since they are confusing.

Also another hint for writing a question: while your code is executable on its own (a big plus), the input was not obvious to me initially. Providing a concrete input (in your case the list q) helps a lot in identifying the problem.

Hope I was of help.

Body:
I am trying to find the number of times a number is shifted from its original sequence. I swap the number in ascending order and I count the number of swaps; if the count is >3 I break from the loop.

But so far when I check the numbers the first iteration only the if condition executes and after that it doesn't check for the condition. I am trying to understand why the if condition isn't executing.

 def minimumBribes(q):
       x=q.copy()
       lis=[]
       i=0
       j=0
       count=0
       flag=0
       while i< len(q):
           k=j+1
           a=q[j]
           b=q[k]
           print(a,b)
           if a>b:
             print(a>b)
             x.pop(x.index(a))
             x.insert(x.index(b),a)

             print(x)
             flag+=1
             if flag>3:
                print('Too chaotic')
                break
             else:
                j+=1
           i+=1
       print(count)

if __name__ == '__main__':
    t = int(input())

    for t_itr in range(t):
        n = int(input())

        q = list(map(int, input().rstrip().split()))

        minimumBribes(q)

Body:
I walked through your code with a debugger and the if-Statement is never entered if the first item in your list is greater than the second.

Say your list looks like this:

q = [1, 2, 4, 3, 8, 7, 6, 0, 10]

Then the first iteration of the while loop would look like that:

k = j + 1 # k = 1
a = q[j] # a = 1
b = q[k] # b = 2
print(a, b) # 1, 2
if a > b: # false
    ...

Since your j is only increased inside the if-Statement, the values for a and b never change.

Also: I could not figure out why you need the variables t, n and lis. Are they used in another part of your code? If so, please remove them from your question, since they are confusing.

Also another hint for writing a question: while your code is executable on its own (a big plus), the input was not obvious to me initially. Providing a concrete input (in your case the list q) helps a lot in identifying the problem.

Hope I was of help.


问:
Need to get output of 2 tables in one column using joins only
I have this scenario question which needs to be solved using joins only. can't use except,intersect or union.

sample code:

```<code>--demo setup
create table t1 (id int)
insert into t1 values (1),(2),(3)

create table t2 (id int)
insert into t2 values (4),(5),(6)

--join
select t1.id,t2.id
from t1 full outer join
t2 on t1.id=t2.id
</code>```

--after join i am getting

```<code>id          id
----------- -----------
1           NULL
2           NULL
3           NULL
NULL        4
NULL        5
NULL        6
</code>```

--But i need is

```<code>id
-----------
1
2
3
4
5
6
</code>```

Can someone help me with this ? i know this can be easily done using union but this challenge needs to be solved using joins only.

any help is appreciated ....

答:
Although UNION ALL is the better option, you can use this following script-</p>

```<code>SELECT
CASE WHEN C.ID1 IS NULL THEN C.ID2 ELSE C.ID1 END V
FROM
(
    SELECT * FROM
    (
        SELECT 'T1' TabName1,id ID1 FROM @t1
    )A
    FULL JOIN (
        SELECT 'T2' TabName2,id ID2 FROM @t2
    )B
    ON A.TabName1 = B.TabName2
)C
ORDER BY 1
</code>```

Body:
I have this scenario question which needs to be solved using joins only. can't use except,intersect or union.

sample code:

--demo setup
create table t1 (id int)
insert into t1 values (1),(2),(3)

create table t2 (id int)
insert into t2 values (4),(5),(6)

--join
select t1.id,t2.id
from t1 full outer join
t2 on t1.id=t2.id

--after join i am getting

id          id
----------- -----------
1           NULL
2           NULL
3           NULL
NULL        4
NULL        5
NULL        6

--But i need is

id
-----------
1
2
3
4
5
6

Can someone help me with this ? i know this can be easily done using union but this challenge needs to be solved using joins only.

any help is appreciated ....

Body:
Although UNION ALL is the better option, you can use this following script-

SELECT
CASE WHEN C.ID1 IS NULL THEN C.ID2 ELSE C.ID1 END V
FROM
(
    SELECT * FROM
    (
        SELECT 'T1' TabName1,id ID1 FROM @t1
    )A
    FULL JOIN (
        SELECT 'T2' TabName2,id ID2 FROM @t2
    )B
    ON A.TabName1 = B.TabName2
)C
ORDER BY 1


问:
How to hide a navigation bar from first ViewController in Swift?
How can I hide a navigation bar from first ViewController or a particular ViewController in swift?

I used the following code in viewDidLoad():

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationController?.isNavigationBarHidden = true
}
</code>```

and also on viewWillAppear:

```<code>override func viewWillAppear(animated: Bool) {
    self.navigationController?.isNavigationBarHidden = true
}
</code>```

Both methods hide the navigation controller from all ViewControllers.

答:
```<code>     private func setupView() {
            view.backgroundColor = .white
            navigationController?.setNavigationBarHidden(true, animated: false)
        }
</code>```

Alternative

in viewDidLoad use this settings

```<code>title = "Madman"
navigationController?.isNavigationBarHidden = false
navigationController?.navigationBar.prefersLargeTitles = true
navigationItem.largeTitleDisplayMode = .always
</code>```

Check the constraints of Collectionview, scrollview or tableView

```<code> NSLayoutConstraint.activate([
            tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
            tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
        ])
</code>```

Body:
How can I hide a navigation bar from first ViewController or a particular ViewController in swift?

I used the following code in viewDidLoad():

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationController?.isNavigationBarHidden = true
}

and also on viewWillAppear:

override func viewWillAppear(animated: Bool) {
    self.navigationController?.isNavigationBarHidden = true
}

Both methods hide the navigation controller from all ViewControllers.

Body:
     private func setupView() {
            view.backgroundColor = .white
            navigationController?.setNavigationBarHidden(true, animated: false)
        }

Alternative

in viewDidLoad use this settings

title = "Madman"
navigationController?.isNavigationBarHidden = false
navigationController?.navigationBar.prefersLargeTitles = true
navigationItem.largeTitleDisplayMode = .always

Check the constraints of Collectionview, scrollview or tableView

 NSLayoutConstraint.activate([
            tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
            tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
            tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
        ])


问:
How to use laravel Models/Repositories with native php
I'm working on a website which is built using native php but to speed up the development i have installed laravel in sub directory called  new  , where im using all the laravel features and serving the new pages as
mywebsite.com/new/any-laravel-route.

I want to use the laravel Models/Repositories outside of laravel container with native php by requiring the minimum amount of files to bootstrap the laravel.

I'm using following code to initialize laravel

```<code>require 'new/bootstrap/autoload.php';
$app = require_once 'new/bootstrap/app.php';
$kernel = $app->make('Illuminate\Contracts\Http\Kernel');
$kernel->handle(
    $request = Illuminate\Http\Request::capture()
);
</code>```

its working quite slow considering the already included files of native platform code as well.

What im looking for is

Use laravel features with native php

Laravel should not handle HTTP request (as its doing with the above code)

答:
Once you have your $app variable in place you should be ready to use Laravel service container.

If you can do $model = $app->make('App\YourModelClass'); you can use it as model.

Body:
I'm working on a website which is built using native php but to speed up the development i have installed laravel in sub directory called  new  , where im using all the laravel features and serving the new pages as
mywebsite.com/new/any-laravel-route.

I want to use the laravel Models/Repositories outside of laravel container with native php by requiring the minimum amount of files to bootstrap the laravel.

I'm using following code to initialize laravel

require 'new/bootstrap/autoload.php';
$app = require_once 'new/bootstrap/app.php';
$kernel = $app->make('Illuminate\Contracts\Http\Kernel');
$kernel->handle(
    $request = Illuminate\Http\Request::capture()
);

its working quite slow considering the already included files of native platform code as well.

What im looking for is

Use laravel features with native php

Laravel should not handle HTTP request (as its doing with the above code)


问:
becomeFirstResponder slows down app
I have two textfields for username and password and a submit button. When the submit button is pressed a check is performed to see if the username and password was typed or not. If not it shows an alert message and the field whose value was not entered becomes the first responder.

```<code>-(IBAction)loginPressed:(id)sender {

    if ([username.text length] == 0)
    {
        [self showAlert:@"Invalid Username/ Password"];
       [username becomeFirstResponder];
        return;
    }

    if ([password.text length] == 0)
    {
        [self showAlert:@"Invalid Username/ Password"];
      [password becomeFirstResponder];
        return;
    }
}
</code>```

I observed that on clicking the button, the button remains selected for about 1.5 seconds and then the alert is shown. If I comment out the becomeFirstResponder method, it works without any pause. However I need becomeFirstResponder to be there. How do I speed things up using this?

答: [self showAlert:@"Invalid Username/ Password"]; will take a time. you cant speeup that thing.</p>

Title: becomeFirstResponder slows down app

Body:
I have two textfields for username and password and a submit button. When the submit button is pressed a check is performed to see if the username and password was typed or not. If not it shows an alert message and the field whose value was not entered becomes the first responder.

-(IBAction)loginPressed:(id)sender {

    if ([username.text length] == 0)
    {
        [self showAlert:@"Invalid Username/ Password"];
       [username becomeFirstResponder];
        return;
    }

    if ([password.text length] == 0)
    {
        [self showAlert:@"Invalid Username/ Password"];
      [password becomeFirstResponder];
        return;
    }
}

I observed that on clicking the button, the button remains selected for about 1.5 seconds and then the alert is shown. If I comment out the becomeFirstResponder method, it works without any pause. However I need becomeFirstResponder to be there. How do I speed things up using this?


问:
How to swap the new added number into the correct position in binary heap?
This question of my homework has passed a list where index 1 is the new node and is also the root. Then I have to check if it's children is smaller then itself and swap it with the smaller child. I've written some code but it's not working.</p>

```<code>def perc_down(data):
    count = 0
    index = 1
    l, r = 2 * index, 2 * index + 1
    while index < len(data):
        if data[index] > data[l] and data[index] > data[r]:
            min_i = data.index(min(data[l], data[r]))
            data[index], data[min_i] = data[min_i], data[index]
            count += 1
            index = min_i
    return count

values = [0, 100, 7, 8, 9, 22, 45, 12, 16, 27, 36]
swaps = perc_down(values)
print('Binary heap =',values)# should be [0, 7, 9, 8, 16, 22, 45, 12, 100, 27, 36]
print('Swaps =', swaps)# should be 3
</code>```

答:
Give l and r values inside the while loop

```<code>while index <= len(data) // 2:
    l, r = 2 * index, 2 * index + 1
    if r >= len(data):
        r = index
    if data[index] > data[l] or data[index] > data[r]:
        min_i = data.index(min(data[l], data[r]))
        data[index], data[min_i] = data[min_i], data[index]
        count += 1
        index = min_i
    print(data) #Added this for easy debugging.
return count
</code>```

And run the loop till half values only because it's binary min heap.

Output:

```<code>[0, 7, 100, 8, 9, 22, 45, 12, 16, 27, 36]
[0, 7, 9, 8, 100, 22, 45, 12, 16, 27, 36]
[0, 7, 9, 8, 16, 22, 45, 12, 100, 27, 36]
Binary heap = [0, 7, 9, 8, 16, 22, 45, 12, 100, 27, 36]
Swaps = 3
</code>```

Revised the algorithm for those indices whose children do not exist.

For : values = [0, 100, 7, 11, 9, 8, 45, 12, 16, 27, 36] for 100 after 2 swaps comes at index 5 which does not have a right child so when it exceeds the length of list we just set it back to original index.

Heapified list : Binary heap = [0, 7, 8, 11, 9, 36, 45, 12, 16, 27, 100].

Body:
This question of my homework has passed a list where index 1 is the new node and is also the root. Then I have to check if it's children is smaller then itself and swap it with the smaller child. I've written some code but it's not working.

def perc_down(data):
    count = 0
    index = 1
    l, r = 2 * index, 2 * index + 1
    while index < len(data):
        if data[index] > data[l] and data[index] > data[r]:
            min_i = data.index(min(data[l], data[r]))
            data[index], data[min_i] = data[min_i], data[index]
            count += 1
            index = min_i
    return count

values = [0, 100, 7, 8, 9, 22, 45, 12, 16, 27, 36]
swaps = perc_down(values)
print('Binary heap =',values)# should be [0, 7, 9, 8, 16, 22, 45, 12, 100, 27, 36]
print('Swaps =', swaps)# should be 3

Body:
Give l and r values inside the while loop

while index <= len(data) // 2:
    l, r = 2 * index, 2 * index + 1
    if r >= len(data):
        r = index
    if data[index] > data[l] or data[index] > data[r]:
        min_i = data.index(min(data[l], data[r]))
        data[index], data[min_i] = data[min_i], data[index]
        count += 1
        index = min_i
    print(data) #Added this for easy debugging.
return count

And run the loop till half values only because it's binary min heap.

Output:

[0, 7, 100, 8, 9, 22, 45, 12, 16, 27, 36]
[0, 7, 9, 8, 100, 22, 45, 12, 16, 27, 36]
[0, 7, 9, 8, 16, 22, 45, 12, 100, 27, 36]
Binary heap = [0, 7, 9, 8, 16, 22, 45, 12, 100, 27, 36]
Swaps = 3

Revised the algorithm for those indices whose children do not exist.

For : values = [0, 100, 7, 11, 9, 8, 45, 12, 16, 27, 36] for 100 after 2 swaps comes at index 5 which does not have a right child so when it exceeds the length of list we just set it back to original index.

Heapified list : Binary heap = [0, 7, 8, 11, 9, 36, 45, 12, 16, 27, 100].


问:
Given a pandas dataframe, how to check and count if a row string is inside a row of nested lists?
Consider this pandas df:

In:

```<code>import pandas as pd
pd.set_option('display.max_colwidth', -1)

df = pd.DataFrame({'col1':['the quick brown fox','hi hello','hello there','good morning'],
                   'col2': [[['the quick brown fox'],['this is a test'], ['how is it going']],
                            ['lore lipsum dolor'],
                            [''],[['good'],['morning']]]})
df
</code>```

Out:

```<code>    col1                      col2
0   the quick brown fox     [[the quick brown fox], [this is a test], [how is it going]]
1   hi hello                [lore lipsum dolor]
2   hello there                  []
3   good morning            [[good], [morning]]
</code>```

How can I check if the full string of col1 is inside any of the lists inside col2 nested lists? For example the expected output should look a new column like this:

In:

```<code>df = pd.DataFrame({'col3':[[1,0,0,0],[0],[0], [[0],[0]]]})
df
</code>```

Out:

```<code>      col3
0   [1, 0, 0]
1   [0]
2   [0]
3   [0, 0]
</code>```

For example tried and would like to apply this idea to my df columns:

```<code>s = 'the quick brown fox'
l = [['the quick brown fox'],['this is a test'], ['how is it going']]

    a_lis = []
    for e in l:
        if s in e:
            a_lis.append(1)
        else:
            a_lis.append(0)

    print(a_lis)
</code>```

答:
Use nested list comprehension with in and convert boolean to integer:

```<code>df['col3'] = [[int(a in x) for x in b] for a, b in zip(df['col1'], df['col2'])]

print (df)
                  col1                                               col2  \
0  the quick brown fox  [[the quick brown fox], [this is a test], [how...
1             hi hello                                [lore lipsum dolor]
2          hello there                                                 []
3         good morning                                [[good], [morning]]

        col3
0  [1, 0, 0]
1        [0]
2        [0]
3     [0, 0]
</code>```

Body:
Consider this pandas df:

In:

import pandas as pd
pd.set_option('display.max_colwidth', -1)

df = pd.DataFrame({'col1':['the quick brown fox','hi hello','hello there','good morning'],
                   'col2': [[['the quick brown fox'],['this is a test'], ['how is it going']],
                            ['lore lipsum dolor'],
                            [''],[['good'],['morning']]]})
df

Out:

    col1                      col2
0   the quick brown fox     [[the quick brown fox], [this is a test], [how is it going]]
1   hi hello                [lore lipsum dolor]
2   hello there                  []
3   good morning            [[good], [morning]]

How can I check if the full string of col1 is inside any of the lists inside col2 nested lists? For example the expected output should look a new column like this:

In:

df = pd.DataFrame({'col3':[[1,0,0,0],[0],[0], [[0],[0]]]})
df

Out:

      col3
0   [1, 0, 0]
1   [0]
2   [0]
3   [0, 0]

For example tried and would like to apply this idea to my df columns:

s = 'the quick brown fox'
l = [['the quick brown fox'],['this is a test'], ['how is it going']]

    a_lis = []
    for e in l:
        if s in e:
            a_lis.append(1)
        else:
            a_lis.append(0)

    print(a_lis)

Body:
Use nested list comprehension with in and convert boolean to integer:

df['col3'] = [[int(a in x) for x in b] for a, b in zip(df['col1'], df['col2'])]

print (df)
                  col1                                               col2  \
0  the quick brown fox  [[the quick brown fox], [this is a test], [how...
1             hi hello                                [lore lipsum dolor]
2          hello there                                                 []
3         good morning                                [[good], [morning]]

        col3
0  [1, 0, 0]
1        [0]
2        [0]
3     [0, 0]


问:
How is it possible that dynamic components overwrite each other's states?
I have created dynamic Room components which are created based on a room object dispatched by Redux.

```<code>{
    rooms && rooms.map((room, index) => {
        const { name, temperature, humidity, timestamp } = room

        return (
            <Col key={index} xs={12} md={6}>
                <Room
                    index={index}
                    name={name}
                    temperature={temperature}
                    humidity={humidity}
                />
            </Col>
        )
    })
}
</code>```

The details of each room are mounted properly. I create a function to maintain 10 objects in an array. However, when the array is passed into Rechart, it seems that my components are updating on top of the same state.

```<code>class Room extends Component {
    linechart = () => {
        const { timestamp, temperature, humidity, name } = this.props
        const { chartData } = this.state

        if(chartData.length > 9) chartData.shift()
        chartData.push({
            name,
            timestamp: moment(timestamp).format('mm:ss'),
            temperature,
            humidity})
    }
}
</code>```

As you can see, the component details are displayed properly. However, the values of chartData are being stored in the same state, despite being unique components.

I ran the function with an interval of 1 second, and the logs show that the state is being updated in 0.5 second intervals. That means both <Room/> components are using the same <LineChart/> component.
Does anyone know how to overcome this issue?

答:
In order to update items in an array, I'd recommend using the spread syntax. Spread syntax works by shallow copying the array, which keeps a reference to the original array, but allows you to overwrite any data types stored within it. This keeps the array immutable.

I'm not sure where you're getting your data from, but since you have a finite amount of rooms, then the array should already be structured like so:

```<code>data: [
   {
     name: "Room1",
     humidity: 11,
     tempature: 30,
     timestamp: "Sat May 25 2019 22:23:06 GMT-0700",
   },
   {
     name: "Room2",
     humidity: 11,
     tempature: 25,
     timestamp: "Sat May 25 2019 22:23:06 GMT-0700",
   },
   ...etc
]
</code>```

Then you can simply store this to state and when needed map over the array and update its properties with incoming data. However, this assumes incoming data contains all the rooms. If you just need to update a specific room within the rooms array, then you can compare an id (or something that uniquely identifies it) to an incoming new data id.

For example, a new update comes in, but it's only updating Room1, then we could do something like so..

incoming data

```<code>data: [
  {
    name: "Room1",
    humidity: 11,
    tempature: 30,
    timestamp: "Sat May 25 2019 22:23:06 GMT-0700",
   }
];
</code>```

current data stored in state as "rooms"

```<code> this.setState(prevState => ({
      ...prevState, // spread out any previous state not related to "rooms"
      rooms: prevState.rooms.map(room => { // map over "rooms" and pull out each "room" object
        return room.name === data[0].name // if the "room.name" matches incoming data's "name", then...
          ? { ...data[0] } // spread and overwrite it with incoming data
          : room; // else leave the "room" as is
      })
 }));
</code>```

Using array prototypes like pop and shift mutate the original array stored within state and React doesn't handle mutations to its state. You can, however, clone the room array with Array.from() or simply create a new array instance and mutate this new instance with some array prototype functions, but you must then re-set this new instance array to state to overwrite the old array -- React handles this without a problem. It's just not as clean as the spread syntax.

Working example includes both spread syntax and Array.prototype options with a setInterval:

Working example of randomly updating one item within an array by an id with a setInterval:

Body:
I have created dynamic Room components which are created based on a room object dispatched by Redux.

{
    rooms && rooms.map((room, index) => {
        const { name, temperature, humidity, timestamp } = room

        return (
            <Col key={index} xs={12} md={6}>
                <Room
                    index={index}
                    name={name}
                    temperature={temperature}
                    humidity={humidity}
                />
            </Col>
        )
    })
}

The details of each room are mounted properly. I create a function to maintain 10 objects in an array. However, when the array is passed into Rechart, it seems that my components are updating on top of the same state.

class Room extends Component {
    linechart = () => {
        const { timestamp, temperature, humidity, name } = this.props
        const { chartData } = this.state

        if(chartData.length > 9) chartData.shift()
        chartData.push({
            name,
            timestamp: moment(timestamp).format('mm:ss'),
            temperature,
            humidity})
    }
}

As you can see, the component details are displayed properly. However, the values of chartData are being stored in the same state, despite being unique components.

I ran the function with an interval of 1 second, and the logs show that the state is being updated in 0.5 second intervals. That means both <Room/> components are using the same <LineChart/> component.
Does anyone know how to overcome this issue?

Body:
In order to update items in an array, I'd recommend using the spread syntax. Spread syntax works by shallow copying the array, which keeps a reference to the original array, but allows you to overwrite any data types stored within it. This keeps the array immutable.

I'm not sure where you're getting your data from, but since you have a finite amount of rooms, then the array should already be structured like so:

data: [
   {
     name: "Room1",
     humidity: 11,
     tempature: 30,
     timestamp: "Sat May 25 2019 22:23:06 GMT-0700",
   },
   {
     name: "Room2",
     humidity: 11,
     tempature: 25,
     timestamp: "Sat May 25 2019 22:23:06 GMT-0700",
   },
   ...etc
]

Then you can simply store this to state and when needed map over the array and update its properties with incoming data. However, this assumes incoming data contains all the rooms. If you just need to update a specific room within the rooms array, then you can compare an id (or something that uniquely identifies it) to an incoming new data id.

For example, a new update comes in, but it's only updating Room1, then we could do something like so..

incoming data

data: [
  {
    name: "Room1",
    humidity: 11,
    tempature: 30,
    timestamp: "Sat May 25 2019 22:23:06 GMT-0700",
   }
];

current data stored in state as "rooms"

 this.setState(prevState => ({
      ...prevState, // spread out any previous state not related to "rooms"
      rooms: prevState.rooms.map(room => { // map over "rooms" and pull out each "room" object
        return room.name === data[0].name // if the "room.name" matches incoming data's "name", then...
          ? { ...data[0] } // spread and overwrite it with incoming data
          : room; // else leave the "room" as is
      })
 }));

Using array prototypes like pop and shift mutate the original array stored within state and React doesn't handle mutations to its state. You can, however, clone the room array with Array.from() or simply create a new array instance and mutate this new instance with some array prototype functions, but you must then re-set this new instance array to state to overwrite the old array -- React handles this without a problem. It's just not as clean as the spread syntax.

Working example includes both spread syntax and Array.prototype options with a setInterval:

Working example of randomly updating one item within an array by an id with a setInterval:


问:
Scroller isn't displaying on the screen
I am having an issue with the position-fix; top 100px;. when I use position-fix; top 100px; and run the program, the result will be "google scroller doesn't show up on the screen". when I don't use when I use position-fix; top 100px; then google scroller shows up on the screen.

Here is the HTML code.

```<code><body>
  <section class="container">
    <div style="position:fixed; top:180px" class="First">
      <ul id="ListName" class="">
        <li><a style="text-decoration:none" href="interest.html"> Interest </a></li>
      </ul>
    </div>

    <div style="position:fixed; top:180px;" class="Second">
      <h1  align="center"> sport</h1>

         <p>

          <ul>
            <li> soccer and,</li>
            <li> football </li>
          </ul>

        </p>

   </div>
 </section>

 <div id="" class="" style="clear:both;"></div>
</body>
</code>```

Here is the CSS code.

```<code><style>
        .container {
            width: 99%;
            height: auto;
            margin: auto;
            padding: 10px;
            font-family: Verdana,Geneva,Tahoma,Arial,Helvetica,sans-serif!important;
        }
        .First {
            height: auto;
            width: 20%;
            background: white;
            border:1px solid #666;
            float: left;
        }
        .Second {
            margin-left: 21%;
            height: auto;
            width:640px;
            border:1px solid #666;
            background: white;
        }

</style>
</code>```

答:
Your requirement is bit confusing, it's not clear that whether you want to make the second div inside the section element scrollable then you can do it by adding a height or max-height property to the Second class.

Same holds true for any container scroll bar appear only when the content inside a div or any container exceeds the height specified.

If you want to make second div scrollable, you need to do following.

```<code>   .Second {
      height:100px !important;
      overflow-y: scroll !important;
      margin-left: 21%;
      height: auto;
      width: 640px;
      border: 1px solid #666;
      background: white;
   }
</code>```

If you want to make body element scrollable then you can set a height property or when your content increases the automatically body will be scrollable.

checkout the fiddle here.

I have added a width property to the second div in order to make it fit in the fiddle window.You may remove it. Also pasted some sample text inside body to demonstrate that body is scrollable when it has enough text or if you want a set a fix height you can do that as well.

NOTE: you need to set the property value with !important so that it overrides and forces browser to apply that css.

```<code>height:100px !important;
</code>```

Hope it helps!!

Title: Scroller isn't displaying on the screen

Body:
I am having an issue with the position-fix; top 100px;. when I use position-fix; top 100px; and run the program, the result will be "google scroller doesn't show up on the screen". when I don't use when I use position-fix; top 100px; then google scroller shows up on the screen.

Here is the HTML code.

 Interest

 sport

 soccer and,

 football

Here is the CSS code.

Body:
Your requirement is bit confusing, it's not clear that whether you want to make the second div inside the section element scrollable then you can do it by adding a height or max-height property to the Second class.

Same holds true for any container scroll bar appear only when the content inside a div or any container exceeds the height specified.

If you want to make second div scrollable, you need to do following.

   .Second {
      height:100px !important;
      overflow-y: scroll !important;
      margin-left: 21%;
      height: auto;
      width: 640px;
      border: 1px solid #666;
      background: white;
   }

If you want to make body element scrollable then you can set a height property or when your content increases the automatically body will be scrollable.

checkout the fiddle here.

I have added a width property to the second div in order to make it fit in the fiddle window.You may remove it. Also pasted some sample text inside body to demonstrate that body is scrollable when it has enough text or if you want a set a fix height you can do that as well.

NOTE: you need to set the property value with !important so that it overrides and forces browser to apply that css.

height:100px !important;

Hope it helps!!


问:
Swift - make String conform to RandomAccessCollection
According to Swift 5 docs, String has method randomElement() with complexity O(1) or O(*n*) depending on conformance to RandomAccessCollection protocol.

Therefore, I am wondering how to make cases where randomElement() of String complexity will be O(1).

My string is just:

```<code>let letters = "abcdefghijklmnopqrstuvwxyz"
</code>```

Questions:

How do I check if my particular string conforms to RandomAccessCollection?

How to create / remove conformance to RandomAccessCollection protocol from a string?

答: A string is never a random access collection. If that’s what you want, cast to an Array. </p>

Body:
According to Swift 5 docs, String has method randomElement() with complexity O(1) or O(*n*) depending on conformance to RandomAccessCollection protocol.

Therefore, I am wondering how to make cases where randomElement() of String complexity will be O(1).

My string is just:

let letters = "abcdefghijklmnopqrstuvwxyz"

Questions:

How do I check if my particular string conforms to RandomAccessCollection?

How to create / remove conformance to RandomAccessCollection protocol from a string?


问:
How to parse nested JSON objects starting with special characters in Unity?
I'm trying to get these information from MongoDB, and it is giving me this JSON to deal with:

```<code>{
    \"values\":
        [
            { \"_id\" : { \"$oid\" : \"5ccf1bc55d0e652b8a6c9153\"} , \"Id\" : 5 ,\"Name\" : \" palups\"} ,
            { \"_id\" : { \"$oid\" : \"5ccf24e91f6e4f29b5ede29b\"} , \"Id\" : 2 ,\"Name\" : \"Maria\"} ,
            { \"_id\" : { \"$oid\" : \"5ccf25071f6e4f29b5ede2c5\"} , \"Id\" : 3 ,\"Name\" : \"marcela\"}
        ]
}
</code>```

The problem is that nested object $oid. I managed to get the Id and the Name, but not the nested object.

Here's what I tried:

```<code>[System.Serializable]
public class ScoreData {
    public List<Values> values = new List<Values>();
}

[System.Serializable]
public class Values
{
    public _id oid;
    public int Id;
    public string Name;
}

[System.Serializable]
public class _id
{
    public string m_oid;
}
</code>```

The part above are the classes that I created, and the code below is the function provided to me, with my additions to make it work the way I want:

```<code>IEnumerator getProductsInDB(){
    UnityWebRequest unityWebRequest = UnityWebRequest.Get (baseURL+databaseName+"/collections/"+collectionName+"?apiKey=" + apiKey);
    yield return unityWebRequest.Send();

    if(unityWebRequest.isNetworkError || unityWebRequest.isHttpError) {
        Debug.Log(unityWebRequest.error);
    }
    else {
        //Debug.Log (unityWebRequest.downloadHandler.text);
        jsonString = unityWebRequest.downloadHandler.text;

        string JSONToParse = "{\"values\":" + jsonString + "}"; //estava faltando no json ???

        ScoreData loadedScoreData = JsonUtility.FromJson<ScoreData>(JSONToParse);

        for (int i = 0; i <= loadedScoreData.values.Count; i++)
        {
            Debug.Log("score: " + loadedScoreData.values[i].oid.m_oid);
            Debug.Log("score: " + loadedScoreData.values[i].Id);
            Debug.Log("name: " + loadedScoreData.values[i].Name);
            Debug.Log("****************************************");
        }
    }
}
</code>```

That's what I get on Unity's console:

(as you can see, the first line is empty).

score:

UnityEngine.Debug:Log(Object)

score: 999

UnityEngine.Debug:Log(Object)

name:  Marcela

UnityEngine.Debug:Log(Object)

So, how to parse the nested value or what am I doing wrong?

答:
For JsonUtility the field names in your classes have to match with the ones in your JSON string. Otherwise the "missing" fields will simply have their default value (in your case "").

So from the naming in your JSON example

in the class Values it should rather be

```<code>  public _id _id;
</code>```

in the class _id it would have to be

```<code>  public string $oid;
</code>```

However the latter is not a valid identifier name in c#

Identifiers must start with a letter, or _.

Identifiers may contain Unicode letter characters, decimal digit characters, Unicode connecting characters, Unicode combining characters, or Unicode formatting characters. For more information on Unicode categories, see the Unicode Category Database. You can declare identifiers that match C# keywords by using the @ prefix on the identifier. The @ is not part of the identifier name. For example, @if declares an identifier named if. These verbatim identifiers are primarily for interoperability with identifiers declared in other languages.

The prefix $ doesn't fit with those rules.

So if you can't change the JSON I fear that JsonUtility doesn't help you in this case and you should look for another Json parser.

You could e.g. use SimpleJson in order to just retrieve this specific field for each Values instance afterwards and pass it in.

Anyway

The simplest solution would be to remove or replace that special character by something else before you parse it like e.g.

```<code>string JSONToParse = ("{\"values\":" + jsonString + "}").Replace('$', '_');
</code>```

and rather change

```<code>[Serializeable]
public class _id
{
    public string _oid;
}
</code>```

Also as Sir Rufo commented are you really sure you have to do that

```<code>string JSONToParse = ("{\"values\":" + jsonString + "}");
</code>```

? In your question you are saying that you already receive the JSON including the { } and the values field...

Body:
I'm trying to get these information from MongoDB, and it is giving me this JSON to deal with:

{
    \"values\":
        [
            { \"_id\" : { \"$oid\" : \"5ccf1bc55d0e652b8a6c9153\"} , \"Id\" : 5 ,\"Name\" : \" palups\"} ,
            { \"_id\" : { \"$oid\" : \"5ccf24e91f6e4f29b5ede29b\"} , \"Id\" : 2 ,\"Name\" : \"Maria\"} ,
            { \"_id\" : { \"$oid\" : \"5ccf25071f6e4f29b5ede2c5\"} , \"Id\" : 3 ,\"Name\" : \"marcela\"}
        ]
}

The problem is that nested object $oid. I managed to get the Id and the Name, but not the nested object.

Here's what I tried:

[System.Serializable]
public class ScoreData {
    public List<Values> values = new List<Values>();
}

[System.Serializable]
public class Values
{
    public _id oid;
    public int Id;
    public string Name;
}

[System.Serializable]
public class _id
{
    public string m_oid;
}

The part above are the classes that I created, and the code below is the function provided to me, with my additions to make it work the way I want:

IEnumerator getProductsInDB(){
    UnityWebRequest unityWebRequest = UnityWebRequest.Get (baseURL+databaseName+"/collections/"+collectionName+"?apiKey=" + apiKey);
    yield return unityWebRequest.Send();

    if(unityWebRequest.isNetworkError || unityWebRequest.isHttpError) {
        Debug.Log(unityWebRequest.error);
    }
    else {
        //Debug.Log (unityWebRequest.downloadHandler.text);
        jsonString = unityWebRequest.downloadHandler.text;

        string JSONToParse = "{\"values\":" + jsonString + "}"; //estava faltando no json ???

        ScoreData loadedScoreData = JsonUtility.FromJson<ScoreData>(JSONToParse);

        for (int i = 0; i <= loadedScoreData.values.Count; i++)
        {
            Debug.Log("score: " + loadedScoreData.values[i].oid.m_oid);
            Debug.Log("score: " + loadedScoreData.values[i].Id);
            Debug.Log("name: " + loadedScoreData.values[i].Name);
            Debug.Log("****************************************");
        }
    }
}

That's what I get on Unity's console:

(as you can see, the first line is empty).

score:

UnityEngine.Debug:Log(Object)

score: 999

UnityEngine.Debug:Log(Object)

name:  Marcela

UnityEngine.Debug:Log(Object)

So, how to parse the nested value or what am I doing wrong?

Body:
For JsonUtility the field names in your classes have to match with the ones in your JSON string. Otherwise the "missing" fields will simply have their default value (in your case "").

So from the naming in your JSON example

in the class Values it should rather be

  public _id _id;

in the class _id it would have to be

  public string $oid;

However the latter is not a valid identifier name in c#

Identifiers must start with a letter, or _.

Identifiers may contain Unicode letter characters, decimal digit characters, Unicode connecting characters, Unicode combining characters, or Unicode formatting characters. For more information on Unicode categories, see the Unicode Category Database. You can declare identifiers that match C# keywords by using the @ prefix on the identifier. The @ is not part of the identifier name. For example, @if declares an identifier named if. These verbatim identifiers are primarily for interoperability with identifiers declared in other languages.

The prefix $ doesn't fit with those rules.

So if you can't change the JSON I fear that JsonUtility doesn't help you in this case and you should look for another Json parser.

You could e.g. use SimpleJson in order to just retrieve this specific field for each Values instance afterwards and pass it in.

Anyway

The simplest solution would be to remove or replace that special character by something else before you parse it like e.g.

string JSONToParse = ("{\"values\":" + jsonString + "}").Replace('$', '_');

and rather change

[Serializeable]
public class _id
{
    public string _oid;
}

Also as Sir Rufo commented are you really sure you have to do that

string JSONToParse = ("{\"values\":" + jsonString + "}");

? In your question you are saying that you already receive the JSON including the { } and the values field...