问:
Can't iterate through a list in python
After recieving data from mysql connector, when I try to iterate over the list, python keeps telling me the data is of type int:

The execute() and fetchall() statements:

```<code>def top_sellers(self):
        q = '''select Item, sum(Quantity) from purchases group by Item;'''
        self.cursor.execute(q)
        s = self.cursor.fetchall()
        print(s)
        print(type(s))
        for i in len(s):
            print(i)
</code>```

The above code exits with:

```<code>[('beep', Decimal('3')), ('item1', Decimal('39')), ('Mask', Decimal('53')), ('Mask1', Decimal('2'))]
<class 'list'>
Traceback (most recent call last):
  File "/data/data/com.termux/files/home/projekt-red/index.py", line 326, in <module>
    main(id, password)
  File "/data/data/com.termux/files/home/projekt-red/index.py", line 324, in main
    x.load_prompt(acc_type)
  File "/data/data/com.termux/files/home/projekt-red/index.py", line 301, in load_prompt
    self.stats()
  File "/data/data/com.termux/files/home/projekt-red/index.py", line 243, in stats
    self.top_sellers()
  File "/data/data/com.termux/files/home/projekt-red/index.py", line 265, in top_sellers
    for i in len(list(s)):
TypeError: 'int' object is not iterable
</code>```

答:
len(s) is an integer, which is not iterable.
If you want to iterate n times, with n = len(s), you need to replace len(s) by range(len(s)) like so:

def top_sellers(self):
        q = '''select Item, sum(Quantity) from purchases group by Item;'''
        self.cursor.execute(q)
        s = self.cursor.fetchall()
        print(s)
        print(type(s))
        for i in range(len(s)):
            print(i)
```

Edit:
This will print all the indices. If you want to print the results stored in s, then simply remove the len() and range(), just keeping for i in s. Or alternatively, keep it as above and replace the print statement by print(s[i]).

Title: Can't iterate through a list in python

Body:
After recieving data from mysql connector, when I try to iterate over the list, python keeps telling me the data is of type int:

The execute() and fetchall() statements:

def top_sellers(self):
        q = '''select Item, sum(Quantity) from purchases group by Item;'''
        self.cursor.execute(q)
        s = self.cursor.fetchall()
        print(s)
        print(type(s))
        for i in len(s):
            print(i)

The above code exits with:

[('beep', Decimal('3')), ('item1', Decimal('39')), ('Mask', Decimal('53')), ('Mask1', Decimal('2'))]
<class 'list'>
Traceback (most recent call last):
  File "/data/data/com.termux/files/home/projekt-red/index.py", line 326, in <module>
    main(id, password)
  File "/data/data/com.termux/files/home/projekt-red/index.py", line 324, in main
    x.load_prompt(acc_type)
  File "/data/data/com.termux/files/home/projekt-red/index.py", line 301, in load_prompt
    self.stats()
  File "/data/data/com.termux/files/home/projekt-red/index.py", line 243, in stats
    self.top_sellers()
  File "/data/data/com.termux/files/home/projekt-red/index.py", line 265, in top_sellers
    for i in len(list(s)):
TypeError: 'int' object is not iterable

Body:
len(s) is an integer, which is not iterable.
If you want to iterate n times, with n = len(s), you need to replace len(s) by range(len(s)) like so:

def top_sellers(self):
        q = '''select Item, sum(Quantity) from purchases group by Item;'''
        self.cursor.execute(q)
        s = self.cursor.fetchall()
        print(s)
        print(type(s))
        for i in range(len(s)):
            print(i)

Edit:
This will print all the indices. If you want to print the results stored in s, then simply remove the len() and range(), just keeping for i in s. Or alternatively, keep it as above and replace the print statement by print(s[i]).


来源: stackexchange

问:
Searching for a string with multiple words
I am trying to find a specific string with 3 words in it using VBA. The string I am searching for is "Material Review Report". My code sort of works if I search for either "Material" or "Material Review" but when I try to search for the full string nothing is returned even though the string does exist in the document. It also won't find anything if I search for "Review Report" for example.
Here is my code:

```<code>Private Function getStringFromWord(strWordFile As String) As String
Dim appWord As Word.Application
Dim docWord As Word.Document
Dim strFind As String
Dim i As Integer
Dim rngDoc As Word.Range

Set appWord = New Word.Application
Set docWord = appWord.Documents.Open(strWordFile)

Set rngDoc = docWord.Content
With rngDoc.Find
    .ClearFormatting
    .Forward = True
    .Wrap = wdFindContinue
    .MatchWildcards = True
        'strFind = "Material" 'Works
        'strFind = "Material Review" 'Works
         strFind = "Material Review Report" 'Does not work???
            .Text = strFind
            .Execute
            If .Found = True Then
                MsgBox "Found!"
            End If
End With

docWord.Close
    Set docWord = Nothing
appWord.Quit
    Set appWord = Nothing
End Function
</code>```

So, what I am doing wrong here? Any help in pointing me to the right direction will be much appreciated.

答:
I agree with @FunThomas. There may be some unexpected white spaces between the words that happens when opening/importing text from PDF or other external sources. Try searching with any or all of these properties set to true

```<code> .IgnorePunct = True
 .IgnoreSpace = True
 .MatchPhrase = True
</code>```

Browse https://www.codevba.com/Word/Find.htm#.YgEsB5qZMuU for more.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to find a specific string with 3 words in it using VBA. The string I am searching for is "Material Review Report". My code sort of works if I search for either "Material" or "Material Review" but when I try to search for the full string nothing is returned even though the string does exist in the document. It also won't find anything if I search for "Review Report" for example.
Here is my code:

Private Function getStringFromWord(strWordFile As String) As String
Dim appWord As Word.Application
Dim docWord As Word.Document
Dim strFind As String
Dim i As Integer
Dim rngDoc As Word.Range

Set appWord = New Word.Application
Set docWord = appWord.Documents.Open(strWordFile)

Set rngDoc = docWord.Content
With rngDoc.Find
    .ClearFormatting
    .Forward = True
    .Wrap = wdFindContinue
    .MatchWildcards = True
        'strFind = "Material" 'Works
        'strFind = "Material Review" 'Works
         strFind = "Material Review Report" 'Does not work???
            .Text = strFind
            .Execute
            If .Found = True Then
                MsgBox "Found!"
            End If
End With

docWord.Close
    Set docWord = Nothing
appWord.Quit
    Set appWord = Nothing
End Function

So, what I am doing wrong here? Any help in pointing me to the right direction will be much appreciated.

Body:
I agree with @FunThomas. There may be some unexpected white spaces between the words that happens when opening/importing text from PDF or other external sources. Try searching with any or all of these properties set to true

 .IgnorePunct = True
 .IgnoreSpace = True
 .MatchPhrase = True

Browse https://www.codevba.com/Word/Find.htm#.YgEsB5qZMuU for more.


问:
The problem with displaying imask with material ui TextField
If I enter One character and remove the focus, the Textfield breaks.
I guess mask problems
As shown in the picture
My code https://codesandbox.io/s/happy-blackwell-5sigw?file=/src/App.js:0-610

```<code>import { TextField } from "@material-ui/core";
import { IMaskMixin } from "react-imask";
import { useForm } from "react-hook-form";

const IMaskPhoneInput = IMaskMixin(({ ...props }) => {
  return <TextField {...props} />;
});

export default function App() {
  const {
    register,
  } = useForm();

  return (
    <div className="App">
      <IMaskPhoneInput
        autoFocus
        fullWidth
        mask={"+{7} (000) 000-00-00"}
        color="primary"
        label={"Телефон"}
        placeholder={"+7 (950) 356-55-44"}
        {...register("phone")}
      />
    </div>
  );
}
</code>```

答:
Have you tried including the shrink prop?

```<code><TextField InputLabelProps={{ shrink: true }} />
</code>```

This is per the documentation at https://mui.com/components/text-fields/ under limitations

Shrink

The input label "shrink" state isn't always correct. The input label is supposed to shrink as soon as the input is displaying something. In some circumstances, we can't determine the "shrink" state (number input, datetime input, Stripe input). You might notice an overlap.

To workaround the issue, you can force the "shrink" state of the label.
<TextField InputLabelProps={{ shrink: true }} /> or <InputLabel shrink>Count</InputLabel>

Body:
If I enter One character and remove the focus, the Textfield breaks.
I guess mask problems
As shown in the picture
My code https://codesandbox.io/s/happy-blackwell-5sigw?file=/src/App.js:0-610

import { TextField } from "@material-ui/core";
import { IMaskMixin } from "react-imask";
import { useForm } from "react-hook-form";

const IMaskPhoneInput = IMaskMixin(({ ...props }) => {
  return <TextField {...props} />;
});

export default function App() {
  const {
    register,
  } = useForm();

  return (

      <IMaskPhoneInput
        autoFocus
        fullWidth
        mask={"+{7} (000) 000-00-00"}
        color="primary"
        label={"Телефон"}
        placeholder={"+7 (950) 356-55-44"}
        {...register("phone")}
      />

  );
}

Body:
Have you tried including the shrink prop?

<TextField InputLabelProps={{ shrink: true }} />

This is per the documentation at https://mui.com/components/text-fields/ under limitations

Shrink

The input label "shrink" state isn't always correct. The input label is supposed to shrink as soon as the input is displaying something. In some circumstances, we can't determine the "shrink" state (number input, datetime input, Stripe input). You might notice an overlap.

To workaround the issue, you can force the "shrink" state of the label.
<TextField InputLabelProps={{ shrink: true }} /> or <InputLabel shrink>Count</InputLabel>


问:
Query circular attribute in graphql
I have the following scheme

```<code>type Product {
   code: ID!
   services: [ServiceGroup]
}

type ServiceGroup {
   code: String!
   options: [ServiceItem]
}

type ServiceItem {
   itemName: String!
   groups: [ServiceGroup]
}
</code>```

Now in the client, how can I query a product and its services considering that groups is nested with more groups.

```<code>gql`
 query getProduct($code: ID!) {
     product(code: $code) {
        code
        services {
           code
           options {
               itemName
               groups {
                  code
                  options {
                    ....
                  }
                }
            }
        }
     }
  }
`

</code>```

答: The query would have to be dynamically written in the client based on what the depth is. You could have another query field that returns this.</p>

Title: Query circular attribute in graphql

Body:
I have the following scheme

type Product {
   code: ID!
   services: [ServiceGroup]
}

type ServiceGroup {
   code: String!
   options: [ServiceItem]
}

type ServiceItem {
   itemName: String!
   groups: [ServiceGroup]
}

Now in the client, how can I query a product and its services considering that groups is nested with more groups.

gql`
 query getProduct($code: ID!) {
     product(code: $code) {
        code
        services {
           code
           options {
               itemName
               groups {
                  code
                  options {
                    ....
                  }
                }
            }
        }
     }
  }
