问:
China not showing on chloropleth map in R
I am trying to make a simple chloropleth map in r. While I can create the map, China does not show up at all, leaving a giant hole in the map. I have checked that China is in the data, so I am not sure what is going on. here is my code:

```<code>library(tidyverse)
library(maps)

## load data ----
data(country.map, package = "choroplethrMaps")
co2 <- read.csv("https://raw.githubusercontent.com/acircleda/tmp/master/food emissions.csv") %>%
  mutate(region = tolower(country))

data<-co2 %>%
  left_join(country.map, by="region") %>%
  group_by(region) %>% mutate(
    c02sum = sum(co2_emmission)
  )

ggplot(data, aes(long, lat, group = group))+
  geom_polygon(aes(fill = c02sum), color = "white", na="grey80")+
  scale_fill_viridis_c(option = "C")

##no china

china<-data %>% filter(region == "china") ##china is in the data
</code>```

答:
You need to group by first, summarise, and then join. I'd also do a full join just to see if there are any countries in the map that are not in your co2 data and if there are any countries in your co2 data that are not in the map (they'll be shown as grey). A right join should give the same reuslts, but a left join will cause these missing countries to appear missing altogether, which will look weird.

```<code>data <- co2 %>%
  group_by(region) %>% summarise(   # do this first
    c02sum = sum(co2_emmission, na.rm=TRUE)) %>%
  full_join(country.map, by="region")

ggplot(data, aes(long, lat, group = group)) +
  geom_polygon(aes(fill = c02sum), color = "white") +
  scale_fill_continuous(na.value = 'grey', name = expression(CO[2]~emission~(tonnes))) +
  ggtitle(expression(Global~CO[2]~emissions~by~country)) +
  theme_void()
</code>```

The countries in the map that are missing from the co2 data (there are 50) are:

```<code>data %>%
   filter(is.na(c02sum)) %>%
   distinct(region) %>%
   arrange(region)
# A tibble: 50 x 1
   region
   <chr>
 1 afghanistan
 2 antarctica
 3 azerbaijan
 4 benin
 5 bhutan
 6 brunei
 7 burkina faso
 8 burundi
 9 central african republic
10 chad
# … with 40 more rows
</code>```

And the countries in your co2 data that are not in the map (there are 8) are:

```<code>data %>%
   filter(is.na(long)) %>%
   distinct(region)
# A tibble: 8 x 1
  region
  <chr>
1 barbados
2 bermuda
3 french polynesia
4 grenada
5 maldives
6 malta
7 mauritius
8 new caledonia
</code>```

You could also determine this using setdiff.

Body:
I am trying to make a simple chloropleth map in r. While I can create the map, China does not show up at all, leaving a giant hole in the map. I have checked that China is in the data, so I am not sure what is going on. here is my code:

library(tidyverse)
library(maps)

## load data ----
data(country.map, package = "choroplethrMaps")
co2 <- read.csv("https://raw.githubusercontent.com/acircleda/tmp/master/food emissions.csv") %>%
  mutate(region = tolower(country))

data<-co2 %>%
  left_join(country.map, by="region") %>%
  group_by(region) %>% mutate(
    c02sum = sum(co2_emmission)
  )

ggplot(data, aes(long, lat, group = group))+
  geom_polygon(aes(fill = c02sum), color = "white", na="grey80")+
  scale_fill_viridis_c(option = "C")

##no china

china<-data %>% filter(region == "china") ##china is in the data

Body:
You need to group by first, summarise, and then join. I'd also do a full join just to see if there are any countries in the map that are not in your co2 data and if there are any countries in your co2 data that are not in the map (they'll be shown as grey). A right join should give the same reuslts, but a left join will cause these missing countries to appear missing altogether, which will look weird.

data <- co2 %>%
  group_by(region) %>% summarise(   # do this first
    c02sum = sum(co2_emmission, na.rm=TRUE)) %>%
  full_join(country.map, by="region")

ggplot(data, aes(long, lat, group = group)) +
  geom_polygon(aes(fill = c02sum), color = "white") +
  scale_fill_continuous(na.value = 'grey', name = expression(CO[2]~emission~(tonnes))) +
  ggtitle(expression(Global~CO[2]~emissions~by~country)) +
  theme_void()

The countries in the map that are missing from the co2 data (there are 50) are:

data %>%
   filter(is.na(c02sum)) %>%
   distinct(region) %>%
   arrange(region)
# A tibble: 50 x 1
   region
   <chr>
 1 afghanistan
 2 antarctica
 3 azerbaijan
 4 benin
 5 bhutan
 6 brunei
 7 burkina faso
 8 burundi
 9 central african republic
10 chad
# … with 40 more rows

And the countries in your co2 data that are not in the map (there are 8) are:

data %>%
   filter(is.na(long)) %>%
   distinct(region)
# A tibble: 8 x 1
  region
  <chr>
1 barbados
2 bermuda
3 french polynesia
4 grenada
5 maldives
6 malta
7 mauritius
8 new caledonia

You could also determine this using setdiff.


来源: stackexchange

问:
Replacing whole XML tree in Python
How to replace a whole XML tree?
Let's say I have a file that looks like:

```<code><root>
  <folder>
    <elem1>'something here'</elem1>
    <elem2>'more stuff here'</elem2>
    <elem3>
       <sub1>'something else here'</sub1>
       <sub2>'blablabla'</sub2>
    </elem3>
    <elem4>'even more stuff here with subelements too'</elem4>
  </folder>
</root>
</code>```

And I also have another xml file that would be an alternative for elem3 that looks like:

```<code>    <NewElem>
       <Difsub1>'something else here, but different'</Difsub1>
       <Difsub2>'all sorts of different blablabla'</Difsub2>
    </NewElem>
</code>```

What I need is to replace elem3 with NewElem, that results in:

```<code><root>
  <folder>
    <elem1>'something here'</elem1>
    <elem2>'more stuff here'</elem2>
    <NewElem>
       <Difsub1>'something else here, but different'</Difsub1>
       <Difsub2>'all sorts of different blablabla'</Difsub2>
    </NewElem>
    <elem4>'even more stuff here with subelements too'</elem4>
  </folder>
</root>
</code>```

I am using xml.etree.ElementTree and tried to append it but I end up getting the NewElem in the end, after </folder>. I could not remove the elem3 of the updated xml file.

I tried to append it using this:

```<code>import xml.etree.ElementTree as ET

tree = ET.parse('base.xml')
baseroot = tree.getroot()
tree2 = ET.parse('new.xml')
newroot = tree2.getroot()

old_element = baseroot.findall('.//elem3')
baseroot.append(newroot)
baseroot.remove(old_element)
</code>```

With that the NewElem gets appended after folder, and I need in the same place where elem3 was, or at least inside <folder>
Also, when removing I get an error:
TypeError: remove() argument must be xml.etree.ElementTree.Element, not list
If I change to

```<code>old_element = baseroot.find('.//elem3')
baseroot.append(newroot)
baseroot.remove(old_element)
</code>```

I get very similar error: ValueError: list.remove(x): x not in list

答:
First, thank you @egur and @Henrik for guiding, specially pointing to a different library. I am using lxml (and this documentation) and so I could do what I wanted using the following code:

```<code>from lxml import etree

tree = etree.parse('base.xml')
new = etree.tostring(etree.parse('new.xml')) # parsing to a string so it can be appended later

for elem in tree.xpath(".//elem3"): # finds the parent where the element to be replaced are
    elem.getparent().append(etree.fromstring(new)) #append in the end of parent, the fromstring() is because append don't like elementTree
    elem.getparent().remove(elem)

print(etree.tostring(tree, encoding="utf-8").decode('utf-8'))
</code>```

The above code produces the following:

```<code><root>
  <folder>
    <elem1>'something here'</elem1>
    <elem2>'more stuff here'</elem2>
    <elem4>'even more stuff here with subelements too'</elem4>
  <NewElem>
       <Difsub1>'something else here, but different'</Difsub1>
       <Difsub2>'all sorts of different blablabla'</Difsub2>
    </NewElem></folder>
</root>
</code>```

Note that the NewElem is after elem4, not exactly where elem3 was, but within folder so I think that solves what I wanted.

ContentLicense: CC BY-SA 4.0

Title: Replacing whole XML tree in Python

Body:
How to replace a whole XML tree?
Let's say I have a file that looks like:

<root>
  <folder>
    <elem1>'something here'</elem1>
    <elem2>'more stuff here'</elem2>
    <elem3>
       <sub1>'something else here'</sub1>
       <sub2>'blablabla'</sub2>
    </elem3>
    <elem4>'even more stuff here with subelements too'</elem4>
  </folder>
</root>

And I also have another xml file that would be an alternative for elem3 that looks like:

    <NewElem>
       <Difsub1>'something else here, but different'</Difsub1>
       <Difsub2>'all sorts of different blablabla'</Difsub2>
    </NewElem>

What I need is to replace elem3 with NewElem, that results in:

<root>
  <folder>
    <elem1>'something here'</elem1>
    <elem2>'more stuff here'</elem2>
    <NewElem>
       <Difsub1>'something else here, but different'</Difsub1>
       <Difsub2>'all sorts of different blablabla'</Difsub2>
    </NewElem>
    <elem4>'even more stuff here with subelements too'</elem4>
  </folder>
</root>

I am using xml.etree.ElementTree and tried to append it but I end up getting the NewElem in the end, after </folder>. I could not remove the elem3 of the updated xml file.

I tried to append it using this:

import xml.etree.ElementTree as ET

tree = ET.parse('base.xml')
baseroot = tree.getroot()
tree2 = ET.parse('new.xml')
newroot = tree2.getroot()

old_element = baseroot.findall('.//elem3')
baseroot.append(newroot)
baseroot.remove(old_element)

With that the NewElem gets appended after folder, and I need in the same place where elem3 was, or at least inside <folder>
Also, when removing I get an error:
TypeError: remove() argument must be xml.etree.ElementTree.Element, not list
If I change to

old_element = baseroot.find('.//elem3')
baseroot.append(newroot)
baseroot.remove(old_element)

I get very similar error: ValueError: list.remove(x): x not in list

Body:
First, thank you @egur and @Henrik for guiding, specially pointing to a different library. I am using lxml (and this documentation) and so I could do what I wanted using the following code:

from lxml import etree

tree = etree.parse('base.xml')
new = etree.tostring(etree.parse('new.xml')) # parsing to a string so it can be appended later

for elem in tree.xpath(".//elem3"): # finds the parent where the element to be replaced are
    elem.getparent().append(etree.fromstring(new)) #append in the end of parent, the fromstring() is because append don't like elementTree
    elem.getparent().remove(elem)

print(etree.tostring(tree, encoding="utf-8").decode('utf-8'))

The above code produces the following:

<root>
  <folder>
    <elem1>'something here'</elem1>
    <elem2>'more stuff here'</elem2>
    <elem4>'even more stuff here with subelements too'</elem4>
  <NewElem>
       <Difsub1>'something else here, but different'</Difsub1>
       <Difsub2>'all sorts of different blablabla'</Difsub2>
    </NewElem></folder>
