问:
UNIT Test Fails, throws COMException "There is no MTS object context"
I have a unit test that contains several test cases. I set them up through the Test Project wizard. It is pretty standard procedure.

When I choose to run one of the test, I got the following error

Test method et.Exec.ProductionBase.Test.etProcessQCItemExecTest.CreateTest threw exception:  System.Runtime.InteropServices.COMException: There is no MTS object context (Exception from HRESULT: 0x8004E004).

I couldn't figure out how to resolve this. I did a little bit of digging online, but none seems to help. All Help is greatly appreciated.

I am running VSTS 2008 Development Edition.

答:
You seem to be exercising production code that depends on having MTS installed. That would be called an integration test.

You need to decouple the production code under test from the MTS dependency and test in isolation (which would be a unit test).


来源: stackexchange

问:
Is there a reason why I should use TryGetComponent instead of GetComponent
I recently found out about TryGetComponent and did some research on it. I found out that main difference is that TryGetComponent "does not allocate in the Editor when the requested component does not exist". I don't really know what that means since I am still new to Unity and why would someone request component that does not exist in the first place, so could somebody explain if I should stop using GetComponent, and if so why?
Thanks in advance.

答:
There might be some reasons to use GetComponent without being sure if this component exists. In this case it is necessary to check if the component is actually there or not.
For example, you have an array of game objects (in this case it is RaycastHit2D array and was aquired from Physics2D.GetRayIntersectionAll method). You need to invoke a specific method from every game object that contains a specific component. You can use GetComponent and check if it equals null or not.

```<code>RaycastHit2D[] ray = Physics2D.GetRayIntersectionAll(_mainCamera.ScreenPointToRay(Input.mousePosition));
        foreach (RaycastHit2D item in ray)
        {
            var myClass = item.transform.GetComponent<MyClass>();
            if (myClass != null )
            {
                myClass.MyMethod();
            }
        }
</code>```

Or you can use TryGetComponent. In this case you do not need to use GetComponent  multiple times or create an additional variable. And the code looks cleaner.

```<code>RaycastHit2D[] ray = Physics2D.GetRayIntersectionAll(_mainCamera.ScreenPointToRay(Input.mousePosition));
        foreach (RaycastHit2D item in ray)
        {

            if (item.transform.TryGetComponent(out MyClass myClass))
            {
                myClass.MyMethod();
            }
        }
</code>```

TryGetComponent seems to be more useful in some particular cases, but not always.

ContentLicense: CC BY-SA 4.0

Body:
There might be some reasons to use GetComponent without being sure if this component exists. In this case it is necessary to check if the component is actually there or not.
For example, you have an array of game objects (in this case it is RaycastHit2D array and was aquired from Physics2D.GetRayIntersectionAll method). You need to invoke a specific method from every game object that contains a specific component. You can use GetComponent and check if it equals null or not.

RaycastHit2D[] ray = Physics2D.GetRayIntersectionAll(_mainCamera.ScreenPointToRay(Input.mousePosition));
        foreach (RaycastHit2D item in ray)
        {
            var myClass = item.transform.GetComponent<MyClass>();
            if (myClass != null )
            {
                myClass.MyMethod();
            }
        }

Or you can use TryGetComponent. In this case you do not need to use GetComponent  multiple times or create an additional variable. And the code looks cleaner.

RaycastHit2D[] ray = Physics2D.GetRayIntersectionAll(_mainCamera.ScreenPointToRay(Input.mousePosition));
        foreach (RaycastHit2D item in ray)
        {

            if (item.transform.TryGetComponent(out MyClass myClass))
            {
                myClass.MyMethod();
            }
        }

TryGetComponent seems to be more useful in some particular cases, but not always.


问:
PHP str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated
I'm getting this error while running my app:

PHP str_replace(): Passing null to parameter #3 ($subject) of type
array|string is deprecated

I am Using CodeIgniter Version : V4.1.8 PHP Version : 8.1.2, full error output below:

```<code>{"data":[
    ["omron","<span class=\"label label-success\">Active<\/span>",
    "<button type=\"button\" class=\"btn btn-default\" onclick=\"editBrand(4)\" data-toggle=\"modal\" data-target=\"#editBrandModal\"><i class=\"fa fa-pencil\"><\/i><\/button> <button type=\"button\" class=\"btn btn-default\" onclick=\"removeBrand(4)\" data-toggle=\"modal\" data-target=\"#removeBrandModal\"><i class=\"fa fa-trash\"><\/i><\/button>\n\t\t\t\t"]
    ]
}
<div style="border:1px solid #990000;padding-left:20px;margin:0 0 10px 0;">

<h4>A PHP Error was encountered</h4>

<p>Severity: 8192</p>
<p>Message:  str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated</p>
<p>Filename: core/Output.php</p>
<p>Line Number: 457</p>

    <p>Backtrace:</p>
</code>```

UPDATE: Code

```<code>if ($this->parse_exec_vars === TRUE)
{
    $memory = round(memory_get_usage() / 1024 / 1024, 2).'MB';
    // below is line 457
    $output = str_replace(array('{elapsed_time}', '{memory_usage}'), array($elapsed, $memory), $output);
}
</code>```

答:
Using a ternary operator will fix this error.

Before Codeigniter existing code:

```<code>$output = str_replace(array('{elapsed_time}', '{memory_usage}'), array($elapsed, $memory), $output);
</code>```

Hopefully, it's will work fine as we will escape str_replace for a null value.

After Using Ternary Operator:

```<code>$output = $output ? str_replace(array('{elapsed_time}', '{memory_usage}'), array($elapsed, $memory), $output): "";
</code>```

Body:
I'm getting this error while running my app:

PHP str_replace(): Passing null to parameter #3 ($subject) of type
array|string is deprecated

I am Using CodeIgniter Version : V4.1.8 PHP Version : 8.1.2, full error output below:

{"data":[
    ["omron","Active<\/span>",
    "<button type=\"button\" class=\"btn btn-default\" onclick=\"editBrand(4)\" data-toggle=\"modal\" data-target=\"#editBrandModal\"><\/i><\/button> <button type=\"button\" class=\"btn btn-default\" onclick=\"removeBrand(4)\" data-toggle=\"modal\" data-target=\"#removeBrandModal\"><\/i><\/button>\n\t\t\t\t"]
    ]
}

A PHP Error was encountered

Severity: 8192

Message:  str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated

Filename: core/Output.php

Line Number: 457

Backtrace:

UPDATE: Code

if ($this->parse_exec_vars === TRUE)
{
    $memory = round(memory_get_usage() / 1024 / 1024, 2).'MB';
    // below is line 457
    $output = str_replace(array('{elapsed_time}', '{memory_usage}'), array($elapsed, $memory), $output);
}

Body:
Using a ternary operator will fix this error.

Before Codeigniter existing code:

$output = str_replace(array('{elapsed_time}', '{memory_usage}'), array($elapsed, $memory), $output);

Hopefully, it's will work fine as we will escape str_replace for a null value.

After Using Ternary Operator:

$output = $output ? str_replace(array('{elapsed_time}', '{memory_usage}'), array($elapsed, $memory), $output): "";


问:
Unity transform.Rotate GetKeyDown and dont rotate again if facing direction?
Hello super new to c# and Unity. I have an empty game object as a child of my player. I have it set up so that when I press my left or right direction buttons the empty rotates with my player using a very short script on the empty object itself. This is for prefab shooting. I was wonder how to make it so if I push the directional button again and I am already facing said direction it dosnt just rotate 180 degrees again. Thank you.

```<code>// Update is called once per frame
void LateUpdate()
{
    {
        if (Input.GetKeyDown(KeyCode.A))
            transform.Rotate(0f, 180f, 0f);
}
    {
        if (Input.GetKeyDown(KeyCode.D ))
            transform.Rotate(0f, -180f, 0f);
    }

}
</code>```

}

答:
I want to tell you that this will only work with 2 directions</p>
```<code>   public class HELPING : MonoBehaviour
{
    bool isFacing;

// Update is called once per frame
void LateUpdate()
{

    if (Input.GetKeyDown(KeyCode.A) && isFacing)
    {
        transform.Rotate(0f, 180f, 0f);
        isFacing = false;
    }

    if (Input.GetKeyDown(KeyCode.D) && isFacing == false)
    {
        transform.Rotate(0f, -180f, 0f);
        isFacing = true;
    }

}
}
</code>```

Body:
Hello super new to c# and Unity. I have an empty game object as a child of my player. I have it set up so that when I press my left or right direction buttons the empty rotates with my player using a very short script on the empty object itself. This is for prefab shooting. I was wonder how to make it so if I push the directional button again and I am already facing said direction it dosnt just rotate 180 degrees again. Thank you.

// Update is called once per frame
void LateUpdate()
{
    {
        if (Input.GetKeyDown(KeyCode.A))
            transform.Rotate(0f, 180f, 0f);
}
    {
        if (Input.GetKeyDown(KeyCode.D ))
            transform.Rotate(0f, -180f, 0f);
    }

}

}

Body:
I want to tell you that this will only work with 2 directions

   public class HELPING : MonoBehaviour
{
    bool isFacing;

// Update is called once per frame
void LateUpdate()
{

    if (Input.GetKeyDown(KeyCode.A) && isFacing)
    {
        transform.Rotate(0f, 180f, 0f);
        isFacing = false;
    }

    if (Input.GetKeyDown(KeyCode.D) && isFacing == false)
    {
        transform.Rotate(0f, -180f, 0f);
        isFacing = true;
    }

}
}


问:
Finding the number of digits of an integer
What is the best method to find the number of digits of a positive integer?

I have found this 3 basic methods:

conversion to string

```<code>String s = new Integer(t).toString();
int len = s.length();
</code>```

for loop

```<code>for(long long int temp = number; temp >= 1;)
{
    temp/=10;
    decimalPlaces++;
}
</code>```

logaritmic calculation

```<code>digits = floor( log10( number ) ) + 1;
</code>```

where you can calculate log10(x) = ln(x) / ln(10) in most languages.

First I thought the string method is the dirtiest one but the more I think about it the more I think it's the fastest way. Or is it?

答:
In Swift 5.x, you get the number of digit in integer as below :

Convert to string and then count number of character in string

```<code>    let nums = [1, 7892, 78, 92, 90]
    for i in nums {
      let ch = String(describing: i)
      print(ch.count)
    }

</code>```

Calculating the number of digits in integer using loop