`


问:
Python Outlook how to handle recall email
My project works on emails in Inbox. When process get a "Recall" email it crashes. Recall email does not have subject attribute. I want to write some error handling. I cannot find method to move email to another folder or delete such email from Outlook.

Currently my Code skip such items using method GetPrevious() but the email is still in Inbox
Do you have any ideas how to make 'recall' email disappear from Inbox folder?

```<code>    obj_emails = obj_inbox.Items
    obj_email = obj_emails.GetLast()

    if obj_email.MessageClass == 'IPM.Outlook.Recall':
        obj_email = obj_emails.GetPrevious()
</code>```

答: Check the Class property - all OOM objects expose it. For the MailItem, it will be 43 (OlObjectClass.olMail). For ReportItem - 46 (OlObjectClass.olReport)

Body:
My project works on emails in Inbox. When process get a "Recall" email it crashes. Recall email does not have subject attribute. I want to write some error handling. I cannot find method to move email to another folder or delete such email from Outlook.

Currently my Code skip such items using method GetPrevious() but the email is still in Inbox
Do you have any ideas how to make 'recall' email disappear from Inbox folder?

    obj_emails = obj_inbox.Items
    obj_email = obj_emails.GetLast()

    if obj_email.MessageClass == 'IPM.Outlook.Recall':
        obj_email = obj_emails.GetPrevious()


问:
Element wise multiplication of 2 pandas series containing matrices as elements
Suppose I have 2 pandas series, a and b, where the elements are matrices as follows

```<code>a = pd.Series([np.array([[1,2], [3,4]]), np.array([[1,2], [3,4]])])

b = pd.Series([np.array([[1,2], [3,4]]), np.array([[1,2], [3,4]])])

</code>```

I would like to multiply the series elements of a with b such that the output looks like:

output of series multiplication

I have the following solution which works:

```<code>
c = []

for i in range(a.shape[0]):

    c.append(np.matmul(a[i], b[i]))

</code>```

however, this requires a for loop and outputs a list rather than a .Series. Any ideas how this could be done in a more compact form? Thanks.

答:
I couldn't figure out how to do it in pandas, but it's so much easier if you convert those Series to numpy arrays.

pd.Series(list(np.matmul(np.array(a.to_list()), np.array(b.to_list()))))
```

Body:
Suppose I have 2 pandas series, a and b, where the elements are matrices as follows

a = pd.Series([np.array([[1,2], [3,4]]), np.array([[1,2], [3,4]])])

b = pd.Series([np.array([[1,2], [3,4]]), np.array([[1,2], [3,4]])])

I would like to multiply the series elements of a with b such that the output looks like:

output of series multiplication

I have the following solution which works:

c = []

for i in range(a.shape[0]):

    c.append(np.matmul(a[i], b[i]))

however, this requires a for loop and outputs a list rather than a .Series. Any ideas how this could be done in a more compact form? Thanks.


问:
Spring boot maven project has to be updated everytime to see a change ECLIPSE IDE
I am using thymeleaf with spring boot my index.html is located in src/main/resources/template every time I want to see a change I have to stop the server, update the project, and rerun the application, this is highly ineffeciant, I just want to run and refresh, I added devtools to my dependencies and also set spring.thymeleaf.cache= false and it still does not work

答:
One of the main challenge for the java developers is to deploy the apps and restart server when ever there is a code change.we can reload the code changes without having to restart the server. In Spring Boot this can be achieved by adding a DevTools module, just add the following dependency in your Spring Boots pom.xml and build it.

```<code><dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-devtools</artifactId>
     <optional>true</optional>
</dependency>
</code>```

Spring Boot DevTools module does exactly what developers needed, this eliminates the process of manually deploying the changes. DevTools will auto restart the server when we have changes. Spring team they haven’t included this feature in Spring Boot’s initial version, upon several request they added this feature later.

Body:
One of the main challenge for the java developers is to deploy the apps and restart server when ever there is a code change.we can reload the code changes without having to restart the server. In Spring Boot this can be achieved by adding a DevTools module, just add the following dependency in your Spring Boots pom.xml and build it.

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-devtools</artifactId>
     <optional>true</optional>
</dependency>

Spring Boot DevTools module does exactly what developers needed, this eliminates the process of manually deploying the changes. DevTools will auto restart the server when we have changes. Spring team they haven’t included this feature in Spring Boot’s initial version, upon several request they added this feature later.


问:
add many view controller
How can I receive different values from appDelegate?</p>

```<code>@synthesize window;
@synthesize viewController;
@synthesize viewController2;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    [self.window addSubview:viewController2.view];
    [self.window addSubview:viewController.view];

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        if (choix==6) {
            XMLTestAppDelegate   *appDelegatess = (BroseFormular2*)[[UIApplication sharedApplication] delegate];
            appDelegatess.viewController2.detailItem =[listOfMovies objectAtIndex:indexPath.row];
        }
        else if (choix==7)
        {
            XMLTestAppDelegate   *appDelegate = (BroseFormular2*)[[UIApplication sharedApplication] delegate];
            appDelegate.viewController2.detailItem =[listOfMovies objectAtIndex:indexPath.row];
        }
        else {
            NSLog(@"no");
            XMLTestAppDelegate   *appDelegates = (authe*)[[UIApplication sharedApplication] delegate];
            appDelegates.viewController.detailItem =[listOfMovies objectAtIndex:indexPath.row];
        }
</code>```

答:
There should be only one view controller in the window on the iPhone.  Only one controller should be controlling the view at a time.

This is going to be a problem:

```<code>[self.window addSubview:viewController2.view];
[self.window addSubview:viewController.view];
</code>```

[EDIT] Actually, there are cases where you can have two view controllers active on the iPad, for example you can have a view controller in a pop up view.

ContentLicense: CC BY-SA 3.0

Title: add many view controller

Body:
How can I receive different values from appDelegate?

@synthesize window;
@synthesize viewController;
@synthesize viewController2;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    [self.window addSubview:viewController2.view];
    [self.window addSubview:viewController.view];

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        if (choix==6) {
            XMLTestAppDelegate   *appDelegatess = (BroseFormular2*)[[UIApplication sharedApplication] delegate];
            appDelegatess.viewController2.detailItem =[listOfMovies objectAtIndex:indexPath.row];
        }
        else if (choix==7)
        {
            XMLTestAppDelegate   *appDelegate = (BroseFormular2*)[[UIApplication sharedApplication] delegate];
            appDelegate.viewController2.detailItem =[listOfMovies objectAtIndex:indexPath.row];
        }
        else {
            NSLog(@"no");
            XMLTestAppDelegate   *appDelegates = (authe*)[[UIApplication sharedApplication] delegate];
            appDelegates.viewController.detailItem =[listOfMovies objectAtIndex:indexPath.row];
        }

Body:
There should be only one view controller in the window on the iPhone.  Only one controller should be controlling the view at a time.

This is going to be a problem:

[self.window addSubview:viewController2.view];
[self.window addSubview:viewController.view];

[EDIT] Actually, there are cases where you can have two view controllers active on the iPad, for example you can have a view controller in a pop up view.


问:
Exception has occurred: Error: ENOENT: no such file or directory
I am trying to debug my nodejs application but on running javascript debugger, it's showing error.

Here is the package.json file of my project.

```<code>{
   "name": "server",
   "version": "1.0.0",
   "description": "server side",
   "main": "index.js",
   "scripts": {
     "start": "nodemon index.js",
     "debug": "nodemon --inspect index.js"
   },
   "keywords": [],
   "dependencies": {
     "aws-sdk": "^2.1069.0",
     "bcryptjs": "^2.4.3",
     "body-parser": "^1.19.1",
     "cors": "^2.8.5",
     "dotenv": "^16.0.0",
     "express": "^4.17.2",
     "express-validator": "^6.14.0",
     "jsonwebtoken": "^8.5.1",
     "mongoose": "^6.2.0",
     "multer": "^1.4.4",
     "nodemon": "^2.0.15"
   },
   "devDependencies": {},
   "author": "alkairis",
   "license": "ISC"
}
</code>```

答:
If you're using VSCode, I recommend to expose a port at inspect like this:

nodemon --inspect=0.0.0.0:9229 index.js

and then you add something like this config to your .vscode/launch.json:

{
              "type": "node",
              "request": "attach",
              "name": "Attach to Remote",
              "restart": true,
              "stopOnEntry": true,
              "port": 9229,
              "address": "0.0.0.0",
              "localRoot": "${workspaceFolder}",
              "sourceMaps": true,
              "protocol": "inspector"
}
```

Body:
I am trying to debug my nodejs application but on running javascript debugger, it's showing error.

Here is the package.json file of my project.

{
   "name": "server",
   "version": "1.0.0",
   "description": "server side",
   "main": "index.js",
   "scripts": {
     "start": "nodemon index.js",
     "debug": "nodemon --inspect index.js"
   },
   "keywords": [],
   "dependencies": {
     "aws-sdk": "^2.1069.0",
     "bcryptjs": "^2.4.3",
     "body-parser": "^1.19.1",
     "cors": "^2.8.5",
     "dotenv": "^16.0.0",
     "express": "^4.17.2",
     "express-validator": "^6.14.0",
     "jsonwebtoken": "^8.5.1",
     "mongoose": "^6.2.0",
     "multer": "^1.4.4",
     "nodemon": "^2.0.15"
   },
   "devDependencies": {},
   "author": "alkairis",
   "license": "ISC"
}


问:
Scatterplot looks strange
my scatterplot that shows the relationship between my principal component and one of my questionnaire items looks strange.
The scatterplot between two of my principal components looks great (see second image).

The item is measured on a Likert scale from 1 to 5 (1 = strongly disagree, 5 = strongly agree). The histogram of this item also has many gaps between the bars, which is strange to me too.

Please let me know which specific output you still need to figure this out.

Thanks

答: That is because the principal components are both metric and the Likert scale is ordinal, so the values can only be integers from 1-5. In this regard the Scatterplot does not look strange but it might be the wrong type of plot. If you anyway want to use a scatterplot you can use jitter(var, 0.3) on the ordinal variable when creating the plot. 0.3 is just a suggestion, it's best if you just try what works. As you didn't provide a reproducible example I wasn't able to try it out.

Title: Scatterplot looks strange


问:
Is battery level info available while using iOS Simulator? Even sample app crashes
I have installed Battery 1.0.1 from pub but can't get it to work in iOS Simulator.
I tried the example app included in the pub, and also my own simple implementation. Both work fine in Android emulator, but in iOS simulator they throw the following

```<code>Exception has occurred.  PlatformException (PlatformException(UNAVAILABLE, Battery info unavailable, null))
</code>```

I've googled, but can't confirm if this info is available at all in iOS simulator, so I don't know if this is a problem on my side.

Is it possible to check for battery level in the simulator at all?
thank you.

答: I had the same issue with IOS simulator. Then I've tried on real IOS device and works well.</p>

Body:
I have installed Battery 1.0.1 from pub but can't get it to work in iOS Simulator.
I tried the example app included in the pub, and also my own simple implementation. Both work fine in Android emulator, but in iOS simulator they throw the following

Exception has occurred.  PlatformException (PlatformException(UNAVAILABLE, Battery info unavailable, null))

I've googled, but can't confirm if this info is available at all in iOS simulator, so I don't know if this is a problem on my side.

Is it possible to check for battery level in the simulator at all?
thank you.


问:
need data before constructor angular (no resolver)
I have a dialog service. I create the dialog component using viewContainerRef and ComponentFactory.
Now, this component is made. and I set a default value to a property in this component.

```<code> this.componentRef = viewContainerRef.createComponent(componentFactory);
 this.componentRef.instance.data = configData;