</root>

Note that the NewElem is after elem4, not exactly where elem3 was, but within folder so I think that solves what I wanted.


问:
How to stop a method while it's running in swiftui
I have a problem and I have to find a solution. I must immediately stop the "Starting" method if the user presses the Cancel button.
I have not fixed the problem yet because I can not block the method while it is running but only at the end or at the beginning of the execution.

ContentView:

```<code>Button(action: {
 self.Starting()
 DispatchQueue.main.asyncAfter(deadline: .init(uptimeNanoseconds: 0), execute: self.workItem)

}) {
    Text("START")
    }

Button(action: {
 self.workItem.cancel()
 }) {
      Text("CANCEL")
    }
</code>```

Starting method:

```<code> func Starting() {
    self.workItem = DispatchWorkItem {
        DispatchQueue.main.async {
            self.impostazioniChek=true
        }

        DispatchQueue.global().async {
            if (self.pm.MarksSwitch)
            {
                sleep(UInt32(self.MarksT))
                self.Marks()
            }

            if (self.pm.ReadySwitch)
            {
               sleep(UInt32(self.ReadyT))
                self.Ready()
            }

            self.Start()
            sleep(3)
            DispatchQueue.main.async {
                self.tm.start()
            }

        }
    }
 }
</code>```

答:
You cannot cancel because

1) almost all the time work items runs on main (UI) queue, so block it

2) inside work item there is no check for isCancelled. DispatchWorkItem.cancel() only marks it cancelled, but does not stops execution you have to do this.

So to make this work it needs to redirect everything not-UI related in your work item into .background queue explicitly.

Eg. instead of

```<code>DispatchQueue.main.asyncAfter(deadline: .init(uptimeNanoseconds: 0), execute: self.workItem)
</code>```

use

```<code>DispatchQueue.global(qos: .background).async { self.workItem }
</code>```

Instead of

```<code>DispatchQueue.global().async {
    if (self.pm.MarksSwitch)
</code>```

Just use (because it is already in background)

```<code>if (self.pm.MarksSwitch)
</code>```

and I'm not sure what is (probably it also should be run on background queue)

```<code>self.tm.start()
</code>```

And on second add inside block interruption on cancellation by regular check, like below

```<code>...
}
if self.workItem.isCancelled { // add as many such as needed
    return
}
if (self.pm.ReadySwitch)
...
</code>```

Body:
I have a problem and I have to find a solution. I must immediately stop the "Starting" method if the user presses the Cancel button.
I have not fixed the problem yet because I can not block the method while it is running but only at the end or at the beginning of the execution.

ContentView:

Button(action: {
 self.Starting()
 DispatchQueue.main.asyncAfter(deadline: .init(uptimeNanoseconds: 0), execute: self.workItem)

}) {
    Text("START")
    }

Button(action: {
 self.workItem.cancel()
 }) {
      Text("CANCEL")
    }

Starting method:

 func Starting() {
    self.workItem = DispatchWorkItem {
        DispatchQueue.main.async {
            self.impostazioniChek=true
        }

        DispatchQueue.global().async {
            if (self.pm.MarksSwitch)
            {
                sleep(UInt32(self.MarksT))
                self.Marks()
            }

            if (self.pm.ReadySwitch)
            {
               sleep(UInt32(self.ReadyT))
                self.Ready()
            }

            self.Start()
            sleep(3)
            DispatchQueue.main.async {
                self.tm.start()
            }

        }
    }
 }

Body:
You cannot cancel because

1) almost all the time work items runs on main (UI) queue, so block it

2) inside work item there is no check for isCancelled. DispatchWorkItem.cancel() only marks it cancelled, but does not stops execution you have to do this.

So to make this work it needs to redirect everything not-UI related in your work item into .background queue explicitly.

Eg. instead of

DispatchQueue.main.asyncAfter(deadline: .init(uptimeNanoseconds: 0), execute: self.workItem)

use

DispatchQueue.global(qos: .background).async { self.workItem }

Instead of

DispatchQueue.global().async {
    if (self.pm.MarksSwitch)

Just use (because it is already in background)

if (self.pm.MarksSwitch)

and I'm not sure what is (probably it also should be run on background queue)

self.tm.start()

And on second add inside block interruption on cancellation by regular check, like below

...
}
if self.workItem.isCancelled { // add as many such as needed
    return
}
if (self.pm.ReadySwitch)
...


问:
storing multiple connection string in xml file asp.net
Based on company and unit selected by user i have to select connection string. I want to know what is the best practice to store multiple connection string. Should i store it in XML file or web.config file? or at any other place.

Thank you very much

答:
We have some legacy systems that run different databases, than our "official" system.
I have always stored the different connection strings in the webconfig, and selected the one I need, in my code.

```<code>ConnectionString = WebConfigurationManager.ConnectionStrings["PDM"].ConnectionString;
</code>```

Personally, I would keep it all in web.config.

ContentLicense: CC BY-SA 2.5

Body:
We have some legacy systems that run different databases, than our "official" system.
I have always stored the different connection strings in the webconfig, and selected the one I need, in my code.

ConnectionString = WebConfigurationManager.ConnectionStrings["PDM"].ConnectionString;

Personally, I would keep it all in web.config.

ContentLicense: CC BY-SA 3.0


问:
How to run function after an api call has been complete in swift
I want my function openDoor to return true, if the API call has given us doorStatus "OPENED" However, I run into a problem, where this function returns before the API call has been made, making it return false every time, because it has been initialised so. My question is how do I make api request first, so that I can assign doorStatusL true or false based on that API call to return it at the end?

```<code>                func openDoor(requesto: URLRequest) ->Bool {
                 var doorstatusL = false;

                func sendRequest() -> Bool {
                NSURLConnection.sendAsynchronousRequest(requesto, queue: OperationQueue.main) {(response, data, error) in

                    guard let data = data else {
                        return
                    }
                    print(String(data: data, encoding: .utf8)!)
                    do {

                        let json = try JSONDecoder().decode([WelcomeElement].self, from: data )
                        //try JSONSerialization.jsonObject(with: data!, options: [])
                        print(json[0].doorstatus)
                        if(json[0].doorstatus == "OPENED"){
                            doorstatusL = true;
                            print(doorstatusL)
                            print("assigned TRUE")
                        }
                    } catch {
                        print("Status Error during JSON serialization: \(error.localizedDescription)")
                    }
                    }
                    return true
                }
                if(sendRequest()==true){
                    print(doorstatusL)
                    print("=======+++++++")
                    return doorstatusL
                } else {
                    print("returned false at the end")
                    return false
                }
               return true;
            }
</code>```

Output from a terminal is

```<code>false
=======+++++++
[{"message":"OPEN, ENTER ","doorstatus":"OPENED"}]
OPENED
true
assigned TRUE
</code>```

Thank you

SOLVED

```<code>                        func sendRequest(requesto: URLRequest, success:Bool, completionHandler: @escaping (Bool)->Void) {
                        var doorStatusL = false

                        NSURLConnection.sendAsynchronousRequest(requesto, queue: OperationQueue.main) { (response, data, error) in
                            guard let data = data else { return }

                            do {
                                let json = try JSONDecoder().decode([WelcomeElement].self, from: data )

                                if(json[0].doorstatus == "OPENED") {
                                    doorStatusL = true
                                    completionHandler(doorStatusL)
                                }
                            } catch {
                                print("Status Error during JSON serialization: \(error.localizedDescription)")
                            }
                        }
                    }

                    let completionhandler:(Bool)->Void = { (success) in
                        if success {
                                sendNotifications()
                        }
                    }

                    sendRequest(requesto: request2, success: true, completionHandler: completionhandler)
</code>```

答:
Add completion handler to api call method

```<code>func sendRequest(completion:@escaping (_ response:Bool) -> Void){
   completion(true)
}
</code>```

then you can call a function on completion of it

```<code>sendRequest(completion: {_ in
    yourFunction()
})
</code>```

Body:
I want my function openDoor to return true, if the API call has given us doorStatus "OPENED" However, I run into a problem, where this function returns before the API call has been made, making it return false every time, because it has been initialised so. My question is how do I make api request first, so that I can assign doorStatusL true or false based on that API call to return it at the end?

                func openDoor(requesto: URLRequest) ->Bool {
                 var doorstatusL = false;

                func sendRequest() -> Bool {
                NSURLConnection.sendAsynchronousRequest(requesto, queue: OperationQueue.main) {(response, data, error) in

                    guard let data = data else {
                        return
                    }
                    print(String(data: data, encoding: .utf8)!)
                    do {

                        let json = try JSONDecoder().decode([WelcomeElement].self, from: data )
                        //try JSONSerialization.jsonObject(with: data!, options: [])
                        print(json[0].doorstatus)
                        if(json[0].doorstatus == "OPENED"){
                            doorstatusL = true;
                            print(doorstatusL)
                            print("assigned TRUE")
                        }
                    } catch {
                        print("Status Error during JSON serialization: \(error.localizedDescription)")
                    }
                    }
                    return true
                }
                if(sendRequest()==true){
                    print(doorstatusL)
                    print("=======+++++++")
                    return doorstatusL
                } else {
                    print("returned false at the end")
                    return false
                }
               return true;
            }

Output from a terminal is

false
=======+++++++
[{"message":"OPEN, ENTER ","doorstatus":"OPENED"}]
OPENED
true
assigned TRUE

Thank you

SOLVED

                        func sendRequest(requesto: URLRequest, success:Bool, completionHandler: @escaping (Bool)->Void) {
                        var doorStatusL = false

                        NSURLConnection.sendAsynchronousRequest(requesto, queue: OperationQueue.main) { (response, data, error) in
                            guard let data = data else { return }

                            do {
                                let json = try JSONDecoder().decode([WelcomeElement].self, from: data )

                                if(json[0].doorstatus == "OPENED") {
                                    doorStatusL = true
                                    completionHandler(doorStatusL)
                                }
                            } catch {
                                print("Status Error during JSON serialization: \(error.localizedDescription)")
                            }
                        }
                    }

                    let completionhandler:(Bool)->Void = { (success) in
                        if success {
                                sendNotifications()
                        }
                    }

                    sendRequest(requesto: request2, success: true, completionHandler: completionhandler)

Body:
Add completion handler to api call method

func sendRequest(completion:@escaping (_ response:Bool) -> Void){
   completion(true)
}

then you can call a function on completion of it

sendRequest(completion: {_ in
    yourFunction()
})


问:
MinMaxScaling vs L1/L2-Normalization
I'm wondering about the difference or the application of the different types of rescaling data.

So far, I'm aware that standardization assumes the data has a gaussian distribution. So if this is the case we should standardize and get values in normal distribution N~(0,1).

If our model does not has assumptions about the data distribution (like FCN or RandomForestClassifiers,...) and we don't know about the data distribution or it is just not gaussian distributed we should normalize the data. But here is my point, there are several methods to normalize e.g. using L2/L1-Norm of the vector (this is how tensorflow has implemented their standard normalization method) or using MinMaxScaling.

