问:
(Micropython) Creating and comparing time objects
Using Micropython for the ESP32 microcontroller, flashed with the latest firmware at time of writing (v1.18)

I'm making an alarm (sort-of) system where I get multiple time values ("13:15" for example) from my website, and then I have to ring an alarm bell at those times.

I've done the website and I can do the ring stuff, but I don't know how to actually create time objects from the previously mentioned strings ("13:15"), and then check if any of the times inputted match the current time, the date is irrelevant.

From reading the documentation, im getting the sense that this cant be done, since ive looked through the micropython module github, and you apparently cant get datetime in micropython, and i know that in regular python my problem can be solved with datetime.

import ntptime
import time
import network

# Set esp as a wifi station
station = network.WLAN(network.STA_IF)
# Activate wifi station
station.active(True)
# Connect to wifi ap
station.connect(ssid,passwd)
while station.isconnected() == False:
        print('.')
        time.sleep(1)
print(station.ifconfig())
try:
        print("Local time before synchronization: %s" %str(time.localtime()))
        ntptime.settime()
        print("Local time after synchronization: %s" %str(time.localtime()))
    except:
        print("Error syncing time, exiting...")
```

this is the shortened code from my project, with only the time parts, now comes into play the time comparison thing I don't know how to do.

答:
Using ntptime to get time from server. I use "time.google.com", to get the time. Then, I transform it into seconds (st) to be more accurate. And set my targets hour in seconds 1 hour = 3600 s.</p>
```<code>import utime
import ntptime

def server_time():
    try:
        # Ask to time.google.com server the current time.
        ntptime.host = "time.google.com"
        ntptime.settime()
        t = time.localtime()
        # print(t)
        # transform tuple time 't' to seconds value. 1 hour =
        st = t[3]*3600 + t[4]*60 + t[5]
        return st
    except:
        # print('no time')
        st = -1
        return st

while True:
      # Returns an increasing millisecond counter since the Board reset.
      now = utime.ticks_ms()

      # Check current time every 5000 ms (5s) without going to sleep or stop any other process.
      if now >= period + 5000:
          period += 5000

          # call your servertime function
          st = server_time()
              if  ((st > 0) and (st < 39600)) or (st > 82800):    # Turn On 17:00 Mexico Time.
                    # something will be On between 17:00 - 06:00
              elif ((st <82800) and (st > 39600)):                # Turn Off 6:00.
                  # something will be Off between 06:00 - 17:00
              else:
                  pass