</code>```

This component inherits from a base class (with super).

There's a virtual method that calls in my component (call from the base class).

I want that default value but the instance is not filled yet.

答:
its by default that you can't access input properties in constructor. if you still want to do it you can use injector for that.

constructor(injector: Injector){};

```<code>const injector = Injector.create({
   providers: [{provide: 'data', useValue: this.configData}],
   parent: this.injector
})

this.componentRef = viewContainerRef.createComponent(componentFactory, {injector});
</code>```

and in your component then you can use it like :-

```<code>constructor(@Inject('data') data: any){
    // source code;
}
</code>```

Body:
I have a dialog service. I create the dialog component using viewContainerRef and ComponentFactory.
Now, this component is made. and I set a default value to a property in this component.

 this.componentRef = viewContainerRef.createComponent(componentFactory);
 this.componentRef.instance.data = configData;

This component inherits from a base class (with super).

There's a virtual method that calls in my component (call from the base class).

I want that default value but the instance is not filled yet.

Body:
its by default that you can't access input properties in constructor. if you still want to do it you can use injector for that.

constructor(injector: Injector){};

const injector = Injector.create({
   providers: [{provide: 'data', useValue: this.configData}],
   parent: this.injector
})

this.componentRef = viewContainerRef.createComponent(componentFactory, {injector});

and in your component then you can use it like :-

constructor(@Inject('data') data: any){
    // source code;
}


问:
Control.Invoke() and Control.BeginInvoke() - Where are the past parameters stored? How is it disposed?
I have done a lot of reading about Control.Invoke and Control.BeginInvoke and understand that Invoke is like SendMessage() and BeginInvoke is like PostMessage(), but I do not understand where the parameter list passed via new object[] { arg, arg, arg, ...} is stored. During a conventional call, parameters are pushed to the stack and popped within the called function, then the call frame is recovered from the stack after exit, I assume releasing any references to any heap objects, allowing them to be collected. So, where is the pushed stack date for Invoke/BeginInvoke stored? How does it get disposed once the method called exits?

Also, I have successfully invoked a control method without loading a new object array with the pass parameters. Why would this work? Better yet, since it does work, why would all the examples I have ever seen show it with a new object array?

This is what I have always seen and used:

```<code>BeginInvoke(FormReceiveEvent, new object[] { Event, Arg1, Arg2, Arg3 });
</code>```

But this works too:

```<code>BeginInvoke(FormReceiveEvent, Event, Arg1, Arg2, Arg3);
</code>```

Any information and comments are always appreciated...

Thanks in advance.

答:
Not always its true that a passed param is stored on stack. Only if its valuetype its stored. Other wise a ref is stored there looking at heap for that ref type.

In this case, the same holds good too. And difference b.w object array and passing as individual array, i guess its the allocation on stack. If you pass them seperately more stack space is allocated. Where as, a ref is allocated in stack pointing out to N number of array objects in heap.

Feel free to correct me.

Body:
I have done a lot of reading about Control.Invoke and Control.BeginInvoke and understand that Invoke is like SendMessage() and BeginInvoke is like PostMessage(), but I do not understand where the parameter list passed via new object[] { arg, arg, arg, ...} is stored. During a conventional call, parameters are pushed to the stack and popped within the called function, then the call frame is recovered from the stack after exit, I assume releasing any references to any heap objects, allowing them to be collected. So, where is the pushed stack date for Invoke/BeginInvoke stored? How does it get disposed once the method called exits?

Also, I have successfully invoked a control method without loading a new object array with the pass parameters. Why would this work? Better yet, since it does work, why would all the examples I have ever seen show it with a new object array?

This is what I have always seen and used:

BeginInvoke(FormReceiveEvent, new object[] { Event, Arg1, Arg2, Arg3 });

But this works too:

BeginInvoke(FormReceiveEvent, Event, Arg1, Arg2, Arg3);

Any information and comments are always appreciated...

Thanks in advance.


问:
Web api not hitting breakpoint and getting 500 internal server error
We are developing webapi project using visual studio 2012. After build my project it shows Build succeeded. I put breakpoint into my webapi function and I was trying to get my output using fiddler. It's not hitting the breakpoint and getting 500 internal server error in my fiddler output.</p>

答:
There may be a variable that may contain any string like HTML. You can include attribute of AllowHTML on that specific property.</p>
```<code>[AllowHtml]
public string OutComes { get; set; }
</code>```

Body:
There may be a variable that may contain any string like HTML. You can include attribute of AllowHTML on that specific property.

[AllowHtml]
public string OutComes { get; set; }


问:
Can't extract value from <> need struct type but got string;
I have some nested json that I have parallelized and spat out as a json.  A complete record would look like:

```<code>{
   "id":"1",
   "type":"site",
   "attributes":{
      "description":"Number 1 Park",
      "activeInactive":{
         "text":"Active",
         "colour":"#4CBB17"
      },
      "lastUpdated":"2019-12-05T08:51:39"
   },
   "relationships":{
      "region":{
         "data":{
            "type":"region",
            "id":"1061",
            "meta":{
               "displayValue":"Park Region"
            }
         }
      }
   }
}
</code>```

However, the data is pending a data cleanse and currently the region field is not populated.

```<code>{
   "id":"1",
   "type":"site",
   "attributes":{
      "description":"Number 1 Park",
      "activeInactive":{
         "text":"Active",
         "colour":"#4CBB17"
      },
      "lastUpdated":"2019-12-05T08:51:39"
   },
   "relationships":{
      "region":{
         "data": null
         }
      }
   }
}
</code>```

The data element will be null if the relationship doesn't exist (i.e. it is an orphaned site).

I run this JSON into a spark dataframe via an RDD.  The schema of the dataframe is:

```<code>attributes:struct
    activeInactive:struct
       colour:string
       text:string
    description:string
    lastUpdated:string
id:string
relationships:struct
    region:struct
       data:string
</code>```

I get errors when coding for region using df.select(col('relationships.region.data.meta.displayValue')) as if the nested fields were there rather than data as per the topic heading.  I'm going to assume this is because of the conflict with the dataframe's schema.

The question is how can I make this more dynamic and still obtain the displayValue as and when this is populated without needing to revisit the code?

答:
While reading a json file, you can impose the schema on the output dataframe using this syntax:

```<code>df = spark.read.json("<path to json file>", schema = <schema object>)
</code>```

This way the data field will still show you null, but it's gonna be StructType() with a complete nested structure.

Based on the data snippet that was provided the applicable schema object looks like this:

```<code>schemaObject = StructType([
  StructField('id', StringType(), True),
  StructField('type', StringType(), True),
  StructField('attributes', StructType([
    StructField('descrption', StringType(), True),
    StructField('activeInactive', StructType([
      StructField('text', StringType(), True),
      StructField('colour', StringType(), True)
    ]), True),
    StructField('lastUpdated', StringType(), True)
  ]), True),
  StructField('relationships'StructType([
    StructField('region', StructType([
      StructField('data', StructType([
        StructField('type', StringType(), True),
        StructField('id', StringType(), True),
        StructField('meta', StructType([
          StructField('displayValue', StringType(), True)
        ]), True)
      ]), True)
    ]), True)
  ]), True)
])
</code>```

Body:
I have some nested json that I have parallelized and spat out as a json.  A complete record would look like:

{
   "id":"1",
   "type":"site",
   "attributes":{
      "description":"Number 1 Park",
      "activeInactive":{
         "text":"Active",
         "colour":"#4CBB17"
      },
      "lastUpdated":"2019-12-05T08:51:39"
   },
   "relationships":{
      "region":{
         "data":{
            "type":"region",
            "id":"1061",
            "meta":{
               "displayValue":"Park Region"
            }
         }
      }
   }
}

However, the data is pending a data cleanse and currently the region field is not populated.

{
   "id":"1",
   "type":"site",
   "attributes":{
      "description":"Number 1 Park",
      "activeInactive":{
         "text":"Active",
         "colour":"#4CBB17"
      },
      "lastUpdated":"2019-12-05T08:51:39"
   },
   "relationships":{
      "region":{
         "data": null
         }
      }
   }
}

The data element will be null if the relationship doesn't exist (i.e. it is an orphaned site).

I run this JSON into a spark dataframe via an RDD.  The schema of the dataframe is:

attributes:struct
    activeInactive:struct
       colour:string
       text:string
    description:string
    lastUpdated:string
id:string
relationships:struct
    region:struct
       data:string

I get errors when coding for region using df.select(col('relationships.region.data.meta.displayValue')) as if the nested fields were there rather than data as per the topic heading.  I'm going to assume this is because of the conflict with the dataframe's schema.

The question is how can I make this more dynamic and still obtain the displayValue as and when this is populated without needing to revisit the code?

Body:
While reading a json file, you can impose the schema on the output dataframe using this syntax:

df = spark.read.json("<path to json file>", schema = <schema object>)

This way the data field will still show you null, but it's gonna be StructType() with a complete nested structure.

Based on the data snippet that was provided the applicable schema object looks like this:

schemaObject = StructType([
  StructField('id', StringType(), True),
  StructField('type', StringType(), True),
  StructField('attributes', StructType([
    StructField('descrption', StringType(), True),
    StructField('activeInactive', StructType([
      StructField('text', StringType(), True),
      StructField('colour', StringType(), True)
    ]), True),
    StructField('lastUpdated', StringType(), True)
  ]), True),
  StructField('relationships'StructType([
    StructField('region', StructType([
      StructField('data', StructType([
        StructField('type', StringType(), True),
        StructField('id', StringType(), True),
        StructField('meta', StructType([
          StructField('displayValue', StringType(), True)
        ]), True)
      ]), True)
    ]), True)
  ]), True)
])


问:
Why nested structure is needed in singly linked list?
I'm new to data structures and algorithms. Right know I'm learning singly linked lists and I'm confused with a piece of code that creates a linked list.

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

struct node
{
    int data;
    struct node *next;
};

int main()
{
    int n;
    struct node *head = NULL;
    head = malloc(sizeof(struct node));

    head->data = 36;
    head->next = NULL;

    printf("%d", head->data);
}
</code>```

My question is why we have to use struct node *next; part in order to refer to memory location of next node.

Why can't we instead use int *next?

答:
This definition

```<code>struct node
{
    int data;
    struct node *next;
};
</code>```

explains

"This is a node, carrying info on an int and pointing to another node (if not NULL), which in turn might point to yet another node... and so on."

A typical linked list.

This is what I understand your alternative to be:

```<code>struct node
{
    int data;
    int *next;
};
</code>```

And it would explain:

"This is a node, carrying info on an int and pointing to another int (if not NULL)."

But an int cannot provide access to yet another int. So this one can provide access to info on one or two ints.