```<code>    var digitCount = 0
   for i in nums {
     var tmp = i
     while tmp >= 1 {
       tmp /= 10
       digitCount += 1
     }
     print(digitCount)
   }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
What is the best method to find the number of digits of a positive integer?

I have found this 3 basic methods:

conversion to string

String s = new Integer(t).toString();
int len = s.length();

for loop

for(long long int temp = number; temp >= 1;)
{
    temp/=10;
    decimalPlaces++;
}

logaritmic calculation

digits = floor( log10( number ) ) + 1;

where you can calculate log10(x) = ln(x) / ln(10) in most languages.

First I thought the string method is the dirtiest one but the more I think about it the more I think it's the fastest way. Or is it?

Body:
In Swift 5.x, you get the number of digit in integer as below :

Convert to string and then count number of character in string

    let nums = [1, 7892, 78, 92, 90]
    for i in nums {
      let ch = String(describing: i)
      print(ch.count)
    }

Calculating the number of digits in integer using loop

    var digitCount = 0
   for i in nums {
     var tmp = i
     while tmp >= 1 {
       tmp /= 10
       digitCount += 1
     }
     print(digitCount)
   }


问:
How to replace value in a dataframe and convert it to a list of dictionary in python pandas
I have a data frame that is created after a query is executed. Call it df1.

```<code> customerID flag
0        123   No
</code>```

Now, I have another list of dictionary like below:

```<code>list2 = [{"customerID": "123", "response": "yes", "flag": ""}]
</code>```

Now, I want to replace the value of the flag with the values of the flag from df1 for that specific customer. So, I converted this list to a data frame say df2 and tried doing it but it didn't give any errors but didn't give my expected output.

Attempt:

```<code>df2.loc[df2['customerID'].isin(df1.to_dict().keys()), 'flag'] = df2['customerID'].map(df1.to_dict())
</code>```

Expected output:

```<code>[{"customerID": "123", "response": "yes", "flag": "No"}]
</code>```

I am looking to replace it in df2 itself. Later on, I can do .to_dict(orient="records") to get the format I need.

答:
You can try achieving what you want with:</p>
```<code># creating dummy data
df1 = pd.DataFrame(
    data = [[123, 'No']],
    columns = ['customerID', 'flag']
)
list2 = [{'customerID': '123', 'response': 'yes', 'flag': ''}]

# creating a dataframe from list2
df2 = pd.DataFrame().from_records(list2)

# getting the flag value for customer 123
flag = df1[df1['customerID'] == 123]['flag'].values[0]

# replacing the flag value in df2
df2.loc[df2['customerID'] == str(123), 'flag'] = flag

# printing results
print(df2.to_dict('records'))

[{'customerID': '123', 'response': 'yes', 'flag': 'No'}]
</code>```

Body:
I have a data frame that is created after a query is executed. Call it df1.

 customerID flag
0        123   No

Now, I have another list of dictionary like below:

list2 = [{"customerID": "123", "response": "yes", "flag": ""}]

Now, I want to replace the value of the flag with the values of the flag from df1 for that specific customer. So, I converted this list to a data frame say df2 and tried doing it but it didn't give any errors but didn't give my expected output.

Attempt:

df2.loc[df2['customerID'].isin(df1.to_dict().keys()), 'flag'] = df2['customerID'].map(df1.to_dict())

Expected output:

[{"customerID": "123", "response": "yes", "flag": "No"}]

I am looking to replace it in df2 itself. Later on, I can do .to_dict(orient="records") to get the format I need.

Body:
You can try achieving what you want with:

# creating dummy data
df1 = pd.DataFrame(
    data = [[123, 'No']],
    columns = ['customerID', 'flag']
)
list2 = [{'customerID': '123', 'response': 'yes', 'flag': ''}]

# creating a dataframe from list2
df2 = pd.DataFrame().from_records(list2)

# getting the flag value for customer 123
flag = df1[df1['customerID'] == 123]['flag'].values[0]

# replacing the flag value in df2
df2.loc[df2['customerID'] == str(123), 'flag'] = flag

# printing results
print(df2.to_dict('records'))

[{'customerID': '123', 'response': 'yes', 'flag': 'No'}]


问:
Flutter :The named parameter 'textAlign' isn't defined
```<code>class Home extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
 return Scaffold(
    appBar: AppBar(),
    drawer: Drawer(),
    body: Text(
      "Home page ,Omar OS ",
      style: TextStyle(
          fontSize: 30,
          color: Colors.red,
          fontWeight: FontWeight.bold,
          fontStyle: FontStyle.italic),
    ),
    textAlign: TextAlign.center);
  }
}
</code>```

Error:

```<code>No named parameter with the name 'textAlign'.
lib/main.dart:30
        textAlign: TextAlign.center);
        ^^^^^^^^^
/C:/flutter/packages/flutter/lib/src/material/scaffold.dart:1470:9: Context: Found this candidate, but the arguments don't match.
  const Scaffold({
</code>```

答:
The textAlign parameter belongs to the Text widget but you've defined it on Scaffold. This should work:

```<code>class Home extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
 return Scaffold(
    appBar: AppBar(),
    drawer: Drawer(),
    body: Text(
      "Home page ,Omar OS ",
      style: TextStyle(
          fontSize: 30,
          color: Colors.red,
          fontWeight: FontWeight.bold,
          fontStyle: FontStyle.italic),
      textAlign: TextAlign.center
    ),
    );
  }
}
</code>```

Body:
class Home extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
 return Scaffold(
    appBar: AppBar(),
    drawer: Drawer(),
    body: Text(
      "Home page ,Omar OS ",
      style: TextStyle(
          fontSize: 30,
          color: Colors.red,
          fontWeight: FontWeight.bold,
          fontStyle: FontStyle.italic),
    ),
    textAlign: TextAlign.center);
  }
}

Error:

No named parameter with the name 'textAlign'.
lib/main.dart:30
        textAlign: TextAlign.center);
        ^^^^^^^^^
/C:/flutter/packages/flutter/lib/src/material/scaffold.dart:1470:9: Context: Found this candidate, but the arguments don't match.
  const Scaffold({

Body:
The textAlign parameter belongs to the Text widget but you've defined it on Scaffold. This should work:

class Home extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
 return Scaffold(
    appBar: AppBar(),
    drawer: Drawer(),
    body: Text(
      "Home page ,Omar OS ",
      style: TextStyle(
          fontSize: 30,
          color: Colors.red,
          fontWeight: FontWeight.bold,
          fontStyle: FontStyle.italic),
      textAlign: TextAlign.center
    ),
    );
  }
}


问:
changin nan values in imagesc to 0 after printing
The way I used imagesc is that I added each layer on top of the other because they have different boundries.

the problem is that because I used such ways beyond the boundry at the start there is NaN values.

My question is how can I change the NaN values to 0 after I already printed the function?
 The code is the following:

```<code>N = 2^9;
z = ones(N-1,1);
c = 1;
ranNum = diag(rand([N 1])-ones(N,1)/2);
Nsig = 10^2;
sigma = ones(Nsig,1).';
E = ones(Nsig,N);
IPR = ones(Nsig,N);
sigjump = 0.01;

for j = 1:Nsig
    sigma(j) = sigjump + sigjump*(j-1);
    H1 = c*(diag(z,1)+ diag(z,-1) + diag(1,N-1)+ diag(1,-N+1));
    V1 = sigma(j) * ranNum ;
    H = H1 + V1;
    [psi,~] = eig(H);
    E(j,:) = eig(H);
    P1 = abs(psi).^2;
    IPR(j,:) = sum(P1.^2);

    imagesc(E(j,:),sigma(j)+sigjump*Nsig/2 ,IPR(j,:));
    colormap('turbo')
    colorbar
    xlabel('E')
    ylabel('sigma')
    h = colorbar;
    ylabel(h, 'IPR')
    hold on

end
</code>```

This is the result (the white at the top left), also, you cant see the entire spectrum.

Body:
The way I used imagesc is that I added each layer on top of the other because they have different boundries.

the problem is that because I used such ways beyond the boundry at the start there is NaN values.

My question is how can I change the NaN values to 0 after I already printed the function?
 The code is the following:

N = 2^9;
z = ones(N-1,1);
c = 1;
ranNum = diag(rand([N 1])-ones(N,1)/2);
Nsig = 10^2;
sigma = ones(Nsig,1).';
E = ones(Nsig,N);
IPR = ones(Nsig,N);
sigjump = 0.01;

for j = 1:Nsig
    sigma(j) = sigjump + sigjump*(j-1);
    H1 = c*(diag(z,1)+ diag(z,-1) + diag(1,N-1)+ diag(1,-N+1));
    V1 = sigma(j) * ranNum ;
    H = H1 + V1;
    [psi,~] = eig(H);
    E(j,:) = eig(H);
    P1 = abs(psi).^2;
    IPR(j,:) = sum(P1.^2);

    imagesc(E(j,:),sigma(j)+sigjump*Nsig/2 ,IPR(j,:));
    colormap('turbo')
    colorbar
    xlabel('E')
    ylabel('sigma')
    h = colorbar;
    ylabel(h, 'IPR')
    hold on

end

This is the result (the white at the top left), also, you cant see the entire spectrum.

Body:
I don't have matlab, but i guess that's the same with Octave (and Scilab):

>> a = rand(2,4)
a =
   0.257914   0.775035   0.608284   0.057678
   0.162044   0.491000   0.285110   0.766687

>> a(a<0.3) = NaN
a =
      NaN   0.7750   0.6083      NaN
      NaN   0.4910      NaN   0.7667

>> a(isnan(a)) = 0
a =
        0   0.7750   0.6083        0
        0   0.4910        0   0.7667


问:
Temporary files are being removed during execution on iOS
Surprisingly, and after some time debugging this, I've found that my app is purging files from tmp directory after 1 minute or so, without any other user action, even while the app is running on the foreground.

Accordingly to the docs, temporary directory should keep the files during app execution and only remove it afterwards or at most on its startup.

I don't want to move/copy to caches directory as workaround here, I'm more surprised about why is this actually happening. If that helps, I'm picking from Files app (using UIDocumentPickerViewController).

To make it even better, sometimes there are files that persist for a long time there, even though they are older than the others that are removed instantly after picking. This can result in bad access because your user selects a file, go grab a coffee while the app is still running, and then presses the button to upload it somewhere or whatever and the file is gone.

I can replicate it everytime with a simple app.

答:
After working with temp files a bit, I don't believe this is a bug, it is a feature for temporary files to be deleted when not opened for a period of time. I do believe you can manage that more directly by differentiating between normal and temporary files. As per a much more detailed article here, you can use the ManagedURL protocol to fix your issue:

```<code>public protocol ManagedURL {
    var contentURL: URL { get }
    func keepAlive()
}