</code>```

Body:
Using Micropython for the ESP32 microcontroller, flashed with the latest firmware at time of writing (v1.18)

I'm making an alarm (sort-of) system where I get multiple time values ("13:15" for example) from my website, and then I have to ring an alarm bell at those times.

I've done the website and I can do the ring stuff, but I don't know how to actually create time objects from the previously mentioned strings ("13:15"), and then check if any of the times inputted match the current time, the date is irrelevant.

From reading the documentation, im getting the sense that this cant be done, since ive looked through the micropython module github, and you apparently cant get datetime in micropython, and i know that in regular python my problem can be solved with datetime.

import ntptime
import time
import network

# Set esp as a wifi station
station = network.WLAN(network.STA_IF)
# Activate wifi station
station.active(True)
# Connect to wifi ap
station.connect(ssid,passwd)
while station.isconnected() == False:
        print('.')
        time.sleep(1)
print(station.ifconfig())
try:
        print("Local time before synchronization: %s" %str(time.localtime()))
        ntptime.settime()
        print("Local time after synchronization: %s" %str(time.localtime()))
    except:
        print("Error syncing time, exiting...")

this is the shortened code from my project, with only the time parts, now comes into play the time comparison thing I don't know how to do.

Body:
Using ntptime to get time from server. I use "time.google.com", to get the time. Then, I transform it into seconds (st) to be more accurate. And set my targets hour in seconds 1 hour = 3600 s.

import utime
import ntptime

def server_time():
    try:
        # Ask to time.google.com server the current time.
        ntptime.host = "time.google.com"
        ntptime.settime()
        t = time.localtime()
        # print(t)
        # transform tuple time 't' to seconds value. 1 hour =
        st = t[3]*3600 + t[4]*60 + t[5]
        return st
    except:
        # print('no time')
        st = -1
        return st

while True:
      # Returns an increasing millisecond counter since the Board reset.
      now = utime.ticks_ms()

      # Check current time every 5000 ms (5s) without going to sleep or stop any other process.
      if now >= period + 5000:
          period += 5000

          # call your servertime function
          st = server_time()
              if  ((st > 0) and (st < 39600)) or (st > 82800):    # Turn On 17:00 Mexico Time.
                    # something will be On between 17:00 - 06:00
              elif ((st <82800) and (st > 39600)):                # Turn Off 6:00.
                  # something will be Off between 06:00 - 17:00
              else:
                  pass


来源: stackexchange

问:
How to read contents of a directory in linux on nodejs?
I am creating an application on nodejs that has to read contents of a folder in the install location. The installer creates the directory 'cert' at the install location.
My code is:

```<code>const dircert = './cert'
files = fs.readdirSync(dircert)
if (!files.length) {
    ***some code***
  } else {
    files.forEach(file => {
      if (path.extname(file) == '.key') {
        pathkey = path.resolve(dircert, file)
      }

      if (path.extname(file) == '.crt') {
        pathcert = path.resolve(dircert, file)
      }
    })
</code>```

This runs fine in windows but not in Linux. The installer is not able to read the contents. What do I need to change to ensure that it works in both? I am pretty new to linux.
The application is getting installed in ProgramFiles in windows but in /opt/AppName in linux. Please suggest.

Editing to add: So this cert folder is getting created under /opt/AppName/ in linux and under c:/ProgramFiles/company/App Name/ in Windows. While this code runs fine on windows, on linux this code tries to look for cert at root. How do I make sure it looks for the folder at the installed location which is /opt/AppName, and it should work on both the platforms.

答:
It's unclear from your question how the files are being installed and how the code is being executed. Both of these matter in Linux. You can use the __dirname node variable with path.resolve() to get the directory of the current module. If cert is below the current module, you can use the following code to resolve the location:

```<code>const path = require('path');
const dircert = path.resolve(__dirname, 'cert');
</code>```

If you're using ES Modules:

```<code>import path from 'path';
const dircert = path.resolve('cert').
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am creating an application on nodejs that has to read contents of a folder in the install location. The installer creates the directory 'cert' at the install location.
My code is:

const dircert = './cert'
files = fs.readdirSync(dircert)
if (!files.length) {
    ***some code***
  } else {
    files.forEach(file => {
      if (path.extname(file) == '.key') {
        pathkey = path.resolve(dircert, file)
      }

      if (path.extname(file) == '.crt') {
        pathcert = path.resolve(dircert, file)
      }
    })

This runs fine in windows but not in Linux. The installer is not able to read the contents. What do I need to change to ensure that it works in both? I am pretty new to linux.
The application is getting installed in ProgramFiles in windows but in /opt/AppName in linux. Please suggest.

Editing to add: So this cert folder is getting created under /opt/AppName/ in linux and under c:/ProgramFiles/company/App Name/ in Windows. While this code runs fine on windows, on linux this code tries to look for cert at root. How do I make sure it looks for the folder at the installed location which is /opt/AppName, and it should work on both the platforms.

Body:
It's unclear from your question how the files are being installed and how the code is being executed. Both of these matter in Linux. You can use the __dirname node variable with path.resolve() to get the directory of the current module. If cert is below the current module, you can use the following code to resolve the location:

const path = require('path');
const dircert = path.resolve(__dirname, 'cert');

If you're using ES Modules:

import path from 'path';
const dircert = path.resolve('cert').


问:
RestAssured how to get the name of a value from response
I did some research in satckoverflow. I could not find any answer. From the response below how can I find out what the value is after payment? It can either be bankAccount or creditCard. Depending on the value I get, I will run the next script. In the example below you can see that the current value is bankAccount.

```<code>{
"code": "I00001",
"description": "Successful.",
"customerProfileId": "1234",
"paymentProfles": [{
    "customerPaymentProfileId": "9874",
    "billingAddress": {
        "address": "123 Steven Road",
        "city": "Hopkins",
        "state": "MN",
        "zipcode": "55344",
        "phoneNumber": "507-3821122",
        "country": "USA"
    },
    "payment": {
        "bankAccount": {
            "accountNumber": "XXXX1234",
            "accountType": "CHECKING",
            "eCheckType": "WEB",
            "nameOnAccount": "QA Tes1t"
        }
    }
}]
</code>```

}

Thanks in advance for your time and help.

答: "payment" will be parent key under which either "bankAccount" or "creditCard" would be present. You can just deserialize "payment" into Map and then get the key of it. Now based on key name you can write ur next step.</p>

Body:
I did some research in satckoverflow. I could not find any answer. From the response below how can I find out what the value is after payment? It can either be bankAccount or creditCard. Depending on the value I get, I will run the next script. In the example below you can see that the current value is bankAccount.

{
"code": "I00001",
"description": "Successful.",
"customerProfileId": "1234",
"paymentProfles": [{
    "customerPaymentProfileId": "9874",
    "billingAddress": {
        "address": "123 Steven Road",
        "city": "Hopkins",
        "state": "MN",
        "zipcode": "55344",
        "phoneNumber": "507-3821122",
        "country": "USA"
    },
    "payment": {
        "bankAccount": {
            "accountNumber": "XXXX1234",
            "accountType": "CHECKING",
            "eCheckType": "WEB",
            "nameOnAccount": "QA Tes1t"
        }
    }
}]

}

Thanks in advance for your time and help.


问:
Download a single folder or directory from a GitHub repo
How can I download only a specific folder or directory from a remote Git repo hosted on GitHub?

Say the example GitHub repo lives here:

```<code>git@github.com:foobar/Test.git
</code>```

Its directory structure:

```<code>Test/
├── foo/
│   ├── a.py
│   └── b.py
└── bar/
    ├── c.py
    └── d.py
</code>```

I want to download only the foo folder and not clone the whole Test project.

答:
If you truly just want to just "download" the folder and not "clone" it (for development), the easiest way to simply get a copy of the most recent version of the repository (and therefore a folder/file within it), without needing to clone the whole repo or even install git in the first place, is to download a zip archive (for any repo, fork, branch, commit, etc.) by going to the desired repository/fork/branch/commit on GitHub (e.g. http(s)://github.com/<user>/<repo>/commit/<Sha1> for a copy of the files as they were after a specific commit) and selecting the Downloads button near the upper-right.

This archive format contains none of the git-repo magic, just the tracked files themselves (and perhaps a few .gitignore files if they were tracked, but you can ignore those :p) - that means that if the code changes and you want to stay on top, you'll have to manually re-download it, and it also means you won't be able to use it as a git repository...

Not sure if that's what you're looking for in this case (again, "download"/view vs "clone"/develop), but it can be useful nonetheless...

Body:
How can I download only a specific folder or directory from a remote Git repo hosted on GitHub?

Say the example GitHub repo lives here:

git@github.com:foobar/Test.git

Its directory structure:

Test/
├── foo/
│   ├── a.py
│   └── b.py
└── bar/
    ├── c.py
    └── d.py

I want to download only the foo folder and not clone the whole Test project.

ContentLicense: CC BY-SA 3.0


问:
How I can access and add value from the list which is nested in the hashmap and list in Java
I am trying to add value for the List which is stored in HashMap and that has one parent List.

When I try to do so I get "The method get in type is not compatible with the List"

I am trying the following code, logic is :

If I get the matching value of tID in the txnValue List I am just adding the "Values" List otherwise I am creating the new HashMap.

List < HashMap > txnvalues = new ArrayList < HashMap > ();
for (LinkedHashMap < String, Object > linkedHashMap: resultset) {

  HashMap data = new HashMap < > ();
  HashMap attrData = new HashMap < > ();
  List values = new ArrayList < > ();
  data.put("values", new ArrayList < > ());
  attrData.put("attrID", linkedHashMap.get("ID"));
  attrData.put("attrVal", linkedHashMap.get("VAL"));
  String txnID = linkedHashMap.get("T_ID").toString();
  if (!txnvalues.stream().anyMatch(list -> list.containsValue(txnID))) {
    data.put("tID", linkedHashMap.get("T_ID"));
    values.add(attrData);
    data.put("Values", values);
    txnvalues.add(data);
  } else {
    txnvalues.get("Values").add(attrData); // this Line throws error
  }

}```
</div>
</div>
</p>
<p>Example :</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>[{
"tID":123,
"Values":[{attrID:1,attrVal:123}]
}]

//Here If linkedHashmap.get("T_ID") = 123 which matches with tID then I want to add data in the Values

[{
"tID":123,
"Values":[{attrID:1,attrVal:123},{attrID:11,attrVal:467}]
}]

//If it doesn't match then I want to create new Hashmap and update txnValues Like this

[{
"tID":123,
"Values":[{attrID:1,attrVal:123},{attrID:2,attrVal:3435}]
},
{
"tID":456,
"Values":[{attrID:2,attrVal:233}]
}
]</code>```

答:
In the else block, you call get method of txnvalues which a list of HashMaps and thus it expects an integer index. I believe you assume that at this point you've got a reference to the HashMap to which you would add the values. But you don't.

So, you need to find the index where to add the values, which means you have to look through the txnvalues list again.

For this reason, you should use a different approach:

```<code>txnvalues.stream()
         .filter(m -> m.get("tID").equals(txnID))
         .findFirst()
         .ifPresentOrElse(
                 m -> m.get("Values").add(attrData),
                 () -> {
                     HashMap data = new HashMap<>();
                     // Other stuff to fill the data
                     txnvalues.add(data);
                 }
         );
</code>```

Here .filter(m -> m.get("tID").equals(txnID)) corresponds to your .anyMatch(list -> list.containsValue(txnID)) (the parameter list is actually instance of HashMap).

I changed the condition: according to your data sample, you looking for Map which has txnID value for the "tID" key, therefore getting the value of this key is faster than looking through all the values in the HashMap. (It may return null.)

So filter will return only the entries which contain match the required value of the "tID" key. Then .findFirst() “returns” the reference to that HashMap. Now .ifPresentOrElse performs the actions you want:

m.get("Values").add(attrData) into the list; this corresponds your one line of code in the else block;

the other code is what you had in the if block: if nothing is found, create the new instance.

Body:
I am trying to add value for the List which is stored in HashMap and that has one parent List.

When I try to do so I get "The method get in type is not compatible with the List"

I am trying the following code, logic is :

If I get the matching value of tID in the txnValue List I am just adding the "Values" List otherwise I am creating the new HashMap.

List < HashMap > txnvalues = new ArrayList < HashMap > ();
for (LinkedHashMap < String, Object > linkedHashMap: resultset) {

  HashMap data = new HashMap < > ();
  HashMap attrData = new HashMap < > ();
  List values = new ArrayList < > ();
  data.put("values", new ArrayList < > ());
  attrData.put("attrID", linkedHashMap.get("ID"));
  attrData.put("attrVal", linkedHashMap.get("VAL"));
  String txnID = linkedHashMap.get("T_ID").toString();
  if (!txnvalues.stream().anyMatch(list -> list.containsValue(txnID))) {
    data.put("tID", linkedHashMap.get("T_ID"));
    values.add(attrData);
    data.put("Values", values);
    txnvalues.add(data);
  } else {
    txnvalues.get("Values").add(attrData); // this Line throws error
  }

}

Example :

[{
"tID":123,
"Values":[{attrID:1,attrVal:123}]
}]

//Here If linkedHashmap.get("T_ID") = 123 which matches with tID then I want to add data in the Values

[{
"tID":123,
"Values":[{attrID:1,attrVal:123},{attrID:11,attrVal:467}]
}]

//If it doesn't match then I want to create new Hashmap and update txnValues Like this

[{
"tID":123,
"Values":[{attrID:1,attrVal:123},{attrID:2,attrVal:3435}]
},
{
"tID":456,
"Values":[{attrID:2,attrVal:233}]
}
]

Body:
In the else block, you call get method of txnvalues which a list of HashMaps and thus it expects an integer index. I believe you assume that at this point you've got a reference to the HashMap to which you would add the values. But you don't.

So, you need to find the index where to add the values, which means you have to look through the txnvalues list again.

For this reason, you should use a different approach:

txnvalues.stream()
         .filter(m -> m.get("tID").equals(txnID))
         .findFirst()
         .ifPresentOrElse(
                 m -> m.get("Values").add(attrData),
                 () -> {
                     HashMap data = new HashMap<>();
                     // Other stuff to fill the data
                     txnvalues.add(data);
                 }
         );

Here .filter(m -> m.get("tID").equals(txnID)) corresponds to your .anyMatch(list -> list.containsValue(txnID)) (the parameter list is actually instance of HashMap).

I changed the condition: according to your data sample, you looking for Map which has txnID value for the "tID" key, therefore getting the value of this key is faster than looking through all the values in the HashMap. (It may return null.)

So filter will return only the entries which contain match the required value of the "tID" key. Then .findFirst() “returns” the reference to that HashMap. Now .ifPresentOrElse performs the actions you want:

m.get("Values").add(attrData) into the list; this corresponds your one line of code in the else block;

the other code is what you had in the if block: if nothing is found, create the new instance.


问:
Slicer controls two columns
I'm quite new to Power BI. I have one lookup table and multiple fact tables and their relationships are all one to many.

I want to create a slicer using category desc column from my lookup table. The slicer is going to filter both category desc and old category columns in a table. Also it is filtering other visuals as a normal filter.

For example if you select golf, the table is going to show category = golf or old category = golf.

Is it possible to just use the slicer from the lookup table which would act as a normal slicer (filtering category desc in my other visuals) while at the same time filter this specific table visual based on the criteria above? Appreciate anyone's help!

```<code>|Category Desc  |Old Category  |Type  |Amount|
|Golf           |Tennis        |J     |11    |
|Tennis         |Golf          |K     |12    |
|Social         |Fitness       |J     |44    |
|Fitness        |Social        |K     |32    |
|Golf           |Other         |K     |23    |
|Other          |Social        |J     |26    |
</code>```

答:
If you want to filter only one specific table, then consider using a measure. Something like this.</p>
```<code>PickThis =
var _FilterSelect = SELECTEDVALUE('LookupTable'[Label])
return
calculate( countrows('SpecificTable'), FILTER(ALL('SpecificTable'[Category], 'SpecificTable'[OldCategory]), 'SpecificTable'[OldCategory]= _FilterSelect  || 'SpecificTable'[Category] = _FilterSelect ))
</code>```

Title: Slicer controls two columns

Body:
I'm quite new to Power BI. I have one lookup table and multiple fact tables and their relationships are all one to many.

I want to create a slicer using category desc column from my lookup table. The slicer is going to filter both category desc and old category columns in a table. Also it is filtering other visuals as a normal filter.

For example if you select golf, the table is going to show category = golf or old category = golf.

Is it possible to just use the slicer from the lookup table which would act as a normal slicer (filtering category desc in my other visuals) while at the same time filter this specific table visual based on the criteria above? Appreciate anyone's help!

|Category Desc  |Old Category  |Type  |Amount|
|Golf           |Tennis        |J     |11    |
|Tennis         |Golf          |K     |12    |
|Social         |Fitness       |J     |44    |
|Fitness        |Social        |K     |32    |
|Golf           |Other         |K     |23    |
|Other          |Social        |J     |26    |

Body:
If you want to filter only one specific table, then consider using a measure. Something like this.

PickThis =
var _FilterSelect = SELECTEDVALUE('LookupTable'[Label])
return
calculate( countrows('SpecificTable'), FILTER(ALL('SpecificTable'[Category], 'SpecificTable'[OldCategory]), 'SpecificTable'[OldCategory]= _FilterSelect  || 'SpecificTable'[Category] = _FilterSelect ))


问:
Creating a function to search for a value in an array and return it's position index using a loop
I'm very new to JavaScript.
I'm trying to create a function that can two take two arguments, an array and a value. The function should return the index where the value is found but ff the value is not
found, it should return -1.
I want to this using a loop and not a method like for example indexOf.

So this is what I got by now:

```<code>function getIndex(arr, value) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === value) {
      return i;
    } else {
      return -1;
    }
  }
}
</code>```

For some reason it keeps returning -1 even if the value if found. What am I doing wrong?

答:
In the first time your if happen you return no matter what!

If arr[i] == value you return the index, else - you return -1.

What you want to do is return -1 in the case that none of the array elements is found.

```<code>function getIndex(arr, value) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === value) {
      return i;
    }
  }
  return -1;
}
</code>```

Body:
I'm very new to JavaScript.
I'm trying to create a function that can two take two arguments, an array and a value. The function should return the index where the value is found but ff the value is not
found, it should return -1.
I want to this using a loop and not a method like for example indexOf.

So this is what I got by now:

function getIndex(arr, value) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === value) {
      return i;
    } else {
      return -1;
    }
  }
}

For some reason it keeps returning -1 even if the value if found. What am I doing wrong?

Body:
In the first time your if happen you return no matter what!

If arr[i] == value you return the index, else - you return -1.

What you want to do is return -1 in the case that none of the array elements is found.

function getIndex(arr, value) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === value) {
      return i;
    }
  }
  return -1;
}


问:
how to check if an array contains the elements from a sub array
i want to check i an array contains the elements of any sub array, i.e.
array1 = [10,11,12]
array 2 = [[10, 11],[20, 21],[30, 31],[40, 41]];

array1 will be checked in series by each of array2's sub arrays and if the sub array elements are also in the array1 then to return true.

i've tried thing like:

      array2.some((arr) => {
        return arr.every((square) => {
          return array1.includes(square);
        });
      });