The idea of a linked list, in contrast, is however that it can (assuming memory) provide access to an indeterminate and quite high number of nodes.

Body:
I'm new to data structures and algorithms. Right know I'm learning singly linked lists and I'm confused with a piece of code that creates a linked list.

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

struct node
{
    int data;
    struct node *next;
};

int main()
{
    int n;
    struct node *head = NULL;
    head = malloc(sizeof(struct node));

    head->data = 36;
    head->next = NULL;

    printf("%d", head->data);
}

My question is why we have to use struct node *next; part in order to refer to memory location of next node.

Why can't we instead use int *next?

Body:
This definition

struct node
{
    int data;
    struct node *next;
};

explains

"This is a node, carrying info on an int and pointing to another node (if not NULL), which in turn might point to yet another node... and so on."

A typical linked list.

This is what I understand your alternative to be:

struct node
{
    int data;
    int *next;
};

And it would explain:

"This is a node, carrying info on an int and pointing to another int (if not NULL)."

But an int cannot provide access to yet another int. So this one can provide access to info on one or two ints.

The idea of a linked list, in contrast, is however that it can (assuming memory) provide access to an indeterminate and quite high number of nodes.


问:
Blazor components (Server-Side). Hide any shared component
Is it possible to display only specific component in Blazor?
I dont want to display/show main menu or login button on the top. ONLY content of a particulate component. For example: show only 'Weather forecast' table when user navigates to a specific URL without showing any shared components like MainLayout or NavMenu.

答:
Blazor uses a default layout, it is Shared\MainLayout.razor

In there you can see how the menu and top row are setup.

First, define your own minimalist layout:

Shared\ClearLayout.razor

```<code>@inherits LayoutComponentBase

<div class="page">
    @Body
</div>
</code>```

And then add 1 line to the top of FetchData.razor:

```<code>@page "/fetchdata"
@layout ClearLayout

<PageTitle>Weather forecast</PageTitle>

...
</code>```

Body:
Blazor uses a default layout, it is Shared\MainLayout.razor

In there you can see how the menu and top row are setup.

First, define your own minimalist layout:

Shared\ClearLayout.razor

@inherits LayoutComponentBase

<div class="page">
    @Body
</div>

And then add 1 line to the top of FetchData.razor:

@page "/fetchdata"
@layout ClearLayout

<PageTitle>Weather forecast</PageTitle>

...


问:
Material UI Autocomplete doesnt mark checkbox with pre loaded values
I want to set Autocomplete with my data already loaded. But its not working for checkbox field. I'd like to mark them

Check the code below:

```<code>const [extensions, setExtensions] = useState([{value: 1, label: 'Excel', extension: 'xls'},{value: 3, label: 'PDF', extension: 'pdf'}]);

<Autocomplete
    multiple
    id="extensions"
    limitTags={1}
    className="autocompleCreate"
    options={extensionList}
    value={extensions}
    disableClearable={true}
    onChange={(event, value) => {
        setExtensions(value);}
    }
    openText={props.t("activity_report_autocomplete_open")}
    closeText={props.t("activity_report_autocomplete_close")}
    getOptionLabel={(option) => option.label}
    renderOption={(option, { selected }) => (
        <React.Fragment>
            <Checkbox
                icon={icon}
                checkedIcon={checkedIcon}
                style={{ marginRight: 8 }}
                checked={selected}
            />
            {option.label}
        </React.Fragment>
    )}
    disabled={type === 3 ? true : false}
    style={{ width: 600, marginRight : 100 }}
    renderInput={(params) => (
        <TextField {...input} {...params} variant="filled" label={props.t("label_configuration_create_extensions")} />
    )}
/>
</code>```

extensionList contains others extensions (others options like Word).

How can I solved it?

答: Just added getOptionSelected={(option, value) => option.value === value.value} and its works

Body:
I want to set Autocomplete with my data already loaded. But its not working for checkbox field. I'd like to mark them

Check the code below:

const [extensions, setExtensions] = useState([{value: 1, label: 'Excel', extension: 'xls'},{value: 3, label: 'PDF', extension: 'pdf'}]);

<Autocomplete
    multiple
    id="extensions"
    limitTags={1}
    className="autocompleCreate"
    options={extensionList}
    value={extensions}
    disableClearable={true}
    onChange={(event, value) => {
        setExtensions(value);}
    }
    openText={props.t("activity_report_autocomplete_open")}
    closeText={props.t("activity_report_autocomplete_close")}
    getOptionLabel={(option) => option.label}
    renderOption={(option, { selected }) => (
        <React.Fragment>
            <Checkbox
                icon={icon}
                checkedIcon={checkedIcon}
                style={{ marginRight: 8 }}
                checked={selected}
            />
            {option.label}
        </React.Fragment>
    )}
    disabled={type === 3 ? true : false}
    style={{ width: 600, marginRight : 100 }}
    renderInput={(params) => (
        <TextField {...input} {...params} variant="filled" label={props.t("label_configuration_create_extensions")} />
    )}
/>

extensionList contains others extensions (others options like Word).

How can I solved it?


答:
When passing some object to Control.Invoke or Control.BeginInvoke, you are passing a parameters to a "method", it is no different from passing parameters to any method. However if you curios about the Invoke and BeginInvoke implementation you can check it in this answer.

For the second part of the question the signiture of BeginInvoke is:

```<code>BeginInvoke(Delegate method, params object[] args);
</code>```

So you are asking about the params keyword, which is a special keyword that allow you to pass n arguments or array of specific type to method.

The params keyword lets you specify a method parameter that takes a variable number of arguments.
  You can send a comma-separated list of arguments of the type specified in the parameter declaration, or an array of arguments of the specified type. You also can send no arguments.

Title: Control.Invoke() and Control.BeginInvoke() - Where are the past parameters stored? How is it disposed?

Body:
When passing some object to Control.Invoke or Control.BeginInvoke, you are passing a parameters to a "method", it is no different from passing parameters to any method. However if you curios about the Invoke and BeginInvoke implementation you can check it in this answer.

For the second part of the question the signiture of BeginInvoke is:

BeginInvoke(Delegate method, params object[] args);

So you are asking about the params keyword, which is a special keyword that allow you to pass n arguments or array of specific type to method.

The params keyword lets you specify a method parameter that takes a variable number of arguments.
  You can send a comma-separated list of arguments of the type specified in the parameter declaration, or an array of arguments of the specified type. You also can send no arguments.


问:
CSS Grid, 2 column dashboard layout, 2 scrollbars 100% height issue
Hi I'm attempting to create a dashboard UI using CSS grid. Is CSS Grid the right choice for what I'm trying to do? Please let me know.

I'm currently stuck on the best way to implement a sidebar that is 100% height but anything over that create a overflow scrollbar. To make the case slightly more difficult, the default sidebar width is min-width: 100px but then when you click on the toggle button it expands and the width increases etc. I'm trying to avoid using magic numbers to make this solution possible.

The end goal is basically a responsive 2 column layout. 2 scrollbars, sidebar column 100% height and a main column that includes a header navbar.

What i'm trying to build

What i have so far:
https://codepen.io/jackwebsitefeatures/pen/QWONzYy

function toggleClass() {
  console.log("test");
  document.querySelector('.app-sidenav').classList.toggle("expanded");
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>*,
*:before,
*:after {
  box-sizing: border-box;
}

body {
  margin: 0;
  min-height: 100vh;
  font-family: sans-serif;
}

/* mobile first */
.app-layout {
  display: grid;
  height: 100vh;
  grid-template-rows: auto 1fr;
}

.app-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 82px;
}

.app-sidenav {
  display: none;
}

.app-sidenav nav a span {
  display: none;
}

.filler-element {
  height: 2000px;
}

/* Desktop */
@media (min-width: 1020px) {
  .app-layout {
    display: grid;
    height: 100vh;
    grid-template-columns: auto 1fr;
  }

  .app-sidenav {
    grid-column: 1;
    grid-row: 1 / 3;
    display: flex;
    flex-direction: column;
    overflow-y: auto;
    min-width: 100px;
    background: grey;
  }

  .app-sidenav.expanded {
    width: 250px;
  }

  .app-sidenav.expanded nav ul li a {
    display: inline-flex;
    align-items: center;
  }

  .app-sidenav.expanded nav ul li a span {
    display: inline-block;
    font-size: 1rem;
    font-weight: 600;
  }

  .app-sidenav.expanded nav ul li a i {
    margin-left: 0;
    margin-right: 1.2rem;
  }

  .app-sidenav nav {
    display: flex;
    flex-direction: column;
  }

  .app-sidenav nav ul li a {
    color: blue;
    text-decoration: none;
    padding: 1rem;
    display: inline-flex;
    align-items: center;
  }

  .app-sidenav nav ul li a:hover {
    color: #fff;
    text-decoration: none;
  }

  .app-sidenav nav ul li a i {
    display: block;
    margin: auto;
  }

  .app-sidenav button {
    margin: auto auto 1rem auto;
  }

  .app-header {
    grid-column: 2;
    grid-row: 1 / 2;
    padding: 0px 6rem;
  }

  .app-main {
    grid-column: 2;
    grid-row: 2 / 3;
    padding: 0px 6rem;
  }
}</code>```

      logo

iconLink

iconLink

iconLink

iconLink

iconLink

iconLink

iconLink

iconLink

iconLink

iconLink

iconLink

iconLink

iconLink

iconLink

iconLink

iconLink

iconLink

iconLink

iconLink

iconLink

    <button onclick="toggleClass()">expand toggle</button>

  im a sticky header - make sure on desktop device to see sidebar

    all main site goes in here... a 2000px filler height element is here btw

```

Any help would be much appreciated.

答:
I've created a jsfiddle with an example here: https://jsfiddle.net/79ujhxdz/1/

I tried to keep the changes to your original code to a minimum.
1st for the sidenav you would need to make the position fixed, set the height to 100vh and simply move it in and out of view:

```<code>.app-sidenav {
  position: fixed;
  grid-column: 1;
  grid-row: 1 / 3;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  min-width: 100px;
  background: grey;
  width: 250px;
  height: 100vh;
  transform: translate(-250px);
}

.app-sidenav.expanded {
   transform: translate(0);
}
</code>```

For the .app-main when the sidenav is expanded you need to also move it to the right and subtract the width of the sidenav from it's overall width to avoid adding horizontal scrolling:

```<code>.app-main.sidenav-expanded {
  transform: translate(250px);
  width: calc(100% - 250px);
}
</code>```

In the html structure I moved the header in the main content so that the .app-layout layer only has the .app-sidenav and .app-main as children.

I've also updated the js part to toggle a class to both the .app-sidenav and .app-main but you could also just toggle a class to the parent .app-layout and update these two through inheritance in your css.

```<code>function toggleClass() {
  document.querySelector('.app-sidenav').classList.toggle("expanded");
  document.querySelector('.app-main').classList.toggle("sidenav-expanded");
}
</code>```

Finally I removed the @media part of the css where you handle the desktop responsiveness to keep the jsfiddle css clearer and easier to understand.