public extension ManagedURL {
    public func keepAlive() { }
}

extension URL: ManagedURL {
    public var contentURL: URL { return self }
}
</code>```

To keep the background operation alive:

```<code>URLSession.shared.uploadTask(with: request, fromFile: fileToUpload.contentURL) { _, _, _ in
    temporaryFile.keepAlive()
}
</code>```

Body:
After working with temp files a bit, I don't believe this is a bug, it is a feature for temporary files to be deleted when not opened for a period of time. I do believe you can manage that more directly by differentiating between normal and temporary files. As per a much more detailed article here, you can use the ManagedURL protocol to fix your issue:

public protocol ManagedURL {
    var contentURL: URL { get }
    func keepAlive()
}

public extension ManagedURL {
    public func keepAlive() { }
}

extension URL: ManagedURL {
    public var contentURL: URL { return self }
}

To keep the background operation alive:

URLSession.shared.uploadTask(with: request, fromFile: fileToUpload.contentURL) { _, _, _ in
    temporaryFile.keepAlive()
}


问:
How do I use CSS to properly hide a form select element, including the select arrow
I'm using display: none; in the style sheet to hide a number of form fields. When the user clicks the visible First Name or Last Name fields, the rest of the fields display using JavaScript getElementById to display block.

Everything works except the down arrow still displays from the select element when it should be hidden with everything else. I tried CSS:

```<code>select {
    appearance: none;
}
</code>```

but that did not work. Image below of the problem and link here to the test page: Form Test Page

答:
Should be able to just set

.elementor-select-wrapper::before { display: none }

Body:
I'm using display: none; in the style sheet to hide a number of form fields. When the user clicks the visible First Name or Last Name fields, the rest of the fields display using JavaScript getElementById to display block.

Everything works except the down arrow still displays from the select element when it should be hidden with everything else. I tried CSS:

select {
    appearance: none;
}

but that did not work. Image below of the problem and link here to the test page: Form Test Page


答:
```<code>  class Home extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
      return Scaffold(
          appBar: AppBar(),
          drawer: Drawer(),
          body: Text(
            "Home page ,Omar OS ",
            style: TextStyle(
                fontSize: 30,
                color: Colors.red,
                fontWeight: FontWeight.bold,
                fontStyle: FontStyle.italic),
              textAlign: TextAlign.center),
          );

    }
  }
</code>```

Title: Flutter :The named parameter 'textAlign' isn't defined


问:
correct version compatibility matrix for expo, npm, node, react-native, typescript?
I am doing the react-native typescript setup which I ran

```<code>npx react-native init MyApp --template react-native-template-typescript
</code>```

I installed typescript

```<code>npm install -g typescript
</code>```

'npx --v' -> 6.14.15

'npm view react-native version' -> 0.67.2

'npm view typescript version' -> 4.5.5

'node -v' -> v12.22.9

and then immediately, I get errors from the template ->

```<code>node_modules/@types/node/globals.d.ts:47:11 - error TS2300: Duplicate identifier 'AbortController'.