So when is normalization using either L1 or L2 norm recommended and when is MinMaxScaling the right choice?

答: Regularization doesn't apply to rescaling data.</p>

Title: MinMaxScaling vs L1/L2-Normalization


问:
How to remove warning messages in R Markdown document?
I have an R Markdown document, which takes a really long time to knit because of heavy computations. Mistakenly there are some code chunks where I forgot to put warnings=False before knitting the document. Is their any way to remove those warning messages, without knitting the document again??
Is there any way to remove warnings from the Markdown document and rebuild an html file from the markdown. I don't want to execute the code again.
Need the similar changes in the markdown document as well.

答:
If you want to turn off messages and warnings in the whole document you can use this code chunk right after the yaml portion.</p>

```<code>```{r setup, include=FALSE}
knitr::opts_chunk$set(warning = FALSE, message = FALSE)
```
</code>```

Body:
If you want to turn off messages and warnings in the whole document you can use this code chunk right after the yaml portion.

```{r setup, include=FALSE}
knitr::opts_chunk$set(warning = FALSE, message = FALSE)
```


问:
Clipboard data sort in VB.NET
I have a form in which I need to sort text from the clipboard into the appropriate fields. Essentially, I copy a customer email, click a button on the form, and it will read the data and put the info into the fields. There are several fields, such as the customer's name, the company's name, the telephone number, whether they have a support plan.

All emails are formatted in the same way (apart from the random spaces which I have no control of) and are used by several employees:

Company:                   TEST LTD

Customer's name:     Joe Johnson

Department:           IT Operations Manager

Customer's phone:     012345678910

Customer's email:       JOE.JOHNSON@TEST.COM

Instrument:                   SUP

Serial Number:             EM2PC2938C

Coverage:             Plan No Warranty

So, my question is:

I need to be able to copy this text straight from an email, click on a button that will look through the text in the clipboard, and put the different pieces of information into different text boxes labelled the same as in the email, but without the identifier (such as 'Email:' or 'Coverage'), so essentially anything after the colon goes into the textbox.

I have some code to get the data and put into into a rich text box which I planned to use to sort the data (I know I can do it straight from code, but didn't know how to)

```<code>rtbx_ClipboardData.text = Clipboard.GetText
</code>```

And some code to remove any text before the colon:

```<code>tbx_Data_Company.Text = rtbx_ClipboardData.Text.Substring(rtbx_ClipboardData.Text.IndexOf(":") + 1)
</code>```

This code works but I need to do it several times and put data into the appropriate fields which is where I am struggling.

If anyone could suggest anything/provide some sample code I'd greatly appreciate it.

答:
Instead of .Substring and .IndexOf, I would use String.Split.

Get the string from the clip board and split it into lines removing any empty lines. Take each element of the resulting array (one line) and split that by the colon. We want the second element of this array (1) trimmed of any leading or trailing spaces and assigned to the appropriate text box. Then repeat with each line.

```<code>Private Sub GetFieldsFromEmail()
    Dim eText As String = Clipboard.GetText()
    Dim lines = eText.Split({Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
    txtCompany.Text = lines(0).Split(":"c)(1).Trim
    txtName.Text = lines(1).Split(":"c)(1).Trim
    txtDepartment.Text = lines(2).Split(":"c)(1).Trim
    txtPhone.Text = lines(3).Split(":"c)(1).Trim
    txtEmail.Text = lines(4).Split(":"c)(1).Trim
    txtInstrument.Text = lines(5).Split(":"c)(1).Trim
    txtSerNum.Text = lines(6).Split(":"c)(1).Trim
    txtCoverage.Text = lines(7).Split(":"c)(1).Trim
End Sub
</code>```

EDIT

If there is random text before and after...

```<code>Private Sub GetFieldsFromEmail()
    Dim eText As String = Clipboard.GetText()
    Dim lines = eText.Split({Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
    Dim StartLine As Integer
    For i = 0 To lines.Count - 1
        If lines(i).StartsWith("Company") Then
            StartLine = i
            Exit For
        End If
    Next
    TextBox18.Text = lines(StartLine).Split(":"c)(1).Trim
    TextBox19.Text = lines(StartLine + 1).Split(":"c)(1).Trim
    TextBox20.Text = lines(StartLine + 2).Split(":"c)(1).Trim
    TextBox21.Text = lines(StartLine + 3).Split(":"c)(1).Trim
    TextBox22.Text = lines(StartLine + 4).Split(":"c)(1).Trim
    TextBox23.Text = lines(StartLine + 5).Split(":"c)(1).Trim
    TextBox24.Text = lines(StartLine + 6).Split(":"c)(1).Trim
    TextBox25.Text = lines(StartLine + 7).Split(":"c)(1).Trim
End Sub
</code>```

I just added a For loop to find where to start reading the data. Tested by copying several paragraphs before and after your data directly from your question. I changed the names of the text boxes to match what I had available.

Title: Clipboard data sort in VB.NET

Body:
I have a form in which I need to sort text from the clipboard into the appropriate fields. Essentially, I copy a customer email, click a button on the form, and it will read the data and put the info into the fields. There are several fields, such as the customer's name, the company's name, the telephone number, whether they have a support plan.

All emails are formatted in the same way (apart from the random spaces which I have no control of) and are used by several employees:

Company:                   TEST LTD

Customer's name:     Joe Johnson

Department:           IT Operations Manager

Customer's phone:     012345678910

Customer's email:       JOE.JOHNSON@TEST.COM

Instrument:                   SUP

Serial Number:             EM2PC2938C

Coverage:             Plan No Warranty

So, my question is:

I need to be able to copy this text straight from an email, click on a button that will look through the text in the clipboard, and put the different pieces of information into different text boxes labelled the same as in the email, but without the identifier (such as 'Email:' or 'Coverage'), so essentially anything after the colon goes into the textbox.

I have some code to get the data and put into into a rich text box which I planned to use to sort the data (I know I can do it straight from code, but didn't know how to)

rtbx_ClipboardData.text = Clipboard.GetText

And some code to remove any text before the colon:

tbx_Data_Company.Text = rtbx_ClipboardData.Text.Substring(rtbx_ClipboardData.Text.IndexOf(":") + 1)

This code works but I need to do it several times and put data into the appropriate fields which is where I am struggling.

If anyone could suggest anything/provide some sample code I'd greatly appreciate it.

Body:
Instead of .Substring and .IndexOf, I would use String.Split.

Get the string from the clip board and split it into lines removing any empty lines. Take each element of the resulting array (one line) and split that by the colon. We want the second element of this array (1) trimmed of any leading or trailing spaces and assigned to the appropriate text box. Then repeat with each line.

Private Sub GetFieldsFromEmail()
    Dim eText As String = Clipboard.GetText()
    Dim lines = eText.Split({Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
    txtCompany.Text = lines(0).Split(":"c)(1).Trim
    txtName.Text = lines(1).Split(":"c)(1).Trim
    txtDepartment.Text = lines(2).Split(":"c)(1).Trim
    txtPhone.Text = lines(3).Split(":"c)(1).Trim
    txtEmail.Text = lines(4).Split(":"c)(1).Trim
    txtInstrument.Text = lines(5).Split(":"c)(1).Trim
    txtSerNum.Text = lines(6).Split(":"c)(1).Trim
    txtCoverage.Text = lines(7).Split(":"c)(1).Trim
End Sub

EDIT

If there is random text before and after...

Private Sub GetFieldsFromEmail()
    Dim eText As String = Clipboard.GetText()
    Dim lines = eText.Split({Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
    Dim StartLine As Integer
    For i = 0 To lines.Count - 1
        If lines(i).StartsWith("Company") Then
            StartLine = i
            Exit For
        End If
    Next
    TextBox18.Text = lines(StartLine).Split(":"c)(1).Trim
    TextBox19.Text = lines(StartLine + 1).Split(":"c)(1).Trim
    TextBox20.Text = lines(StartLine + 2).Split(":"c)(1).Trim
    TextBox21.Text = lines(StartLine + 3).Split(":"c)(1).Trim
    TextBox22.Text = lines(StartLine + 4).Split(":"c)(1).Trim
    TextBox23.Text = lines(StartLine + 5).Split(":"c)(1).Trim
    TextBox24.Text = lines(StartLine + 6).Split(":"c)(1).Trim
    TextBox25.Text = lines(StartLine + 7).Split(":"c)(1).Trim
End Sub

I just added a For loop to find where to start reading the data. Tested by copying several paragraphs before and after your data directly from your question. I changed the names of the text boxes to match what I had available.


问:
How to insert data into foregin key column with JPA + Rest service
I have below table structure . Assume that all JPA annotations are used .

public class EntityA{

int id // PK
.....
}

public class EntityB{

int id // PK
.....
}

public class EntityC {

int id // PK

int someId // FK referes to EntityA id column .oneToOne mapping

int someId // FK referes to EntityB id column .oneToOne mapping

}

we have 3 different API to save the data into EntityA,B,C .

My question is .

is it right way of inserting the data when we have OneToOne mapping

when I m inserting data with separate API , foreign key table (column) is inserted with null value .

Can anyone tell me how  to insert data for foreign key table with separate API . ?

答:
1) is it right way of inserting the data when we have OneToOne mapping ?

It depends on your requirement. But the whole thing can be achieved with single API instead of having three since it is any way one to one mapping. Get two JSON object and then you can split it up according to your table requirements and save it to database

2) when I am inserting data with separate API , foreign key table (column) is inserted with null value ?

No it is not supposed to be empty. If you are going to have three different API then the API which write to child table must provide information about parent table like primary key id (something to identify the parent table). If it is a single API this is going to simple any way


问:
sql query question for most name in table with multiple most names
fbn table:

```<code>create table fbn (
id int,
name varchar(40),
birthday date,
gender varchar(10));

INSERT into fbn values
(1, "James", "2000-04-22", "male"),
(2, "Julia", "2006-02-27", "female"),
(3, "Ethan", "2013-05-23", "male"),
(4, "Lion", "2014-09-11", "male"),
(5, "Ethan", "2006-01-01", "male"),
(6, "Lion", "2006-02-01", "male");
</code>```

what's the name that occur most? note that there are two names (Ethan and Lion) occur most often. I have two solutions as below:

```<code>select tmp2.name
from (select tmp.name,
             dense_rank() over(order by tmp.name_count desc) rank
      from (select name,
                   count(*) name_count
            from fbn
            group by name) tmp
      ) tmp2
where tmp2.rank = 1;
</code>```

and the 2nd solution:

```<code>select name from fbn
group by name
having count(name) = (select count(name) from fbn
                      group by name
                      order by count(name) desc
                      limit 1);
</code>```

both seem to be working, but both looks like too complicated. is there any other solution that's more concise easier to understand? Thanks

答:
For Ms :</p>

```<code>select Top 1 count(id) as num_names, name from fbn group by name order by num_names desc
</code>```

Body:
fbn table:

create table fbn (
id int,
name varchar(40),
birthday date,
gender varchar(10));

INSERT into fbn values
(1, "James", "2000-04-22", "male"),
(2, "Julia", "2006-02-27", "female"),
(3, "Ethan", "2013-05-23", "male"),
(4, "Lion", "2014-09-11", "male"),
(5, "Ethan", "2006-01-01", "male"),
(6, "Lion", "2006-02-01", "male");

what's the name that occur most? note that there are two names (Ethan and Lion) occur most often. I have two solutions as below:

select tmp2.name
from (select tmp.name,
             dense_rank() over(order by tmp.name_count desc) rank
      from (select name,
                   count(*) name_count
            from fbn
            group by name) tmp
      ) tmp2
where tmp2.rank = 1;

and the 2nd solution:

select name from fbn
group by name
having count(name) = (select count(name) from fbn
                      group by name
                      order by count(name) desc
                      limit 1);

both seem to be working, but both looks like too complicated. is there any other solution that's more concise easier to understand? Thanks

Body:
For Ms :

select Top 1 count(id) as num_names, name from fbn group by name order by num_names desc


问:
inserting the records in the c# form
I am working with C#.

I want to insert record in the table. I m using the MS Access database. I have the following code:

```<code>private void button1_Click(object sender, EventArgs e)
{
    con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;
        Data Source=C:\\Documents and Settings\\mayur patil\\
                       My Documents\\Dairy_db\\tblCompany.mdb";
    con.Open();
    OleDbCommand cmd = new OleDbCommand(
       "INSERT INTO tblCompany (CoCode,CoName_mar)
       VALUES("+textBox1.Text+","+textBox4.Text+")", con);
    cmd.ExecuteNonQuery();
    con.Close();

    this.Hide();
    Form1 f = new Form1();
    f.ShowDialog();
}
</code>```

I am not getting the answer..

答:
A much better way to create your command would be to add parameters to it.

This frees you completely from thinking about the neccessity of quotes and, as an important "side effect" you eliminate the risk of SQL injection attacks. :-)

You can find a more complete explanation on MSDN here, for example.

Your command might then look like this:

```<code>OleDbCommand cmd = new OleDbCommand(
   "INSERT INTO tblCompany (CoCode,CoName_mar)
   VALUES(@ParamCoCode, @ParamCoName_mar)", con);

OleDbParameter paramCoCode = new OleDbParameter();
paramCoCode.ParameterName = "@ParamCoCode";
paramCoCode.SqlDbType = SqlDbType.NVarChar;
paramCoCode.Value = categoryName;

OleDbParameter paramCoName_mar = new OleDbParameter ();
paramCoName_mar.ParameterName = "@ParamCoCode";
paramCoName_mar.SqlDbType = SqlDbType.NVarChar;
paramCoName_mar.Value = categoryName;

// Add the parameters to the Parameters collection.
cmdParameters.Add(paramCoCode);
cmdParameters.Add(paramCoName_mar);

cmd.ExecuteNonQuery();
con.Close();
</code>```

Please keep in mind that the parameters need to be added in the same order as thay occur in the SQL statement.

Title: inserting the records in the c# form

Body:
I am working with C#.

I want to insert record in the table. I m using the MS Access database. I have the following code:

private void button1_Click(object sender, EventArgs e)
{
    con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;
        Data Source=C:\\Documents and Settings\\mayur patil\\
                       My Documents\\Dairy_db\\tblCompany.mdb";
    con.Open();
    OleDbCommand cmd = new OleDbCommand(
       "INSERT INTO tblCompany (CoCode,CoName_mar)
       VALUES("+textBox1.Text+","+textBox4.Text+")", con);
    cmd.ExecuteNonQuery();
    con.Close();

    this.Hide();
    Form1 f = new Form1();
    f.ShowDialog();
}

I am not getting the answer..

Body:
A much better way to create your command would be to add parameters to it.

This frees you completely from thinking about the neccessity of quotes and, as an important "side effect" you eliminate the risk of SQL injection attacks. :-)

You can find a more complete explanation on MSDN here, for example.

Your command might then look like this:

OleDbCommand cmd = new OleDbCommand(
   "INSERT INTO tblCompany (CoCode,CoName_mar)
   VALUES(@ParamCoCode, @ParamCoName_mar)", con);

OleDbParameter paramCoCode = new OleDbParameter();
paramCoCode.ParameterName = "@ParamCoCode";
paramCoCode.SqlDbType = SqlDbType.NVarChar;
paramCoCode.Value = categoryName;

OleDbParameter paramCoName_mar = new OleDbParameter ();
paramCoName_mar.ParameterName = "@ParamCoCode";
paramCoName_mar.SqlDbType = SqlDbType.NVarChar;
paramCoName_mar.Value = categoryName;

// Add the parameters to the Parameters collection.
cmdParameters.Add(paramCoCode);
cmdParameters.Add(paramCoName_mar);

cmd.ExecuteNonQuery();
con.Close();

Please keep in mind that the parameters need to be added in the same order as thay occur in the SQL statement.


问:
Height transition with CSS instead of Javascript?
I have made these cards with HTML and CSS. For height transition, I have used javascript but depends on the page sometimes it works really slow. Is there a way to write this animate function in CSS without my javascript code?
2. Question
I set from 110px to 160px height raisement in JS, is it possible to raise the box's height depends on the text's height so if there is more text hidden the box will raise more?

$('#dynamic-cards .card-box').hover(function(){
   $(this).find('.description').animate({
        'height': '160px'
    }, 500);
},function(){
  $(this).find('.description').animate({
        'height': '110px'
    }, 300);
}).trigger('mouseleave');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#dynamic-cards {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  max-width: 1000px;
}
#dynamic-cards .card-box {
  position: relative;
  font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
  z-index: 1;
  display: block;
  background: #ffffff;
  height: 450px;
  -webkit-transition: all 0.3s linear 0s;
  -moz-transition: all 0.3s linear 0s;
  -ms-transition: all 0.3s linear 0s;
  -o-transition: all 0.3s linear 0s;
  transition: all 0.3s linear 0s;
}

#dynamic-cards .card-box:hover .card-pic img,
#dynamic-cards .hover .card-pic img {
  -webkit-transform: scale(1.1);
  -moz-transform: scale(1.1);
  transform: scale(1.1);
  opacity: 0.6;
}

#dynamic-cards .card-box .card-pic {
  background: #000000;
  overflow: hidden;
}