```
<p>or</p>
<pre class="lang-js prettyprint-override"><code>    for (let elem of array2) {
        if (elem.every((x) => array1.includes(x))) {
          return false;
        } else {
          return true;
        }
      }
</code>```

any advice would be helpfull.
thank you

答:
You need to iterate the sub array as well for the sequence.

const
    array1 = [10, 11, 12],
    array2 = [[10, 11], [20, 21], [30, 31], [40, 41]],
    result = array2.some(a => {
        for (let i = 0, l = array1.length - 1; i < l; i++) {
            if (a.every((v, j) => v === array1[i + j])) return true;
        }
        return false;
    });

console.log(result);```

Body:
i want to check i an array contains the elements of any sub array, i.e.
array1 = [10,11,12]
array 2 = [[10, 11],[20, 21],[30, 31],[40, 41]];

array1 will be checked in series by each of array2's sub arrays and if the sub array elements are also in the array1 then to return true.

i've tried thing like:

      array2.some((arr) => {
        return arr.every((square) => {
          return array1.includes(square);
        });
      });

or

    for (let elem of array2) {
        if (elem.every((x) => array1.includes(x))) {
          return false;
        } else {
          return true;
        }
      }

any advice would be helpfull.
thank you


问:
In MySQL, how do I join two fields in one table to the same table's primary key?
I am working with a MySQL backend (version 5.7.19), and a LibreOffice Base frontend(version 7.0.6.2 x64) on 64-bit Windows.  I have a table that lists personnel with a primary key id.  I also have a workorders table that has an "entered by" field and a "reviewed by" field, both of which need to store the id of the personnel who complete those tasks.  If I wanted to have two foreign keys in one table pointing to the same table's primary key, what would my SELECT statement need to look like?

In my case, I have a table 'personnel' with two fields with ID as the primary key, thus:

ID
Name

1
John Smith

2
John Adams

3
Samuel Adams

which can be created and populated thus:

```<code>CREATE TABLE orders(
workorder int(10) unsigned NOT NULL AUTO_INCREMENT,
entered_by int(10) unsigned NOT NULL,
reviewed_by int(10) unsigned NOT NULL,
PRIMARY KEY (workorder),
FOREIGN KEY (entered_by) REFERENCES personnel(id),
FOREIGN KEY (reviewed_by) REFERENCES personnel(id)
);
ALTER TABLE orders AUTO_INCREMENT = 1;
INSERT INTO personnel(name) VALUES('John Smith');
INSERT INTO personnel(name) VALUES('John Adams');
INSERT INTO personnel(name) VALUES('Samuel Adams');
</code>```

Also, a table 'orders' with three fields with entered_by and reviewed_by as foreign keys to personnel.id

workorder
entered_by
reviewed_by

1
2
3

2
3
1

which can be created and populated thus:

```<code>CREATE TABLE orders(
workorder int(10) unsigned NOT NULL AUTO_INCREMENT,
entered_by int(10) unsigned NOT NULL,
reviewed_by int(10) unsigned NOT NULL,
PRIMARY KEY (workorder),
FOREIGN KEY (entered_by) REFERENCES personnel(id),
FOREIGN KEY (reviewed_by) REFERENCES personnel(id)
);
INSERT INTO orders(entered_by, reviewed_by) VALUES (2,3);
INSERT INTO orders(entered_by, reviewed_by) VALUES (3,1);
</code>```

I know how to

```<code>SELECT workorder, personnel.name AS entered
FROM orders JOIN personnel
ON personnel.id = orders.entered_by
ORDER BY orders.workorder;
</code>```

which results in

workorder
entered

1
John Adams

2
Samuel Adams

and how to

```<code>SELECT workorder, personnel.name AS entered
FROM orders JOIN personnel
ON personnel.id = orders.entered_by
ORDER BY orders.workorder;
</code>```

which yields:

workorder
reviewed

1
Samuel Adams

2
John Smith

but I'm not sure how to put them into a single query (that I can use in a query form in Base), so that it will display:

workorder
entered
reviewed

1
John Adams
Samuel Adams

2
Samuel Adams
John Smith

答:
Yes, according to relational algebra every pair of tables can have multiple relationships between them.

For example, the typical illustration of this case, is a money_transfer table that records money flowing from one account to another. In this case this table will have two foreign keys against the account table: one to indicate where the money is coming from, and the other to indicate where money is going to.

Other pairs of tables can have many more relationships between them. I've seen cases for authorization purposes and auditing, that have many FKs.

For example, the requirements stated that the app needed to record who entered the data, who verified it, who accepted it, and who executed the transaction; sometimes it even has "first-level of approval" (for amounts above US$10K) and "second-level of approval" (for amounts above $100K).

EDIT - Joining the Same Table Multiple Times

As requested, when joining the same table multiple times you need to assign different names to each "instance" of the table. Typically this is done by adding an alias to each table instance according to its role.

In this case the roles are "entered by" and "reviewed by", so the query can use the aliases e and r respectively. The query could take the form:

```<code>select o.*, e.name, r.name
from workorders o
join personnel e on e.id = o.entered_by
join personnel r on r.id = o.reviewed_by
</code>```

Body:
I am working with a MySQL backend (version 5.7.19), and a LibreOffice Base frontend(version 7.0.6.2 x64) on 64-bit Windows.  I have a table that lists personnel with a primary key id.  I also have a workorders table that has an "entered by" field and a "reviewed by" field, both of which need to store the id of the personnel who complete those tasks.  If I wanted to have two foreign keys in one table pointing to the same table's primary key, what would my SELECT statement need to look like?

In my case, I have a table 'personnel' with two fields with ID as the primary key, thus:

ID
Name

1
John Smith

2
John Adams

3
Samuel Adams

which can be created and populated thus:

CREATE TABLE orders(
workorder int(10) unsigned NOT NULL AUTO_INCREMENT,
entered_by int(10) unsigned NOT NULL,
reviewed_by int(10) unsigned NOT NULL,
PRIMARY KEY (workorder),
FOREIGN KEY (entered_by) REFERENCES personnel(id),
FOREIGN KEY (reviewed_by) REFERENCES personnel(id)
);
ALTER TABLE orders AUTO_INCREMENT = 1;
INSERT INTO personnel(name) VALUES('John Smith');
INSERT INTO personnel(name) VALUES('John Adams');
INSERT INTO personnel(name) VALUES('Samuel Adams');

Also, a table 'orders' with three fields with entered_by and reviewed_by as foreign keys to personnel.id

workorder
entered_by
reviewed_by

1
2
3

2
3
1

which can be created and populated thus:

CREATE TABLE orders(
workorder int(10) unsigned NOT NULL AUTO_INCREMENT,
entered_by int(10) unsigned NOT NULL,
reviewed_by int(10) unsigned NOT NULL,
PRIMARY KEY (workorder),
FOREIGN KEY (entered_by) REFERENCES personnel(id),
FOREIGN KEY (reviewed_by) REFERENCES personnel(id)
);
INSERT INTO orders(entered_by, reviewed_by) VALUES (2,3);
INSERT INTO orders(entered_by, reviewed_by) VALUES (3,1);

I know how to

SELECT workorder, personnel.name AS entered
FROM orders JOIN personnel
ON personnel.id = orders.entered_by
ORDER BY orders.workorder;

which results in

workorder
entered

1
John Adams

2
Samuel Adams

and how to

SELECT workorder, personnel.name AS entered
FROM orders JOIN personnel
ON personnel.id = orders.entered_by
ORDER BY orders.workorder;

which yields:

workorder
reviewed

1
Samuel Adams

2
John Smith

but I'm not sure how to put them into a single query (that I can use in a query form in Base), so that it will display:

workorder
entered
reviewed

1
John Adams
Samuel Adams

2
Samuel Adams
John Smith

Body:
Yes, according to relational algebra every pair of tables can have multiple relationships between them.

For example, the typical illustration of this case, is a money_transfer table that records money flowing from one account to another. In this case this table will have two foreign keys against the account table: one to indicate where the money is coming from, and the other to indicate where money is going to.

Other pairs of tables can have many more relationships between them. I've seen cases for authorization purposes and auditing, that have many FKs.

For example, the requirements stated that the app needed to record who entered the data, who verified it, who accepted it, and who executed the transaction; sometimes it even has "first-level of approval" (for amounts above US$10K) and "second-level of approval" (for amounts above $100K).

EDIT - Joining the Same Table Multiple Times

As requested, when joining the same table multiple times you need to assign different names to each "instance" of the table. Typically this is done by adding an alias to each table instance according to its role.

In this case the roles are "entered by" and "reviewed by", so the query can use the aliases e and r respectively. The query could take the form:

select o.*, e.name, r.name
from workorders o
join personnel e on e.id = o.entered_by
join personnel r on r.id = o.reviewed_by


问:
TypeError: Cannot read properties of null when using Locomotive Scroll with Next.js
I am trying to use locomotive scroll but but I get an error

I try to use react-locomotive-scroll but get the same error

My _app.tsx looks like this

Where is my mistake? I try to put inside layout component which wraps the entire page, but it didn't work too

```<code>import type { AppProps } from "next/app";
import { ThemeProvider, Global } from "@emotion/react";
import { theme } from "../src/common/theme";
import { globalStyles } from "../src/styles/global";
import { appWithTranslation } from "next-i18next";
import "locomotive-scroll/dist/locomotive-scroll.css";
import { useEffect } from "react";

function MyApp({ Component, pageProps }: AppProps) {
  useEffect(() => {
    let scroll;
    import("locomotive-scroll").then((locomotiveModule) => {
      scroll = new locomotiveModule.default({
        el: document.querySelector("[data-scroll-container]"),
        smooth: true,
        smoothMobile: false,
        resetNativeScroll: true,
      });
    });

    // `useEffect`'s cleanup phase
    return () => scroll.destroy();
  });

  return (
    <ThemeProvider theme={theme}>
      <Global styles={globalStyles(theme)} />
      <Component {...pageProps} data-scroll-container />
    </ThemeProvider>
  );
}

export default appWithTranslation(MyApp);
</code>```

I also use next-transpile-modules

```<code>const withTM = require("next-transpile-modules")(["gsap", "locomotive-scroll"]);
</code>```

答:
The error occurs because no element with the data-scroll-container attribute is present on the DOM.

Setting data-scroll-container in Component doesn't actually add the attribute to any element. Component is a React component, not an HTML element.

You should add a new element that wraps Component and set the attribute on it instead.

    <Component {...pageProps} />

```

Body:
I am trying to use locomotive scroll but but I get an error

I try to use react-locomotive-scroll but get the same error

My _app.tsx looks like this

Where is my mistake? I try to put inside layout component which wraps the entire page, but it didn't work too

import type { AppProps } from "next/app";
import { ThemeProvider, Global } from "@emotion/react";
import { theme } from "../src/common/theme";
import { globalStyles } from "../src/styles/global";
import { appWithTranslation } from "next-i18next";
import "locomotive-scroll/dist/locomotive-scroll.css";
import { useEffect } from "react";