Body:
Hi I'm attempting to create a dashboard UI using CSS grid. Is CSS Grid the right choice for what I'm trying to do? Please let me know.

I'm currently stuck on the best way to implement a sidebar that is 100% height but anything over that create a overflow scrollbar. To make the case slightly more difficult, the default sidebar width is min-width: 100px but then when you click on the toggle button it expands and the width increases etc. I'm trying to avoid using magic numbers to make this solution possible.

The end goal is basically a responsive 2 column layout. 2 scrollbars, sidebar column 100% height and a main column that includes a header navbar.

What i'm trying to build

What i have so far:
https://codepen.io/jackwebsitefeatures/pen/QWONzYy

function toggleClass() {
  console.log("test");
  document.querySelector('.app-sidenav').classList.toggle("expanded");
}

*,
*:before,
*:after {
  box-sizing: border-box;
}

body {
  margin: 0;
  min-height: 100vh;
  font-family: sans-serif;
}

/* mobile first */
.app-layout {
  display: grid;
  height: 100vh;
  grid-template-rows: auto 1fr;
}

.app-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 82px;
}

.app-sidenav {
  display: none;
}

.app-sidenav nav a span {
  display: none;
}

.filler-element {
  height: 2000px;
}

/* Desktop */
@media (min-width: 1020px) {
  .app-layout {
    display: grid;
    height: 100vh;
    grid-template-columns: auto 1fr;
  }

  .app-sidenav {
    grid-column: 1;
    grid-row: 1 / 3;
    display: flex;
    flex-direction: column;
    overflow-y: auto;
    min-width: 100px;
    background: grey;
  }

  .app-sidenav.expanded {
    width: 250px;
  }

  .app-sidenav.expanded nav ul li a {
    display: inline-flex;
    align-items: center;
  }

  .app-sidenav.expanded nav ul li a span {
    display: inline-block;
    font-size: 1rem;
    font-weight: 600;
  }

  .app-sidenav.expanded nav ul li a i {
    margin-left: 0;
    margin-right: 1.2rem;
  }

  .app-sidenav nav {
    display: flex;
    flex-direction: column;
  }

  .app-sidenav nav ul li a {
    color: blue;
    text-decoration: none;
    padding: 1rem;
    display: inline-flex;
    align-items: center;
  }

  .app-sidenav nav ul li a:hover {
    color: #fff;
    text-decoration: none;
  }

  .app-sidenav nav ul li a i {
    display: block;
    margin: auto;
  }

  .app-sidenav button {
    margin: auto auto 1rem auto;
  }

  .app-header {
    grid-column: 2;
    grid-row: 1 / 2;
    padding: 0px 6rem;
  }

  .app-main {
    grid-column: 2;
    grid-row: 2 / 3;
    padding: 0px 6rem;
  }
}

      logo

iconLink

iconLink

iconLink

iconLink

iconLink

iconLink

iconLink

iconLink

iconLink

iconLink

iconLink

iconLink

iconLink

iconLink

iconLink

iconLink

iconLink

iconLink

iconLink

iconLink

    <button onclick="toggleClass()">expand toggle</button>

  im a sticky header - make sure on desktop device to see sidebar

    all main site goes in here... a 2000px filler height element is here btw

Any help would be much appreciated.

Body:
I've created a jsfiddle with an example here: https://jsfiddle.net/79ujhxdz/1/

I tried to keep the changes to your original code to a minimum.
1st for the sidenav you would need to make the position fixed, set the height to 100vh and simply move it in and out of view:

.app-sidenav {
  position: fixed;
  grid-column: 1;
  grid-row: 1 / 3;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  min-width: 100px;
  background: grey;
  width: 250px;
  height: 100vh;
  transform: translate(-250px);
}

.app-sidenav.expanded {
   transform: translate(0);
}

For the .app-main when the sidenav is expanded you need to also move it to the right and subtract the width of the sidenav from it's overall width to avoid adding horizontal scrolling:

.app-main.sidenav-expanded {
  transform: translate(250px);
  width: calc(100% - 250px);
}

In the html structure I moved the header in the main content so that the .app-layout layer only has the .app-sidenav and .app-main as children.

I've also updated the js part to toggle a class to both the .app-sidenav and .app-main but you could also just toggle a class to the parent .app-layout and update these two through inheritance in your css.

function toggleClass() {
  document.querySelector('.app-sidenav').classList.toggle("expanded");
  document.querySelector('.app-main').classList.toggle("sidenav-expanded");
}

Finally I removed the @media part of the css where you handle the desktop responsiveness to keep the jsfiddle css clearer and easier to understand.


问:
I used Python Selenium to choose a "Year" from the dropdown box, clicked "search," and it apparently worked. But the data says otherwise
There is a page with tables of statistics I'm trying to pull.

The page has the default year as 2020, with a dropdown box to select different years. I wrote this code to select 2009.

```<code>from selenium import webdriver as wd
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from pandas.io.html import read_html
from selenium.webdriver.support.ui import Select

import numpy as np
import re
import pandas as pd

driver=wd.Chrome()
driver.implicitly_wait(10)
driver.get('https://www.cpbl.com.tw/standings/history')

select = Select(driver.find_element_by_id('Year'))

# select by visible text
select.select_by_visible_text('2009')

button = driver.find_elements_by_xpath("//input[@value='查詢']")[0]
button.click()

main=driver.find_elements_by_xpath('//*[(@id = "PageListContainer")]')[0]
main_att=main.get_attribute('innerHTML')
tab=pd.read_html(main_att)
</code>```

I purposely didn't say driver.close() to leave the browser open, so I can look at it, and apparently the selection of 2009 worked. The browser had tables for 2009. However, the data my code pulled was still from the default year (2020). I want data from 2009. Anyone know why?

I am using Python 3.7 and Spyder 4.0.1

答: It worked when I used time.sleep(10)

Body:
There is a page with tables of statistics I'm trying to pull.

The page has the default year as 2020, with a dropdown box to select different years. I wrote this code to select 2009.

from selenium import webdriver as wd
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from pandas.io.html import read_html
from selenium.webdriver.support.ui import Select

import numpy as np
import re
import pandas as pd

driver=wd.Chrome()
driver.implicitly_wait(10)
driver.get('https://www.cpbl.com.tw/standings/history')

select = Select(driver.find_element_by_id('Year'))

# select by visible text
select.select_by_visible_text('2009')

button = driver.find_elements_by_xpath("//input[@value='查詢']")[0]
button.click()

main=driver.find_elements_by_xpath('//*[(@id = "PageListContainer")]')[0]
main_att=main.get_attribute('innerHTML')
tab=pd.read_html(main_att)

I purposely didn't say driver.close() to leave the browser open, so I can look at it, and apparently the selection of 2009 worked. The browser had tables for 2009. However, the data my code pulled was still from the default year (2020). I want data from 2009. Anyone know why?

I am using Python 3.7 and Spyder 4.0.1

Body: It worked when I used time.sleep(10)


问:
Vs Code nx console generate command not working : This command has no flags to set
I'm have nx console extension installed in my Vs Code and upon trying to use the generate command (generate component, service, library etc.) its saying "ng generate @schematics/angular:component
This command has no flags to set" . I don't want to write the commands manually since it is time consuming. I have tried uninstalling and reinstalling the extension, closing my VsCode but i still get the same error.

答: The latest version has a problem. Install a previous one - 17.13.7, it works


问:
How to remove subdomains without hardcode URL with nginx?
I have this domain structure and need make some redirect like:

```<code>sub1.sub2.sub3.domain.com/path -> sub2.sub3.domain.com/path
sub2.sub3.domain.com/path -> sub3.domain.com/path
sub1.domain1.com/path1 -> domain1.com/path1
sub2.domain1.com/path2 -> domain1.com/path2
sub3.sub4.domain1.com/path -> sub4.domain1.com/path
sub4.domain.uk.co/path -> sub4.domain1.uk.co/path

sub5.domain6.com/path3 -> domain6.com/path3
sub7.domain6.com/path4 -> domain6.com/path4
sub8.sub8.domain9.com/path5 -> sub8.domain9.com/path5
www.domain9.com/path5 -> domain9.com/path5
</code>```

"domain.com" "domain6.com" "domain9.com" "domain1.uk.co" isn't host in this server.

I need redirect without hardcode any domain name. I try this:

```<code>if ( $host ~ ^www\.(.+)$ ) {
    set $without_www $1;
    rewrite ^ $scheme://$without_www$uri permanent;
}
</code>```

But I need hadcoding "www" (and subXXX). How can I get the part before the point and dispose at the new address?

答:
Read this answer (and the whole thread too). If such a guess is ok for you (since the national TLDs are always two letter, we can assume that any .xx.xx and .xxx.xx domain suffix is very likely some national two component TLD), you can use two if blocks - first one to check if the base domain has two-component TLD and second one like have been shown in comments:

if ($host ~ "\w+\.(?<basedomain>[^.]+\.\w{2,3}\.\w{2})$") {
    rewrite ^ $scheme://$basedomain$request_uri permanent;
}
if ($host ~ \w+\.(?<basedomain>[^.]+\.[^.]+)$) {
    rewrite ^ $scheme://$basedomain$request_uri permanent;
}
```
<p>To remove subdomains recursively one-by-one you can try the following:</p>
<pre class="lang-none prettyprint-override"><code>if ($host ~ "^[^.]+\.(?<domain>(?!\w{2,3}\.\w{2}$)[^.]+\..+)$") {
    rewrite ^ $scheme://$domain$request_uri permanent;
}
</code>```

Body:
I have this domain structure and need make some redirect like:

sub1.sub2.sub3.domain.com/path -> sub2.sub3.domain.com/path
sub2.sub3.domain.com/path -> sub3.domain.com/path
sub1.domain1.com/path1 -> domain1.com/path1
sub2.domain1.com/path2 -> domain1.com/path2
sub3.sub4.domain1.com/path -> sub4.domain1.com/path
sub4.domain.uk.co/path -> sub4.domain1.uk.co/path

sub5.domain6.com/path3 -> domain6.com/path3
sub7.domain6.com/path4 -> domain6.com/path4
sub8.sub8.domain9.com/path5 -> sub8.domain9.com/path5
www.domain9.com/path5 -> domain9.com/path5

"domain.com" "domain6.com" "domain9.com" "domain1.uk.co" isn't host in this server.

I need redirect without hardcode any domain name. I try this:

if ( $host ~ ^www\.(.+)$ ) {
    set $without_www $1;
    rewrite ^ $scheme://$without_www$uri permanent;
}

But I need hadcoding "www" (and subXXX). How can I get the part before the point and dispose at the new address?

Body:
Read this answer (and the whole thread too). If such a guess is ok for you (since the national TLDs are always two letter, we can assume that any .xx.xx and .xxx.xx domain suffix is very likely some national two component TLD), you can use two if blocks - first one to check if the base domain has two-component TLD and second one like have been shown in comments:

if ($host ~ "\w+\.(?<basedomain>[^.]+\.\w{2,3}\.\w{2})$") {
    rewrite ^ $scheme://$basedomain$request_uri permanent;
}
if ($host ~ \w+\.(?<basedomain>[^.]+\.[^.]+)$) {
    rewrite ^ $scheme://$basedomain$request_uri permanent;
}