#dynamic-cards .card-box .card-pic img {
  display: block;
  max-width: 300px;
  -webkit-transition: all 0.3s linear 0s;
  -moz-transition: all 0.3s linear 0s;
  -ms-transition: all 0.3s linear 0s;
  -o-transition: all 0.3s linear 0s;
  transition: all 0.3s linear 0s;
}

#dynamic-cards .card-box .card-box-content {
  position: absolute;
  bottom: 0;
  background-color: #EFEFEF;
  width: 100%;
  padding: 15px 15px 0px 15px;
  -webkti-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  -webkit-transition: all 0.3s cubic-bezier(0.37, 0.75, 0.61, 1.05) 0s;
  -moz-transition: all 0.3s cubic-bezier(0.37, 0.75, 0.61, 1.05) 0s;
  -ms-transition: all 0.3s cubic-bezier(0.37, 0.75, 0.61, 1.05) 0s;
  -o-transition: all 0.3s cubic-bezier(0.37, 0.75, 0.61, 1.05) 0s;
  transition: all 0.3s cubic-bezier(0.37, 0.75, 0.61, 1.05) 0s;
}

#dynamic-cards .card-box .card-box-content .category {
  position: absolute;
  top: -34px;
  left: 0;
  background: #002776;
  padding: 10px 15px;
  color: #ffffff;
  font-size: 14px;
  font-weight: 600;
  text-transform: uppercase;
}

#dynamic-cards .card-box .card-box-content .title {
  margin: 0;
  padding: 0 0 10px;
  margin-top: 10px;
  color: #002776;
  font-size: 26px;
  font-weight: 700;
}

#dynamic-cards .card-box .card-box-content .sub_title {
  margin: 0;
  padding: 0 0 20px;
  color: #002776;
  font-size: 20px;
  font-weight: 400;
}

#dynamic-cards .card-box .card-box-content .description {
  height: 105px;
  color: black;
  font-size: 15px;
  line-height: 1.4em;
  padding-bottom: 0px !important;
}

#dynamic-cards .card-box .card-box-content .card-box-footer {
  font-size: 14px;
  height: 20%;
  position: relative;
  background-color: #EFEFEF;
  padding-bottom: 27px;
  margin: 0px;
}

#dynamic-cards .card-box .card-box-content .card-box-footer a {
  color: white;
  background-color: #002776;
  padding: 10px;
  font-weight: bold;
}

#dynamic-cards .card-box .card-box-content .card-box-footer a:hover {
  background-color: #009fda;
}

#dynamic-cards .hover .card-box-content .description {
  display: block !important;
  height: auto !important;
  opacity: 1 !important;
}</code>```

Headline

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed
                diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero
                eos et accusam et justo duo dolores et ea rebum.

                Button

Headline

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed
                diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero
                eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est
                Lorem ipsum dolor sit amet.

                Button

Headline

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed
                diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero
                eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata.

```

https://codepen.io/rahman23/pen/MWweeoN

答:
You can create this animation by adding the following style without using JavaScript

```<code>.card-box:hover .card-box-content{
  transform: translateY(-80px);
}
</code>```

Keep in mind that inserting a static height for text is not a fun job.
I suggest not considering the height and if you have to, consider overfolow-y:scroll for it.

Body:
I have made these cards with HTML and CSS. For height transition, I have used javascript but depends on the page sometimes it works really slow. Is there a way to write this animate function in CSS without my javascript code?
2. Question
I set from 110px to 160px height raisement in JS, is it possible to raise the box's height depends on the text's height so if there is more text hidden the box will raise more?

$('#dynamic-cards .card-box').hover(function(){
   $(this).find('.description').animate({
        'height': '160px'
    }, 500);
},function(){
  $(this).find('.description').animate({
        'height': '110px'
    }, 300);
}).trigger('mouseleave');

#dynamic-cards {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  max-width: 1000px;
}
#dynamic-cards .card-box {
  position: relative;
  font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
  z-index: 1;
  display: block;
  background: #ffffff;
  height: 450px;
  -webkit-transition: all 0.3s linear 0s;
  -moz-transition: all 0.3s linear 0s;
  -ms-transition: all 0.3s linear 0s;
  -o-transition: all 0.3s linear 0s;
  transition: all 0.3s linear 0s;
}

#dynamic-cards .card-box:hover .card-pic img,
#dynamic-cards .hover .card-pic img {
  -webkit-transform: scale(1.1);
  -moz-transform: scale(1.1);
  transform: scale(1.1);
  opacity: 0.6;
}

#dynamic-cards .card-box .card-pic {
  background: #000000;
  overflow: hidden;
}

#dynamic-cards .card-box .card-pic img {
  display: block;
  max-width: 300px;
  -webkit-transition: all 0.3s linear 0s;
  -moz-transition: all 0.3s linear 0s;
  -ms-transition: all 0.3s linear 0s;
  -o-transition: all 0.3s linear 0s;
  transition: all 0.3s linear 0s;
}