function MyApp({ Component, pageProps }: AppProps) {
  useEffect(() => {
    let scroll;
    import("locomotive-scroll").then((locomotiveModule) => {
      scroll = new locomotiveModule.default({
        el: document.querySelector("[data-scroll-container]"),
        smooth: true,
        smoothMobile: false,
        resetNativeScroll: true,
      });
    });

    // `useEffect`'s cleanup phase
    return () => scroll.destroy();
  });

  return (
    <ThemeProvider theme={theme}>
      <Global styles={globalStyles(theme)} />
      <Component {...pageProps} data-scroll-container />
    </ThemeProvider>
  );
}

export default appWithTranslation(MyApp);

I also use next-transpile-modules

const withTM = require("next-transpile-modules")(["gsap", "locomotive-scroll"]);

Body:
The error occurs because no element with the data-scroll-container attribute is present on the DOM.

Setting data-scroll-container in Component doesn't actually add the attribute to any element. Component is a React component, not an HTML element.

You should add a new element that wraps Component and set the attribute on it instead.

<div data-scroll-container>
    <Component {...pageProps} />
</div>


问:
Visual Studio 2008 unit tests and nunit
When you right click on a method in a code file in Visual Studio 2008 you get this

which creates the unit test skeleton for that method.

Is there a way (by means of a template change or some nifty hack) by which I can change this to create unit tests based on Nunit rather than Visual Studio unit testing tools?

Something like this…

```<code>using System.Collections;
using NUnit.Framework;

    namespace Domain.UnitTest
    {
      [TestFixture]
      public class ManagerTest
      {
        [Test]
        public void SomethingTest()
        {
          string expected = null;
          string acutal = Something.Create();
          Assert.AreEqual(expected, acutal);
        }
</code>```

答:
Try modifying the file C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplatesCache\CSharp\1033\SimpleUnitTest.zip\SimpleUnitTest.cs (after making a backup, of course).  Keep a copy of your updated version elsewhere as this may get overwritten by updates.

FWIW -- I found this by searching for the string using Microsoft.VisualStudio.TestTools.UnitTesting; inside files starting at the top level directory of the VS application directory.

OwnerDisplayName: Cherian

ContentLicense: CC BY-SA 2.5

Title: Visual Studio 2008 unit tests and nunit

Body:
When you right click on a method in a code file in Visual Studio 2008 you get this

which creates the unit test skeleton for that method.

Is there a way (by means of a template change or some nifty hack) by which I can change this to create unit tests based on Nunit rather than Visual Studio unit testing tools?

Something like this…