To remove subdomains recursively one-by-one you can try the following:

if ($host ~ "^[^.]+\.(?<domain>(?!\w{2,3}\.\w{2}$)[^.]+\..+)$") {
    rewrite ^ $scheme://$domain$request_uri permanent;
}


问:
How to access dataframe from another observeEvent?
An example:

UI.R

```<code>library(shiny)
shinyUI(fluidPage(
  titlePanel("Example"),
  sidebarLayout(
    sidebarPanel(
      radioButtons("orderdata", "Sort by :",

                   c("Name" = "name",
                     "MRDNo" = "mrdno"
                   ))
    ),

    mainPanel(
      uiOutput("deatilscv")
    )
  )
))

Server.R
library(shiny)
library(shinyjs)

shinyServer(function(input, output) {
  observeEvent(input$orderdata,
   {

     output$deatilscv <- renderUI({
     if(input$orderdata=="name")
     {

    mid<-c("1","2")
    name<-c("a","b")

    datatable1 <- data.frame(mid,name)
    fluidPage(shinyjs::useShinyjs(),
              actionButton("button1", "CLICK")  )
     }

    else if(input$orderdata=="mrdno")
    {
      mid<-c("3","4")
      name<-c("c","d")

      datatable2 <- data.frame(mid,name)
      fluidPage(shinyjs::useShinyjs(),
                actionButton("button1", "CLICK")  )
     }

     })
  })

  observeEvent(
    input$button1,{
      a <- datatable1[1,2]  #this shows an error object 'datatable1' not found
      print(a)
    })
  observeEvent(

    input$button2,{

      a <- datatable2[1,2]  #this shows an error object 'datatable2' not found
      print(a)
    })
})
</code>```

There are two errors in the program as shown above.How can the  datatables be accessed in the observe event?

答:
I think you need to separate observeEvent function from renderTable function.

Then, save the observeEvent as a class object to be called later in the renderTable (output) function, something like this:

```<code>my_table <- observeEvent({

datatable <- data.frame(input$orderdata)
### to call your table later on
print(datatable)
      })

#Put the render function outside the observe event

   output$deatilscv <- renderTable({
  rendered_table <- mytable( )

})

}
</code>```

Body:
An example:

UI.R

library(shiny)
shinyUI(fluidPage(
  titlePanel("Example"),
  sidebarLayout(
    sidebarPanel(
      radioButtons("orderdata", "Sort by :",

                   c("Name" = "name",
                     "MRDNo" = "mrdno"
                   ))
    ),

    mainPanel(
      uiOutput("deatilscv")
    )
  )
))

Server.R
library(shiny)
library(shinyjs)

shinyServer(function(input, output) {
  observeEvent(input$orderdata,
   {

     output$deatilscv <- renderUI({
     if(input$orderdata=="name")
     {

    mid<-c("1","2")
    name<-c("a","b")

    datatable1 <- data.frame(mid,name)
    fluidPage(shinyjs::useShinyjs(),
              actionButton("button1", "CLICK")  )
     }

    else if(input$orderdata=="mrdno")
    {
      mid<-c("3","4")
      name<-c("c","d")

      datatable2 <- data.frame(mid,name)
      fluidPage(shinyjs::useShinyjs(),
                actionButton("button1", "CLICK")  )
     }

     })
  })

  observeEvent(
    input$button1,{
      a <- datatable1[1,2]  #this shows an error object 'datatable1' not found
      print(a)
    })
  observeEvent(

    input$button2,{

      a <- datatable2[1,2]  #this shows an error object 'datatable2' not found
      print(a)
    })
})

There are two errors in the program as shown above.How can the  datatables be accessed in the observe event?

Body:
I think you need to separate observeEvent function from renderTable function.

Then, save the observeEvent as a class object to be called later in the renderTable (output) function, something like this:

my_table <- observeEvent({

datatable <- data.frame(input$orderdata)
### to call your table later on
print(datatable)
      })

#Put the render function outside the observe event

   output$deatilscv <- renderTable({
  rendered_table <- mytable( )

})

}


问:
Upgrade the version of nodejs to 5.12.0
I tried to install node.js by NVM in Ubuntu 16.04 server by following this link. And I got:

```<code>root@instance-15s8fbzx:/opt# nodejs --version
v4.2.6
root@instance-15s8fbzx:/opt# npm --version
5.3.0
root@instance-15s8fbzx:/opt# node --version
v8.4.0
</code>```

Then, we I run a mean-stack project by sudo npm start, I got

```<code>class User {
^^^^^

SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
</code>```

Then, I saw this link, I think maybe because the nodejs version is not correct. I have another server with v5.12.0 as the version of nodejs, and the project worked well there.

Then, I tried to do

```<code>sudo npm install -g npm
sudo npm install -g n
sudo n stable
sudo ln -sf /usr/local/n/versions/node/8.4.0/bin/node /usr/bin/node
</code>```

But the version of the nodejs is still 4.2.6. Does anyone know how to upgrade its version to 5.12.0?

答:
```<code>After upgrading to the Nodejs version, the following error occurred for the Laravel and VUE js packages I already had:
</code>```

PHP Fatal error: During inheritance of IteratorAggregate: Uncaught
ErrorException: Return type of
Symfony\Component\HttpFoundation\ParameterBag::getIterator() should
either be compatible with IteratorAggregate::getIterator():
Traversable, or the #[\ReturnTypeWillChange] attribute should be used
to temporarily suppress the notice in
C:\xampp\htdocs\clerk\vendor\symfony\http-foundation\ParameterBag.php:210

```<code>To solve the issue, I did the following:
</code>```

composer update

npm update

npm run dev

php artisan serve

Title: Upgrade the version of nodejs to 5.12.0

Body:
I tried to install node.js by NVM in Ubuntu 16.04 server by following this link. And I got:

root@instance-15s8fbzx:/opt# nodejs --version
v4.2.6
root@instance-15s8fbzx:/opt# npm --version
5.3.0
root@instance-15s8fbzx:/opt# node --version
v8.4.0

Then, we I run a mean-stack project by sudo npm start, I got