#dynamic-cards .card-box .card-box-content {
  position: absolute;
  bottom: 0;
  background-color: #EFEFEF;
  width: 100%;
  padding: 15px 15px 0px 15px;
  -webkti-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  -webkit-transition: all 0.3s cubic-bezier(0.37, 0.75, 0.61, 1.05) 0s;
  -moz-transition: all 0.3s cubic-bezier(0.37, 0.75, 0.61, 1.05) 0s;
  -ms-transition: all 0.3s cubic-bezier(0.37, 0.75, 0.61, 1.05) 0s;
  -o-transition: all 0.3s cubic-bezier(0.37, 0.75, 0.61, 1.05) 0s;
  transition: all 0.3s cubic-bezier(0.37, 0.75, 0.61, 1.05) 0s;
}

#dynamic-cards .card-box .card-box-content .category {
  position: absolute;
  top: -34px;
  left: 0;
  background: #002776;
  padding: 10px 15px;
  color: #ffffff;
  font-size: 14px;
  font-weight: 600;
  text-transform: uppercase;
}

#dynamic-cards .card-box .card-box-content .title {
  margin: 0;
  padding: 0 0 10px;
  margin-top: 10px;
  color: #002776;
  font-size: 26px;
  font-weight: 700;
}

#dynamic-cards .card-box .card-box-content .sub_title {
  margin: 0;
  padding: 0 0 20px;
  color: #002776;
  font-size: 20px;
  font-weight: 400;
}

#dynamic-cards .card-box .card-box-content .description {
  height: 105px;
  color: black;
  font-size: 15px;
  line-height: 1.4em;
  padding-bottom: 0px !important;
}

#dynamic-cards .card-box .card-box-content .card-box-footer {
  font-size: 14px;
  height: 20%;
  position: relative;
  background-color: #EFEFEF;
  padding-bottom: 27px;
  margin: 0px;
}

#dynamic-cards .card-box .card-box-content .card-box-footer a {
  color: white;
  background-color: #002776;
  padding: 10px;
  font-weight: bold;
}

#dynamic-cards .card-box .card-box-content .card-box-footer a:hover {
  background-color: #009fda;
}

#dynamic-cards .hover .card-box-content .description {
  display: block !important;
  height: auto !important;
  opacity: 1 !important;
}

Headline

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed
                diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero
                eos et accusam et justo duo dolores et ea rebum.

                Button

Headline

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed
                diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero
                eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est
                Lorem ipsum dolor sit amet.

                Button

Headline

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed
                diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero
                eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata.

https://codepen.io/rahman23/pen/MWweeoN

Body:
You can create this animation by adding the following style without using JavaScript

.card-box:hover .card-box-content{
  transform: translateY(-80px);
}

Keep in mind that inserting a static height for text is not a fun job.
I suggest not considering the height and if you have to, consider overfolow-y:scroll for it.


问:
TypeScript query property does not exist
I try to add Query types on GraphQL query using TypeScript, but i don't understand why TS return me this error :

Property 'userMe' does not exist on type 'Query | null'.

My Query :

```<code>const { userMe }: Query | null = cache.readQuery({
  query: ME,
});
</code>```

And my types :

```<code>export type Query = {
  __typename?: 'Query';
  files?: Maybe<Array<Maybe<UploadFile>>>;
  me?: Maybe<UsersPermissionsMe>;
  userMe?: Maybe<CustomUsersPermissionsMe>;
};
</code>```

userMe is present, but not required. I don't understand why TS cry about this :D I use TS v3.7.5.

Anyone can help me ?

答:
It's because the return value of cache.readQuery() may be null. Its return type is Query | null by the look of the error message. Your code will throw an exception if it is null.

Instead of:

```<code>const { userMe }: Query | null = cache.readQuery({
  query: ME,
});
</code>```

You need to do:

```<code>const query = cache.readQuery({
  query: ME,
});
const userMe = query && query.userMe ? query.userMe: undefined
</code>```

You need to deal with the fact that the query result may be null, and that the userMe may be undefined on a non-null query.

At a high-level, TypeScript is forcing you to write code that deals with the fact that things may be null or undefined at runtime. Your type signature models two scenarios where that may be the case (null Query result, and undefined field on non-null Query).

How you handle that in your code depends on how your program should behave in that situation.

At the very least you do something like:

```<code>if (userMe !=== undefined) {
  // TS now knows that in here userMe is Maybe<CustomUsersPermissionsMe>
}
</code>```

You have to guard against undefined because it is nullable on the Query object itself. And then it is a Maybe, so you have a bunch of guards to write.

Body:
I try to add Query types on GraphQL query using TypeScript, but i don't understand why TS return me this error :

Property 'userMe' does not exist on type 'Query | null'.

My Query :

const { userMe }: Query | null = cache.readQuery({
  query: ME,
});

And my types :

export type Query = {
  __typename?: 'Query';
  files?: Maybe<Array<Maybe<UploadFile>>>;
  me?: Maybe<UsersPermissionsMe>;
  userMe?: Maybe<CustomUsersPermissionsMe>;
};

userMe is present, but not required. I don't understand why TS cry about this :D I use TS v3.7.5.

Anyone can help me ?

Body:
It's because the return value of cache.readQuery() may be null. Its return type is Query | null by the look of the error message. Your code will throw an exception if it is null.

Instead of:

const { userMe }: Query | null = cache.readQuery({
  query: ME,
});

You need to do:

const query = cache.readQuery({
  query: ME,
});
const userMe = query && query.userMe ? query.userMe: undefined

You need to deal with the fact that the query result may be null, and that the userMe may be undefined on a non-null query.

At a high-level, TypeScript is forcing you to write code that deals with the fact that things may be null or undefined at runtime. Your type signature models two scenarios where that may be the case (null Query result, and undefined field on non-null Query).

How you handle that in your code depends on how your program should behave in that situation.

At the very least you do something like:

if (userMe !=== undefined) {
  // TS now knows that in here userMe is Maybe<CustomUsersPermissionsMe>
}

You have to guard against undefined because it is nullable on the Query object itself. And then it is a Maybe, so you have a bunch of guards to write.


问:
Java scheduler that works with native image compilation by GraalVM
I have the app on top of Quarkus framework. The main functionality of the app - simple REST API for scheduling some tasks (now it just posts some message to the log).

Scheduling functionality I implemented with Quartz framework and in common it looks like when the app get POST request for scheduling a new event it does two things:

save entity from the request to the database;

schedule Quartz job on mentioned in JSON date and time.

Also for case when the application just starts I created method which take all entities from database and schedule Quartz jobs for them.

But when I tried to build native image for that application using GraalVM I faced with such exception:

com.oracle.graal.pointsto.constraints.UnsupportedFeatureException: No
  instances of sun.security.provider.NativePRNG are allowed in the image
  heap as this class should be initialized at image runtime.

Fast search in Google gave me closed issue in GraalVM Github repo which say, that Quartz use RMI's ObjID with run-time initialization. Due to that Quartz couldn't be used in applications where is required native image compilation by GraalVM.

So does Quarkus scheduler provides abilities to schedule jobs right in Java code (something like in my implementation with Quartz)?  In all examples and pieces of code I found I could see only pretty simple usage of @Scheduled annotation on methods (like in official guide). Or maybe there are any other alternative tools for scheduling tasks in Java that works with native image compilation?

答:
So Quarkus Quartz extension (built on top of quarkus-scheduler) does support GraalVM native images. The truth is that the API does not support programmatic scheduling and it's not possible to access the underlying Quartz Scheduler instance. I've created https://github.com/quarkusio/quarkus/issues/7246 to address the latter issue.

So does Quarkus scheduler provides abilities to schedule jobs right in Java code...

Yes, see https://stackoverflow.com/a/60275796/2654154.


问:
Use Environment Variables within a Traefik dynamic configuration
I am trying to build a Traefik dynamic configuration that has a rule for "Host(app.localhost)" in development but uses "Host(realname.com)" in production. I'm also using Docker but I don't think that is relevant to my question. My question is: is there an idiomatic way to use environment variables in my dynamic configuration?

The docs mention Go templates but I don't understand it beyond that. It's really lacking. I've also considered something like envsubst but was hoping to not have to install another tool.

I'm using Traefik 2.0+. Also, I must use the File Provider as I'm using a self-signed cert locally for TLS. From Traefik's documentation:

In the above example, we've used the file provider to handle these definitions. It is the only available method to configure the certificates (as well as the options and the stores). However, in Kubernetes, the certificates can and must be provided by secrets.

答: Unless traefik supports some way of using environment variables for dynamic-configuration as with static-configurations your are usually stuck with sed or envsubst templating configurations at startup.


问:
Which part of this WHERE IN subquery is wrong? It produces no output
This is a valid query, which generates no results but it was shown by someone else that it has results.
The question was 'What was the total monthly revenue for the top 50 products sold in July 2017 for each of the 11 months prior to July 2017?

```<code>SELECT PARSE_DATE("%m",date) AS Month, product.v2ProductName AS Product_Name, SUM(totals.transactionRevenue)/1000000 AS Total_Revenue,
FROM `bigquery-public-data.google_analytics_sample.ga_sessions_*`,
  UNNEST(hits) AS hit,
  UNNEST(hit.product) AS product
WHERE _TABLE_SUFFIX BETWEEN '20170801' AND '20170630' AND totals.transactions >= 1
AND
product.v2ProductName IN (
SELECT
product.v2ProductName AS Product_Name
FROM `bigquery-public-data.google_analytics_sample.ga_sessions_*`,
  UNNEST(hits) AS hit,
  UNNEST(hit.product) AS product
WHERE _TABLE_SUFFIX BETWEEN '20170701' AND '20170731' AND totals.transactions >= 1
Group by product_Name
Order by SUM(totals.transactionRevenue)/1000000
LIMIT 50)
Group by PARSE_DATE("%m",date), Product_Name
</code>```

Please help! Thanks.

答:
Thanks everyone. The dates were wrong:

```<code>WHERE _TABLE_SUFFIX BETWEEN '20170801' AND '20170630'
</code>```

It was supposed to be between 20160801 and 20170630.

Body:
This is a valid query, which generates no results but it was shown by someone else that it has results.
The question was 'What was the total monthly revenue for the top 50 products sold in July 2017 for each of the 11 months prior to July 2017?

SELECT PARSE_DATE("%m",date) AS Month, product.v2ProductName AS Product_Name, SUM(totals.transactionRevenue)/1000000 AS Total_Revenue,
FROM `bigquery-public-data.google_analytics_sample.ga_sessions_*`,
  UNNEST(hits) AS hit,
  UNNEST(hit.product) AS product
WHERE _TABLE_SUFFIX BETWEEN '20170801' AND '20170630' AND totals.transactions >= 1
AND
product.v2ProductName IN (
SELECT
product.v2ProductName AS Product_Name
FROM `bigquery-public-data.google_analytics_sample.ga_sessions_*`,
  UNNEST(hits) AS hit,
  UNNEST(hit.product) AS product
WHERE _TABLE_SUFFIX BETWEEN '20170701' AND '20170731' AND totals.transactions >= 1
Group by product_Name
Order by SUM(totals.transactionRevenue)/1000000
LIMIT 50)
Group by PARSE_DATE("%m",date), Product_Name