47 interface AbortController {
    ~~~~~~~~~~~~~~~

    node_modules/@types/react-native/globals.d.ts:435:15
    435 declare class AbortController {
    ~~~~~~~~~~~~~~~
    'AbortController' was also declared here.
</code>```

Once I solve this my next question is having all developers use the same tool versions to avoid this dependency hell.  The only one dealing with dep hell will be the person doing the upgrade.  everyone else will magically get their tool and lib versions changed hopefully!!!

答:
Well, today I ran

npx react-native init MyApp --template react-native-template-typescript

in another directory and running 'tsc' works

tsc still does not work in the other MyApp directory and a comparison shows a whole slew of things that are not different versions.  I have no idea why but my guess is this is a 'always using latest versions' issue.  At least the template locks into a version(I think) so versions will not change on my working project(I hope).

Body:
I am doing the react-native typescript setup which I ran

npx react-native init MyApp --template react-native-template-typescript

I installed typescript

npm install -g typescript

'npx --v' -> 6.14.15

'npm view react-native version' -> 0.67.2

'npm view typescript version' -> 4.5.5

'node -v' -> v12.22.9

and then immediately, I get errors from the template ->

node_modules/@types/node/globals.d.ts:47:11 - error TS2300: Duplicate identifier 'AbortController'.

47 interface AbortController {
    ~~~~~~~~~~~~~~~

    node_modules/@types/react-native/globals.d.ts:435:15
    435 declare class AbortController {
    ~~~~~~~~~~~~~~~
    'AbortController' was also declared here.

Once I solve this my next question is having all developers use the same tool versions to avoid this dependency hell.  The only one dealing with dep hell will be the person doing the upgrade.  everyone else will magically get their tool and lib versions changed hopefully!!!


问:
Xml database in PHP
I need to use xml as database in php. Till now i used mssql,mysql as database in php. Is it possible to do so? </p>

答:
Of course it is, it depends how you want it laid out though.

Although, XML isn't technically a database.

If you were using a system that requires the use of user registration, you could have either an XML file per user, or an overall user XML file.

1 - User1.xml

```<code><user>
    <username>User</username>
    <password>Pass</password>
</user>
</code>```

2 - Users.xml

```<code><user>
    <username>User1</username>
    <password>Pass</password>
</user>
<user>
    <username>User2</username>
    <password>Pass2</password>
</user>
</code>```

These are some very simple methods that could be used.

Then in order to check if a user has logged in you would need to iterate through the nodes in the XML file(s) and check the details.

Title: Xml database in PHP

Body:
Of course it is, it depends how you want it laid out though.

Although, XML isn't technically a database.

If you were using a system that requires the use of user registration, you could have either an XML file per user, or an overall user XML file.

1 - User1.xml

<user>
    <username>User</username>
    <password>Pass</password>
</user>

2 - Users.xml

<user>
    <username>User1</username>
    <password>Pass</password>
</user>
<user>
    <username>User2</username>
    <password>Pass2</password>
</user>

These are some very simple methods that could be used.

Then in order to check if a user has logged in you would need to iterate through the nodes in the XML file(s) and check the details.


问:
Get the all values of "a" tags
I make a mini-project to reach a better level but I stuck here. Here is my code:

```<code>from bs4 import BeautifulSoup
import requests

html_from =  requests.get("http://www.muhfak.hacettepe.edu.tr/tr/duyurular")
html_from.encoding = "UTF-8"
html_text = html_from.text
soup = BeautifulSoup(html_text, 'html.parser')

titles = soup.find_all("div", class_="liste")

print(titles[0])
</code>```

I have to add "[0]" after the "titles" because the whole part is in a one-length list. I can see all the sections that I need in HTML codes. Is there a way to put each value in different list values?
When I make "titles[0].text", I can see the values I want. But "print(titles[0].a.text)" is not working and its output is only the latest value. How can I reach that values?

This is "titles[0].text" :

Yandal Başvurusu Hakkında 2022-01-05 15:00:00
2019/2020 - 2020/2021 Akademik Yıllarını Kapsayan Fakültemiz  Faaliyet Raporu için Tıklayınız.
2021-12-14 08:00:00
13 Eylül 2021 Tarihinde Yapılan Mezuniyet Töreni Videosu için Tıklayınız. 2021-09-15 15:00:00
...

This is "titles[0].text" :
Yandal Başvurusu Hakkında

This is the part of the source and there are lots of "a" tags :

```<code><script charset="utf-8" type="text/javascript">
        $(document).ready(function() {
            $('#duyurular_7').dataTable( {
                "sPaginationType": "full_numbers",
                "bStateSave": false,
                "bSort": false,
                "olanguage": {
                    "url": "//hu-iys.hacettepe.edu.tr/templates/template3/js/datatables_langs/tr.json"
                }
            } );
        } );
    </script>
<table class="table table-striped table-bordered" id="duyurular_7">
<thead>
<tr> <th>Başlık</th> </tr>
</thead>
<tbody>
<tr><td><a href="/tr/yandal_basvurusu_hakkinda-177">Yandal Başvurusu Hakkında</a> <span class="tarih">2022-01-05 15:00:00</span></td></tr>
<tr><td><a href="/tr/20192020_20202021_akademik_yil-184">2019/2020 - 2020/2021 Akademik Yıllarını Kapsayan Fakültemiz  Faaliyet Raporu için Tıklayınız.
</a> <span class="tarih">2021-12-14 08:00:00</span></td></tr>
<tr><td><a href="https://www.youtube.com/watch?v=k55WKZAfmU8">13 Eylül 2021 Tarihinde Yapılan Mezuniyet Töreni Videosu için Tıklayınız.</a> <span class="tarih">2021-09-15 15:00:00</span></td></tr>
<tr><td><a href="https://universitem.hacettepe.edu.tr/hayatin-butun-renkleri-burada-2/">Fakültemiz Bölümlerinin Tanıtım Günleri İçin Tıklayınız.</a> <span class="tarih">2021-08-06 10:00:00</span></td></tr>
<tr><td><a href="http://fs.hacettepe.edu.tr/muhfak/dosyalar/Duyurular/2020_2021_Guz_Yandal_sonuclari.pdf">2020-2021 Akademik Yılı Yandal Programı Sonuçları için tıklayınız.</a> <span class="tarih">2020-10-02 11:00:00</span></td></tr>```

```

答:
To get all  tags under tag with class="liste" you can use CSS selector ".liste a". For example:

import requests
from bs4 import BeautifulSoup

html_from = requests.get("http://www.muhfak.hacettepe.edu.tr/tr/duyurular")
html_from.encoding = "UTF-8"
html_text = html_from.text
soup = BeautifulSoup(html_text, "html.parser")

for a in soup.select(".liste a"):
    print(a.get_text(strip=True))
    print(a["href"])
    print()
```
<p>Prints:</p>
<pre class="lang-none prettyprint-override"><code>Yandal Başvurusu Hakkında
/tr/yandal_basvurusu_hakkinda-177

2019/2020 - 2020/2021 Akademik Yıllarını Kapsayan Fakültemiz  Faaliyet Raporu için Tıklayınız.
/tr/20192020_20202021_akademik_yil-184

13 Eylül 2021 Tarihinde Yapılan Mezuniyet Töreni Videosu için Tıklayınız.
https://www.youtube.com/watch?v=k55WKZAfmU8

Fakültemiz Bölümlerinin Tanıtım Günleri İçin Tıklayınız.
https://universitem.hacettepe.edu.tr/hayatin-butun-renkleri-burada-2/

...and so on.
</code>```

Title: Get the all values of "a" tags

Body:
I make a mini-project to reach a better level but I stuck here. Here is my code:

from bs4 import BeautifulSoup
import requests

html_from =  requests.get("http://www.muhfak.hacettepe.edu.tr/tr/duyurular")
html_from.encoding = "UTF-8"
html_text = html_from.text
soup = BeautifulSoup(html_text, 'html.parser')

titles = soup.find_all("div", class_="liste")

print(titles[0])

I have to add "[0]" after the "titles" because the whole part is in a one-length list. I can see all the sections that I need in HTML codes. Is there a way to put each value in different list values?
When I make "titles[0].text", I can see the values I want. But "print(titles[0].a.text)" is not working and its output is only the latest value. How can I reach that values?

This is "titles[0].text" :

Yandal Başvurusu Hakkında 2022-01-05 15:00:00
2019/2020 - 2020/2021 Akademik Yıllarını Kapsayan Fakültemiz  Faaliyet Raporu için Tıklayınız.
2021-12-14 08:00:00
13 Eylül 2021 Tarihinde Yapılan Mezuniyet Töreni Videosu için Tıklayınız. 2021-09-15 15:00:00
...

This is "titles[0].text" :
Yandal Başvurusu Hakkında

This is the part of the source and there are lots of "a" tags :

 Başlık

Yandal Başvurusu Hakkında 2022-01-05 15:00:00

2019/2020 - 2020/2021 Akademik Yıllarını Kapsayan Fakültemiz  Faaliyet Raporu için Tıklayınız.
 2021-12-14 08:00:00

13 Eylül 2021 Tarihinde Yapılan Mezuniyet Töreni Videosu için Tıklayınız. 2021-09-15 15:00:00

Fakültemiz Bölümlerinin Tanıtım Günleri İçin Tıklayınız. 2021-08-06 10:00:00

2020-2021 Akademik Yılı Yandal Programı Sonuçları için tıklayınız. 2020-10-02 11:00:00
```

Body:
To get all <a> tags under tag with class="liste" you can use CSS selector ".liste a". For example:

import requests
from bs4 import BeautifulSoup

html_from = requests.get("http://www.muhfak.hacettepe.edu.tr/tr/duyurular")
html_from.encoding = "UTF-8"
html_text = html_from.text
soup = BeautifulSoup(html_text, "html.parser")

for a in soup.select(".liste a"):
    print(a.get_text(strip=True))
    print(a["href"])
    print()

Prints:

Yandal Başvurusu Hakkında
/tr/yandal_basvurusu_hakkinda-177

2019/2020 - 2020/2021 Akademik Yıllarını Kapsayan Fakültemiz  Faaliyet Raporu için Tıklayınız.
/tr/20192020_20202021_akademik_yil-184

13 Eylül 2021 Tarihinde Yapılan Mezuniyet Töreni Videosu için Tıklayınız.
https://www.youtube.com/watch?v=k55WKZAfmU8

Fakültemiz Bölümlerinin Tanıtım Günleri İçin Tıklayınız.
https://universitem.hacettepe.edu.tr/hayatin-butun-renkleri-burada-2/

...and so on.


问:
CBLAS - ** On entry to SGEMM / DGEMM, parameter number X had an illegal value?
I am calling cblas_sgemm using the following parameters:

order: CblasRowMajor

transA, transB: either CblasTrans or CblasNoTrans

M: the number of rows (height) of the  matrix op(A)  and of the  matrix  C

N: the number of columns (width) of the matrix op(B) and of the matrix C

K: the number of columns (width) of the matrix op(A) and the number of rows (height) of the matrix op(B)

alpha: scalar

A: pointer to matrix A

LDA: When  transA = CblasNoTrans then LDA = M, otherwise  LDA = K

B: pointer to matrix B

LDB: when transB = CblasNoTrans then LDB = K, otherwise LDB = N

beta: scalar

C: pointer to matrix C (bias on entry and the result on exit)

LDC = M

where, op(M) = M if transM is CblasNoTrans, and Transpose(M) otherwise

The parameters are correct (according to the documentation) but I am getting am error:
"** On entry to SGEMM, parameter number X had an illegal value" - How do I fix this error?

答:
TL;DR
When using: CblasRowMajor

Keep M,N,K setting as listed above.

Flip Transpose value when computing LDA,LDB, and set LDC = N

Details:
I ran into this problem using multiplication with Transpose and could not find a detailed answer that answers my problem. I write this Q/A in hope it will be useful for others.

The root problem, as others have noted, is that cblas is a wrapper over BLAS, which is written in FORTRAN that does not have an order parameter and expect column major matrix representation. The available documentation (usually) is the BLAS documentation - which I used above in the question.

However, While M,N,and K are logical values (the width/height of matrix regardless of its representation) the leading dimensions (LDA, LDB, LDC) are not. Therefore the computation of M,N, and K should stay the same when using CblasRowMajor. However, the transpose of op(A), op(B) and C, should be use when computing LDA, LDB, and LDC.

If  CblasColMajor is used then it is the same representation as Fortran and the parameter setting shown in the question is the correct one.

Also note that when you get and error in parameter X, X is shifted by 1 because the error originated in BLAS that does not have an order parameter.


问:
Angular - Add form values from a FormBuilder Form.group into a Map data structure
I have a FormBuilder form group called AddStatusBoxForm:

```<code>AddStatusBoxForm = this.Form.group({
    name: ['']
  });
</code>```

I then have a Map data structure which I think would have a type of Map<string, string>:

```<code>statusBoxValues = new Map<string, string>
  ([
    ['name', this.AddStatusBoxForm.get('name')?.value]
  ]);
</code>```

The Map data structure takes in this.AddStatusBoxForm.get('name')?.value as the item in the map, with the key being the string 'name'.

I test a few things with console.log(). First I print out the type of the value retrieved from the AddStatusBoxForm which returns a type of string. Then I print out the actual value of the input in the form which returns that same value. Lastly I attempt to print out the first item in my statusBoxValues Map, which contains the same code used to retrieve values from the AddStatusBoxForm form group. However this returns empty string, when I expect it to return the value that was inputted into the form.

```<code>console.log(typeof(this.AddStatusBoxForm.get('name')?.value)) //returns string
console.log(this.AddStatusBoxForm.get('name')?.value) // returns value of input
console.log(this.statusBoxValues.get('name')) // returns <empty string>
</code>```

Would anyone be able to help me so that I could add the values from a Form Group into a Map data structure, or maybe an equalivant data strucuture that has key pair values?

Thanks.

答:
Your issue is that this.AddStatusBoxForm.get('name')?.value is firing, once and only once as you add it to the map.

Try this instead:

```<code>var statusBoxValues = {
  'name': () => this.AddStatusBoxForm.get('name')?.value,
  'otherName': () => this.AddStatusBoxForm.get('otherName')?.value,
};
</code>```

You can then call the function like this:

```<code>this.statusBoxValues['name']();
</code>```

Body:
I have a FormBuilder form group called AddStatusBoxForm:

AddStatusBoxForm = this.Form.group({
    name: ['']
  });

I then have a Map data structure which I think would have a type of Map<string, string>:

statusBoxValues = new Map<string, string>
  ([
    ['name', this.AddStatusBoxForm.get('name')?.value]
  ]);

The Map data structure takes in this.AddStatusBoxForm.get('name')?.value as the item in the map, with the key being the string 'name'.

I test a few things with console.log(). First I print out the type of the value retrieved from the AddStatusBoxForm which returns a type of string. Then I print out the actual value of the input in the form which returns that same value. Lastly I attempt to print out the first item in my statusBoxValues Map, which contains the same code used to retrieve values from the AddStatusBoxForm form group. However this returns empty string, when I expect it to return the value that was inputted into the form.

console.log(typeof(this.AddStatusBoxForm.get('name')?.value)) //returns string
console.log(this.AddStatusBoxForm.get('name')?.value) // returns value of input
console.log(this.statusBoxValues.get('name')) // returns <empty string>

Would anyone be able to help me so that I could add the values from a Form Group into a Map data structure, or maybe an equalivant data strucuture that has key pair values?

Thanks.

Body:
Your issue is that this.AddStatusBoxForm.get('name')?.value is firing, once and only once as you add it to the map.

Try this instead:

var statusBoxValues = {
  'name': () => this.AddStatusBoxForm.get('name')?.value,
  'otherName': () => this.AddStatusBoxForm.get('otherName')?.value,
};

You can then call the function like this:

this.statusBoxValues['name']();


问:
Is it possible to use WHERE with ANY and ARRAY together?
I have a table called 'reviews' that I want to start the data cleaning process, so I want to find out if there are any records that have any NULL columns (there are 6 columns in the table).

So, instead of using the code below:

```<code>SELECT *
FROM reviews
WHERE listing_id IS NULL
    OR id IS NULL
    OR date IS NULL
    OR reviewer_id IS NULL
    OR reviewer_name IS NULL
    OR comments IS NULL

'''
</code>```

I would like to simplify the code, using something like this:

```<code>SELECT *
FROM reviews
WHERE ANY( ARRAY [listing_id, id, date, reviewer_id, reviewer_name, comments]) IS NULL
</code>```

But It doesn't work.

What's wrong with the second code?

Are there other more efficient ways to check?

答:
you can use num_nulls()</p>
```<code>where num_nulls(listing_id, id, date, reviewer_id, reviewer_name, comments) > 0
</code>```

Body:
I have a table called 'reviews' that I want to start the data cleaning process, so I want to find out if there are any records that have any NULL columns (there are 6 columns in the table).

So, instead of using the code below:

SELECT *
FROM reviews
WHERE listing_id IS NULL
    OR id IS NULL
    OR date IS NULL
    OR reviewer_id IS NULL
    OR reviewer_name IS NULL
    OR comments IS NULL

'''

I would like to simplify the code, using something like this:

SELECT *
FROM reviews
WHERE ANY( ARRAY [listing_id, id, date, reviewer_id, reviewer_name, comments]) IS NULL

But It doesn't work.

What's wrong with the second code?

Are there other more efficient ways to check?

Body:
you can use num_nulls()

where num_nulls(listing_id, id, date, reviewer_id, reviewer_name, comments) > 0


问:
Tiles won't parse Struts tags
I'm tried using tiles but it seems that it's not parsing the Struts tags, It outputs them directly e.g.  instead of ...
What seems to be the problem?</p>

答:
I've seen evaluation-order things with netsed tags in jsp's - you're likely to run into problems with things like

```<code> <t:x name="<c:out ...
</code>```

Can you post code and output? (I'm guessing you're code got parsed out because you didn't use the nice binary-logo button)

OwnerDisplayName: mamamambo

ContentLicense: CC BY-SA 2.5

Title: Tiles won't parse Struts tags

Body:
I've seen evaluation-order things with netsed tags in jsp's - you're likely to run into problems with things like

 <t:x name="<c:out ...

Can you post code and output? (I'm guessing you're code got parsed out because you didn't use the nice binary-logo button)

OwnerDisplayName: Steve B.


问:
Linq - Expression.And to join N elements BinayExpression
I have a list of BinaryExpression and I need to join the elements of this list in a single "object".

```<code>IList<BinaryExpression> lstBin = new List<BinaryExpression>();
</code>```

Inside my List I have this:

```<code>{(item.Field1 = 1)} //First Element
{(item.Field2 = 99)} //Second Element
//So on..
</code>```

I need something like this:

```<code>(item => item.Field1 == 1 && item.Field2 == 99 && item.Field3 == 45)
</code>```

I know that Linq has Expression.And, and I need to make a logic to implement this, but I couldn't. I tried to make a loop inside my list but Expression.And needs two Expression, and inside my loop I have only one.
After this, I'll make a Expression.Lamba from this single "object", like this:

```<code>Expression<Func<T, bool>> expr = Expression.Lambda<Func<T, bool>>(singleExpression, parameter);
</code>```

答:
I think you want (with LINQ):

```<code>var singleExpression = lstBin.Aggregate(Expression.AndAlso);
</code>```

If you prefer writing a loop:

```<code>var singleExpression = lstBin.First();

foreach (var expr in lstBin.Skip(1))
    singleExpression = Expression.AndAlso(singleExpression, expr);
</code>```

Body:
I have a list of BinaryExpression and I need to join the elements of this list in a single "object".

IList<BinaryExpression> lstBin = new List<BinaryExpression>();

Inside my List I have this:

{(item.Field1 = 1)} //First Element
{(item.Field2 = 99)} //Second Element
//So on..

I need something like this:

(item => item.Field1 == 1 && item.Field2 == 99 && item.Field3 == 45)

I know that Linq has Expression.And, and I need to make a logic to implement this, but I couldn't. I tried to make a loop inside my list but Expression.And needs two Expression, and inside my loop I have only one.
After this, I'll make a Expression.Lamba from this single "object", like this:

Expression<Func<T, bool>> expr = Expression.Lambda<Func<T, bool>>(singleExpression, parameter);

Body:
I think you want (with LINQ):

var singleExpression = lstBin.Aggregate(Expression.AndAlso);

If you prefer writing a loop:

var singleExpression = lstBin.First();

foreach (var expr in lstBin.Skip(1))
    singleExpression = Expression.AndAlso(singleExpression, expr);


问:
Cannot run getMore on cursor
I have a really simple MongoDB find query which filters a fairly large collection on one field.

```<code>let client = new MongoClient(`mongodb://${ip}:27019/test`, { w: 0 })
client.connect()
const db = client.db(dbName)
const messages = db.collection('messages')

;(async () => {
    for (let i = 0; i < 10; i++) {
      const cursor = messages.find({ deviceId: '786b06a838163326023e7726bd6f42481cc6b1ab' })
      const allValues = await cursor.toArray()

      console.log(allValues)
      cursor.close()
    }
})()
</code>```

Running the query once works fine. But when i try to run it multiple times in sequence, it immediately returns this error without returning any other result.

```<code>MongoServerError: Cannot run getMore on cursor 2366016547291243997, which was not created in a session, in session 6c5c71bf-88b2-45d7-b234-bf7bb93554b8 - 47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=
    at MessageStream.messageHandler (/home/tobias/Github/BachelorArbeit/node_modules/mongodb/lib/cmap/connection.js:462:30)
    at MessageStream.emit (node:events:390:28)
    at processIncomingData (/home/tobias/Github/BachelorArbeit/node_modules/mongodb/lib/cmap/message_stream.js:108:16)
    at MessageStream._write (/home/tobias/Github/BachelorArbeit/node_modules/mongodb/lib/cmap/message_stream.js:28:9)
    at writeOrBuffer (node:internal/streams/writable:389:12)
    at _write (node:internal/streams/writable:330:10)
    at MessageStream.Writable.write (node:internal/streams/writable:334:10)
    at Socket.ondata (node:internal/streams/readable:754:22)
    at Socket.emit (node:events:390:28)
    at addChunk (node:internal/streams/readable:315:12) {
  ok: 0,
  code: 50799,
  codeName: 'Location50799',
  '$clusterTime': {
    clusterTime: Timestamp { low: 2, high: 1643509041, unsigned: true },
    signature: {
      hash: Binary {
        sub_type: 0,
        buffer: Buffer(20) [Uint8Array] [
          0, 0, 0, 0, 0, 0, 0,
          0, 0, 0, 0, 0, 0, 0,
          0, 0, 0, 0, 0, 0
        ],
        position: 20
      },
      keyId: 0
    }
  },
  operationTime: Timestamp { low: 2, high: 1643509041, unsigned: true }
}
</code>```

Strangely it works when i set a low limit like 100.

Googling the problem and looking at the other StackOverflow posts with this error did not help. What am i missing here?

答:
Specifying Write Concern as 0 is the problem (I don't know why though)

```<code>let client = new MongoClient(`mongodb://${ip}:27019/test`, { w: 1 })
</code>```

Changing it to 1 or the default value fixed the problem.

Title: Cannot run getMore on cursor

Body:
I have a really simple MongoDB find query which filters a fairly large collection on one field.

let client = new MongoClient(`mongodb://${ip}:27019/test`, { w: 0 })
client.connect()
const db = client.db(dbName)
const messages = db.collection('messages')

;(async () => {
    for (let i = 0; i < 10; i++) {
      const cursor = messages.find({ deviceId: '786b06a838163326023e7726bd6f42481cc6b1ab' })
      const allValues = await cursor.toArray()

      console.log(allValues)
      cursor.close()
    }
})()

Running the query once works fine. But when i try to run it multiple times in sequence, it immediately returns this error without returning any other result.

MongoServerError: Cannot run getMore on cursor 2366016547291243997, which was not created in a session, in session 6c5c71bf-88b2-45d7-b234-bf7bb93554b8 - 47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=
    at MessageStream.messageHandler (/home/tobias/Github/BachelorArbeit/node_modules/mongodb/lib/cmap/connection.js:462:30)
    at MessageStream.emit (node:events:390:28)
    at processIncomingData (/home/tobias/Github/BachelorArbeit/node_modules/mongodb/lib/cmap/message_stream.js:108:16)
    at MessageStream._write (/home/tobias/Github/BachelorArbeit/node_modules/mongodb/lib/cmap/message_stream.js:28:9)
    at writeOrBuffer (node:internal/streams/writable:389:12)
    at _write (node:internal/streams/writable:330:10)
    at MessageStream.Writable.write (node:internal/streams/writable:334:10)
    at Socket.ondata (node:internal/streams/readable:754:22)
    at Socket.emit (node:events:390:28)
    at addChunk (node:internal/streams/readable:315:12) {
  ok: 0,
  code: 50799,
  codeName: 'Location50799',
  '$clusterTime': {
    clusterTime: Timestamp { low: 2, high: 1643509041, unsigned: true },
    signature: {
      hash: Binary {
        sub_type: 0,
        buffer: Buffer(20) [Uint8Array] [
          0, 0, 0, 0, 0, 0, 0,
          0, 0, 0, 0, 0, 0, 0,
          0, 0, 0, 0, 0, 0
        ],
        position: 20
      },
      keyId: 0
    }
  },
  operationTime: Timestamp { low: 2, high: 1643509041, unsigned: true }
}

Strangely it works when i set a low limit like 100.

Googling the problem and looking at the other StackOverflow posts with this error did not help. What am i missing here?

Body:
Specifying Write Concern as 0 is the problem (I don't know why though)

let client = new MongoClient(`mongodb://${ip}:27019/test`, { w: 1 })

Changing it to 1 or the default value fixed the problem.


问:
live server vscode on another computer
I have 2 computers. when I open the project with live server on the first one it gives me this url 127.0.0.1:5500/index.html
I want to put that url on the other computer's browser but it doesn't work.
is there any solution to this?</p>

答: It doesn't work because you are using loopback address (127.0.0.1), in order to access your live server on entire LAN you need to change this address in vscode/liveserver settings to your private address, it will be something like (192.168.100.XXX)</p>

Title: live server vscode on another computer


问:
OpenGL texture gets worse when moving camera away from object
The texture gets generally worse more I move the camera away from the object. I need to be really close to the object for the texture to be fine. Does anyone know what would cause it and how to fix it?

this is how I load the texture

```<code>stbi_set_flip_vertically_on_load(1);
m_Local_buffer = stbi_load(path.c_str(), &m_width, &m_height, &m_bpp, 4);

glGenTextures(1, &m_rendererID);
glBindTexture(GL_TEXTURE_2D, m_rendererID);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, m_width, m_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_Local_buffer);
glGenerateMipmap(GL_TEXTURE_2D);

glBindTexture(GL_TEXTURE_2D, 0);
</code>```

image of the bad texture

Edit: updated the code.

答:
For mipmapping you have to use one of the mipmap minifying filters. e.g.: GL_LINEAR_MIPMAP_LINEAR (see glTexParameter):

<s>glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); </s>

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
```

Body:
The texture gets generally worse more I move the camera away from the object. I need to be really close to the object for the texture to be fine. Does anyone know what would cause it and how to fix it?

this is how I load the texture

stbi_set_flip_vertically_on_load(1);
m_Local_buffer = stbi_load(path.c_str(), &m_width, &m_height, &m_bpp, 4);

glGenTextures(1, &m_rendererID);
glBindTexture(GL_TEXTURE_2D, m_rendererID);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, m_width, m_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_Local_buffer);
glGenerateMipmap(GL_TEXTURE_2D);

glBindTexture(GL_TEXTURE_2D, 0);

image of the bad texture

Edit: updated the code.


问:
C++: Iteratively call a member's object methods /// a table of objects
I have a bunch of object classes (A, B and C in this example) which I instantiate in my application. They all inherit one and a same interface, which I call Base. I want to interate over the objects and do a call on them.

Here are the classes and the base:

```<code>class Base
{
public:
    virtual CResult init() noexcept;
};

class A : public Base
{
public:
    ...
};

class B : public Base
{
public:
    ...
};

class C : public Base
{
public:
    ...
};
</code>```

I have then an instance of A, B and C in the application, together with its init() method:

```<code>class Application
{
public:
    CResult init() noexcept;
private:
    A a;
    B b;
    C c;
};

CResult Application::init()
{
    /// iterate on a, b, c and call .init()
    /// add code
}
</code>```

Now, I want to call the init() methods of all my objects a, b and c iteratively.
That would mean I need to define a table with a, b and c "references" (I say references, but yes it is not possible to have, say, vector of object references). Then to iterate over the table and call each member's init() method.

What is the best OOP way to achieve this? Can anyone share sample code with the table and the iteration?

答:
The easiest way is probably this:

```<code>Base *ptrs[] = {&a, &b, &c};
for (auto ptr : ptrs)
    ptr->init();
</code>```

If the variables had the same type, you could shorten this to for (auto ptr : {&a, &b, &c}). But since the types are different, you have to manually spell the pointer type when creating the array.

Body:
I have a bunch of object classes (A, B and C in this example) which I instantiate in my application. They all inherit one and a same interface, which I call Base. I want to interate over the objects and do a call on them.

Here are the classes and the base:

class Base
{
public:
    virtual CResult init() noexcept;
};

class A : public Base
{
public:
    ...
};

class B : public Base
{
public:
    ...
};

class C : public Base
{
public:
    ...
};

I have then an instance of A, B and C in the application, together with its init() method:

class Application
{
public:
    CResult init() noexcept;
private:
    A a;
    B b;
    C c;
};

CResult Application::init()
{
    /// iterate on a, b, c and call .init()
    /// add code
}

Now, I want to call the init() methods of all my objects a, b and c iteratively.
That would mean I need to define a table with a, b and c "references" (I say references, but yes it is not possible to have, say, vector of object references). Then to iterate over the table and call each member's init() method.

What is the best OOP way to achieve this? Can anyone share sample code with the table and the iteration?

Body:
The easiest way is probably this:

Base *ptrs[] = {&a, &b, &c};
for (auto ptr : ptrs)
    ptr->init();

If the variables had the same type, you could shorten this to for (auto ptr : {&a, &b, &c}). But since the types are different, you have to manually spell the pointer type when creating the array.


问:
how can apply routerLinkActive directive to this.router.navigate(...) method in angular?;
we can apply routerLinkActive directive along with [routerLink] simply as:

```<code><a [routerLink]="'/profile'" routerLinkActive="active"> My Profile </a>
</code>```

of course for tag . but if we want to navigate for action as bellow:
.ts file:

navigateToMyProfile(): void {
 this.router.navigate(['/profile']);
}```

And the template is:

<mat-list-item (click)="navigateToMyProfile()">

where we can apply routerLinkActive directive for above method? Best regards

答:
Use mat-list-item as an attribute instead.

Use mat-nav-list tags for navigation lists (i.e. lists that have anchor tags).

Simple navigation lists can use the mat-list-item attribute on anchor tag elements directly

<mat-nav-list>
  My Profile
</mat-nav-list>
```

Body:
we can apply routerLinkActive directive along with [routerLink] simply as:

 My Profile

of course for tag . but if we want to navigate for action as bellow:
.ts file:

navigateToMyProfile(): void {
 this.router.navigate(['/profile']);
}

And the template is:

<mat-list-item (click)="navigateToMyProfile()">

where we can apply routerLinkActive directive for above method? Best regards

Body:
Use mat-list-item as an attribute instead.

Use mat-nav-list tags for navigation lists (i.e. lists that have anchor tags).

Simple navigation lists can use the mat-list-item attribute on anchor tag elements directly

<mat-nav-list>
  <a mat-list-item routerLink="/profile" routerLinkActive="active">My Profile</a>
</mat-nav-list>


问:
async/await swift 5.5 on X86_64 linux
I'm use swift 5.5.2 for linux service.

And decided start using async/await for linux service, but  async/await is not supported.

I need use something like this?

```<code>if #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) {
    Task(priority: .utility){
        //do something
    }
} else {
    DispatchQueue.global(qos: .utility).async{
        //do something
    }
}
</code>```

答:
I would suggest you defer the adoption of Swift concurrency (async-await) until it is available on your platform. It will be a frustrating experience to try to write good async-await code without compiler support, having a rich library of framework API that support async-await, the ability to experiment and test your attempts, etc.

Besides, while a deep understanding of GCD will be useful when you dive into async-await, you should dispel notions of one-for-one replacements for your existing GCD API. The new Swift concurrency employs completely different patterns than you would see in GCD. E.g., the most compelling use-case is to replace towers of nested GCD completion handler closures with more natural async-await flow.

Also, let us consider your example: Task { ... } and DispatchQueue.global() { ... } solve different problems. The former is for “I have some Swift concurrency async code that I wish to start in its own Task (e.g., perhaps launching it from a non-asynchronous calling point)” and the latter is for “I have something slow/blocking that I need to get off the main queue.” They are two completely different propositions. If anything, IMHO, Task.detached { ... } is a closer analog to the old “dispatch something slow to a global queue” pattern.

Bottom line, the new Swift concurrency is not just a new surface layer replacement for GCD with one-for-one equivalency at the API level. You would be best served to learn it on a platform with Swift concurrency support (or defer such an exercise until you have access to it on your platform).

I might suggest watching WWDC 2021 video Swift concurrency: Update a sample app. While this focuses on a different platform (iOS), it gives you a good sense of how one goes about refactoring GCD code to the new Swift concurrency. A bunch of if #available(...)-else statements is unlikely to be the approach you will want to take.

Title: async/await swift 5.5 on X86_64 linux

Body:
I'm use swift 5.5.2 for linux service.

And decided start using async/await for linux service, but  async/await is not supported.

I need use something like this?

if #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) {
    Task(priority: .utility){
        //do something
    }
} else {
    DispatchQueue.global(qos: .utility).async{
        //do something
    }
}


问:
Anonymous function implementation in flutter
So, I am learning about anonymous functions in dart which I know helps to reduce and simplify the code when passing a function as an argument to another function. Now, what I want to know is how exactly is this used in building an application using flutter. I am here seeking some practical implementation in actual flutter applications.</p>

答:
Imagine you wanted to implement a CustomButton to reuse it across your entire app. In that case, it typically makes sense for it to return a callback function and handle the event where the button is being used. To do so, you pass an onPressed function to the button, which will be invoked by the button's internal onPressed function.

class CustomButton extends StatelessWidget {
  const CustomButton({
    required this.onPressed,
    required this.title,
  });

  final void Function() onPressed;
  final String title;

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: onPressed,
      child: Text(title),
    );
  }
}
```
<p>Using it:</p>
<pre class="lang-dart prettyprint-override"><code>CustomButton(
  onPressed: () => Navigator.pushNamed(context, '/pageTwo'),
  title: 'Navigate',
)

</code>```

The CustomButton can now push, pop, or do all kinds of things. It is way more flexible than if you implemented a button without a callback function:

class ForwardButton extends StatelessWidget {
  const ForwardButton({
    required this.destination,
    required this.title,
  });

  final String destination;
  final String title;

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () => Navigator.pushNamed(context, destination),
      child: Text(title),
    );
  }
}
```
<pre class="lang-dart prettyprint-override"><code>ForwardButton(
  destination: '/pageTwo',
  title: 'Navigate',
)
</code>```

If you wanted the ForwardButton to do things other than Navigator.pushNamed, you'd need to add more logic or arguments to the constructor, and it'll quickly become messy.

Body:
Imagine you wanted to implement a CustomButton to reuse it across your entire app. In that case, it typically makes sense for it to return a callback function and handle the event where the button is being used. To do so, you pass an onPressed function to the button, which will be invoked by the button's internal onPressed function.

class CustomButton extends StatelessWidget {
  const CustomButton({
    required this.onPressed,
    required this.title,
  });

  final void Function() onPressed;
  final String title;

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: onPressed,
      child: Text(title),
    );
  }
}

Using it:

CustomButton(
  onPressed: () => Navigator.pushNamed(context, '/pageTwo'),
  title: 'Navigate',
)

The CustomButton can now push, pop, or do all kinds of things. It is way more flexible than if you implemented a button without a callback function:

class ForwardButton extends StatelessWidget {
  const ForwardButton({
    required this.destination,
    required this.title,
  });

  final String destination;
  final String title;

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: () => Navigator.pushNamed(context, destination),
      child: Text(title),
    );
  }
}

ForwardButton(
  destination: '/pageTwo',
  title: 'Navigate',
)

If you wanted the ForwardButton to do things other than Navigator.pushNamed, you'd need to add more logic or arguments to the constructor, and it'll quickly become messy.


问:
Exception error when trying to pass down URL from a for loop into a API query
```<code>import requests
import json

api_url = "https://api.taxes.info.net/taxes/%s/rate?page=1"

list =[
{"state": "Ohio",
"state": "California",
"state": "Georgia"}
      ]

for i in list:
   state_name = i.get("state")
   urls = api_url % state_name
print(urls) returns: >>>>> https://api.taxes.info.net/taxes/Ohio/rate?page=1 https://api.taxes.info.net/taxes/California/rate?page=1 https://api.taxes.info.net/taxes/Georgia/rate?page=1

    for url in urls:
        response = requests.get(url, headers={"Accept": "state.api+jsonv3", "Authorization": "password1234")

 Getting error message: >>>>> requests.exceptions.MissingSchema: Invalid URL 'h': No schema supplied. Perhaps you meant http://h?

</code>```

I'm trying to pass down the urls stored in my first for loop and pass it down to my API request. I'm fairly new to programming so any suggestions or pointers would be greatly appreciated. I did confirm my indentation is correct in my second for loop.

答:
In your first loop you create a variable urls which is an string and should represent a url.
After that you're doing another loop inside the first loop and in this  one you go trough every letter in this urls variabe.
The error message you get is because you try to make a request to 'h'.
Your code should look like that:</p>
```<code>import requests
import json

api_url = "https://api.taxes.info.net/taxes/%s/rate?page=1"

list = [
    {"state": "Ohio",
     "state": "California",
     "state": "Georgia"}
]
urls = []
for i in list:
    state_name = i.get("state")
    urls.append(api_url % state_name)
print(urls)

for url in urls:
    response = requests.get(url, headers={"Accept": "state.api+jsonv3", "Authorization": "password1234"})
</code>```

Body:
import requests
import json

api_url = "https://api.taxes.info.net/taxes/%s/rate?page=1"

list =[
{"state": "Ohio",
"state": "California",
"state": "Georgia"}
      ]

for i in list:
   state_name = i.get("state")
   urls = api_url % state_name
print(urls) returns: >>>>> https://api.taxes.info.net/taxes/Ohio/rate?page=1 https://api.taxes.info.net/taxes/California/rate?page=1 https://api.taxes.info.net/taxes/Georgia/rate?page=1

    for url in urls:
        response = requests.get(url, headers={"Accept": "state.api+jsonv3", "Authorization": "password1234")

 Getting error message: >>>>> requests.exceptions.MissingSchema: Invalid URL 'h': No schema supplied. Perhaps you meant http://h?

I'm trying to pass down the urls stored in my first for loop and pass it down to my API request. I'm fairly new to programming so any suggestions or pointers would be greatly appreciated. I did confirm my indentation is correct in my second for loop.

Body:
In your first loop you create a variable urls which is an string and should represent a url.
After that you're doing another loop inside the first loop and in this  one you go trough every letter in this urls variabe.
The error message you get is because you try to make a request to 'h'.
Your code should look like that:

import requests
import json

api_url = "https://api.taxes.info.net/taxes/%s/rate?page=1"

list = [
    {"state": "Ohio",
     "state": "California",
     "state": "Georgia"}
]
urls = []
for i in list:
    state_name = i.get("state")
    urls.append(api_url % state_name)
print(urls)

for url in urls:
    response = requests.get(url, headers={"Accept": "state.api+jsonv3", "Authorization": "password1234"})


问:
file_put_content arrays, but adding just one line
Currently, I'm using this

```<code>$a = "one line";
$emails = array();
while ($row = $data->fetch(PDO::FETCH_ASSOC)) {
    emails[] = $row['id'];
}

file_put_contents("uploads/",$emails, FILE_APPEND | LOCK_EX);
</code>```

And so ofcourse it prints

```<code>1
2
3
4
5
6
7
8
</code>```

Is it possible to attach $a to the top of the print file? Just single line of text instead of arrays.

I basically need it to look like this

```<code>one line
1
2
3
4
5
6
7
8
</code>```

答:
Try this</p>
```<code>$emails = "one line\n";
while ($row = $data->fetch(PDO::FETCH_ASSOC)) {
    $emails .= $row['id']."\n";
}

file_put_contents("uploads/",$emails, FILE_APPEND | LOCK_EX);
</code>```

Body:
Currently, I'm using this

$a = "one line";
$emails = array();
while ($row = $data->fetch(PDO::FETCH_ASSOC)) {
    emails[] = $row['id'];
}

file_put_contents("uploads/",$emails, FILE_APPEND | LOCK_EX);

And so ofcourse it prints

1
2
3
4
5
6
7
8

Is it possible to attach $a to the top of the print file? Just single line of text instead of arrays.

I basically need it to look like this

one line
1
2
3
4
5
6
7
8

Body:
Try this

$emails = "one line\n";
while ($row = $data->fetch(PDO::FETCH_ASSOC)) {
    $emails .= $row['id']."\n";
}

file_put_contents("uploads/",$emails, FILE_APPEND | LOCK_EX);


问:
Django how to create, update and keep clone objects to another database for backup purpose?
postgresql is my primary data base. If any object create in my original database then I want it will also keep an duplicate object in my secondary database. I read Django documentation for create an clone database but didn't work.   here is my code:

#replicarouter.py

```<code> class PrimaryReplicaRouter:
    def db_for_read(self, model, **hints):
        """
        Reads go to a randomly-chosen replica.
        """
        return 'primary'

    def db_for_write(self, model, **hints):
        """
        Writes always go to primary.
        """
        return 'primary'

    def allow_relation(self, obj1,**hints):
        """
        Relations between objects are allowed if both objects are
        in the primary/replica pool.
        """
        db_set = {'primary', 'replica_database'}
        if obj1._state.db in db_set:
            return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        """
        All non-auth models end up in this pool.
        """
        return True

</code>```

settings.py

```<code>     DATABASES = {
        'default':{},
        'primary': {
            'ENGINE': 'django.db.backends.postgresql',
            'NAME': 'my_db_name',
            'USER': 'postgres',
            'PASSWORD': 'my_db_pass',
            'HOST': 'localhost',
            'PORT':5432,
        },

        'replica_database': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'my_db_name',
            'USER': 'root',
            'PASSWORD': '',
            'HOST': 'localhost',
            'PORT': 3306,
        }

    }

DATABASE_ROUTERS = ['my_root_folder_name.dbrouters.AuthRouter','my_root_folder_name.replicarouter.PrimaryReplicaRouter']
</code>```

right now all new objects creating in my primary database. I want to keep clone of every new object in my replica_database. If any object added in my primary database then it will also add an clone object in my replica_database.

答:
finally I find out an solution. After reading django multiple database documentation we can use multiple database but can't keep clone object in our database. Let explain little bit assume you have two model teacher and student. You can use two separate database for teacher and student but you can't use another database for keep clone objects of your teacher and student model. So here we will use django siganls for keep clone objects in our replica_database. Signals will be triggered and create clone object whenever any objects create in our model.  Here is my code:

settings.py

```<code>'default': {
        'NAME': 'primary_database',
        'ENGINE': 'django.db.backends.mysql',
        'HOST': 'localhost',
        'USER': 'root',
        'PASSWORD': '',
    },
    'replica1_database': {
        'NAME': 'replica1_database',
        'ENGINE': 'django.db.backends.mysql',
        'HOST': 'localhost',
        'USER': 'root',
        'PASSWORD': '', },
</code>```

models.py:

```<code>from django.db.models.signals import post_save
from django.dispatch import receiver

class Contact(models.Model):
      name = models.CharField(blank=True, null=True, max_length=100)

@receiver(post_save, sender=Contact, dispatch_uid="clone_objects")
def replica1_databse(sender, instance, created, **kwargs):
    if created: #cerate clone object in our replica1 database
         obj = instance
         obj.save(using='replica1')
    else: #updating clone object in our replica1 database
         obj = Contact.objects.using('replica1').update(
         name=instance.name)
</code>```

Here I am triggering signals for create an clone objects in my replica1_database.

Now run python manage.py makemigrtions contact and python manage.py migrate contact this two migrations applied in your default database. This is the most important step ----> You have to run python manage.py migrate --database=replica1 This migrate applied for your replica1 database.

I Think it also an good idea to keep an backup database for avoid any unexcepted situation such as server down.

Body:
postgresql is my primary data base. If any object create in my original database then I want it will also keep an duplicate object in my secondary database. I read Django documentation for create an clone database but didn't work.   here is my code:

#replicarouter.py

 class PrimaryReplicaRouter:
    def db_for_read(self, model, **hints):
        """
        Reads go to a randomly-chosen replica.
        """
        return 'primary'

    def db_for_write(self, model, **hints):
        """
        Writes always go to primary.
        """
        return 'primary'

    def allow_relation(self, obj1,**hints):
        """
        Relations between objects are allowed if both objects are
        in the primary/replica pool.
        """
        db_set = {'primary', 'replica_database'}
        if obj1._state.db in db_set:
            return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        """
        All non-auth models end up in this pool.
        """
        return True

settings.py

     DATABASES = {
        'default':{},
        'primary': {
            'ENGINE': 'django.db.backends.postgresql',
            'NAME': 'my_db_name',
            'USER': 'postgres',
            'PASSWORD': 'my_db_pass',
            'HOST': 'localhost',
            'PORT':5432,
        },

        'replica_database': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'my_db_name',
            'USER': 'root',
            'PASSWORD': '',
            'HOST': 'localhost',
            'PORT': 3306,
        }

    }

DATABASE_ROUTERS = ['my_root_folder_name.dbrouters.AuthRouter','my_root_folder_name.replicarouter.PrimaryReplicaRouter']

right now all new objects creating in my primary database. I want to keep clone of every new object in my replica_database. If any object added in my primary database then it will also add an clone object in my replica_database.

Body:
finally I find out an solution. After reading django multiple database documentation we can use multiple database but can't keep clone object in our database. Let explain little bit assume you have two model teacher and student. You can use two separate database for teacher and student but you can't use another database for keep clone objects of your teacher and student model. So here we will use django siganls for keep clone objects in our replica_database. Signals will be triggered and create clone object whenever any objects create in our model.  Here is my code:

settings.py

'default': {
        'NAME': 'primary_database',
        'ENGINE': 'django.db.backends.mysql',
        'HOST': 'localhost',
        'USER': 'root',
        'PASSWORD': '',
    },
    'replica1_database': {
        'NAME': 'replica1_database',
        'ENGINE': 'django.db.backends.mysql',
        'HOST': 'localhost',
        'USER': 'root',
        'PASSWORD': '', },

models.py:

from django.db.models.signals import post_save
from django.dispatch import receiver

class Contact(models.Model):
      name = models.CharField(blank=True, null=True, max_length=100)

@receiver(post_save, sender=Contact, dispatch_uid="clone_objects")
def replica1_databse(sender, instance, created, **kwargs):
    if created: #cerate clone object in our replica1 database
         obj = instance
         obj.save(using='replica1')
    else: #updating clone object in our replica1 database
         obj = Contact.objects.using('replica1').update(
         name=instance.name)

Here I am triggering signals for create an clone objects in my replica1_database.

Now run python manage.py makemigrtions contact and python manage.py migrate contact this two migrations applied in your default database. This is the most important step ----> You have to run python manage.py migrate --database=replica1 This migrate applied for your replica1 database.

I Think it also an good idea to keep an backup database for avoid any unexcepted situation such as server down.


问:
Calling a Function During Array Creation to export contents of folder containing Zip files
I am having trouble trying to call a function for a script that I'm using to build a list of zip files in a folder on my PC.  The final CSV I need is to create is a list of the zip files with their uncompressed sizes.  Here is what I have so far (compiled from several posts):

Function to get the uncompressed size:

```<code>function Get-UncompressedZipFileSize {

param (
    $Path
)

$shell = New-Object -ComObject shell.application
$zip = $shell.NameSpace($Path)
$size = 0
foreach ($item in $zip.items()) {
    if ($item.IsFolder) {
        $size += Get-UncompressedZipFileSize -Path $item.Path
    } else {
        $size += $item.size
    }
}

[System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$shell) | Out-Null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

return $size
}
</code>```

Here is my Array Creation:

```<code>$arr = @()
gci C:\zips -recurse | ? {$_.PSIsContainer -eq $False} | % {
$obj = New-Object PSObject
$obj | Add-Member NoteProperty Name $_.Name
$obj | Add-Member NoteProperty FullPath $_.FullName
$arr += $obj
}
$arr | Export-CSV -notypeinformation c:\zips
</code>```

I'm stuck at creating a new member object into my array that will call the get-uncompressedzipfilesize function to pass that size back into the array as a new column in my zip. Is something like this even possible.?

答:
Here is an alternative using ZipFile Class. The SizeConvert Class is inspired from this answer. The output of the Get-ZipFileSize would be the absolute path of the Zip File, its compressed and expanded size and its formatted friendly sizes (i.e.: 7.88 MB instead of 8262942).

using namespace System.IO
using namespace System.IO.Compression
using namespace System.Linq

function Get-ZipFileSize {
    [cmdletbinding()]
    param(
        [parameter(ValueFromPipelineByPropertyName)]
        [string] $FullName
    )

    begin {
        if(-not $IsCoreCLR) {
            Add-Type -AssemblyName System.IO.Compression.FileSystem
        }

        class SizeConvert {
            static [string[]] $Suffix = "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"

            static [string] ToFriendlySize([int64] $Length, [int] $DecimalPoints) {
                $idx = 0

                while ($Length -ge 1kb) {
                    $Length /= 1kb
                    $idx++
                }
                return '{0} {1}' -f [math]::Round($Length, $DecimalPoints), [SizeConvert]::Suffix[$idx]
            }
        }
    }
    process {
        try {
            $zip = [ZipFile]::OpenRead($FullName)

            $expanded   = [Enumerable]::Sum([Int64[]] $zip.Entries.Length)
            $compressed = [Enumerable]::Sum([int64[]] $zip.Entries.CompressedLength)

            [pscustomobject]@{
                FilePath            = $FullName
                RawExpanded         = $expanded
                RawCompressed       = $compressed
                FormattedExpanded   = [SizeConvert]::ToFriendlySize($expanded, 2)
                FormattedCompressed = [SizeConvert]::ToFriendlySize($compressed, 2)
            }
        }
        catch {
            $PSCmdlet.WriteError($_)
        }
        finally {
            if($zip -is [System.IDisposable]) {
                $zip.Dispose()
            }
        }
    }
}

Get-ChildItem -Filter *.zip -Recurse | Get-ZipFileSize | Export-Csv ....
```

Body:
I am having trouble trying to call a function for a script that I'm using to build a list of zip files in a folder on my PC.  The final CSV I need is to create is a list of the zip files with their uncompressed sizes.  Here is what I have so far (compiled from several posts):

Function to get the uncompressed size:

function Get-UncompressedZipFileSize {

param (
    $Path
)

$shell = New-Object -ComObject shell.application
$zip = $shell.NameSpace($Path)
$size = 0
foreach ($item in $zip.items()) {
    if ($item.IsFolder) {
        $size += Get-UncompressedZipFileSize -Path $item.Path
    } else {
        $size += $item.size
    }
}

[System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$shell) | Out-Null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

return $size
}

Here is my Array Creation:

$arr = @()
gci C:\zips -recurse | ? {$_.PSIsContainer -eq $False} | % {
$obj = New-Object PSObject
$obj | Add-Member NoteProperty Name $_.Name
$obj | Add-Member NoteProperty FullPath $_.FullName
$arr += $obj
}
$arr | Export-CSV -notypeinformation c:\zips

I'm stuck at creating a new member object into my array that will call the get-uncompressedzipfilesize function to pass that size back into the array as a new column in my zip. Is something like this even possible.?


问:
Firefox box shadow inset not working properly
I'm using box-shadow to create internal "border" on left and right. It works great in Chrome or Edge but in Firefox it creates "bottom border" as well. I tried prefixing with -moz- and -webkit- but unsuccessfully.

I don't know how to simulate it in chrome so please run the code in Firefox to see what I am talking about.

Also, it sometimes glitches when zooming in or out in the browser (But zooming in or out in Firefox didn't fix it)

div{
      width: 150px;
    height: 200px;
    box-sizing: border-box;
    margin: 0 auto;
    background: #001f49;
    display: grid;
    grid-template-rows: 77% 23%;
    align-items: center
}
h1{
  color: white;
    text-align: center;
    text-transform: uppercase;
    font-size:18px;
}
span{
      background: white;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    box-shadow: inset -1px 0px 0 0 #001f49, inset 1px 0 0 0 #001f49, inset 0 -1px 0 0 #001f49;
    -moz-box-shadow: inset -1px 0px 0 0 #001f49, inset 1px 0 0 0 #001f49, inset 0 -1px 0 0 #001f49;
    -webkit-box-shadow: inset -1px 0px 0 0 #001f49, inset 1px 0 0 0 #001f49, inset 0 -1px 0 0 #001f49;
}
span::before{
  background: inherit;
    top: -22px;
    content: '';
    display: block;
    height: 22px;
    left: 0;
    position: absolute;
    right: 0;
    transform: skewY(352deg);
    transform-origin: 100%;
    box-shadow: inset -1px 0px 0 0 #001f49, inset 1px 0 0 0 #001f49;
    -moz-box-shadow: inset -1px 0px 0 0 #001f49, inset 1px 0 0 0 #001f49;
    -webkit-box-shadow: inset -1px 0px 0 0 #001f49, inset 1px 0 0 0 #001f49;
}
a{
  color: #ed174a;
    text-decoration: none;
    font-weight: bold;
    font-size: 18px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<h1>
Change
</h1>
<span>Pricelist</span>
</div></code>```

答:
I would do the whole thing differently using background and less of code:

div {
  width: 150px;
  height: 200px;
  margin: 0 auto;
  border:1px solid #001f49;
  background: linear-gradient(-13deg,#0000 33%,#001f49 34%);
  display: grid;
  grid-template-rows: 77% 1fr;
  align-items: center;
  text-align: center;
}

h1 {
  color: white;
  text-transform: uppercase;
  font-size: 18px;
}

a {
  color: #ed174a;
  text-decoration: none;
  font-weight: bold;
  font-size: 18px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <h1>
    Change
  </h1>
  <span>Pricelist</span>
</div></code>```

Body:
I'm using box-shadow to create internal "border" on left and right. It works great in Chrome or Edge but in Firefox it creates "bottom border" as well. I tried prefixing with -moz- and -webkit- but unsuccessfully.

I don't know how to simulate it in chrome so please run the code in Firefox to see what I am talking about.

Also, it sometimes glitches when zooming in or out in the browser (But zooming in or out in Firefox didn't fix it)

div{
      width: 150px;
    height: 200px;
    box-sizing: border-box;
    margin: 0 auto;
    background: #001f49;
    display: grid;
    grid-template-rows: 77% 23%;
    align-items: center
}
h1{
  color: white;
    text-align: center;
    text-transform: uppercase;
    font-size:18px;
}
span{
      background: white;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    box-shadow: inset -1px 0px 0 0 #001f49, inset 1px 0 0 0 #001f49, inset 0 -1px 0 0 #001f49;
    -moz-box-shadow: inset -1px 0px 0 0 #001f49, inset 1px 0 0 0 #001f49, inset 0 -1px 0 0 #001f49;
    -webkit-box-shadow: inset -1px 0px 0 0 #001f49, inset 1px 0 0 0 #001f49, inset 0 -1px 0 0 #001f49;
}
span::before{
  background: inherit;
    top: -22px;
    content: '';
    display: block;
    height: 22px;
    left: 0;
    position: absolute;
    right: 0;
    transform: skewY(352deg);
    transform-origin: 100%;
    box-shadow: inset -1px 0px 0 0 #001f49, inset 1px 0 0 0 #001f49;
    -moz-box-shadow: inset -1px 0px 0 0 #001f49, inset 1px 0 0 0 #001f49;
    -webkit-box-shadow: inset -1px 0px 0 0 #001f49, inset 1px 0 0 0 #001f49;
}
a{
  color: #ed174a;
    text-decoration: none;
    font-weight: bold;
    font-size: 18px;
}

Change

Pricelist

Body:
I would do the whole thing differently using background and less of code:

div {
  width: 150px;
  height: 200px;
  margin: 0 auto;
  border:1px solid #001f49;
  background: linear-gradient(-13deg,#0000 33%,#001f49 34%);
  display: grid;
  grid-template-rows: 77% 1fr;
  align-items: center;
  text-align: center;
}

h1 {
  color: white;
  text-transform: uppercase;
  font-size: 18px;
}

a {
  color: #ed174a;
  text-decoration: none;
  font-weight: bold;
  font-size: 18px;
}

<div>
  <h1>
    Change
  </h1>
  <span><a href="#">Pricelist</a></span>
</div>


答:
Let's go in order.

You have created a list of one dict.
Although in your case, you need to create an array and list the necessary elements in it.

```<code>list =[
{"state": "Ohio",
"state": "California",
"state": "Georgia"}
      ]
</code>```

further in the loop, you create the urls variable, and it seems to be correct, but you redefine it. This means that if you have 100 elements, then the variable will still have the last one.

```<code>for i in list:
   state_name = i.get("state")
   urls = api_url % state_name
</code>```

And since your urls is a string, then looping through it, the python will iterate each character, which is exactly what requests complain about.

Below I have attached the code which should work correctly
import requests
import json

```<code>api_url = "https://api.taxes.info.net/taxes/%s/rate?page=1"

states = ["Ohio", "California", "Georgia"]
request_urls = []

for state in states:
    state_name = state
    request_urls.append(api_url % state_name)

for url in request_urls:
    response = requests.get(url, headers={"Accept": "state.api+jsonv3", "Authorization": "password1234"})
</code>```

Title: Exception error when trying to pass down URL from a for loop into a API query

Body:
Let's go in order.

You have created a list of one dict.
Although in your case, you need to create an array and list the necessary elements in it.

list =[
{"state": "Ohio",
"state": "California",
"state": "Georgia"}
      ]

further in the loop, you create the urls variable, and it seems to be correct, but you redefine it. This means that if you have 100 elements, then the variable will still have the last one.

for i in list:
   state_name = i.get("state")
   urls = api_url % state_name

And since your urls is a string, then looping through it, the python will iterate each character, which is exactly what requests complain about.

Below I have attached the code which should work correctly
import requests
import json

api_url = "https://api.taxes.info.net/taxes/%s/rate?page=1"

states = ["Ohio", "California", "Georgia"]
request_urls = []

for state in states:
    state_name = state
    request_urls.append(api_url % state_name)

for url in request_urls:
    response = requests.get(url, headers={"Accept": "state.api+jsonv3", "Authorization": "password1234"})