class User {
^^^^^

SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode

Then, I saw this link, I think maybe because the nodejs version is not correct. I have another server with v5.12.0 as the version of nodejs, and the project worked well there.

Then, I tried to do

sudo npm install -g npm
sudo npm install -g n
sudo n stable
sudo ln -sf /usr/local/n/versions/node/8.4.0/bin/node /usr/bin/node

But the version of the nodejs is still 4.2.6. Does anyone know how to upgrade its version to 5.12.0?

Body:
After upgrading to the Nodejs version, the following error occurred for the Laravel and VUE js packages I already had:

PHP Fatal error: During inheritance of IteratorAggregate: Uncaught
ErrorException: Return type of
Symfony\Component\HttpFoundation\ParameterBag::getIterator() should
either be compatible with IteratorAggregate::getIterator():
Traversable, or the #[\ReturnTypeWillChange] attribute should be used
to temporarily suppress the notice in
C:\xampp\htdocs\clerk\vendor\symfony\http-foundation\ParameterBag.php:210

To solve the issue, I did the following:

composer update

npm update

npm run dev

php artisan serve


问:
How to stop firebase functions from propagating triggers
I have a Firebase function to decrease the commentCount when a comment is deleted, like this

```<code>export const onArticleCommentDeleted = functions.firestore.document('articles/{articleId}/comments/{uid}').onDelete((snapshot, context) => {
    return db.collection('articles').doc(context.params.articleId).update({
        commentCount: admin.firestore.FieldValue.increment(-1)
    })
})
</code>```

I also have firebase functions to recursively delete comments of an article when it's deleted

```<code>export const onArticleDeleted = functions.firestore.document('articles/{id}').onDelete((snapshot, context) => {
    const commentsRef = db.collection('articles').doc(snapshot.id).collection('comments');
    db.recursiveDelete(commentsRef); // this triggers the onArticleCommentDeleted multiple times
})
</code>```

When I delete an article, the onArticleCommentDeleted is triggered and it tries to update the article that has already been deleted. Of course I can check if the article exists before updating it. But it's really cumbersome and waste of resources.

Are there any ways to avoid from propagating further triggers?

答: There is no way to prevent triggering the Cloud Function on the comments when you delete the comments for that article. You will have to check for that condition in the function code itself, as you already said.</p>

Body:
I have a Firebase function to decrease the commentCount when a comment is deleted, like this

export const onArticleCommentDeleted = functions.firestore.document('articles/{articleId}/comments/{uid}').onDelete((snapshot, context) => {
    return db.collection('articles').doc(context.params.articleId).update({
        commentCount: admin.firestore.FieldValue.increment(-1)
    })
})

I also have firebase functions to recursively delete comments of an article when it's deleted

export const onArticleDeleted = functions.firestore.document('articles/{id}').onDelete((snapshot, context) => {
    const commentsRef = db.collection('articles').doc(snapshot.id).collection('comments');
    db.recursiveDelete(commentsRef); // this triggers the onArticleCommentDeleted multiple times
})

When I delete an article, the onArticleCommentDeleted is triggered and it tries to update the article that has already been deleted. Of course I can check if the article exists before updating it. But it's really cumbersome and waste of resources.

Are there any ways to avoid from propagating further triggers?


问:
Visual Studio Code debug python file stopped working
Visual Studio Code debug Python file stopped working
I have been using visual studio code for years, and for no apparent reason debug stopped working.  It worked yesterday, but not today.  Here is what I do:

Double click a simple "Hello World" .py file.  It opens with visual studio code

Press arrow on the left side for run and debug

Select “Python File”.  Nothing happens

Similarly, if I select the pulldown menu on the right and “debug Python file” nothing happens

But if I select the pulldown menu on the right and “run Python file”, the program runs: a terminal opens, and hello world is printed.

How do I get debug to work (again)?

I tried reboot and reinstall.

Below is the version I am using
Version: 1.64.0 (user setup)
Commit: 5554b12acf27056905806867f251c859323ff7e9
Date: 2022-02-03T04:22:20.678Z
Electron: 13.5.2
Chromium: 91.0.4472.164
Node.js: 14.16.0
V8: 9.1.269.39-electron.0
OS: Windows_NT x64 10.0.19043

I am running on Window 10

答: I uninstalled VSCODE, removed user .vscode directory, and then reinstalled


问:
Why do we usually use || over |? What is the difference?
I'm just wondering why we usually use logical OR || between two booleans not bitwise OR |, though they are both working well.

I mean, look at the following:

```<code>if(true  | true)  // pass
if(true  | false) // pass
if(false | true)  // pass
if(false | false) // no pass
</code>```

```<code>if(true  || true)  // pass
if(true  || false) // pass
if(false || true)  // pass
if(false || false) // no pass
</code>```

Can we use | instead of ||? Same thing with & and &&.

答:
Logical || and && check the right hand side only if necessary. The | and & check both the sides everytime.

For example:

```<code>int i = 12;
if (i == 10 & i < 9) // It will check if i == 10 and if i < 9
...
</code>```

Rewrite it:

```<code>int i = 12;
if (i == 10 && i < 9) // It will check if i == 10 and stop checking afterward because i != 10
...
</code>```

Another example:

```<code>int i = 12;
if (i == 12 | i > 10) // It will check if i == 12 and it will check if i > 10
...
</code>```

Rewrite it:

```<code>int i = 12;
if (i == 12 || i > 10) // It will check if i == 12, it does, so it stops checking and executes what is in the if statement
...
</code>```

Body:
I'm just wondering why we usually use logical OR || between two booleans not bitwise OR |, though they are both working well.

I mean, look at the following:

if(true  | true)  // pass
if(true  | false) // pass
if(false | true)  // pass
if(false | false) // no pass

if(true  || true)  // pass
if(true  || false) // pass
if(false || true)  // pass
if(false || false) // no pass

Can we use | instead of ||? Same thing with & and &&.

Body:
Logical || and && check the right hand side only if necessary. The | and & check both the sides everytime.

For example:

int i = 12;
if (i == 10 & i < 9) // It will check if i == 10 and if i < 9
...

Rewrite it:

int i = 12;
if (i == 10 && i < 9) // It will check if i == 10 and stop checking afterward because i != 10
...

Another example:

int i = 12;
if (i == 12 | i > 10) // It will check if i == 12 and it will check if i > 10
...

Rewrite it:

int i = 12;
if (i == 12 || i > 10) // It will check if i == 12, it does, so it stops checking and executes what is in the if statement
...


问:
Snowflake query performance is unexpectedly slower for external Parquet tables vs. internal tables
When I run queries on external Parquet tables in Snowflake, the queries are orders of magnitude slower than on the same tables copied into Snowflake or with any other cloud data warehouse I have tested on the same files.

Context:

I have tables belonging to the 10TB TPC-DS dataset in Parquet format on GCS and a Snowflake account in the same region (US Central). I have loaded those tables into Snowflake using create as select. I can run TPC-DS queries(here #28) on these internal tables with excellent performance. I was also able to query those files on GCS directly with data lake engines with excellent performance, as the files are "optimally" sized and internally sorted. However, when I query the same external tables on Snowflake, the query does not seem to finish in reasonable time (>4 minutes and counting, as opposed to 30 seconds, on the same virtual warehouse). Looking at the query profile, it seems that the number of records read in the table scans keeps growing indefinitely, resulting in a proportional amount of spilling to disk.

The table happens to be partitioned but it those not matter on the query of interest (which I tested with other engines).

What I would expect:

Assuming proper data "formatting", I would expect no major performance degradation compared to internal tables, as the setup is technically the same - data stored in columnar format in cloud object store - and as it is advertised as such by Snowflake. For example I saw no performance degradation with BigQuery on the exact same experiment.

Other than double checking my setup, I see don't see many things to try...

This is what the "in progress" part of the plan looks like 4 minutes into execution on the external table. All other operators are at 0% progress. You can see external bytes scanned=bytes spilled and 26G!! rows are produced. And this is what it looked like on a finished execution on the internal table executed in ~20 seconds. You can see that the left-most table scan should produce 1.4G rows but had produced 23G rows with the external table.

This is a sample of the DDL I used (I also tested without defining the partitioning column):

```<code>create or replace external table tpc_db.tpc_ds.store_sales (
    ss_sold_date_sk bigint as
      cast(split_part(split_part(metadata$filename, '/', 4), '=', 2) as bigint)
    ,
    ss_sold_time_sk bigint as (value:ss_sold_time_sk::bigint),
    ss_item_sk bigint as (value:ss_item_sk::bigint),
    ss_customer_sk bigint as (value:ss_customer_sk::bigint),
    ss_cdemo_sk bigint as (value:ss_cdemo_sk::bigint),
    ss_hdemo_sk bigint as (value:ss_hdemo_sk::bigint),
    ss_addr_sk bigint as (value:ss_addr_sk::bigint),
    ss_store_sk bigint as (value:ss_store_sk::bigint),
    ss_promo_sk bigint as (value:ss_promo_sk::bigint),
    ss_ticket_number bigint as (value:ss_ticket_number::bigint),
    ss_quantity bigint as (value:ss_quantity::bigint),
    ss_wholesale_cost double as (value:ss_wholesale_cost::double),
    ss_list_price double as (value:ss_list_price::double),
    ss_sales_price double as (value:ss_sales_price::double),
    ss_ext_discount_amt double as (value:ss_ext_discount_amt::double),
    ss_ext_sales_price double as (value:ss_ext_sales_price::double),
    ss_ext_wholesale_cost double as (value:ss_ext_wholesale_cost::double),
    ss_ext_list_price double as (value:ss_ext_list_price::double),
    ss_ext_tax double as (value:ss_ext_tax::double),
    ss_coupon_amt double as (value:ss_coupon_amt::double),
    ss_net_paid double as (value:ss_net_paid::double),
    ss_net_paid_inc_tax double as (value:ss_net_paid_inc_tax::double),
    ss_net_profit double as (value:ss_net_profit::double)
)
    partition by (ss_sold_date_sk)
    with location = @tpc_ds/store_sales/
    file_format = (type = parquet)
    auto_refresh = false
    pattern = '.*sales.*[.]parquet';
</code>```

答:
I don't know how your query looks but there is also a small chance that you suffer from a known issue where Snowflake interprets a function in the partition filter as dynamic and thus runs over all data, see details in Joao Marques blog on Medium: Using Snowflake External Tables? You must read this!.

Example of how not to do it from the blog

```<code>SELECT COUNT(*)
FROM EXTERNAL_TABLE
WHERE PARTITION_KEY = dateadd(day, -1, current_date)
</code>```

Example of how to do it from the blog

```<code>SET my_var = (select dateadd(day, -1, current_date));
SELECT COUNT(*)
FROM EXTERNAL_TABLE
WHERE PARTITION_KEY = $my_var
</code>```

All credits to the blog author, I have merely stumbled across this issue myself and found his blog.

Body:
When I run queries on external Parquet tables in Snowflake, the queries are orders of magnitude slower than on the same tables copied into Snowflake or with any other cloud data warehouse I have tested on the same files.

Context:

I have tables belonging to the 10TB TPC-DS dataset in Parquet format on GCS and a Snowflake account in the same region (US Central). I have loaded those tables into Snowflake using create as select. I can run TPC-DS queries(here #28) on these internal tables with excellent performance. I was also able to query those files on GCS directly with data lake engines with excellent performance, as the files are "optimally" sized and internally sorted. However, when I query the same external tables on Snowflake, the query does not seem to finish in reasonable time (>4 minutes and counting, as opposed to 30 seconds, on the same virtual warehouse). Looking at the query profile, it seems that the number of records read in the table scans keeps growing indefinitely, resulting in a proportional amount of spilling to disk.

The table happens to be partitioned but it those not matter on the query of interest (which I tested with other engines).

What I would expect:

Assuming proper data "formatting", I would expect no major performance degradation compared to internal tables, as the setup is technically the same - data stored in columnar format in cloud object store - and as it is advertised as such by Snowflake. For example I saw no performance degradation with BigQuery on the exact same experiment.

Other than double checking my setup, I see don't see many things to try...

This is what the "in progress" part of the plan looks like 4 minutes into execution on the external table. All other operators are at 0% progress. You can see external bytes scanned=bytes spilled and 26G!! rows are produced. And this is what it looked like on a finished execution on the internal table executed in ~20 seconds. You can see that the left-most table scan should produce 1.4G rows but had produced 23G rows with the external table.

This is a sample of the DDL I used (I also tested without defining the partitioning column):

create or replace external table tpc_db.tpc_ds.store_sales (
    ss_sold_date_sk bigint as
      cast(split_part(split_part(metadata$filename, '/', 4), '=', 2) as bigint)
    ,
    ss_sold_time_sk bigint as (value:ss_sold_time_sk::bigint),
    ss_item_sk bigint as (value:ss_item_sk::bigint),
    ss_customer_sk bigint as (value:ss_customer_sk::bigint),
    ss_cdemo_sk bigint as (value:ss_cdemo_sk::bigint),
    ss_hdemo_sk bigint as (value:ss_hdemo_sk::bigint),
    ss_addr_sk bigint as (value:ss_addr_sk::bigint),
    ss_store_sk bigint as (value:ss_store_sk::bigint),
    ss_promo_sk bigint as (value:ss_promo_sk::bigint),
    ss_ticket_number bigint as (value:ss_ticket_number::bigint),
    ss_quantity bigint as (value:ss_quantity::bigint),
    ss_wholesale_cost double as (value:ss_wholesale_cost::double),
    ss_list_price double as (value:ss_list_price::double),
    ss_sales_price double as (value:ss_sales_price::double),
    ss_ext_discount_amt double as (value:ss_ext_discount_amt::double),
    ss_ext_sales_price double as (value:ss_ext_sales_price::double),
    ss_ext_wholesale_cost double as (value:ss_ext_wholesale_cost::double),
    ss_ext_list_price double as (value:ss_ext_list_price::double),
    ss_ext_tax double as (value:ss_ext_tax::double),
    ss_coupon_amt double as (value:ss_coupon_amt::double),
    ss_net_paid double as (value:ss_net_paid::double),
    ss_net_paid_inc_tax double as (value:ss_net_paid_inc_tax::double),
    ss_net_profit double as (value:ss_net_profit::double)
)
    partition by (ss_sold_date_sk)
    with location = @tpc_ds/store_sales/
    file_format = (type = parquet)
    auto_refresh = false
    pattern = '.*sales.*[.]parquet';

Body:
I don't know how your query looks but there is also a small chance that you suffer from a known issue where Snowflake interprets a function in the partition filter as dynamic and thus runs over all data, see details in Joao Marques blog on Medium: Using Snowflake External Tables? You must read this!.

Example of how not to do it from the blog

SELECT COUNT(*)
FROM EXTERNAL_TABLE
WHERE PARTITION_KEY = dateadd(day, -1, current_date)

Example of how to do it from the blog

SET my_var = (select dateadd(day, -1, current_date));
SELECT COUNT(*)
FROM EXTERNAL_TABLE
WHERE PARTITION_KEY = $my_var

All credits to the blog author, I have merely stumbled across this issue myself and found his blog.


问:
pgadmin4 : postgresql application server could not be contacted.
I have installed PostgreSQL 9.6.2 on my Windows 8.1. But the pgadmin4 is not able to contact the local server. I have tried several solutions suggested here in stackoverflow, tried to uninstall and reinstall PostgreSQL 9.6.2 , tried to modify the config.py, config_distro.py, and delete the files in Roaming folder,i tried standalone pgadmin4 installation, but no success.However, in my local machine i am able to access the server using psql.exe and log as as superuser (postgres user). Can you please suggest any possible solutions to starting/running pgadmin4 ? Thank you.</p>

答:
I had this issue after installing Postgres 13 on a windows 10 machine where already i had postgres 11.

After uninstalling all and reinstall 13 only I still had the problem.

I finally managed in his way:

uninstall postgres from control panel /uninstall applications choosing the option "uninstall components" and choosing "pgadmin" ad component to uninstall

downloaded pgadmin installer from pgadmin.org

installed pgagdmin

from the pgadmin preferences in the binarypath i put
C:\Program Files\PostgreSQL\13\bin

This solved the issue for me.


问:
Vexing linq to sql predicate building in a for loop
I'm building a LINQ query using a loop that appends predicates using an array:

```<code>foreach (string tag in tags)
{
    result = result.Where(p => (p.TagsDelimited).Contains("," + tag + ","));
}
</code>```

This creates all the necessary clauses, but each clause compares only the last element in the tags array, producing the sql

```<code>(((',' + [t0].[TagsDelimited]) + ',') LIKE '%,taglast,%') AND (((',' + [t0].[TagsDelimited]) + ',') LIKE '%,taglast,%')
</code>```

instead of one clause for each tag.

I can work around this by adding

```<code>string temp = tag;
</code>```

inside the for loop and using temp instead of tag.

The question is: How is this possible!?

答:
The lambda captures the variable, not the value.

For more explanation, you might want to read my answer to this question

OwnerDisplayName: BC

ContentLicense: CC BY-SA 2.5

Body:
I'm building a LINQ query using a loop that appends predicates using an array:

foreach (string tag in tags)
{
    result = result.Where(p => (p.TagsDelimited).Contains("," + tag + ","));
}

This creates all the necessary clauses, but each clause compares only the last element in the tags array, producing the sql

(((',' + [t0].[TagsDelimited]) + ',') LIKE '%,taglast,%') AND (((',' + [t0].[TagsDelimited]) + ',') LIKE '%,taglast,%')

instead of one clause for each tag.

I can work around this by adding

string temp = tag;

inside the for loop and using temp instead of tag.

The question is: How is this possible!?

OwnerDisplayName: Mehrdad


问:
How to read BLOB data from a WebSocket which is not an image
I created a WebSocket connection to my webserver to receive some data. However, when I log the event that I receive in the onmessage function, then I cannot see the real content of the data.

When I copy the network connection that my Chrome browser v32 opens as a curl command and run it on my OS console, then everything works fine. So I think that somehow my WebSocket setup must be wrong. The event.data object is an instance of Blob.

Here is my code (actually CoffeeScript, but easy to understand):

```<code>socket = new WebSocket "wss://myserverurl/some-endpoint"

socket.onopen = (event) ->
    console.log 'Connection opened (WebSocket)'

socket.onclose = (event) ->
    console.log 'Connection closed (WebSocket)'
    code = event.code
    reason = event.reason
    wasClean = event.wasClean

socket.onmessage = (event) ->
    console.log JSON.stringify event
</code>```

The event that I get:

```<code>{
    "ports": [],
    "data": {
        "type": "",
        "size": 594
    },
    ...
    "cancelBubble": false,
    "returnValue": true,
    "srcElement": {
        "binaryType": "blob",
        "extensions": "",
        "protocol": "",
        "onerror": null,
        "bufferedAmount": 0,
        "readyState": 1
    },
    "defaultPrevented": false,
    "timeStamp": 1390578698613,
    "cancelable": false,
    "bubbles": false,
    "eventPhase": 2,
    "currentTarget": {
        "binaryType": "blob",
        "extensions": "",
        "protocol": "",
        "onerror": null,
        "bufferedAmount": 0,
        "readyState": 1
    },
    "target": {
        "binaryType": "blob",
        "extensions": "",
        "protocol": "",
        "onerror": null,
        "bufferedAmount": 0,
        "readyState": 1
    },
    "type": "message"
}
</code>```

答:
you can also use Blob.text().

```<code>socket.addEventListener("message", event => {
    // event.data is Blob
    event.data.text().then(txt=>console.log(txt))
});
</code>```

Body:
I created a WebSocket connection to my webserver to receive some data. However, when I log the event that I receive in the onmessage function, then I cannot see the real content of the data.

When I copy the network connection that my Chrome browser v32 opens as a curl command and run it on my OS console, then everything works fine. So I think that somehow my WebSocket setup must be wrong. The event.data object is an instance of Blob.

Here is my code (actually CoffeeScript, but easy to understand):

socket = new WebSocket "wss://myserverurl/some-endpoint"

socket.onopen = (event) ->
    console.log 'Connection opened (WebSocket)'

socket.onclose = (event) ->
    console.log 'Connection closed (WebSocket)'
    code = event.code
    reason = event.reason
    wasClean = event.wasClean

socket.onmessage = (event) ->
    console.log JSON.stringify event

The event that I get:

{
    "ports": [],
    "data": {
        "type": "",
        "size": 594
    },
    ...
    "cancelBubble": false,
    "returnValue": true,
    "srcElement": {
        "binaryType": "blob",
        "extensions": "",
        "protocol": "",
        "onerror": null,
        "bufferedAmount": 0,
        "readyState": 1
    },
    "defaultPrevented": false,
    "timeStamp": 1390578698613,
    "cancelable": false,
    "bubbles": false,
    "eventPhase": 2,
    "currentTarget": {
        "binaryType": "blob",
        "extensions": "",
        "protocol": "",
        "onerror": null,
        "bufferedAmount": 0,
        "readyState": 1
    },
    "target": {
        "binaryType": "blob",
        "extensions": "",
        "protocol": "",
        "onerror": null,
        "bufferedAmount": 0,
        "readyState": 1
    },
    "type": "message"
}

Body:
you can also use Blob.text().

socket.addEventListener("message", event => {
    // event.data is Blob
    event.data.text().then(txt=>console.log(txt))
});


问:
How to change expo push notification icon and point to a specific screen when app is closed
The problem I am having is that

push notifications received from expo notification service always have the expo icon instead of the one specified (my app's icon),

and when clicked point to the expo client instead of the standalone app

Local scheduled notification show the app icon as intended

Questions:

How can I change the remote notification icon to a custom one and

point to a specific path/screen in the standalone app instead of the expo client?

Image description:
Top notification shows a local scheduled notification and bottom the push notification using the expo push notification service

my app.json:

```<code>  "expo": {
    "name": "Vevivo",
    "slug": "Vevivo",
    "privacy": "public",
    "sdkVersion": "34.0.0",
    "platforms": [
      "ios",
      "android"
    ],
    "version": "1.2.2",
    "orientation": "portrait",
    "icon": "./assets/images/AppIcon.png",
    "splash": {
      "image": "./assets/images/splash.png",
      "resizeMode": "cover",
      "backgroundColor": "#ffffff"
    },
    "updates": {
      "fallbackToCacheTimeout": 0
    },
    "assetBundlePatterns": [
      "**/*"
    ],
    "primaryColor": "#E6762F",
    "scheme": "vevivo",
    "ios": {
      "supportsTablet": false,
      "bundleIdentifier": "com.vevivo.vevivo"
    },
    "android": {
      "package": "com.vevivo.vevivo",
      "googleServicesFile": "./google-services.json",
      "versionCode": 5
    },
    "notification": {
      "icon": "https://vevivo-images-bucket-develop.s3-eu-west-1.amazonaws.com/public/common/logo96Gray.png",
</code>```

}

Any help will be much appreciated!

答:
You're trying to see your notification icon in iOS so your app should be standalone app.

ExpoKit: To change the notification icon, edit or replace the shell_notification_icon.png files in android/app/src/main/res/mipmap-. On iOS, notification icons are the same as the app icon. All other properties are set at runtime.

For build for standalone app follows this guide

Body:
The problem I am having is that

push notifications received from expo notification service always have the expo icon instead of the one specified (my app's icon),

and when clicked point to the expo client instead of the standalone app

Local scheduled notification show the app icon as intended

Questions:

How can I change the remote notification icon to a custom one and

point to a specific path/screen in the standalone app instead of the expo client?

Image description:
Top notification shows a local scheduled notification and bottom the push notification using the expo push notification service

my app.json:

  "expo": {
    "name": "Vevivo",
    "slug": "Vevivo",
    "privacy": "public",
    "sdkVersion": "34.0.0",
    "platforms": [
      "ios",
      "android"
    ],
    "version": "1.2.2",
    "orientation": "portrait",
    "icon": "./assets/images/AppIcon.png",
    "splash": {
      "image": "./assets/images/splash.png",
      "resizeMode": "cover",
      "backgroundColor": "#ffffff"
    },
    "updates": {
      "fallbackToCacheTimeout": 0
    },
    "assetBundlePatterns": [
      "**/*"
    ],
    "primaryColor": "#E6762F",
    "scheme": "vevivo",
    "ios": {
      "supportsTablet": false,
      "bundleIdentifier": "com.vevivo.vevivo"
    },
    "android": {
      "package": "com.vevivo.vevivo",
      "googleServicesFile": "./google-services.json",
      "versionCode": 5
    },
    "notification": {
      "icon": "https://vevivo-images-bucket-develop.s3-eu-west-1.amazonaws.com/public/common/logo96Gray.png",

}

Any help will be much appreciated!


问:
Setup vite --template react and eslint (airbnb)
I'm trying to configure a project using vite.js and airbnb eslint setup.
I would like a "create-react-app"-kind of workflow where the linting is made every time the server starts/restarts, but I'm having a lot of trouble in doing so. To make things work I followed this video in particular: https://www.youtube.com/watch?v=cSl12yjFgDo. They use @rollup/plugin-eslint to achieve linting on every server restart, with the option { enforce: "pre" }, but it's absolutely not working for me. I have 200+ linting errors from files internal to vite.
This is my vite.config.js:

```<code>import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import eslint from '@rollup/plugin-eslint';

export default defineConfig({
  plugins: [react(), { ...eslint(), enforce: 'pre' }],
});
</code>```

This my .eslintrc.js

```<code>module.exports = {
  env: {
    browser: true,
    es2021: true,
  },
  extends: ['airbnb', 'airbnb/hooks'],
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 'latest',
    sourceType: 'module',
  },
  plugins: [],
  rules: {},
};
</code>```

As you can see it's all very minimal at the moment.
Can you please point me towards the right direction?

答: I just needed to move eslint plugin before react plugin in vite.config.js</p>

Body:
I'm trying to configure a project using vite.js and airbnb eslint setup.
I would like a "create-react-app"-kind of workflow where the linting is made every time the server starts/restarts, but I'm having a lot of trouble in doing so. To make things work I followed this video in particular: https://www.youtube.com/watch?v=cSl12yjFgDo. They use @rollup/plugin-eslint to achieve linting on every server restart, with the option { enforce: "pre" }, but it's absolutely not working for me. I have 200+ linting errors from files internal to vite.
This is my vite.config.js:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import eslint from '@rollup/plugin-eslint';

export default defineConfig({
  plugins: [react(), { ...eslint(), enforce: 'pre' }],
});

This my .eslintrc.js

module.exports = {
  env: {
    browser: true,
    es2021: true,
  },
  extends: ['airbnb', 'airbnb/hooks'],
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 'latest',
    sourceType: 'module',
  },
  plugins: [],
  rules: {},
};

As you can see it's all very minimal at the moment.
Can you please point me towards the right direction?