Please help! Thanks.

Body:
Thanks everyone. The dates were wrong:

WHERE _TABLE_SUFFIX BETWEEN '20170801' AND '20170630'

It was supposed to be between 20160801 and 20170630.


问:
How to update the text based on the response value in quasar?
I have a q-table where I get a response from API. In one of the entries, it gives the value of the flag as 0 or 1 which I need to update it as Yes or No.
How can I do this?

I am using q-badge to change the bg color and highlight it but unable to update the text.

```<code>      <template v-slot:body-cell-processed="props">
        <q-td :props="props" >
          <q-badge style="background-color:white" :class="props.row.processed==0?'bg-red':'text-black'">
              {{ props.row.processed }}
            </q-badge>
        </q-td>
      </template>
</code>```

答:
I have tries this and it's working fine.

```<code><q-td key="processed" :props="props">
            <q-badge style="background-color:white" :class="props.row.processed==0?'bg-red text-white text-weight-bolder':'bg-blue text-black'">
              {{ props.row.processed }}
            </q-badge>
          </q-td>
</code>```

Codepen - https://codepen.io/Pratik__007/pen/PoqzzLx?editable=true&editors=101

Body:
I have a q-table where I get a response from API. In one of the entries, it gives the value of the flag as 0 or 1 which I need to update it as Yes or No.
How can I do this?

I am using q-badge to change the bg color and highlight it but unable to update the text.

      <template v-slot:body-cell-processed="props">
        <q-td :props="props" >
          <q-badge style="background-color:white" :class="props.row.processed==0?'bg-red':'text-black'">
              {{ props.row.processed }}
            </q-badge>
        </q-td>
      </template>

Body:
I have tries this and it's working fine.

<q-td key="processed" :props="props">
            <q-badge style="background-color:white" :class="props.row.processed==0?'bg-red text-white text-weight-bolder':'bg-blue text-black'">
              {{ props.row.processed }}
            </q-badge>
          </q-td>

Codepen - https://codepen.io/Pratik__007/pen/PoqzzLx?editable=true&editors=101


问:
Accessing values in list inside dictionary when you don't know the count
I have output in below form:

```<code>data = {ItemA: [123456, 123654], ItemB: [456789, 456987]}
</code>```

To get the values, I can access them as data.ItemA[0], data.ItemA[1]

But how do you deal when you don't know how many values are there for ItemA in the list. How can I get all individual values of ItemA without knowing how many items will be in list beforehand.

答:
So for that you need to iterate over dictionary and than from the key you get you need to iterate the list inside that.

```<code>data = {'ItemA': [123456, 123654], 'ItemB': [456789, 456987]}
for key in data:
    for items in data[key]:
        print(key ,':' , items)
</code>```

Key will iterate over dictionary and contains 'ItemA' and 'ItemB'. Then from there yoū can iterate over that dictionary key and get list

Body:
I have output in below form:

data = {ItemA: [123456, 123654], ItemB: [456789, 456987]}

To get the values, I can access them as data.ItemA[0], data.ItemA[1]

But how do you deal when you don't know how many values are there for ItemA in the list. How can I get all individual values of ItemA without knowing how many items will be in list beforehand.

Body:
So for that you need to iterate over dictionary and than from the key you get you need to iterate the list inside that.

data = {'ItemA': [123456, 123654], 'ItemB': [456789, 456987]}
for key in data:
    for items in data[key]:
        print(key ,':' , items)

Key will iterate over dictionary and contains 'ItemA' and 'ItemB'. Then from there yoū can iterate over that dictionary key and get list


问:
Unable to filter logstreams for boto3 logs of aws lambda function
I am unable to filter out logStreams for lambda function using boto3 API, with 'endtime' filter or 'logStreamNamePrefix' filter.

This works:

```<code>client = boto3.client('logs',
                      aws_access_key_id=aws_account['access_key'],
                      aws_secret_access_key=aws_account['secret_key'],
                      region_name=region)
logGroupName = '/aws/lambda/' + function_name
response = client.filter_log_events(
    logGroupName=logGroupName,
    startTime=int((datetime(2020, 1, 15)- datetime(1970, 1, 1)).total_seconds()),   # epoch_time
)
</code>```

But these don`t:

1.

```<code>response = client.filter_log_events(
    logGroupName=logGroupName,
    startTime=int((datetime(2020, 1, 15)- datetime(1970, 1, 1)).total_seconds()),   # epoch_time
    endTime=int((datetime(2020, 1, 31)- datetime(1970, 1, 1)).total_seconds())
)
</code>```

ERROR: Empty list is returned, although log data is there for the
  specified time range

2.

```<code>response = client.filter_log_events(
    logGroupName=logGroupName,
    startTime=int((datetime(2020, 1, 15)- datetime(1970, 1, 1)).total_seconds()),   # epoch_time
    logStreamNamePrefix='^2020/01'  # logs starting with this prefix
)
</code>```

ERROR:

```<code>botocore.exceptions.ParamValidationError: Parameter validation failed:
Unknown parameter in input: "logStreamNamePrefix", must be one of: logGroupName, logStreamNames, startTime, endTime, filterPattern, nextToken, limit, interleaved
</code>```

答:
As a temporary fix, I am polling all the responses and then filtering it expilictly.</p>

```<code>response = client.filter_log_events(
    logGroupName=logGroupName,
    startTime=int((datetime(2020, 1, 15)- datetime(1970, 1, 1)).total_seconds()),   # epoch_time
)

filtered_response = list(filter(lambda x: x['logStreamName'].startswith('2020/01'), response['events']))
</code>```

Body:
I am unable to filter out logStreams for lambda function using boto3 API, with 'endtime' filter or 'logStreamNamePrefix' filter.

This works:

client = boto3.client('logs',
                      aws_access_key_id=aws_account['access_key'],
                      aws_secret_access_key=aws_account['secret_key'],
                      region_name=region)
logGroupName = '/aws/lambda/' + function_name
response = client.filter_log_events(
    logGroupName=logGroupName,
    startTime=int((datetime(2020, 1, 15)- datetime(1970, 1, 1)).total_seconds()),   # epoch_time
)

But these don`t:

1.

response = client.filter_log_events(
    logGroupName=logGroupName,
    startTime=int((datetime(2020, 1, 15)- datetime(1970, 1, 1)).total_seconds()),   # epoch_time
    endTime=int((datetime(2020, 1, 31)- datetime(1970, 1, 1)).total_seconds())
)

ERROR: Empty list is returned, although log data is there for the
  specified time range

2.

response = client.filter_log_events(
    logGroupName=logGroupName,
    startTime=int((datetime(2020, 1, 15)- datetime(1970, 1, 1)).total_seconds()),   # epoch_time
    logStreamNamePrefix='^2020/01'  # logs starting with this prefix
)

ERROR:

botocore.exceptions.ParamValidationError: Parameter validation failed:
Unknown parameter in input: "logStreamNamePrefix", must be one of: logGroupName, logStreamNames, startTime, endTime, filterPattern, nextToken, limit, interleaved

Body:
As a temporary fix, I am polling all the responses and then filtering it expilictly.

response = client.filter_log_events(
    logGroupName=logGroupName,
    startTime=int((datetime(2020, 1, 15)- datetime(1970, 1, 1)).total_seconds()),   # epoch_time
)

filtered_response = list(filter(lambda x: x['logStreamName'].startswith('2020/01'), response['events']))


问:
Change route after submit form in react with typescript
I am new in react. I write react with typescript without redux.
In my sample project i want after submit form, change route, but i can not do this. following code is my try. how can I change route in fetch then function? why this value is undefined!</p>

```<code>import * as React from 'react';
import 'isomorphic-fetch';
import { ReactRouter } from 'react-router-dom';

export interface Props {router?: ReactRouter.History.History;}

interface State {name: string;}

export class CreateItem extends React.Component<Props, State> {

    private input: HTMLInputElement;

    constructor(props: Props) {

        super(props);

        this.state = {name: ""};

        this.input = null;
    }

    public render(){

        return <form onSubmit={this.handleSubmit} className="form-horizontal">
            <div className="form-group">
                <label className="col-sm-2 control-label">Date</label>
                <div className="col-sm-5">
                    <input name="name" type="text" value={this.state.name} onChange={this.handleInputChange} className="form-control">
                    </input>
                </div>
            </div>

            <div className="form-group">
                <div className="col-sm-offset-2 col-sm-5">
                    <button type="submit" className="btn btn-default" disabled={!this.state.name}>ADD</button>
                </div>
            </div>
        </form>;
    }

    private handleSubmit = (event: React.FormEvent<HTMLFormElement>): void => {

        event.preventDefault();

        if (this.state.name) {

            var form = new FormData();

            form.append('name', name);

            fetch('/api/SampleData/', { method: 'POST', body: form })
                .then(function (res) {
                    this.props.history.push('/fetchdata');// **this code not work**
                });

            this.setState({
                name: ""
            });
        }
    }

    private handleInputChange = (event: React.FormEvent<HTMLInputElement>): void => {

        const target = event.target;
        const name = target["name"];

        this.setState({
            [name]: (event as any).target.value
        })
    }
}
</code>```

答:
You are using the React Router in the wrong way. Here it is, how using it.

styles comes from MaterialUI.

```<code>const styles = (theme: Theme) =>
  createStyles
  ({})

interface IState
{}

interface IProps
{}

class Home extends React.Component<IProps & WithStyles<typeof styles> & RouteComponentProps<{}>, IState>
{
    constructor(props: IProps & WithStyles<typeof styles> & RouteComponentProps<{}>)
    {
        super(props);

        this.state =
        {
        }
    }
}
</code>```

to navigate use: this.props.history.push(your route goes here);

Body:
I am new in react. I write react with typescript without redux.
In my sample project i want after submit form, change route, but i can not do this. following code is my try. how can I change route in fetch then function? why this value is undefined!

import * as React from 'react';
import 'isomorphic-fetch';
import { ReactRouter } from 'react-router-dom';

export interface Props {router?: ReactRouter.History.History;}

interface State {name: string;}

export class CreateItem extends React.Component<Props, State> {

    private input: HTMLInputElement;

    constructor(props: Props) {

        super(props);

        this.state = {name: ""};

        this.input = null;
    }

    public render(){

        return <form onSubmit={this.handleSubmit} className="form-horizontal">

                Date

                    <input name="name" type="text" value={this.state.name} onChange={this.handleInputChange} className="form-control">
                    </input>

                    <button type="submit" className="btn btn-default" disabled={!this.state.name}>ADD</button>

        </form>;
    }

    private handleSubmit = (event: React.FormEvent<HTMLFormElement>): void => {

        event.preventDefault();

        if (this.state.name) {

            var form = new FormData();

            form.append('name', name);

            fetch('/api/SampleData/', { method: 'POST', body: form })
                .then(function (res) {
                    this.props.history.push('/fetchdata');// **this code not work**
                });

            this.setState({
                name: ""
            });
        }
    }