using System.Collections;
using NUnit.Framework;

    namespace Domain.UnitTest
    {
      [TestFixture]
      public class ManagerTest
      {
        [Test]
        public void SomethingTest()
        {
          string expected = null;
          string acutal = Something.Create();
          Assert.AreEqual(expected, acutal);
        }

OwnerDisplayName: tvanfosson


问:
Playing AVI with PHP readfile()
I have embeded player in  HTML:

```<code><OBJECT id=WindowsMediaPlayer1 width=320 height=264 hspace=5
vspace=5 classid=clsid:6BF52A52-394A-11D3-B153-00C04F79FAA6 border="5" align="middle" >
<param name="URL" value="http://www.my.domain/stream.php">

<EMBED type='application/x-mplayer2'
pluginspage='http://microsoft.com/windows/mediaplayer/en/download/'
id='mediaPlayer' name='mediaPlayer' displaysize='4' autosize='-1'
bgcolor='darkblue' showcontrols="true" showtracker='-1'
showdisplay='0' showstatusbar='-1' videoborder3d='-1' width="320" height="264"
src="http://www.my.domain/stream.php" autostart="0" designtimesp='5311'>
</EMBED>
</OBJECT>
</code>```

stream.php

```<code><?php
$path='/path/to/file/my.avi';
header('Content-type: video/x-msvideo');
header('Content-Length: '.filesize($path));
readfile($path);
?>
</code>```

video is playing when: src="http://www.my.domain/my.avi
video is not playing when: src="http://www.my.domain/stream.php (no pictures)

P.S. mp4,flv,mov works

can you help me?

lubo

答:
I suspect you are sending the wrong content-type header.  It is generally necessary to get that header right, if you want the client to know what type of content it is.

You can verify this by using Fiddler and comparing the headers from when the file is accessed directly, vs. when access via your script.

Title: Playing AVI with PHP readfile()

Body:
I have embeded player in  HTML:

<OBJECT id=WindowsMediaPlayer1 width=320 height=264 hspace=5
vspace=5 classid=clsid:6BF52A52-394A-11D3-B153-00C04F79FAA6 border="5" align="middle" >
<param name="URL" value="http://www.my.domain/stream.php">

<EMBED type='application/x-mplayer2'
pluginspage='http://microsoft.com/windows/mediaplayer/en/download/'
id='mediaPlayer' name='mediaPlayer' displaysize='4' autosize='-1'
bgcolor='darkblue' showcontrols="true" showtracker='-1'
showdisplay='0' showstatusbar='-1' videoborder3d='-1' width="320" height="264"
src="http://www.my.domain/stream.php" autostart="0" designtimesp='5311'>
</EMBED>
</OBJECT>

stream.php

<?php
$path='/path/to/file/my.avi';
header('Content-type: video/x-msvideo');
header('Content-Length: '.filesize($path));
readfile($path);
?>

video is playing when: src="http://www.my.domain/my.avi
video is not playing when: src="http://www.my.domain/stream.php (no pictures)

P.S. mp4,flv,mov works

can you help me?

lubo


问:
Postgres Update multiple JSONB columns
I have a table (postgres 12) with the below schema

```<code>ID (Int)  | Meta (JSONb)

1   | {"id": 1, "source": "a"}
</code>```

I need to update multiple rows to the below format

```<code>ID (Int)  | Meta (JSONb)

1   | {"id": "1", "source": "a"}
</code>```

My only options are

Fetch all records on my application server. update the struct and then update each row individually by looping within a transaction. (Im using go-sqlx which unfortunately doesnt seem to have support for batch updates)

There are about 3k records I have to update. so this seems inefficient

The other idea i had is to try something like this

```<code>update
    tbl
set meta = jsonb_set(meta, 'id' , meta ->> 'id'::text)
where meta ->> 'source' = 'a'
</code>```

This unfortunately doesnt seem to work. is there a way for me to get the old column value here -

jsonb_set(meta, 'id' , "how do i get old json key value here?"::text)

i get the below error

function jsonb_set(jsonb, unknown, text) does not exist....

What is the best approach here?

EDIT based on Edonaurds answer and other threads. I modified the query a bit

```<code>update
    tbl
set meta = jsonb_set(meta, '{id}', (meta->>'id')::jsonb)
where meta ->> 'Source' = 'a'
</code>```

While this updates - i still cant seem to convert the ID field into string

i still get back the original row

答:
try this :</p>
```<code>update
    tbl
set meta = jsonb_set(meta, '{id}' :: text[] , to_jsonb(meta ->> 'id'))
where meta ->> 'source' = 'a'
</code>```

Title: Postgres Update multiple JSONB columns

Body:
I have a table (postgres 12) with the below schema

ID (Int)  | Meta (JSONb)

1   | {"id": 1, "source": "a"}

I need to update multiple rows to the below format

ID (Int)  | Meta (JSONb)

1   | {"id": "1", "source": "a"}

My only options are

Fetch all records on my application server. update the struct and then update each row individually by looping within a transaction. (Im using go-sqlx which unfortunately doesnt seem to have support for batch updates)

There are about 3k records I have to update. so this seems inefficient

The other idea i had is to try something like this

update
    tbl
set meta = jsonb_set(meta, 'id' , meta ->> 'id'::text)
where meta ->> 'source' = 'a'

This unfortunately doesnt seem to work. is there a way for me to get the old column value here -

jsonb_set(meta, 'id' , "how do i get old json key value here?"::text)

i get the below error

function jsonb_set(jsonb, unknown, text) does not exist....

What is the best approach here?

EDIT based on Edonaurds answer and other threads. I modified the query a bit

update
    tbl
set meta = jsonb_set(meta, '{id}', (meta->>'id')::jsonb)
where meta ->> 'Source' = 'a'

While this updates - i still cant seem to convert the ID field into string

i still get back the original row

Body:
try this :

update
    tbl
set meta = jsonb_set(meta, '{id}' :: text[] , to_jsonb(meta ->> 'id'))
where meta ->> 'source' = 'a'


问:
Is it possible to use SQLite in EFS reliably?
Is it possible to use SQLite in AWS EFS safely? In my readings trying to determine if this is viable there appears to be some allusions that it should be doable since AWS EFS implemented NFSv4 back in 2017. In practice I am having no luck getting consistent behavior out of it.

Quick Points:

"Just use AWS RDS": Due to issues with other AWS architecture another team has implemented we are trying to work around resource starving cause by the API (DynamoDB isn't an option)

"This goes against SQLite's primary use case (being a locally access DB): Yes, but given the circumstances it seems like the best approach.

I have verified that we are running nfsv4 on our EC2 instance

Current results are very inconsistent with 3 exceptions encountered irrespective of approach I use

"file is encrypted or is not a database"

"disk I/O error (potentially related to EFS open file limits)"

"database disk image is malformed" (The database actually isn't corrupted after this)

database code:

```<code>SQLITE_VAR_LIMIT = 999
dgm_db_file_name = ''
db = SqliteExtDatabase(None)
lock_file = f'{os.getenv("efs_path", "tmp")}/db_lock_file.lock'

def lock_db_file():
    with open(lock_file, 'w+') as lock:
        limit = 900
        while limit:
            try:
                fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
                print(f'db locked')
                break
            except Exception as e:
                print(f'Exception: {str(e)}')
                limit -= 1
                time.sleep(1)

    if not limit:
        raise ValueError(f'Timed out after 900 seconds while waiting for database lock.')

def unlock_db_file():
    with open(lock_file, 'w+') as lock:
        fcntl.flock(lock, fcntl.LOCK_UN)
        print(f'db unlocked')

def initialize_db(db_file_path=dgm_db_file_name):
    print(f'Initializing db ')
    global db
    db.init(db_file_path, pragmas={
        'journal_mode': 'wal',
        'cache_size': -1 * 64000,  # 64MB
        'foreign_keys': 1})
    print(f'db initialized')

class Thing(Model):
    name = CharField(primary_key=True)
    etag = CharField()
    last_modified = CharField()

    class Meta:
        database = db

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    @staticmethod
    def insert_many(stuff):
        data = [(k, v['ETag'], v['Last-Modified']) for k, v in stuff.items()]
        fields = [Thing.name, Thing.etag, Thing.last_modified]
        limit = 900
        while True:
            try:
                with db.atomic():
                    for key_batch in chunked(data, SQLITE_VAR_LIMIT // len(fields)):
                        s = Thing.insert_many(key_batch, fields=[Thing.name, Thing.etag, Thing.last_modified]) \
                            .on_conflict_replace().execute()
                break
            except Exception as e:
                print(f'Exception: {str(e)}')
                print(f'Will try for {limit} more seconds.')
                limit -= 1
                time.sleep(1)

        if not limit:
            raise ValueError('Failed to exectue query after 900 seconds.')
</code>```

Example Call:

```<code>        print(f'Critical section start')
        # lock_db_file() # I have tried with a secondary lock file as well
        self.stuff_db = Thing()
        if not Path(self.db_file_path).exists():
            initialize_db(self.db_file_path)
            print('creating tables')
            db.create_tables([Thing], safe=True)
        else:
            initialize_db(self.db_file_path)

        getattr(Thing, insert_many)(self.stuff_db, stuff_db)
        # db.close()
        # unlock_db_file()
        print(f'Critical section end')
        print(f'len after update: {len(stuff)}')
</code>```

Additional peculiarities:

If a lamda gets stuck catching the "malformed image" exception and a new lambda execution is triggered, the error resolves in the other lambda.

答:
After some trial and error I discovered it is a workable solution. It appears that the design will need to use APSWDatabase(..., vfs='unix-excl') to properly enforce locking.

Database code:

```<code>from peewee import *
from playhouse.apsw_ext import APSWDatabase

SQLITE_VAR_LIMIT = 999
db = APSWDatabase(None, vfs='unix-excl')

def initialize_db(db_file_path):
    global db
    db.init(db_file_path, pragmas={
        'journal_mode': 'wal',
        'cache_size': -1 * 64000})
    db.create_tables([Thing], safe=True)

    return Thing()

class Thing(Model):
    field_1 = CharField(primary_key=True)
    field_2 = CharField()
    field_3 = CharField()

    class Meta:
        database = db
</code>```

This allows for the following usage:

```<code>        db_model = initialize_db(db_file_path)
        with db:
            # Do database queries here with the db_model
            pass
</code>```

Note: If you don't use the context managed database connection you will need to explicitly call db.close() otherwise the lock will not be released from the file. Additionally, calling db_init(...) causes a lock to be placed on the databased until it is closed.

Body:
Is it possible to use SQLite in AWS EFS safely? In my readings trying to determine if this is viable there appears to be some allusions that it should be doable since AWS EFS implemented NFSv4 back in 2017. In practice I am having no luck getting consistent behavior out of it.

Quick Points:

"Just use AWS RDS": Due to issues with other AWS architecture another team has implemented we are trying to work around resource starving cause by the API (DynamoDB isn't an option)

"This goes against SQLite's primary use case (being a locally access DB): Yes, but given the circumstances it seems like the best approach.

I have verified that we are running nfsv4 on our EC2 instance

Current results are very inconsistent with 3 exceptions encountered irrespective of approach I use

"file is encrypted or is not a database"

"disk I/O error (potentially related to EFS open file limits)"

"database disk image is malformed" (The database actually isn't corrupted after this)

database code:

SQLITE_VAR_LIMIT = 999
dgm_db_file_name = ''
db = SqliteExtDatabase(None)
lock_file = f'{os.getenv("efs_path", "tmp")}/db_lock_file.lock'

def lock_db_file():
    with open(lock_file, 'w+') as lock:
        limit = 900
        while limit:
            try:
                fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
                print(f'db locked')
                break
            except Exception as e:
                print(f'Exception: {str(e)}')
                limit -= 1
                time.sleep(1)

    if not limit:
        raise ValueError(f'Timed out after 900 seconds while waiting for database lock.')

def unlock_db_file():
    with open(lock_file, 'w+') as lock:
        fcntl.flock(lock, fcntl.LOCK_UN)
        print(f'db unlocked')

def initialize_db(db_file_path=dgm_db_file_name):
    print(f'Initializing db ')
    global db
    db.init(db_file_path, pragmas={
        'journal_mode': 'wal',
        'cache_size': -1 * 64000,  # 64MB
        'foreign_keys': 1})
    print(f'db initialized')

class Thing(Model):
    name = CharField(primary_key=True)
    etag = CharField()
    last_modified = CharField()

    class Meta:
        database = db

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    @staticmethod
    def insert_many(stuff):
        data = [(k, v['ETag'], v['Last-Modified']) for k, v in stuff.items()]
        fields = [Thing.name, Thing.etag, Thing.last_modified]
        limit = 900
        while True:
            try:
                with db.atomic():
                    for key_batch in chunked(data, SQLITE_VAR_LIMIT // len(fields)):
                        s = Thing.insert_many(key_batch, fields=[Thing.name, Thing.etag, Thing.last_modified]) \
                            .on_conflict_replace().execute()
                break
            except Exception as e:
                print(f'Exception: {str(e)}')
                print(f'Will try for {limit} more seconds.')
                limit -= 1
                time.sleep(1)

        if not limit:
            raise ValueError('Failed to exectue query after 900 seconds.')

Example Call:

        print(f'Critical section start')
        # lock_db_file() # I have tried with a secondary lock file as well
        self.stuff_db = Thing()
        if not Path(self.db_file_path).exists():
            initialize_db(self.db_file_path)
            print('creating tables')
            db.create_tables([Thing], safe=True)
        else:
            initialize_db(self.db_file_path)

        getattr(Thing, insert_many)(self.stuff_db, stuff_db)
        # db.close()
        # unlock_db_file()
        print(f'Critical section end')
        print(f'len after update: {len(stuff)}')

Additional peculiarities:

If a lamda gets stuck catching the "malformed image" exception and a new lambda execution is triggered, the error resolves in the other lambda.

Body:
After some trial and error I discovered it is a workable solution. It appears that the design will need to use APSWDatabase(..., vfs='unix-excl') to properly enforce locking.

Database code:

from peewee import *
from playhouse.apsw_ext import APSWDatabase

SQLITE_VAR_LIMIT = 999
db = APSWDatabase(None, vfs='unix-excl')

def initialize_db(db_file_path):
    global db
    db.init(db_file_path, pragmas={
        'journal_mode': 'wal',
        'cache_size': -1 * 64000})
    db.create_tables([Thing], safe=True)

    return Thing()

class Thing(Model):
    field_1 = CharField(primary_key=True)
    field_2 = CharField()
    field_3 = CharField()

    class Meta:
        database = db

This allows for the following usage:

        db_model = initialize_db(db_file_path)
        with db:
            # Do database queries here with the db_model
            pass

Note: If you don't use the context managed database connection you will need to explicitly call db.close() otherwise the lock will not be released from the file. Additionally, calling db_init(...) causes a lock to be placed on the databased until it is closed.


问:
I need help to get vision on server client program in python
I work in office
We have 11 branches, in 7 city
That each of them have about 10 pc.
They are connected under activ directory.

I want write application, that outomatically pop up screen in users desktop for seconds,  and show them message ,then disappear.

Im intermediate in python
What should i know and what libs need To be able do it?

答:
try to start from this topic for creating a pop-up in the windows system:

The result looks like this:

As one of the possible cases of implementation, the receiving these messages could be performed through RabbitMQ (pika library for python)


问:
NUKE Build: Could not find a suitable MSBuild instance (Visual Studio 2022)
After upgrade Visual Studio 2019 to 2022, I got the following error when I try to build the project with NUKE Build (Debug/Release):

```<code>╬════════════
║ Compile
╬═══

Assertion failed: Could not find a suitable MSBuild instance.
   at Nuke.Common.Tools.MSBuild.MSBuildToolPathResolver.Resolve(Nullable`1 msBuildVersion, Nullable`1 msBuildPlatform)
   at Nuke.Common.Tools.MSBuild.MSBuildSettings.GetProcessToolPath()
   at Nuke.Common.Tools.MSBuild.MSBuildSettings.get_ProcessToolPath()
   at Nuke.Common.Tooling.ProcessTasks.StartProcess(ToolSettings toolSettings)
   at Nuke.Common.Tools.MSBuild.MSBuildTasks.MSBuild(MSBuildSettings toolSettings)
   at Nuke.Common.Tools.MSBuild.MSBuildTasks.MSBuild(Configure`1 configurator)
   at AREGIS.Build.DeagBuild.<get_Compile>b__21_1() in C:\Work.Vertex\Vertex\40 Build\DeagBuild.cs:line 98
   at Nuke.Common.Execution.BuildExecutor.<>c.<Execute>b__4_2(Action x)
   at Nuke.Common.Utilities.Collections.EnumerableExtensions.ForEach[T](IEnumerable`1 enumerable, Action`1 action)
   at Nuke.Common.Execution.BuildExecutor.Execute(NukeBuild build, ExecutableTarget target, IReadOnlyCollection`1 previouslyExecutedTargets, Boolean failureMode)

Repeating warnings and errors:
Assertion failed: Could not find a suitable MSBuild instance.
</code>```

Compile method:

```<code>        Target Compile => _ => _
        .DependsOn(this.RestoreFramework)
        .Executes(() =>
        {
            var compileOutput = MSBuild(x => x
                .SetTargetPath(this.MySolution)
                .Set...
                .Set...
                );
        });
</code>```

Target framework: .NET Framework 4.8

Is there any way to fix it?

答:
To add to this answer: https://stackoverflow.com/a/70097525/569302

I am using Visual Studio Community 2022 right now:

For me the path was: C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin\MSBuild.exe

Body:
After upgrade Visual Studio 2019 to 2022, I got the following error when I try to build the project with NUKE Build (Debug/Release):

╬════════════
║ Compile
╬═══

Assertion failed: Could not find a suitable MSBuild instance.
   at Nuke.Common.Tools.MSBuild.MSBuildToolPathResolver.Resolve(Nullable`1 msBuildVersion, Nullable`1 msBuildPlatform)
   at Nuke.Common.Tools.MSBuild.MSBuildSettings.GetProcessToolPath()
   at Nuke.Common.Tools.MSBuild.MSBuildSettings.get_ProcessToolPath()
   at Nuke.Common.Tooling.ProcessTasks.StartProcess(ToolSettings toolSettings)
   at Nuke.Common.Tools.MSBuild.MSBuildTasks.MSBuild(MSBuildSettings toolSettings)
   at Nuke.Common.Tools.MSBuild.MSBuildTasks.MSBuild(Configure`1 configurator)
   at AREGIS.Build.DeagBuild.<get_Compile>b__21_1() in C:\Work.Vertex\Vertex\40 Build\DeagBuild.cs:line 98
   at Nuke.Common.Execution.BuildExecutor.<>c.<Execute>b__4_2(Action x)
   at Nuke.Common.Utilities.Collections.EnumerableExtensions.ForEach[T](IEnumerable`1 enumerable, Action`1 action)
   at Nuke.Common.Execution.BuildExecutor.Execute(NukeBuild build, ExecutableTarget target, IReadOnlyCollection`1 previouslyExecutedTargets, Boolean failureMode)

Repeating warnings and errors:
Assertion failed: Could not find a suitable MSBuild instance.

Compile method:

        Target Compile => _ => _
        .DependsOn(this.RestoreFramework)
        .Executes(() =>
        {
            var compileOutput = MSBuild(x => x
                .SetTargetPath(this.MySolution)
                .Set...
                .Set...
                );
        });

Target framework: .NET Framework 4.8

Is there any way to fix it?


问:
How to create a 2D array of size nxn according to the following rules?
How can I create a 2D array of size nxn according to the following rules:

On the main diagonal put 0

On the diagonal adjacent to main put 1

On the next diagonal put 2, and so forth

Example:

```<code>n = 5

output = [[0, 1, 2, 3, 4],
          [1, 0, 1, 2, 3],
          [2, 1, 0, 1, 2],
          [3, 2, 1, 0, 1],
          [4, 3, 2, 1, 0]]
</code>```

Preferably I would like to print every row on a single line.

I probably has to do with 2D array offsets, but more than that I am stumped.

答:
You can find the grid distance of each cell by doing abs(i - j). When they're equal, then you must be on the diagonal, so the difference is zero. One off the diagonal would make the difference 1, two off the diagonal would be 2, etc.

This is easy to do in a nested list comprehension:

```<code>n = 5
output = [[abs(i - j) for i in range(n)] for j in range(n)]

# print each row on its own line
import pprint
pprint.pprint(output)
# [[0, 1, 2, 3, 4],
#  [1, 0, 1, 2, 3],
#  [2, 1, 0, 1, 2],
#  [3, 2, 1, 0, 1],
#  [4, 3, 2, 1, 0]]
</code>```

Body:
How can I create a 2D array of size nxn according to the following rules:

On the main diagonal put 0

On the diagonal adjacent to main put 1

On the next diagonal put 2, and so forth

Example:

n = 5

output = [[0, 1, 2, 3, 4],
          [1, 0, 1, 2, 3],
          [2, 1, 0, 1, 2],
          [3, 2, 1, 0, 1],
          [4, 3, 2, 1, 0]]

Preferably I would like to print every row on a single line.

I probably has to do with 2D array offsets, but more than that I am stumped.

Body:
You can find the grid distance of each cell by doing abs(i - j). When they're equal, then you must be on the diagonal, so the difference is zero. One off the diagonal would make the difference 1, two off the diagonal would be 2, etc.

This is easy to do in a nested list comprehension:

n = 5
output = [[abs(i - j) for i in range(n)] for j in range(n)]

# print each row on its own line
import pprint
pprint.pprint(output)
# [[0, 1, 2, 3, 4],
#  [1, 0, 1, 2, 3],
#  [2, 1, 0, 1, 2],
#  [3, 2, 1, 0, 1],
#  [4, 3, 2, 1, 0]]


问:
Specific Time Range Query in SQL Server
I'm trying to query a specific range of time:

i.e. 3/1/2009 - 3/31/2009

between 6AM-10PM each day

Tues/Wed/Thurs only

I've seen that you can get data for a particular range, but only for start to end and this is quite a bit more specific.  I didn't see any SQL Server commands that would directly help me on this, so does anybody else have any thoughts on how you would form this?

I've seen this, but I don't think it's nearly specific enough for this range.

Thanks!

答:
If you want to get results for specific time period, use the query below:</p>
```<code>Select * from [your_table_name]
where date between '2021-10-05' AND '2021-12-10'
</code>```

Title: Specific Time Range Query in SQL Server

Body:
If you want to get results for specific time period, use the query below:

Select * from [your_table_name]
where date between '2021-10-05' AND '2021-12-10'


问:
Intercepting (Consuming) key events
I can successfully detect when the user has hit the ENTER key in a TextField by wrapping the TextField in a RawKeyboardListener and using the onKey function.  However, I want to prevent the TextField from receiving the ENTER keystroke and adding a new line.  How can I prevent the ENTER keystroke from being passed to the TextField?

答:
use focusNode:

```<code>final focusNode = FocusNode(onKey: (node, event) {
  if (event.isKeyPressed(LogicalKeyboardKey.enter)) {
    return KeyEventResult.handled;
  }
  return KeyEventResult.ignored;
});
</code>```

and then pass focusNode to your TextField

The FocusManager receives key events from RawKeyboard and
HardwareKeyboard and will pass them to the focused nodes. It starts
with the node with the primary focus, and will call the onKey or
onKeyEvent callback for that node. If the callback returns
KeyEventResult.ignored, indicating that it did not handle the event,
the FocusManager will move to the parent of that node and call its
onKey or onKeyEvent. If that onKey or onKeyEvent returns
KeyEventResult.handled, then it will stop propagating the event. If it
reaches the root FocusScopeNode, FocusManager.rootScope, the event is
discarded.

Title: Intercepting (Consuming) key events

Body:
use focusNode:

final focusNode = FocusNode(onKey: (node, event) {
  if (event.isKeyPressed(LogicalKeyboardKey.enter)) {
    return KeyEventResult.handled;
  }
  return KeyEventResult.ignored;
});

and then pass focusNode to your TextField

The FocusManager receives key events from RawKeyboard and
HardwareKeyboard and will pass them to the focused nodes. It starts
with the node with the primary focus, and will call the onKey or
onKeyEvent callback for that node. If the callback returns
KeyEventResult.ignored, indicating that it did not handle the event,
the FocusManager will move to the parent of that node and call its
onKey or onKeyEvent. If that onKey or onKeyEvent returns
KeyEventResult.handled, then it will stop propagating the event. If it
reaches the root FocusScopeNode, FocusManager.rootScope, the event is
discarded.


问:
Positioning of bootstrap modal in blazor page
i am fairly new in web coding word so i ask sorry if there are some obvious error i am unaware of. I was challenging myself on using a modal inside a toy project i was working on, but i'm having some trouble

As you can see, my modal is not modal at all. It just appear under the grid.

```<code>@page "/"

<PageTitle>Index</PageTitle>

<div>
    <div>
        <h1 id="impListH">TestApp</h1> <button id="impListB" class="btn btn-primary" @onclick="@(() => { showModal = true; })" >Importa</button>
    </div>
    <br />
    <br />
    <DataGrid TItem="Employee" MySource="employees" Columns="columnDefinitions"></DataGrid>
</div>

@if (showModal)
{
    <div class="modal-dialog" tabindex="-1" role="dialog" style="display: initial;" id="myModal">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Modal title</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">
                    <p>
                        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Omnes enim iucundum motum, quo sensus hilaretur.
                        <i>Quis istud possit, inquit, negare?</i>
                        <mark>Ego vero isti, inquam, permitto.</mark> Duo Reges: constructio interrete.
                    </p>
                    <FetchData />
                    <dl>
                        <dt><dfn>Stoici scilicet.</dfn></dt>
                        <dd>An hoc usque quaque, aliter in vita?</dd>
                        <dt><dfn>Erat enim Polemonis.</dfn></dt>
                        <dd>Quod cum accidisset ut alter alterum necopinato videremus, surrexit statim.</dd>
                    </dl>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary">Save changes</button>
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
}
</code>```

i followed this answer to build the model. I really don't understand what is wrong. Can you help me?

答:
Per Bootstrap's Modal Documentation

Your root div should use the class modal instead of modal-dialog.
the following changes should fix your issue:

```<code>@if (showModal)
{
    <div class="modal" tabindex="-1" role="dialog" style="display: initial;" id="myModal">
        <div class="modal-dialog" role="document">
</code>```

Body:
i am fairly new in web coding word so i ask sorry if there are some obvious error i am unaware of. I was challenging myself on using a modal inside a toy project i was working on, but i'm having some trouble

As you can see, my modal is not modal at all. It just appear under the grid.

@page "/"

<PageTitle>Index</PageTitle>

TestApp
 <button id="impListB" class="btn btn-primary" @onclick="@(() => { showModal = true; })" >Importa</button>

    <DataGrid TItem="Employee" MySource="employees" Columns="columnDefinitions"></DataGrid>

@if (showModal)
{

Modal title

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        ×
                    </button>

                        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Omnes enim iucundum motum, quo sensus hilaretur.
                        Quis istud possit, inquit, negare?
                        Ego vero isti, inquam, permitto. Duo Reges: constructio interrete.

                    <FetchData />

<dfn>Stoici scilicet.</dfn>

An hoc usque quaque, aliter in vita?

<dfn>Erat enim Polemonis.</dfn>

Quod cum accidisset ut alter alterum necopinato videremus, surrexit statim.

                    <button type="button" class="btn btn-primary">Save changes</button>
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

}

i followed this answer to build the model. I really don't understand what is wrong. Can you help me?

Body:
Per Bootstrap's Modal Documentation

Your root div should use the class modal instead of modal-dialog.
the following changes should fix your issue:

@if (showModal)
{
    <div class="modal" tabindex="-1" role="dialog" style="display: initial;" id="myModal">
        <div class="modal-dialog" role="document">


问:
React Router Dom Relative Path
I have an application published in a domain similar to this "www.domain.com/app/client/store"

When I developed it at the beginning, it was not contemplated that the domain be that way but something like "www.domain.com" the issue is that it is causing problems with the Router

when you access the initial route "www.domain.com/app/client/store" it does not find the path that is the login and jumps to management

I need that regardless of the url always find the initial path which "/"

My router currently looks like this

```<code>const Routes = () => {
  return (
    <Router>
      <Switch>
        <Route exact path="/" component={Login} />
        <Route exact path="/main" component={Main} />
        <Route exact path="/main/:id" component={Main} />
        <Route exact="/management" component={Management} />
      </Switch>
    </Router>
  );
};
</code>```

The domain will be relative so it is not a good idea to put the absolute URL in the path

How can I make the route relative and not affect the initial page of the application?

The routes would be more or less like this

"www.domain.com/app/client1/store5"
"www.domain.com/app/client5/store1"
"www.domain.com/app/client2/store3"

Thanks in advance for your help and feedback

答:
In order to properly route, your path requires the public URL appended to every route.

```<code>const baseURL = process.env.PUBLIC_URL;

const Routes = () => {
  return (
    <Router>
      <Switch>
        <Route exact path="${baseURL}/" component={Login} />
        <Route exact path="${baseURL}/main" component={Main} />
        <Route exact path="${baseURL}/main/:id" component={Main} />
        <Route exact="${baseURL}/management" component={Management} />
      </Switch>
    </Router>
  );
};

</code>```

Something like that should work. There are also packages out there you could use in order to make life easier that would automatically append this, But this is a pretty simple approach.

Title: React Router Dom Relative Path

Body:
I have an application published in a domain similar to this "www.domain.com/app/client/store"

When I developed it at the beginning, it was not contemplated that the domain be that way but something like "www.domain.com" the issue is that it is causing problems with the Router

when you access the initial route "www.domain.com/app/client/store" it does not find the path that is the login and jumps to management

I need that regardless of the url always find the initial path which "/"

My router currently looks like this

const Routes = () => {
  return (
    <Router>
      <Switch>
        <Route exact path="/" component={Login} />
        <Route exact path="/main" component={Main} />
        <Route exact path="/main/:id" component={Main} />
        <Route exact="/management" component={Management} />
      </Switch>
    </Router>
  );
};

The domain will be relative so it is not a good idea to put the absolute URL in the path

How can I make the route relative and not affect the initial page of the application?

The routes would be more or less like this

"www.domain.com/app/client1/store5"
"www.domain.com/app/client5/store1"
"www.domain.com/app/client2/store3"

Thanks in advance for your help and feedback

Body:
In order to properly route, your path requires the public URL appended to every route.

const baseURL = process.env.PUBLIC_URL;

const Routes = () => {
  return (
    <Router>
      <Switch>
        <Route exact path="${baseURL}/" component={Login} />
        <Route exact path="${baseURL}/main" component={Main} />
        <Route exact path="${baseURL}/main/:id" component={Main} />
        <Route exact="${baseURL}/management" component={Management} />
      </Switch>
    </Router>
  );
};

Something like that should work. There are also packages out there you could use in order to make life easier that would automatically append this, But this is a pretty simple approach.


问:
Must consteval constructor initialize all data members?
In the next program struct B has immediate consteval default constructor, which does not initialize i field. Then this constructor is used to make a temporary and its i field remains untouched:

```<code>struct B {
    bool b = true;
    int i;
    consteval B() {}
};

static_assert( B{}.b );
</code>```

Clang and MSVC are fine with it. But GCC complains:

```<code> error: 'B{true}' is not a constant expression
    7 | static_assert( B{}.b );
      |                  ^
error: 'B()' is not a constant expression because it refers to an incompletely initialized variable
</code>```

Demo: https://gcc.godbolt.org/z/x4n6ezrhT

Which compiler is right here?

Update:

I reported this issue to GCC: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=104512
And it was closed with the explanation

This gives the hint that both MSVC and clang are incorrect really. EDG also implements correctly static_assert not being an immediate function context.

答:
From cppreference's consteval specifier (since C++20):

The consteval specifier declares a function or function template to be
an immediate function,

...

An immediate function is a constexpr function, and must satisfy the
requirements applicable to constexpr functions or constexpr
constructors, as the case may be.

And if we go to cppreference's constexpr specifier (since C++11):

A constexpr function must satisfy the following requirements:

...

A constexpr constructor whose function body is not =delete; must satisfy the following additional requirements:

...

for the constructor of a class or struct, every base class sub-object
and every non-variant non-static data member must be initialized.

However, as @user17732522 accurately pointed out in a comment below, this last requirement applies only until C++20.

So I would say i doesn't need to be initialized in this case (Clang/MSVC are correct, gcc is wrong).

Body:
In the next program struct B has immediate consteval default constructor, which does not initialize i field. Then this constructor is used to make a temporary and its i field remains untouched:

struct B {
    bool b = true;
    int i;
    consteval B() {}
};

static_assert( B{}.b );

Clang and MSVC are fine with it. But GCC complains:

 error: 'B{true}' is not a constant expression
    7 | static_assert( B{}.b );
      |                  ^
error: 'B()' is not a constant expression because it refers to an incompletely initialized variable

Demo: https://gcc.godbolt.org/z/x4n6ezrhT

Which compiler is right here?

Update:

I reported this issue to GCC: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=104512
And it was closed with the explanation

This gives the hint that both MSVC and clang are incorrect really. EDG also implements correctly static_assert not being an immediate function context.


问:
When using subprocess.Popen to create tmux sessions is it possible to change the envionment variables for each new tmux session spawned from Popen?
I'm trying to spawn multiple tmux sessions with different environment variables from the same python3 script.

I have been arguing {**os.environ, "CUDA_VISIBLE_DEVICES":str(device_id)} to the env key word argument to subprocess.Popen.

```<code>for device_id in device_ids:
    new_env = {**os.environ, "CUDA_VISIBLE_DEVICES":str(device_id)}
    p = subprocess.Popen([
        'tmux', 'new', '-d', "-c", "./", '-s',
        sesh_name,
        "python3",
        path_to_script
    ], env=new_env)
</code>```

I'm finding that the CUDA_VISIBLE_DEVICES parameter, however, is equal to the first device_id that I argue across all processes. What is the meaning of this!?

Is this an inherent issue with Popen and the subprocess module? If so, how do I fix it?

I've tried to argue the device id to the script of the new process, but sadly torch won't allow me to update the environment variable after it's been imported and it would be way more trouble than it's worth to rework the code for that.

EDIT: Providing minimal example

Save this script as test.py (or whatever else you fancy):

import subprocess
import os

def sesh(name):
    procs = []
    for device_id in [4,5,6]:
        proc_env = {**os.environ, "CUDA_VISIBLE_DEVICES": str(device_id)}
        p = subprocess.Popen(['tmux', 'new', '-d', "-c", "./", '-s', name+str(device_id), "python3", "deleteme.py"], env=proc_env)
        procs.append(p)
    return procs

if __name__=="__main__":
    sesh("foo")
```
<p>Save this script as <code>deleteme.py</code> within the same directory:</p>
<pre class="lang-py prettyprint-override"><code>import time
import os

if __name__=="__main__":
    print(os.environ)
    for i in range(11):
        print("running")
        if "CUDA_VISIBLE_DEVICES" in os.environ:
            print(os.environ["CUDA_VISIBLE_DEVICES"])
        else:
            print("CUDA_VISIBLE_DEVICES not found")
        time.sleep(5)
</code>```

Then run test.py from the terminal.

```<code>$ python3 test.py
</code>```

Then switch to the tmux sessions to figure out what environment is being created.

答:
For anyone else running into this problem, you can use os.system instead of subprocess.Popen in the following way.

import os

def sesh(name, device_id, script):
    command = "tmux new -d -s \"{}{}\" \'export CUDA_VISIBLE_DEVICES={}; python3 {} \'"
    command = command.format(
        name,
        device_id,
        device_id,
        script
    )
    os.system(command)

if __name__=="__main__":
    sesh("foo", 4, "deleteme.py")
```

Body:
I'm trying to spawn multiple tmux sessions with different environment variables from the same python3 script.

I have been arguing {**os.environ, "CUDA_VISIBLE_DEVICES":str(device_id)} to the env key word argument to subprocess.Popen.

for device_id in device_ids:
    new_env = {**os.environ, "CUDA_VISIBLE_DEVICES":str(device_id)}
    p = subprocess.Popen([
        'tmux', 'new', '-d', "-c", "./", '-s',
        sesh_name,
        "python3",
        path_to_script
    ], env=new_env)

I'm finding that the CUDA_VISIBLE_DEVICES parameter, however, is equal to the first device_id that I argue across all processes. What is the meaning of this!?

Is this an inherent issue with Popen and the subprocess module? If so, how do I fix it?

I've tried to argue the device id to the script of the new process, but sadly torch won't allow me to update the environment variable after it's been imported and it would be way more trouble than it's worth to rework the code for that.

EDIT: Providing minimal example

Save this script as test.py (or whatever else you fancy):

import subprocess
import os

def sesh(name):
    procs = []
    for device_id in [4,5,6]:
        proc_env = {**os.environ, "CUDA_VISIBLE_DEVICES": str(device_id)}
        p = subprocess.Popen(['tmux', 'new', '-d', "-c", "./", '-s', name+str(device_id), "python3", "deleteme.py"], env=proc_env)
        procs.append(p)
    return procs

if __name__=="__main__":
    sesh("foo")

Save this script as deleteme.py within the same directory:

import time
import os

if __name__=="__main__":
    print(os.environ)
    for i in range(11):
        print("running")
        if "CUDA_VISIBLE_DEVICES" in os.environ:
            print(os.environ["CUDA_VISIBLE_DEVICES"])
        else:
            print("CUDA_VISIBLE_DEVICES not found")
        time.sleep(5)

Then run test.py from the terminal.

$ python3 test.py

Then switch to the tmux sessions to figure out what environment is being created.


问:
I can't figure out why can't pass my variables in main
I try to pass variables to my employee class but I can't see to figure out why it isn't working. I was following along with a tutorial explaining how it works but did cover how to do with already declared variables. So what do take variables initialized in main and pass them employee so I can use function raise to calculate raise later in the code. Im writing this text to padd the word count so I can post it. How much padding does it what.</p>
```<code>class Employee
{
private:
        string name;
        int yearjoined;
        double monthlySalary;

public:

    Employee()
    {
        name = " ";
        yearjoined = 0;
        monthlySalary = 0;
    }

    void raise(string workerName, int yearJoin, double salary);

    Employee(string workerName, int yearJoin, double salary)
    {
        int yearsworked;
        name = workerName;
        yearjoined = yearJoin;
        monthlySalary = salary;

        cout << name;
        cout << yearjoined;
        cout << monthlySalary;
        /*raise(monthlySalary);*/

    }

    void raise(double salary)
        {

        }

};

int main()
{

    string userName;
    int userStart;
    double userSalary;

    cout << "What is you name?";
    cin >> userName;
    cout << "What year did you join the company?";
    cin >> userStart;
    cout << "What is you monthly salary?";
    cin >> userSalary;
    Employee worker(string userName, int userStart, double userSalary);
    worker(userName, userStart, userSalary);

}
</code>```

答:
You made one error trying to pass the variables, which made the compiler think you wanted something completely different.

This line:

```<code>Employee worker(string userName, int userStart, double userSalary);
</code>```

The compiler understands it as deceleration of a function named worker that receives 3 arguments and returns an object of class Employee.

This is because you wrote types and variable names in the brackets.

Next, this line:

```<code>worker(userName, userStart, userSalary);
</code>```

The compiler now thinks you want to call the worker function you declared in the previous line (because you wrote nothing before worker), but when it comes the time to link your code (put it together with all functions it needs), there is no function worker defined anywhere, so you get an error.

What you need to do, is combine those 2 line in one like this:

```<code>Employee worker(userName, userStart, userSalary);
</code>```

Now you are telling the compiler to create a variable of type Employee and initialize it with 3 values using the constructor you wrote.

Body:
I try to pass variables to my employee class but I can't see to figure out why it isn't working. I was following along with a tutorial explaining how it works but did cover how to do with already declared variables. So what do take variables initialized in main and pass them employee so I can use function raise to calculate raise later in the code. Im writing this text to padd the word count so I can post it. How much padding does it what.

class Employee
{
private:
        string name;
        int yearjoined;
        double monthlySalary;

public:

    Employee()
    {
        name = " ";
        yearjoined = 0;
        monthlySalary = 0;
    }

    void raise(string workerName, int yearJoin, double salary);

    Employee(string workerName, int yearJoin, double salary)
    {
        int yearsworked;
        name = workerName;
        yearjoined = yearJoin;
        monthlySalary = salary;

        cout << name;
        cout << yearjoined;
        cout << monthlySalary;
        /*raise(monthlySalary);*/

    }

    void raise(double salary)
        {

        }

};

int main()
{

    string userName;
    int userStart;
    double userSalary;

    cout << "What is you name?";
    cin >> userName;
    cout << "What year did you join the company?";
    cin >> userStart;
    cout << "What is you monthly salary?";
    cin >> userSalary;
    Employee worker(string userName, int userStart, double userSalary);
    worker(userName, userStart, userSalary);

}

Body:
You made one error trying to pass the variables, which made the compiler think you wanted something completely different.

This line:

Employee worker(string userName, int userStart, double userSalary);

The compiler understands it as deceleration of a function named worker that receives 3 arguments and returns an object of class Employee.

This is because you wrote types and variable names in the brackets.

Next, this line:

worker(userName, userStart, userSalary);

The compiler now thinks you want to call the worker function you declared in the previous line (because you wrote nothing before worker), but when it comes the time to link your code (put it together with all functions it needs), there is no function worker defined anywhere, so you get an error.

What you need to do, is combine those 2 line in one like this:

Employee worker(userName, userStart, userSalary);

Now you are telling the compiler to create a variable of type Employee and initialize it with 3 values using the constructor you wrote.


问:
IIS ASP.NET 6 startup throws System.IO.DirectoryNotFoundException: D:\agent\_work\38\s\IdentityServer\wwwroot\
We are updating one of our applications, in this case IdentityServer, from .NET 5 to .NET 6.  It is being hosted by IIS and deployed by Azure Devops Services.  The issue we are seeing is that on our development environment the website fails to load but on our staging environment it runs just fine.  The error we are seeing on development is

```<code>12:45:37.519|Fatal|1||Host terminated unexpectedly.||
System.IO.DirectoryNotFoundException: D:\agent\_work\38\s\IdentityServer\wwwroot\
   at Microsoft.Extensions.FileProviders.PhysicalFileProvider..ctor(String root, ExclusionFilters filters)
   at Microsoft.Extensions.FileProviders.PhysicalFileProvider..ctor(String root)
   at Microsoft.AspNetCore.Hosting.StaticWebAssets.StaticWebAssetsLoader.<>c.<UseStaticWebAssetsCore>b__1_0(String contentRoot)
   at Microsoft.AspNetCore.StaticWebAssets.ManifestStaticWebAssetFileProvider..ctor(StaticWebAssetManifest manifest, Func`2 fileProviderFactory)
   at Microsoft.AspNetCore.Hosting.StaticWebAssets.StaticWebAssetsLoader.UseStaticWebAssetsCore(IWebHostEnvironment environment, Stream manifest)
   at Microsoft.AspNetCore.Hosting.StaticWebAssets.StaticWebAssetsLoader.UseStaticWebAssets(IWebHostEnvironment environment, IConfiguration configuration)
   at Microsoft.AspNetCore.WebHost.<>c.<ConfigureWebDefaults>b__9_0(WebHostBuilderContext ctx, IConfigurationBuilder cb)
   at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass9_0.<ConfigureAppConfiguration>b__0(HostBuilderContext context, IConfigurationBuilder builder)
   at Microsoft.Extensions.Hosting.HostBuilder.BuildAppConfiguration()
   at Microsoft.Extensions.Hosting.HostBuilder.Build()
   at IdentityServer.Program.Main(String[] args) in D:\agent\_work\38\s\IdentityServer\Program.cs:line 23

</code>```

The path it reports, D:\agent\_work\38\s\IdentityServer\wwwroot\ is interesting because that path is the same as the path from the DevOps build machine.  We don't see this error if we revert back to .NET 5 and we don't see the problem on our staging machine.

The Program.cs class is defined as

using System;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using NewRelic.LogEnrichers.Serilog;
using Serilog;
using Serilog.Events;

namespace IdentityServer
{
    public class Program
    {
        public static int Main(string[] args)
        {
            try
            {
                CreateLogger();
                Log.Information("Starting host...");
                CreateHostBuilder(args).Build().Run();
                return 0;
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly.");
                return 1;
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }

        public static void CreateLogger()
        {
            var configuration = GetConfiguration();
            Log.Logger = new LoggerConfiguration()
                .ReadFrom.Configuration(configuration)
                .Enrich.FromLogContext() // allows logging middleware to inject output values
                .Enrich.WithThreadId()
                .Enrich.WithNewRelicLogsInContext()
                .CreateLogger();
        }

        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            var configuration = GetConfiguration();
            return Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(
                    webBuilder =>
                    {
                        webBuilder.UseConfiguration(configuration);
                        webBuilder.UseSerilog();
                        webBuilder.UseIIS();
                        webBuilder.CaptureStartupErrors(true);
                        webBuilder.UseStartup<Startup>();
                    });
        }

        private static IConfiguration GetConfiguration()
        {
            var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
            var builder = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .AddJsonFile($"appsettings.{environment}.json", true, true);
            var configuration = builder.Build();

            return configuration;
        }
    }
}
```
<p>We do have other .NET 6 web applications running just fine on this instance of IIS.  I was thinking that the problem might be in our release pipelines but they are identical in their task configurations between the environments.  Tried looking for the directory path in the code or configuration but don't see it anywhere.  Have tried manually setting the WebRoot and ContentRoot paths via <code>.UseWebRoot("path to folder")</code> and <code>.UseContentRoot("path to folder")</code> in the <em>Program.cs</em> but didn't see any change in the logs or the app starting.</p>
<p>Even updated the <em>web.config</em> file to have the exact path for executing the project dll in the <code>aspNetCore</code> element but still no change.</p>
<h2>Update 10 Feb 2022</h2>
<p>Added debug output to the startup to verify file and folder paths.  Everything in the environment variables and execution file path look correct.</p>
```ASPNETCORE_IIS_PHYSICAL_PATH - C:\inetpub\webapps\IdentityServer\
Executable Path: C:\inetpub\webapps\IdentityServer\IdentityServer.dll
```

答:
The problem ended up being how we were pushing our updates out to the servers from DevOps. Our pipelines were built to copy over files out of the Release directory of the build folder. One of the problems with this approach is that files not needed for a site to run but generated during a build are also copied to the release server. In this case, a new file which is generated in .NET 6, .staticwebassets.runtime.json, was getting copied to our servers.

The way .NET 6 seems to behave is that if the environment is set to Development then it will look for this file to figure out where the static web assets are located. If the file doesn't exist then it will assume the files are in a wwwroot sub-directory of the site. This makes sense for instances where you are running the project from your local Visual Studio. More details about this file are available in another SO post with links to the source code in GitHub. To fix our problem we changed our release pipeline to use the publish.zip file that is generated when you run the publish command on a solution. The archive only contains the files needed to run the site, so none of the extraneous files like .staticwebassets.runtime.json are included. We should have been doing this the whole time... lesson learned.

We now unzip the publish.zip file, apply any file transformations, then copy the unzipped files to the web server.

Body:
We are updating one of our applications, in this case IdentityServer, from .NET 5 to .NET 6.  It is being hosted by IIS and deployed by Azure Devops Services.  The issue we are seeing is that on our development environment the website fails to load but on our staging environment it runs just fine.  The error we are seeing on development is

12:45:37.519|Fatal|1||Host terminated unexpectedly.||
System.IO.DirectoryNotFoundException: D:\agent\_work\38\s\IdentityServer\wwwroot\
   at Microsoft.Extensions.FileProviders.PhysicalFileProvider..ctor(String root, ExclusionFilters filters)
   at Microsoft.Extensions.FileProviders.PhysicalFileProvider..ctor(String root)
   at Microsoft.AspNetCore.Hosting.StaticWebAssets.StaticWebAssetsLoader.<>c.<UseStaticWebAssetsCore>b__1_0(String contentRoot)
   at Microsoft.AspNetCore.StaticWebAssets.ManifestStaticWebAssetFileProvider..ctor(StaticWebAssetManifest manifest, Func`2 fileProviderFactory)
   at Microsoft.AspNetCore.Hosting.StaticWebAssets.StaticWebAssetsLoader.UseStaticWebAssetsCore(IWebHostEnvironment environment, Stream manifest)
   at Microsoft.AspNetCore.Hosting.StaticWebAssets.StaticWebAssetsLoader.UseStaticWebAssets(IWebHostEnvironment environment, IConfiguration configuration)
   at Microsoft.AspNetCore.WebHost.<>c.<ConfigureWebDefaults>b__9_0(WebHostBuilderContext ctx, IConfigurationBuilder cb)
   at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass9_0.<ConfigureAppConfiguration>b__0(HostBuilderContext context, IConfigurationBuilder builder)
   at Microsoft.Extensions.Hosting.HostBuilder.BuildAppConfiguration()
   at Microsoft.Extensions.Hosting.HostBuilder.Build()
   at IdentityServer.Program.Main(String[] args) in D:\agent\_work\38\s\IdentityServer\Program.cs:line 23

The path it reports, D:\agent\_work\38\s\IdentityServer\wwwroot\ is interesting because that path is the same as the path from the DevOps build machine.  We don't see this error if we revert back to .NET 5 and we don't see the problem on our staging machine.

The Program.cs class is defined as

using System;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using NewRelic.LogEnrichers.Serilog;
using Serilog;
using Serilog.Events;

namespace IdentityServer
{
    public class Program
    {
        public static int Main(string[] args)
        {
            try
            {
                CreateLogger();
                Log.Information("Starting host...");
                CreateHostBuilder(args).Build().Run();
                return 0;
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly.");
                return 1;
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }

        public static void CreateLogger()
        {
            var configuration = GetConfiguration();
            Log.Logger = new LoggerConfiguration()
                .ReadFrom.Configuration(configuration)
                .Enrich.FromLogContext() // allows logging middleware to inject output values
                .Enrich.WithThreadId()
                .Enrich.WithNewRelicLogsInContext()
                .CreateLogger();
        }

        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            var configuration = GetConfiguration();
            return Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(
                    webBuilder =>
                    {
                        webBuilder.UseConfiguration(configuration);
                        webBuilder.UseSerilog();
                        webBuilder.UseIIS();
                        webBuilder.CaptureStartupErrors(true);
                        webBuilder.UseStartup<Startup>();
                    });
        }

        private static IConfiguration GetConfiguration()
        {
            var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
            var builder = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .AddJsonFile($"appsettings.{environment}.json", true, true);
            var configuration = builder.Build();

            return configuration;
        }
    }
}

We do have other .NET 6 web applications running just fine on this instance of IIS.  I was thinking that the problem might be in our release pipelines but they are identical in their task configurations between the environments.  Tried looking for the directory path in the code or configuration but don't see it anywhere.  Have tried manually setting the WebRoot and ContentRoot paths via .UseWebRoot("path to folder") and .UseContentRoot("path to folder") in the Program.cs but didn't see any change in the logs or the app starting.

Even updated the web.config file to have the exact path for executing the project dll in the aspNetCore element but still no change.

Update 10 Feb 2022

Added debug output to the startup to verify file and folder paths.  Everything in the environment variables and execution file path look correct.

ASPNETCORE_IIS_PHYSICAL_PATH - C:\inetpub\webapps\IdentityServer\
Executable Path: C:\inetpub\webapps\IdentityServer\IdentityServer.dll