    private handleInputChange = (event: React.FormEvent<HTMLInputElement>): void => {

        const target = event.target;
        const name = target["name"];

        this.setState({
            [name]: (event as any).target.value
        })
    }
}

Body:
You are using the React Router in the wrong way. Here it is, how using it.

styles comes from MaterialUI.

const styles = (theme: Theme) =>
  createStyles
  ({})

interface IState
{}

interface IProps
{}

class Home extends React.Component<IProps & WithStyles<typeof styles> & RouteComponentProps<{}>, IState>
{
    constructor(props: IProps & WithStyles<typeof styles> & RouteComponentProps<{}>)
    {
        super(props);

        this.state =
        {
        }
    }
}

to navigate use: this.props.history.push(your route goes here);


问:
Jenkins: how to make parameters required in a parameterized build?
In Jenkins is there a plugin for parameterized builds to make the parameters required?  The fields under the standard "This build is parameterized" option do not seem to provide that.

Clarification: by "required" I mean that the build will not execute until the field is populated with a value.  This would obviously preclude automated triggers.

答:
Couldn't comment to answer Miguel's question, so answering here:

To fail a build if a parameter is not set, one could do something like this:

```<code>stage('Checkout')
    {
        steps
        {
            checkout scm
            script
            {
                if (params.myParam == '') { // and/or whatever condition you want
                    currentBuild.result = 'ABORTED'
                    error('myParam not set')
                }
            }
        }
    }
</code>```

Body:
Couldn't comment to answer Miguel's question, so answering here:

To fail a build if a parameter is not set, one could do something like this:

stage('Checkout')
    {
        steps
        {
            checkout scm
            script
            {
                if (params.myParam == '') { // and/or whatever condition you want
                    currentBuild.result = 'ABORTED'
                    error('myParam not set')
                }
            }
        }
    }


问:
C# - Constant value '4294901760' cannot be converted to a 'int'
Greetings,

I can't believe I'm asking such a basic question, but it doesn't make sense so here it is :).

In C# on Windows Phone 7 / .net, I'm trying to define a constant in a class as follows:

```<code>// error CS0266: Cannot implicitly convert type 'uint' to 'int'.
// An explicit conversion exists (are you missing a cast?)
public const int RED = 0xffff0000;
</code>```

If I put an (int) cast around it like so, I get another error:

```<code>// error CS0221: Constant value '4294901760' cannot be converted to a 'int'
// (use 'unchecked' syntax to override)
public const int RED = (int)0xffff0000;
</code>```

But I know that my int is 32-bit, hence has a range of -2,147,483,648 to 2,147,483,647, see http://msdn.microsoft.com/en-us/library/5kzh1b5w(v=vs.80).aspx

So what gives?

Thanks in advance!

swine

答:
As you note, the range of Int32 is -2,147,483,648 to 2,147,483,647, so any number within that range can be held, but ONLY numbers within that range can be held. 4,294,901,760 is greater than 2,147,483,647, so doesn't fit in an Int32.

What to do about this depends on what you want to achieve. If you just want an Int32 with the bit pattern ffff0000, then as suggested use unchecked :

```<code>int y = unchecked((int)0xffff0000);
</code>```

y now has the value -65536, which is that bit pattern interpreted as a signed integer.

However! If you actually want the value 4,294,901,760 you should use a datatype appropriate to it - so UInt32.

Body:
Greetings,

I can't believe I'm asking such a basic question, but it doesn't make sense so here it is :).

In C# on Windows Phone 7 / .net, I'm trying to define a constant in a class as follows:

// error CS0266: Cannot implicitly convert type 'uint' to 'int'.
// An explicit conversion exists (are you missing a cast?)
public const int RED = 0xffff0000;

If I put an (int) cast around it like so, I get another error:

// error CS0221: Constant value '4294901760' cannot be converted to a 'int'
// (use 'unchecked' syntax to override)
public const int RED = (int)0xffff0000;

But I know that my int is 32-bit, hence has a range of -2,147,483,648 to 2,147,483,647, see http://msdn.microsoft.com/en-us/library/5kzh1b5w(v=vs.80).aspx

So what gives?

Thanks in advance!

swine

Body:
As you note, the range of Int32 is -2,147,483,648 to 2,147,483,647, so any number within that range can be held, but ONLY numbers within that range can be held. 4,294,901,760 is greater than 2,147,483,647, so doesn't fit in an Int32.

What to do about this depends on what you want to achieve. If you just want an Int32 with the bit pattern ffff0000, then as suggested use unchecked :

int y = unchecked((int)0xffff0000);

y now has the value -65536, which is that bit pattern interpreted as a signed integer.

However! If you actually want the value 4,294,901,760 you should use a datatype appropriate to it - so UInt32.


问:
How does type is submit work in javascript?
Type="Submit" and type="Button" in element input. How are they different? When I use type="button" then it submits successfully but type="Submit" does not? why is that?

```<code> <form class="crush-form">
    <div>
        <input class="name" type="text" name="name" required />
        <label for="">Name</label>
    </div>
    <div>
        <input class="address" type="text" name="address" required />
        <label for="">Address</label>
    </div>
    <div class="lol">
        <input
            type="submit"
            onclick="SubmitClickHandle()"
            name="huhu"
            value="ggg"
        />
        <button onclick="closeDialog()">Close Dialog</button>
    </div>
</form>
</code>```

答:
Submit buttons trigger the submission of a form (and when they do, their name and value are included in the submitted form data).

Button buttons don't.

When I use type="button" then it submits successfully but type="Submit" does not? why is that?

Presumably, because your idea of "submits successfully" doesn't involve performing a normal form submission but instead means "Executes the SubmitClickHandle() function without leaving the page".

Body:
Type="Submit" and type="Button" in element input. How are they different? When I use type="button" then it submits successfully but type="Submit" does not? why is that?

 <form class="crush-form">

        <input class="name" type="text" name="name" required />
        Name

        <input class="address" type="text" name="address" required />
        Address

        <input
            type="submit"
            onclick="SubmitClickHandle()"
            name="huhu"
            value="ggg"
        />
        <button onclick="closeDialog()">Close Dialog</button>

</form>


问:
Display user control in active workbook
I have a VSTO Excel Add-in project. I have a ribbon called "ManageTaskPaneRibbon" and on the ribbon I have a toggle button called "toggleButton1" which opens a User Control called "TaskPaneControl". When I run the addin and click on the button, the custom pane appears correctly in "Book1".

Book1 opens pane correctly from ribbon toggle button

But when I click on New Workbook, the ribbon in the new workbook "Book2" opens with the toggle button already clicked, like in "Book1".

Book1 panel closes, Book2 toggle button unchecks, Book1 toggle button remains checked

When I click on the toggle button in "Book2" the pane in "Book1" disappears, the toggle button in "Book2" is now unchecked but the togglebutton in "Book1" remains checked.

enter image description here

I based my test on this walkthrough...

Microsoft walkthrough example

In ThisAddIn, I delcared an instance of TaskPaneControl...

private TaskPaneControl taskPaneControl1;
private Microsoft.Office.Tools.CustomTaskPane taskPaneValue;```
</div>
</div>
</p>

<p>In ThisAddIn_Startup I added the TaskPaneControl to CustomTaskPanes field...</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>  taskPaneControl1 = new TaskPaneControl();
  taskPaneValue = this.CustomTaskPanes.Add(taskPaneControl1, "MyCustomTaskPane");
  taskPaneValue.VisibleChanged += new EventHandler(taskPaneValue_VisibleChanged);</code>```

And in the toggle button click I added the code to display the pane...

            Globals.ThisAddIn.TaskPane.Visible = ((RibbonToggleButton)sender).Checked;
            Globals.ThisAddIn.TaskPane.DockPosition = Microsoft.Office.Core.MsoCTPDockPosition.msoCTPDockPositionLeft;
            Globals.ThisAddIn.TaskPane.Width = 250;```

I'm not sure whether I need to load a new instance of the ribbon when a new file is opened or if I need to create a new instance of the panel. Of course I am not sure how to do either. Can anyone help me figure this out?

Thanks
T

答:
If your source was https://learn.microsoft.com/en-us/visualstudio/vsto/how-to-add-a-custom-task-pane-to-an-application, then:

Keep in mind that the equivalent of "this" in C# is the same as "Me" in vb.net.

it might be causing you that no other interop is being activated other that the 1st instance.

Title: Display user control in active workbook

Body:
I have a VSTO Excel Add-in project. I have a ribbon called "ManageTaskPaneRibbon" and on the ribbon I have a toggle button called "toggleButton1" which opens a User Control called "TaskPaneControl". When I run the addin and click on the button, the custom pane appears correctly in "Book1".

Book1 opens pane correctly from ribbon toggle button

But when I click on New Workbook, the ribbon in the new workbook "Book2" opens with the toggle button already clicked, like in "Book1".

Book1 panel closes, Book2 toggle button unchecks, Book1 toggle button remains checked

When I click on the toggle button in "Book2" the pane in "Book1" disappears, the toggle button in "Book2" is now unchecked but the togglebutton in "Book1" remains checked.

enter image description here

I based my test on this walkthrough...

Microsoft walkthrough example

In ThisAddIn, I delcared an instance of TaskPaneControl...

private TaskPaneControl taskPaneControl1;
private Microsoft.Office.Tools.CustomTaskPane taskPaneValue;

In ThisAddIn_Startup I added the TaskPaneControl to CustomTaskPanes field...

  taskPaneControl1 = new TaskPaneControl();
  taskPaneValue = this.CustomTaskPanes.Add(taskPaneControl1, "MyCustomTaskPane");
  taskPaneValue.VisibleChanged += new EventHandler(taskPaneValue_VisibleChanged);

And in the toggle button click I added the code to display the pane...

            Globals.ThisAddIn.TaskPane.Visible = ((RibbonToggleButton)sender).Checked;
            Globals.ThisAddIn.TaskPane.DockPosition = Microsoft.Office.Core.MsoCTPDockPosition.msoCTPDockPositionLeft;
            Globals.ThisAddIn.TaskPane.Width = 250;

I'm not sure whether I need to load a new instance of the ribbon when a new file is opened or if I need to create a new instance of the panel. Of course I am not sure how to do either. Can anyone help me figure this out?

Thanks
T


问:
Use Bootstrap only for its Form styling
I have a Django website already complete with its CSS. One of its templates has a form. As anyone familiar with Django forms, the most common way to style it nicely is by using crispy form or Bootstrap. However, with my CSS already in place whenever I use either of the above solution, the website appearance gets messed up.

Things I have already done and attempted:

placed the Bootstrap stylesheet before my own stylesheet

override Bootstrap but realised it was so tedious when I only want to style a single form

Is there a way to use only the Form styling of Bootstrap so it doesn't mess up the rest of my stylesheet?

答: django widget tweaks seems to be the solution for my problem. It saves me a lot of time and it allows me to edit forms on template level (instead of editing at forms.py).</p>

Title: Use Bootstrap only for its Form styling


问:
Listview TwoWay Binding With ObservableCollection
:::::::::: ObservableCollection ::::::::::

```<code>    ObservableCollection<Friend> Friends = new ObservableCollection<Friend> ( );
</code>```

:::::::::: InitializeFriends ::::::::::

```<code>        private void InitializeFriends ( )
        {
            JsonObject _JsonObject = Process . FacebookClient . Get ( "/me/friends" ) as JsonObject;

            if ( _JsonObject != null )
            {
                JsonArray _JsonArray = _JsonObject [ "data" ] as JsonArray;
                foreach ( JsonObject Friend in _JsonArray )
                {
                    Friends . Add ( new Friend ( ) { Name = Friend [ "name" ] . ToString ( ) } );
                }
            }
        }
</code>```

:::::::::: Friend ::::::::::

```<code>    public class Friend
    {
        public string Name { get; set; }
        public Conversation Chat { get; set; }
        public BitmapImage Image { get; set; }
    }
</code>```

:::::::::: ListView ::::::::::

```<code>        <ListView Name="Panel"
              Width="Auto"
              Margin="0,200,0,0"
              HorizontalAlignment="Stretch"
              VerticalAlignment="Stretch"
              Background="{x:Null}"
              BorderThickness="0"
              ItemsSource="{Binding Path=Friends,
                                    Mode=TwoWay}"
              ScrollViewer.HorizontalScrollBarVisibility="Disabled"
              SelectionMode="Single">
        <ListView.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel Orientation="Horizontal" />
            </ItemsPanelTemplate>
        </ListView.ItemsPanel>
        <ListView.View>
            <GridView ColumnHeaderContainerStyle="{StaticResource hiddenStyle}">
                <GridViewColumn Width="200" DisplayMemberBinding="{Binding Path=Name}" />
                <GridViewColumn Width="100">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel>
                                <Image Width="30"
                                       Height="30"
                                       Source="{Binding Path=Image}" />
                            </StackPanel>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>
</code>```

List View Not Binding May Be Binding But Not Updating ?!!!

There is something WRONG

答:
if your datacontext is right your binding should work. btw you just need Mode=OneWay

```<code><ListView Name="Panel" ItemsSource="{Binding Path=Friends, Mode=OneWay}" />
</code>```

so you should first check your DataContext. the easiest way is to use Snoop. you can also check your visual studio output window to see binding errors

Body:
:::::::::: ObservableCollection ::::::::::

    ObservableCollection<Friend> Friends = new ObservableCollection<Friend> ( );

:::::::::: InitializeFriends ::::::::::

        private void InitializeFriends ( )
        {
            JsonObject _JsonObject = Process . FacebookClient . Get ( "/me/friends" ) as JsonObject;

            if ( _JsonObject != null )
            {
                JsonArray _JsonArray = _JsonObject [ "data" ] as JsonArray;
                foreach ( JsonObject Friend in _JsonArray )
                {
                    Friends . Add ( new Friend ( ) { Name = Friend [ "name" ] . ToString ( ) } );
                }
            }
        }

:::::::::: Friend ::::::::::

    public class Friend
    {
        public string Name { get; set; }
        public Conversation Chat { get; set; }
        public BitmapImage Image { get; set; }
    }

:::::::::: ListView ::::::::::

        <ListView Name="Panel"
              Width="Auto"
              Margin="0,200,0,0"
              HorizontalAlignment="Stretch"
              VerticalAlignment="Stretch"
              Background="{x:Null}"
              BorderThickness="0"
              ItemsSource="{Binding Path=Friends,
                                    Mode=TwoWay}"
              ScrollViewer.HorizontalScrollBarVisibility="Disabled"
              SelectionMode="Single">
        <ListView.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel Orientation="Horizontal" />
            </ItemsPanelTemplate>
        </ListView.ItemsPanel>
        <ListView.View>
            <GridView ColumnHeaderContainerStyle="{StaticResource hiddenStyle}">
                <GridViewColumn Width="200" DisplayMemberBinding="{Binding Path=Name}" />
                <GridViewColumn Width="100">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel>
                                <Image Width="30"
                                       Height="30"
                                       Source="{Binding Path=Image}" />
                            </StackPanel>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>

List View Not Binding May Be Binding But Not Updating ?!!!

There is something WRONG

Body:
if your datacontext is right your binding should work. btw you just need Mode=OneWay

<ListView Name="Panel" ItemsSource="{Binding Path=Friends, Mode=OneWay}" />

so you should first check your DataContext. the easiest way is to use Snoop. you can also check your visual studio output window to see binding errors


问:
Update docker image in Azure Container Instances
I have an image in the repository on the docker hub. I created azure container instance based on the image in the repository on the docker hub. I updated the image in the repository on the docker hub. How can I apply changes to a container?</p>

答:
If you follow the practice of naming tags :latest then no need to re-create the Container

Push the image

Reset the Container Instance

Done!

This is for image only update


问:
How can we pass all items in a list from model class repository to controller and then to view?
I need to pass all elements from a list to view through controller. The list was created and it is coded in Model class. I had used findAll but it doesn't work.
I don't need any particular condition to satisfy!
here is my list

```<code>Rq = new List<Customers>()
{
    new Customers{Id=2, Fname="Thomas", Lname="shelby", Location="Canada",Contact=9874561230,Email="thomas@gmail.com",Password="143",Category="developer",Status="pending"},
    new Customers{Id=3, Fname="markuz", Lname="shelby", Location="Britan",Contact=9874561239,Email="mark@gmail.com",Password="13",Category="user",Status="approved"},
    new Customers{Id=1, Fname="James", Lname="M", Location="Kottayam", Contact=9685748596, Email="james@gmail.com", Password="123", Category="admin", Status="approved" },
};
</code>```

I had used this function

```<code>public Customers Addap(Customers customers)
{
    return Rq.FindAll(p => p.Id > 1);
}
</code>```

Addap is my action in home controller.

```<code>public async Task<IActionResult> AddapAsync()
{
    ViewBag.oid = oid;
    HttpResponseMessage Res = await client.GetAsync("https://localhost:44397/api/Values/Addap");
    if (Res.IsSuccessStatusCode)
    {
        Customers user = JsonConvert.DeserializeObject<Customers>(await Res.Content.ReadAsStringAsync());
        ViewBag.Customers = user;
        return View(user);
    }
    else
    {
        return RedirectToAction("Error", "Home");
    }
}
</code>```

my api controller is

```<code>[HttpGet("Addap")]
public IActionResult Addap(Customers customers)
{
    cust = new Customers();
    cust = _customerRepo.Addap(customers);
    if (cust != null)
    {
        return Ok(cust);
    }
    else
    {
        return (null);
    }
}
</code>```

view i have used

```<code>@{Customer.Models.Customers cust = ViewBag.Customers;
    int id = ViewBag.oid;
}
<html>

<head>
</head>

<body>
    <form asp-controller="Home">
        <table class="table">
            <thead>
                <tr>
                    <th>
                        ID
                    </th>
                    <th>
                        FNAME
                    </th>
                    <th>
                        LNAME
                    </th>
                    <th>
                        LOCATION
                    </th>
                    <th>
                        CONTACT
                    </th>
                    <th>
                        EMAIL
                    </th>

                    <th>
                        PASSWORD
                    </th>

                    <th>
                        CATEGORY
                    </th>
                    <th>
                        STATUS
                    </th>

                    <th></th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model) {
                <tr>

                    <td>@cust.Id</td>
                    <td>@cust.Fname</td>
                    <td>@cust.Lname</td>
                    <td>@cust.Location</td>
                    <td>@cust.Contact</td>
                    <td>@cust.Email</td>
                    <td>**********</td>
                    <td>@cust.Category</td>
                    <td>@cust.Status</td>
                    <td>
                        <button type="button" class="btn btn-primary" onclick="location.href='@Url.Action(" Approve ", "Home ", new { cust.Id})'">Details</button>
                    </td>
                    <td>
                        <button type="button" class="btn btn-primary" onclick="">Activity Log</button>
                    </td>
                </tr>
                }
                <tr>
                    <td>
                        <button type="button" class="btn btn-primary" onclick="location.href='@Url.Action(" Details ", "Home ", new { id})'">Back</button>
                    </td>
                </tr>

            </tbody>
        </table>
    </form>
</body>

</html>
</code>```

答:
If you want to return the full list Rq, you can create your method like this:

```<code>public List<Customers> Addap()
{
    return Rq;
}
</code>```

Body:
I need to pass all elements from a list to view through controller. The list was created and it is coded in Model class. I had used findAll but it doesn't work.
I don't need any particular condition to satisfy!
here is my list

Rq = new List<Customers>()
{
    new Customers{Id=2, Fname="Thomas", Lname="shelby", Location="Canada",Contact=9874561230,Email="thomas@gmail.com",Password="143",Category="developer",Status="pending"},
    new Customers{Id=3, Fname="markuz", Lname="shelby", Location="Britan",Contact=9874561239,Email="mark@gmail.com",Password="13",Category="user",Status="approved"},
    new Customers{Id=1, Fname="James", Lname="M", Location="Kottayam", Contact=9685748596, Email="james@gmail.com", Password="123", Category="admin", Status="approved" },
};

I had used this function

public Customers Addap(Customers customers)
{
    return Rq.FindAll(p => p.Id > 1);
}

Addap is my action in home controller.

public async Task<IActionResult> AddapAsync()
{
    ViewBag.oid = oid;
    HttpResponseMessage Res = await client.GetAsync("https://localhost:44397/api/Values/Addap");
    if (Res.IsSuccessStatusCode)
    {
        Customers user = JsonConvert.DeserializeObject<Customers>(await Res.Content.ReadAsStringAsync());
        ViewBag.Customers = user;
        return View(user);
    }
    else
    {
        return RedirectToAction("Error", "Home");
    }
}

my api controller is

[HttpGet("Addap")]
public IActionResult Addap(Customers customers)
{
    cust = new Customers();
    cust = _customerRepo.Addap(customers);
    if (cust != null)
    {
        return Ok(cust);
    }
    else
    {
        return (null);
    }
}

view i have used

@{Customer.Models.Customers cust = ViewBag.Customers;
    int id = ViewBag.oid;
}

    <form asp-controller="Home">

                        ID

                        FNAME

                        LNAME

                        LOCATION

                        CONTACT

                        EMAIL

                        PASSWORD

                        CATEGORY

                        STATUS

                @foreach (var item in Model) {

                    @cust.Id
                    @cust.Fname
                    @cust.Lname
                    @cust.Location
                    @cust.Contact
                    @cust.Email
                    **********
                    @cust.Category
                    @cust.Status

                        <button type="button" class="btn btn-primary" onclick="location.href='@Url.Action(" Approve ", "Home ", new { cust.Id})'">Details</button>

                        <button type="button" class="btn btn-primary" onclick="">Activity Log</button>

                }

                        <button type="button" class="btn btn-primary" onclick="location.href='@Url.Action(" Details ", "Home ", new { id})'">Back</button>

    </form>

Body:
If you want to return the full list Rq, you can create your method like this:

public List<Customers> Addap()
{
    return Rq;
}