问:
How to separate character string by a word and adding the word on both sides, using R?
I have a df that looks like this (dput()at the end of question):

```<code>id                                                                                leg_activity
1044                                          home, pt, work, adpt, home, adpt, work, adpt, home
1215                 home, adpt, work, adpt, home, car, outside, car, work, car, work, car, home
1238                                                             home, work, leisure, adpt, home
1458                                          home, outside, pt, home, adpt, leisure, adpt, home
1569 home, car_passenger, leisure, walk, work, walk, leisure, walk, work, adpt, home, walk, home
1615                                          home, adpt, work, walk, work, walk, work, pt, home
</code>```

I want to separate the cells of leg_activity into multiple columns. The separation of the character string should occur as soon as , home occurs. The idea is to see what happens between two home entries. For the first row the desired result would look like this:

```<code>id      1                              2
1044    home, pt, work, adpt, home     home, adpt, work, adpt, home
</code>```

As you can see, I'd like to keep home in both new cells.

My approach so far can not do this, it simply deletes home but I need it to appear on both sides of the cut:

```<code>library(dplyr)

df  <- agents %>%
  mutate(n = row_number()) %>%
  separate_rows(leg_activity, sep = 'home, ') %>%
  group_by(n, id) %>%
  mutate(n2 = row_number()) %>%
  spread(n2, leg_activity) %>%
  select(-n)
</code>```

Thank you very much for your help in advance!

data to try the code:

```<code>structure(list(id = c(9L, 10L, 11L, 96L, 97L, 101L, 103L, 248L,
499L, 1044L, 1215L, 1238L, 1458L, 1569L, 1615L, 1626L, 1734L,
1735L, 1790L, 1912L, 9040L, 14858L, 14859L, 14967L, 15011L, 15012L,
15015L, 15045L, 15050L, 15058L, 15060L, 15086L, 15088L, 15094L,
15109L, 15113L, 15152L, 15157L, 15192L, 15193L, 15222L, 15230L,
15231L, 15234L, 15235L, 15237L, 15256L, 15257L, 15258L, 15269L
), leg_activity = c("home, adpt, shop, car_passenger, home, adpt, work, adpt, home, work, outside, pt, home",
"home, pt, outside, pt, home, car, leisure, car, other, car, leisure, car, leisure, car, other, car, leisure, car, other, car, leisure, car, home, adpt, leisure, adpt, home",
"home, work, adpt, home", "home, car, work, car, home, work, adpt, home",
"home, adpt, work, car_passenger, leisure, car_passenger, work, adpt, home, car_passenger, outside, car_passenger, outside, car_passenger, home",
"home, bike, outside, car_passenger, outside, car_passenger, outside, bike, home, adpt, leisure, adpt, home, bike, leisure, bike, home",
"home, adpt, work, adpt, home, walk, other, pt, home", "home, adpt, work, walk, home, adpt, work, walk, home",
"home, adpt, leisure, adpt, home, bike, outside, bike, home",
"home, pt, work, adpt, home, adpt, work, adpt, home", "home, adpt, work, adpt, home, car, outside, car, work, car, work, car, home",
"home, work, leisure, adpt, home", "home, outside, pt, home, adpt, leisure, adpt, home",
"home, car_passenger, leisure, walk, work, walk, leisure, walk, work, adpt, home, walk, home",
"home, adpt, work, walk, work, walk, work, pt, home", "home, car, work, pt, leisure, adpt, work, car, home, car, home",
"home, adpt, other, adpt, home, car, home", "home, adpt, other, adpt, home",
"home, education, walk, shop, walk, education, pt, outside, home, adpt, leisure, adpt, home",
"home, adpt, work, adpt, home, walk, home", "home, adpt, work, pt, leisure, adpt, work, adpt, work, adpt, home, adpt, other, walk, home",
"home, adpt, work, adpt, home, adpt, work, adpt, home, walk, leisure, walk, home",
"home, adpt, work, adpt, home, work, adpt, home, walk, leisure, walk, home",
"home, adpt, work, adpt, home, car_passenger, outside, car_passenger, leisure, car_passenger, home, car_passenger, home",
"home, adpt, other, adpt, home, car, work, car, home", "home, adpt, education, adpt, leisure, adpt, home, walk, leisure, walk, home",
"home, car_passenger, other, pt, home, walk, other, walk, home, car_passenger, other, walk, home, adpt, other, adpt, home",
"home, work, pt, work, adpt, work, adpt, home", "home, adpt, leisure, adpt, home, car, shop, car, other, car, home",
"home, adpt, work, adpt, home, walk, other, adpt, home", "home, adpt, work, adpt, home, car_passenger, leisure, car_passenger, home",
"home, car, other, car, home, adpt, shop, adpt, home", "home, pt, work, adpt, home",
"home, adpt, work, adpt, home", "home, adpt, work, adpt, home",
"home, walk, education, adpt, home, walk, education, walk, home, bike, leisure, bike, home",
"home, adpt, shop, adpt, home, car, home", "home, adpt, leisure, walk, leisure, walk, leisure, adpt, home",
"home, adpt, shop, pt, home, adpt, other, adpt, home", "home, adpt, other, adpt, home, car_passenger, leisure, walk, home",
"home, adpt, work, adpt, home, car_passenger, shop, car_passenger, home",
"home, adpt, other, adpt, work, adpt, home", "home, adpt, work, adpt, home, adpt, other, walk, shop, walk, home, car, outside, car, outside, car, outside, car, home",
"home, adpt, other, adpt, home", "home, adpt, education, adpt, home, adpt, education, adpt, home",
"home, pt, work, adpt, work, adpt, work, adpt, work, adpt, home, adpt, work, adpt, home",
"home, walk, other, car_passenger, education, walk, home, car_passenger, education, adpt, home",
"home, walk, shop, walk, home, walk, leisure, adpt, leisure, adpt, home",
"home, adpt, work, adpt, home, walk, shop, walk, home, walk, leisure, walk, home, walk, home",
"home, adpt, leisure, adpt, home")), row.names = c(NA, 50L), class = "data.frame")
</code>```

答:
Here is a solution using dplyr, stringr and tidyr (or better tidyverse):

df %>%
  separate_rows(leg_activity, sep = "home, ") %>%
  mutate(leg_activity = str_replace(leg_activity, "(, (home)*)$", "")) %>%
  filter(leg_activity != "") %>%
  mutate(leg_activity = str_c("home, ", leg_activity, ", home")) %>%
  group_by(id) %>%
  mutate(n = row_number()) %>%
  pivot_wider(names_from = n, values_from = leg_activity)
```

<p>I guess, there are better solution, but this should give you your desired output. </p>

```> df2
# A tibble: 50 x 5
# Groups:   id [50]
      id `1`                           `2`                             `3`           `4`
   <int> <chr>                         <chr>                           <chr>         <chr>
 1     9 home, adpt, shop, car_passen~ home, adpt, work, adpt, home    home, work, ~ NA
 2    10 home, pt, outside, pt, home   home, car, leisure, car, other~ home, adpt, ~ NA
 3    11 home, work, adpt, home        NA                              NA            NA
 4    96 home, car, work, car, home    home, work, adpt, home          NA            NA
 5    97 home, adpt, work, car_passen~ home, car_passenger, outside, ~ NA            NA
 6   101 home, bike, outside, car_pas~ home, adpt, leisure, adpt, home home, bike, ~ NA
 7   103 home, adpt, work, adpt, home  home, walk, other, pt, home     NA            NA
 8   248 home, adpt, work, walk, home  home, adpt, work, walk, home    NA            NA
 9   499 home, adpt, leisure, adpt, h~ home, bike, outside, bike, home NA            NA
10  1044 home, pt, work, adpt, home    home, adpt, work, adpt, home    NA            NA
```

Body:
I have a df that looks like this (dput()at the end of question):

id                                                                                leg_activity
1044                                          home, pt, work, adpt, home, adpt, work, adpt, home
1215                 home, adpt, work, adpt, home, car, outside, car, work, car, work, car, home
1238                                                             home, work, leisure, adpt, home
1458                                          home, outside, pt, home, adpt, leisure, adpt, home
1569 home, car_passenger, leisure, walk, work, walk, leisure, walk, work, adpt, home, walk, home
1615                                          home, adpt, work, walk, work, walk, work, pt, home

I want to separate the cells of leg_activity into multiple columns. The separation of the character string should occur as soon as , home occurs. The idea is to see what happens between two home entries. For the first row the desired result would look like this:

id      1                              2
1044    home, pt, work, adpt, home     home, adpt, work, adpt, home

As you can see, I'd like to keep home in both new cells.

My approach so far can not do this, it simply deletes home but I need it to appear on both sides of the cut:

library(dplyr)

df  <- agents %>%
  mutate(n = row_number()) %>%
  separate_rows(leg_activity, sep = 'home, ') %>%
  group_by(n, id) %>%
  mutate(n2 = row_number()) %>%
  spread(n2, leg_activity) %>%
  select(-n)

Thank you very much for your help in advance!

data to try the code:

structure(list(id = c(9L, 10L, 11L, 96L, 97L, 101L, 103L, 248L,
499L, 1044L, 1215L, 1238L, 1458L, 1569L, 1615L, 1626L, 1734L,
1735L, 1790L, 1912L, 9040L, 14858L, 14859L, 14967L, 15011L, 15012L,
15015L, 15045L, 15050L, 15058L, 15060L, 15086L, 15088L, 15094L,
15109L, 15113L, 15152L, 15157L, 15192L, 15193L, 15222L, 15230L,
15231L, 15234L, 15235L, 15237L, 15256L, 15257L, 15258L, 15269L
), leg_activity = c("home, adpt, shop, car_passenger, home, adpt, work, adpt, home, work, outside, pt, home",
"home, pt, outside, pt, home, car, leisure, car, other, car, leisure, car, leisure, car, other, car, leisure, car, other, car, leisure, car, home, adpt, leisure, adpt, home",
"home, work, adpt, home", "home, car, work, car, home, work, adpt, home",
"home, adpt, work, car_passenger, leisure, car_passenger, work, adpt, home, car_passenger, outside, car_passenger, outside, car_passenger, home",
"home, bike, outside, car_passenger, outside, car_passenger, outside, bike, home, adpt, leisure, adpt, home, bike, leisure, bike, home",
"home, adpt, work, adpt, home, walk, other, pt, home", "home, adpt, work, walk, home, adpt, work, walk, home",
"home, adpt, leisure, adpt, home, bike, outside, bike, home",
"home, pt, work, adpt, home, adpt, work, adpt, home", "home, adpt, work, adpt, home, car, outside, car, work, car, work, car, home",
"home, work, leisure, adpt, home", "home, outside, pt, home, adpt, leisure, adpt, home",
"home, car_passenger, leisure, walk, work, walk, leisure, walk, work, adpt, home, walk, home",
"home, adpt, work, walk, work, walk, work, pt, home", "home, car, work, pt, leisure, adpt, work, car, home, car, home",
"home, adpt, other, adpt, home, car, home", "home, adpt, other, adpt, home",
"home, education, walk, shop, walk, education, pt, outside, home, adpt, leisure, adpt, home",
"home, adpt, work, adpt, home, walk, home", "home, adpt, work, pt, leisure, adpt, work, adpt, work, adpt, home, adpt, other, walk, home",
"home, adpt, work, adpt, home, adpt, work, adpt, home, walk, leisure, walk, home",
"home, adpt, work, adpt, home, work, adpt, home, walk, leisure, walk, home",
"home, adpt, work, adpt, home, car_passenger, outside, car_passenger, leisure, car_passenger, home, car_passenger, home",
"home, adpt, other, adpt, home, car, work, car, home", "home, adpt, education, adpt, leisure, adpt, home, walk, leisure, walk, home",
"home, car_passenger, other, pt, home, walk, other, walk, home, car_passenger, other, walk, home, adpt, other, adpt, home",
"home, work, pt, work, adpt, work, adpt, home", "home, adpt, leisure, adpt, home, car, shop, car, other, car, home",
"home, adpt, work, adpt, home, walk, other, adpt, home", "home, adpt, work, adpt, home, car_passenger, leisure, car_passenger, home",
"home, car, other, car, home, adpt, shop, adpt, home", "home, pt, work, adpt, home",
"home, adpt, work, adpt, home", "home, adpt, work, adpt, home",
"home, walk, education, adpt, home, walk, education, walk, home, bike, leisure, bike, home",
"home, adpt, shop, adpt, home, car, home", "home, adpt, leisure, walk, leisure, walk, leisure, adpt, home",
"home, adpt, shop, pt, home, adpt, other, adpt, home", "home, adpt, other, adpt, home, car_passenger, leisure, walk, home",
"home, adpt, work, adpt, home, car_passenger, shop, car_passenger, home",
"home, adpt, other, adpt, work, adpt, home", "home, adpt, work, adpt, home, adpt, other, walk, shop, walk, home, car, outside, car, outside, car, outside, car, home",
"home, adpt, other, adpt, home", "home, adpt, education, adpt, home, adpt, education, adpt, home",
"home, pt, work, adpt, work, adpt, work, adpt, work, adpt, home, adpt, work, adpt, home",
"home, walk, other, car_passenger, education, walk, home, car_passenger, education, adpt, home",
"home, walk, shop, walk, home, walk, leisure, adpt, leisure, adpt, home",
"home, adpt, work, adpt, home, walk, shop, walk, home, walk, leisure, walk, home, walk, home",
"home, adpt, leisure, adpt, home")), row.names = c(NA, 50L), class = "data.frame")

Body:
Here is a solution using dplyr, stringr and tidyr (or better tidyverse):

df %>%
  separate_rows(leg_activity, sep = "home, ") %>%
  mutate(leg_activity = str_replace(leg_activity, "(, (home)*)$", "")) %>%
  filter(leg_activity != "") %>%
  mutate(leg_activity = str_c("home, ", leg_activity, ", home")) %>%
  group_by(id) %>%
  mutate(n = row_number()) %>%
  pivot_wider(names_from = n, values_from = leg_activity)

I guess, there are better solution, but this should give you your desired output.

> df2
# A tibble: 50 x 5
# Groups:   id [50]
      id `1`                           `2`                             `3`           `4`
   <int> <chr>                         <chr>                           <chr>         <chr>
 1     9 home, adpt, shop, car_passen~ home, adpt, work, adpt, home    home, work, ~ NA
 2    10 home, pt, outside, pt, home   home, car, leisure, car, other~ home, adpt, ~ NA
 3    11 home, work, adpt, home        NA                              NA            NA
 4    96 home, car, work, car, home    home, work, adpt, home          NA            NA
 5    97 home, adpt, work, car_passen~ home, car_passenger, outside, ~ NA            NA
 6   101 home, bike, outside, car_pas~ home, adpt, leisure, adpt, home home, bike, ~ NA
 7   103 home, adpt, work, adpt, home  home, walk, other, pt, home     NA            NA
 8   248 home, adpt, work, walk, home  home, adpt, work, walk, home    NA            NA
 9   499 home, adpt, leisure, adpt, h~ home, bike, outside, bike, home NA            NA
10  1044 home, pt, work, adpt, home    home, adpt, work, adpt, home    NA            NA


来源: stackexchange

问:
AttributeError: type object 'DataFrame' has no attribute 'pd'
```<code>import pandas as pd
import os
import time
from datetime import datetime

path = "C:/Users/Aben/Downloads/intraQuarter"

def Key_Stats(gather="Total Debt/Equity (mrq)"):
    statspath = path+'/_KeyStats'
    stock_list = [x[0] for x in os.walk(statspath)]
    df = pd.DataFrame(columns = ['Date','Unix','Ticker','DE Ratio'])

    sp500_df = pd.DataFrame.pd.read_csv("YAHOO-INDEX_CSPC.csv")

    for each_dir in stock_list[1:]:
        each_file = os.listdir(each_dir)
        ticker = each_dir.split("\\")[1]
        if len(each_file) > 0:
            for file in each_file:
                date_stamp = datetime.strptime(file, '%Y%m%d%H%M%S.html')
                unix_time = time.mktime(date_stamp.timetuple())
                full_file_path = each_dir+'/'+file
                source = open(full_file_path,'r').read()
                try:
                    value = float(source.split(gather+':</td><td class="yfnc_tabledata1">')[1].split('</td>')[0])

                    try:
                        sp500_date = datetime.fromtimestamp(unix_time).strftime('%Y-%m-%d')
                        row = sp500_df[sp500_df["Date"] == sp500_date]
                        sp500_value = float(row["Adj Close"])
                    except:
                        sp500_date = datetime.fromtimestamp(unix_time-259200).strftime('%Y-%m-%d')
                        row = sp500_df[sp500_df["Date"] == sp500_date]
                        sp500_value = float(row["Adj Close"])

                    stock_price = float(source.split('</small><big><b>')[1].split('</b></big>')[0])
                    print("stock_price:",stock_price,"ticker:",ticker)

                    df = df.append({'Date':date_stamp,'Unix':unix_time,'Ticker':ticker,'DE Ratio':value,}, ignore_index = True)
                except Exception as e:
                    pass

    save = gather.replace(' ','').replace('(','').replace(')','').replace('/','')+('.csv')
    print(save)
    df.to_csv(save)

Key_Stats()
</code>```

when running this code in python 3.8.3, I get this error message:

```<code>Traceback (most recent call last):
  File "C:\Users\Aben\Downloads\pythonstuff\stockbot.py", line 49, in <module>
    Key_Stats()
  File "C:\Users\Aben\Downloads\pythonstuff\stockbot.py", line 14, in Key_Stats
    sp500_df = DataFrame.pd.read_csv("YAHOO-INDEX_CSPC.csv")
AttributeError: type object 'DataFrame' has no attribute 'pd'
</code>```

anyone know why? I replaced from_csv with pd.read_csv, but now I have another error. The file I'm using is actually a txt file, but I renamed it with the .csv extension at the end.
I'm using this tutorial btw

答:
Replace this line:

```<code>sp500_df = pd.DataFrame.pd.read_csv("YAHOO-INDEX_CSPC.csv")
</code>```

with

```<code>sp500_df = pd.read_csv("YAHOO-INDEX_CSPC.csv")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
import pandas as pd
import os
import time
from datetime import datetime

path = "C:/Users/Aben/Downloads/intraQuarter"

def Key_Stats(gather="Total Debt/Equity (mrq)"):
    statspath = path+'/_KeyStats'
    stock_list = [x[0] for x in os.walk(statspath)]
    df = pd.DataFrame(columns = ['Date','Unix','Ticker','DE Ratio'])

    sp500_df = pd.DataFrame.pd.read_csv("YAHOO-INDEX_CSPC.csv")

    for each_dir in stock_list[1:]:
        each_file = os.listdir(each_dir)
        ticker = each_dir.split("\\")[1]
        if len(each_file) > 0:
            for file in each_file:
                date_stamp = datetime.strptime(file, '%Y%m%d%H%M%S.html')
                unix_time = time.mktime(date_stamp.timetuple())
                full_file_path = each_dir+'/'+file
                source = open(full_file_path,'r').read()
                try:
                    value = float(source.split(gather+':	')[1].split('	')[0])

                    try:
                        sp500_date = datetime.fromtimestamp(unix_time).strftime('%Y-%m-%d')
                        row = sp500_df[sp500_df["Date"] == sp500_date]
                        sp500_value = float(row["Adj Close"])
                    except:
                        sp500_date = datetime.fromtimestamp(unix_time-259200).strftime('%Y-%m-%d')
                        row = sp500_df[sp500_df["Date"] == sp500_date]
                        sp500_value = float(row["Adj Close"])

                    stock_price = float(source.split('<big>')[1].split('</big>')[0])
                    print("stock_price:",stock_price,"ticker:",ticker)

                    df = df.append({'Date':date_stamp,'Unix':unix_time,'Ticker':ticker,'DE Ratio':value,}, ignore_index = True)
                except Exception as e:
                    pass

    save = gather.replace(' ','').replace('(','').replace(')','').replace('/','')+('.csv')
    print(save)
    df.to_csv(save)

Key_Stats()

when running this code in python 3.8.3, I get this error message:

Traceback (most recent call last):
  File "C:\Users\Aben\Downloads\pythonstuff\stockbot.py", line 49, in <module>
    Key_Stats()
  File "C:\Users\Aben\Downloads\pythonstuff\stockbot.py", line 14, in Key_Stats
    sp500_df = DataFrame.pd.read_csv("YAHOO-INDEX_CSPC.csv")
AttributeError: type object 'DataFrame' has no attribute 'pd'

anyone know why? I replaced from_csv with pd.read_csv, but now I have another error. The file I'm using is actually a txt file, but I renamed it with the .csv extension at the end.
I'm using this tutorial btw

Body:
Replace this line:

sp500_df = pd.DataFrame.pd.read_csv("YAHOO-INDEX_CSPC.csv")

with

sp500_df = pd.read_csv("YAHOO-INDEX_CSPC.csv")


问:
how to read a compressed file from c# in R
```<code>        String fileName = "0001.gff";
        using (FileStream zipToOpen = new FileStream(fileName, FileMode.Create))
        {
            using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
            {
                ZipArchiveEntry write_entry = archive.CreateEntry(fileName);
                using (BinaryWriter writer = new BinaryWriter(write_entry.Open()))
                {
                    writer.Write((Int32)1);
                    writer.Write((Int32)2);
                    writer.Write((Int32)3);
                    writer.Write((Int32)4);
                }
            }
        }
</code>```

I have created the file myFile in c#, but i want to read it in R. How can i do that?

答:
There is a function called read.gff from the ape package the documentation says to try using

```<code>read.gff(file)
</code>```

Body:
        String fileName = "0001.gff";
        using (FileStream zipToOpen = new FileStream(fileName, FileMode.Create))
        {
            using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
            {
                ZipArchiveEntry write_entry = archive.CreateEntry(fileName);
                using (BinaryWriter writer = new BinaryWriter(write_entry.Open()))
                {
                    writer.Write((Int32)1);
                    writer.Write((Int32)2);
                    writer.Write((Int32)3);
                    writer.Write((Int32)4);
                }
            }
        }

I have created the file myFile in c#, but i want to read it in R. How can i do that?

Body:
There is a function called read.gff from the ape package the documentation says to try using

read.gff(file)


问:
Cast struct to array?
I'm currently learning C and I have trouble understanding the following code:

```<code>struct dns_header
{
    unsigned char ra : 1;
    unsigned char z : 1;
    unsigned char ad : 1;
    unsigned char cd : 1;
    unsigned char rcode : 4;
    unsigned short q_count : 16;

};

int main(void)
{
    struct dns_header *ptr;
    unsigned char buffer[256];

    ptr = (struct dns_header *) &buffer;

    ptr->ra = 0;
    ptr->z = 0;
    ptr->ad = 0;
    ptr->cd = 0;
    ptr->rcode = 0;
    ptr->q_count = htons(1);

}
</code>```

The line I don't understand is ptr = (struct dns_header *) &buffer;

Can anyone explain this in detail?

答:
A struct directly references a contiguous block of memory and each field within a struct is located at a certain fixed offset from the start. Variables can then be accessed via a struct pointer or by the struct declared name which returns the same address.

Here we declare a packed struct which references a contiguous block of memory:

#pragma pack(push, 1)
struct my_struct
{
    unsigned char b0;
    unsigned char b1;
    unsigned char b2;
    unsigned char b3;
    unsigned char b4;
};
#pragma pack(pop)
```
<p>Pointers can then be used to refer to the struct by its address. See this example:</p>
<pre class="lang-c prettyprint-override"><code>int main(void)
{
    struct my_struct *ptr;
    unsigned char buffer[5];

    ptr = (struct my_struct *) buffer;

    ptr->b0 = 'h';
    ptr->b1 = 'e';
    ptr->b2 = 'l';
    ptr->b3 = 'l';
    ptr->b4 = 'o';

    for (int i = 0; i < 5; i++)
    {
        putchar(buffer[i]); // Print "hello"
    }

    return 0;
}
</code>```

Here we explicitly map 1:1 the struct contiguous block of memory to the contiguous block of memory pointed by buffer (using the address to the first element).

An array address and the name of the address are numerically identical but have different types. These two lines are thus equivalent:

ptr = (struct my_struct *) buffer;
ptr = (struct my_struct *) &buffer;
```

This is usually not a problem if we use the address as is and cast it appropriately. Dereferencing an array address of type pointer to array-of-type yields the same pointer but with a different type array-of-type.

Although it might seem convenient to manipulate memory in this fashion, it is strongly discouraged as the resulting code becomes painfully difficult to understand. If you really have no choice, I suggest using an union to specify that the struct is to be used in a particular manner.

ContentLicense: CC BY-SA 3.0

Title: Cast struct to array?

Body:
I'm currently learning C and I have trouble understanding the following code:

struct dns_header
{
    unsigned char ra : 1;
    unsigned char z : 1;
    unsigned char ad : 1;
    unsigned char cd : 1;
    unsigned char rcode : 4;
    unsigned short q_count : 16;

};

int main(void)
{
    struct dns_header *ptr;
    unsigned char buffer[256];

    ptr = (struct dns_header *) &buffer;

    ptr->ra = 0;
    ptr->z = 0;
    ptr->ad = 0;
    ptr->cd = 0;
    ptr->rcode = 0;
    ptr->q_count = htons(1);

}

The line I don't understand is ptr = (struct dns_header *) &buffer;

Can anyone explain this in detail?

Body:
A struct directly references a contiguous block of memory and each field within a struct is located at a certain fixed offset from the start. Variables can then be accessed via a struct pointer or by the struct declared name which returns the same address.

Here we declare a packed struct which references a contiguous block of memory:

#pragma pack(push, 1)
struct my_struct
{
    unsigned char b0;
    unsigned char b1;
    unsigned char b2;
    unsigned char b3;
    unsigned char b4;
};
#pragma pack(pop)

Pointers can then be used to refer to the struct by its address. See this example:

int main(void)
{
    struct my_struct *ptr;
    unsigned char buffer[5];

    ptr = (struct my_struct *) buffer;

    ptr->b0 = 'h';
    ptr->b1 = 'e';
    ptr->b2 = 'l';
    ptr->b3 = 'l';
    ptr->b4 = 'o';

    for (int i = 0; i < 5; i++)
    {
        putchar(buffer[i]); // Print "hello"
    }

    return 0;
}

Here we explicitly map 1:1 the struct contiguous block of memory to the contiguous block of memory pointed by buffer (using the address to the first element).

An array address and the name of the address are numerically identical but have different types. These two lines are thus equivalent:

ptr = (struct my_struct *) buffer;
ptr = (struct my_struct *) &buffer;

This is usually not a problem if we use the address as is and cast it appropriately. Dereferencing an array address of type pointer to array-of-type yields the same pointer but with a different type array-of-type.

Although it might seem convenient to manipulate memory in this fashion, it is strongly discouraged as the resulting code becomes painfully difficult to understand. If you really have no choice, I suggest using an union to specify that the struct is to be used in a particular manner.


问:
Date as variable name
I'd like to use the date as a variable name. I understand I'll need to append a character to the front and also that it's not a good way to store data (it's purely for report aesthetics). I've tried %eval() but can't solve it.

```<code>%let var_date = '_'||today();
data date;
    %eval(&var_date) = .;
run;
</code>```

I'd like the variable name to be _02JUN2011. Thanks for any help.

答: You really want to use a hash - this is not maintainable code..</p>

Title: Date as variable name

Body:
I'd like to use the date as a variable name. I understand I'll need to append a character to the front and also that it's not a good way to store data (it's purely for report aesthetics). I've tried %eval() but can't solve it.

%let var_date = '_'||today();
data date;
    %eval(&var_date) = .;
run;

I'd like the variable name to be _02JUN2011. Thanks for any help.


问:
How can I insert elements in an alphabetically sorted list in C?
I'm trying to implement a linked list consisting of Nodes which have a char item as a payload.
New nodes should be insered alphabetically.

When trying to retrieve the elements of the list, I receive a Segmentation Fault. That means I'm accessing an invalid address somehow.

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

typedef struct node {
    struct node *next;
    char *item;
} Node;

static Node *list = NULL;

void insert(char *item) {
    Node *currentNode = list;
    while (strcmp(currentNode->item, item) < 0) {
        printf("next..\n");
        currentNode = currentNode->next;
    }
    Node *new = malloc(sizeof(Node));
    new->item = item;
    Node *tmp = currentNode->next;
    currentNode->next = new;
    new->next = tmp;
}

void retrieve() {
    Node *current = list;
    while (current->next != NULL) {
        printf("%c", *(current->item));
        current = current->next;
    }
    printf("\n");
}

int main() {

    // Initialize.
    list = malloc(sizeof(Node));
    char a = 'a';
    list->item = &a;
    retrieve();

    char b = 'b';
    char c = 'c';

    insert(&b);
    retrieve();

    return 0;
}
</code>```

答:
You only partially define list. Where you have

```<code>list->item = &a;
</code>```

you should also have

```<code> list->next = NULL;
</code>```

As Adrian Mole suggests, you should also be inputting null terminated strings. E.g. "a" rather than 'a'.

Body:
I'm trying to implement a linked list consisting of Nodes which have a char item as a payload.
New nodes should be insered alphabetically.

When trying to retrieve the elements of the list, I receive a Segmentation Fault. That means I'm accessing an invalid address somehow.

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

typedef struct node {
    struct node *next;
    char *item;
} Node;

static Node *list = NULL;

void insert(char *item) {
    Node *currentNode = list;
    while (strcmp(currentNode->item, item) < 0) {
        printf("next..\n");
        currentNode = currentNode->next;
    }
    Node *new = malloc(sizeof(Node));
    new->item = item;
    Node *tmp = currentNode->next;
    currentNode->next = new;
    new->next = tmp;
}

void retrieve() {
    Node *current = list;
    while (current->next != NULL) {
        printf("%c", *(current->item));
        current = current->next;
    }
    printf("\n");
}

int main() {

    // Initialize.
    list = malloc(sizeof(Node));
    char a = 'a';
    list->item = &a;
    retrieve();

    char b = 'b';
    char c = 'c';

    insert(&b);
    retrieve();

    return 0;
}

Body:
You only partially define list. Where you have

list->item = &a;

you should also have

 list->next = NULL;

As Adrian Mole suggests, you should also be inputting null terminated strings. E.g. "a" rather than 'a'.


问:
ASM 8086 division without div
I need to write in asm 8086 a program like b=a/6 but without the DIV instruction. I know how to do it with SAR but only 2,4,8,16...

```<code>mov ax,a
sar ax,1 ;//div a by 2
mov b,ax
</code>```

my question is how can I do it to div by 6?

答:
you can use subtraction and count how many times it take to get to zero, eg. 30/6=5 and 30-6-6-6-6-6=0 so for 30 you must 5 times subtract 6 to get to zero

Something like that:

```<code>mov cx,0
mov ax, dividend

divloop:
  cmp ax, 0
  jle done
  sub ax, divisor
  inc cx
  jmp divloop

done:
  ;result is in cx
</code>```

Title: ASM 8086 division without div

Body:
I need to write in asm 8086 a program like b=a/6 but without the DIV instruction. I know how to do it with SAR but only 2,4,8,16...

mov ax,a
sar ax,1 ;//div a by 2
mov b,ax

my question is how can I do it to div by 6?

Body:
you can use subtraction and count how many times it take to get to zero, eg. 30/6=5 and 30-6-6-6-6-6=0 so for 30 you must 5 times subtract 6 to get to zero

Something like that:

mov cx,0
mov ax, dividend

divloop:
  cmp ax, 0
  jle done
  sub ax, divisor
  inc cx
  jmp divloop

done:
  ;result is in cx


问:
When I store a Date field in Oracle database it always shows 00:00:00 hour ¿Is it problem of SimpleDateFormat class?
In my Java action file, I am obtaining the actual date to store it in an Oracle database. However, when I store the date in the database, it always appear like 30/05/2020, 00:00:00. I mean, it is not taking the current hour, always appearing 00:00:00.

This is the java code that obtains the date:

```<code>    SimpleDateFormat sdffecha_modif = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
    String fechaModif = sdffecha_modif.format(new Date());
</code>```

Is it a common error? Does anybody know what is happening?

答:
You have not posted enough details and code to diagnose your problem. I can only guess, and I can fix two major problems.

java.sql.Date versus java.util.Date

My guess: You may be using the java.sql.Date class that pretends to represent a date-only value without a time-of-day and without a time zone.

In contrast, the java.util.Date class represents a moment in UTC, a date with time-of-day on offset of zero minutes-hours-seconds.

Avoid legacy date-time classes

Never use either  Date class, nor SimpleDateFormat. These terrible classes were years ago supplanted by the modern java.time classes defined in JSR 310.

Smart objects, not dumb strings

Exchange smart objects with the database rather than dumb strings. As of JDBC 4.2 we can exchange java.time objects.

The DATE type in Oracle database is akin to the SQL-standard type TIMESTAMP WITHOUT TIME ZONE. Be aware this type cannot represent a moment, cannot be used for a point in the timeline. Lacking a time zone or offset means these values can represent any moment only a range of about 26-27 hours, the range of time zones around the globe.

java.time

The equivalent type in Java is LocalDateTime.

```<code>LocalDate ld = LocalDate.of( 2021 , Month.MAY , 23 ) ;
LocalTime lt = LocalTime.of( 12 , 30 ) ;
LocalDateTime ldt = LocalDateTime.of( ld , lt ) ;
</code>```

Write to database.

```<code>myPreparedStatement.setObject( … , ldt ) ;
</code>```

Retrieval.

```<code>LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class ) ;
</code>```

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later  - Part of the standard Java API with a bundled implementation.

Java 9 adds some minor features and fixes.

Java SE 6 and Java SE 7

Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

Android

Later versions of Android bundle implementations of the java.time classes.

For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

Body:
In my Java action file, I am obtaining the actual date to store it in an Oracle database. However, when I store the date in the database, it always appear like 30/05/2020, 00:00:00. I mean, it is not taking the current hour, always appearing 00:00:00.

This is the java code that obtains the date:

    SimpleDateFormat sdffecha_modif = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
    String fechaModif = sdffecha_modif.format(new Date());

Is it a common error? Does anybody know what is happening?

Body:
You have not posted enough details and code to diagnose your problem. I can only guess, and I can fix two major problems.

java.sql.Date versus java.util.Date

My guess: You may be using the java.sql.Date class that pretends to represent a date-only value without a time-of-day and without a time zone.

In contrast, the java.util.Date class represents a moment in UTC, a date with time-of-day on offset of zero minutes-hours-seconds.

Avoid legacy date-time classes

Never use either  Date class, nor SimpleDateFormat. These terrible classes were years ago supplanted by the modern java.time classes defined in JSR 310.

Smart objects, not dumb strings

Exchange smart objects with the database rather than dumb strings. As of JDBC 4.2 we can exchange java.time objects.

The DATE type in Oracle database is akin to the SQL-standard type TIMESTAMP WITHOUT TIME ZONE. Be aware this type cannot represent a moment, cannot be used for a point in the timeline. Lacking a time zone or offset means these values can represent any moment only a range of about 26-27 hours, the range of time zones around the globe.

java.time

The equivalent type in Java is LocalDateTime.

LocalDate ld = LocalDate.of( 2021 , Month.MAY , 23 ) ;
LocalTime lt = LocalTime.of( 12 , 30 ) ;
LocalDateTime ldt = LocalDateTime.of( ld , lt ) ;

Write to database.

myPreparedStatement.setObject( … , ldt ) ;

Retrieval.

LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later  - Part of the standard Java API with a bundled implementation.

Java 9 adds some minor features and fixes.

Java SE 6 and Java SE 7

Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

Android

Later versions of Android bundle implementations of the java.time classes.

For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….


问:
Block X-Frame Firefox => How to enable on Html5?
```<code>    <!-- TELA -->
    <td colspan="3">
<iframe src="radio.html" width="800" marginwidth="0" height="450" marginheight="0" scrolling="no" frameborder="0" hspace="0" allowtransparency="0">
    </iframe>
</code>```

How to enable the X-frame on firefox Html5 ?

答:
You can try several options

1) you can add this meta tag in your head tag, most chances that it won't work!

```<code>  <meta name="X-FRAME-OPTIONS" content="ALLOW-FROM" />
</code>```

2) You can bypass X-Frame-Options in an using X-Frame-Bypass Web Component.

3) You can use this Add-on of firefox for ignoring the X-FRAME

Body:
You can try several options

1) you can add this meta tag in your head tag, most chances that it won't work!

  <meta name="X-FRAME-OPTIONS" content="ALLOW-FROM" />

2) You can bypass X-Frame-Options in an <iframe>using X-Frame-Bypass Web Component.

3) You can use this Add-on of firefox for ignoring the X-FRAME


问:
Check if GTK window has keyboard and mouse focus window C++
Is there a GTK3 function that detects if a window has focus? I am currently using the following code:

```<code>#include <gtk/gtk.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
GtkWidget *LinuxWindow;
static void buttonMessage(GtkWidget *widget, gpointer data)
{
  g_print("Yay, you clicked me!\n");
}
int main() {
  GtkWidget *Box, *Button;
  int argC = 0;
  char **argV;
  // Setup the window and fixed grid
  gtk_init(&argC, &argV);
  LinuxWindow = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  Box = gtk_fixed_new();
  // Set the title
  gtk_window_set_title(GTK_WINDOW(LinuxWindow), "Title");
  // Setup the window events
  gtk_widget_show_all(LinuxWindow);
  g_signal_connect(G_OBJECT(LinuxWindow), "destroy", G_CALLBACK(gtk_main_quit),
                   NULL);
  // Add controls
  Button = gtk_button_new_with_label("Click Me!");
  g_signal_connect(Button, "clicked", G_CALLBACK(buttonMessage), NULL);
  gtk_fixed_put(GTK_FIXED(Box), Button, 20, 20);
  gtk_fixed_move(GTK_FIXED(Box), Button, 20, 20);
  gtk_widget_set_size_request(Button, 30, 100);
  gtk_container_add(GTK_CONTAINER(LinuxWindow), Box);
  gtk_widget_show_all(LinuxWindow);
  // Create a dialog
  GtkWidget *dialog;
  dialog = gtk_message_dialog_new(
      GTK_WINDOW(LinuxWindow), GTK_DIALOG_DESTROY_WITH_PARENT,
      GTK_MESSAGE_INFO, GTK_BUTTONS_OK, "Hello and welcome to my GTK GUI...", NULL);
  gint ret = gtk_dialog_run(GTK_DIALOG(dialog));
  gtk_widget_destroy(GTK_WIDGET(dialog));
  printf("%i", ret);
  // Add the fixed grid and go the to the main window loop

  gtk_main();

  return 0;
}
</code>```

I am compiling it using

```<code>g++ -std=c++17 -m64 -o gtkTest myGtkApp.cpp -lX11 `pkg-config --cflags gtk+-3.0` `pkg-config --libs gtk+-3.0`
</code>```

I want to detect if the window is focused and print it to the console.

答:
There is a function: gtk_widget_is_focus ().

You need to assure parents have the "has-focus" property set.
Doc. excerpt:

gtk_widget_is_focus (GtkWidget *widget);

Determines if the widget is the focus widget within its toplevel. (This does not mean that the “has-focus” property is necessarily set; “has-focus” will only be set if the toplevel widget additionally has the global input focus.)

If you want to receive an event when the window is focused then register a callback for the enter-notify-event (signal)

In the linked doc. there is a section just three points after enter-notify-event that is what you want:

The “focus” signal

Sorry, I should have to mention this event the first time.

Edit for new links from docs.gtk.org:

gtk_widget_is_focus ()

enter-notify-event

Body:
Is there a GTK3 function that detects if a window has focus? I am currently using the following code:

#include <gtk/gtk.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
GtkWidget *LinuxWindow;
static void buttonMessage(GtkWidget *widget, gpointer data)
{
  g_print("Yay, you clicked me!\n");
}
int main() {
  GtkWidget *Box, *Button;
  int argC = 0;
  char **argV;
  // Setup the window and fixed grid
  gtk_init(&argC, &argV);
  LinuxWindow = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  Box = gtk_fixed_new();
  // Set the title
  gtk_window_set_title(GTK_WINDOW(LinuxWindow), "Title");
  // Setup the window events
  gtk_widget_show_all(LinuxWindow);
  g_signal_connect(G_OBJECT(LinuxWindow), "destroy", G_CALLBACK(gtk_main_quit),
                   NULL);
  // Add controls
  Button = gtk_button_new_with_label("Click Me!");
  g_signal_connect(Button, "clicked", G_CALLBACK(buttonMessage), NULL);
  gtk_fixed_put(GTK_FIXED(Box), Button, 20, 20);
  gtk_fixed_move(GTK_FIXED(Box), Button, 20, 20);
  gtk_widget_set_size_request(Button, 30, 100);
  gtk_container_add(GTK_CONTAINER(LinuxWindow), Box);
  gtk_widget_show_all(LinuxWindow);
  // Create a dialog
  GtkWidget *dialog;
  dialog = gtk_message_dialog_new(
      GTK_WINDOW(LinuxWindow), GTK_DIALOG_DESTROY_WITH_PARENT,
      GTK_MESSAGE_INFO, GTK_BUTTONS_OK, "Hello and welcome to my GTK GUI...", NULL);
  gint ret = gtk_dialog_run(GTK_DIALOG(dialog));
  gtk_widget_destroy(GTK_WIDGET(dialog));
  printf("%i", ret);
  // Add the fixed grid and go the to the main window loop

  gtk_main();

  return 0;
}

I am compiling it using

g++ -std=c++17 -m64 -o gtkTest myGtkApp.cpp -lX11 `pkg-config --cflags gtk+-3.0` `pkg-config --libs gtk+-3.0`

I want to detect if the window is focused and print it to the console.


问:
Printing out values of different rows and column in 2d array using for loops
I have this 2d array of the first row being first names and the second being last names.

String[][] ladrones2 = {
        {"Phil", "Kim", "Phil", "Perry"},
        {"Garcia", "Gimena", "Basinger", "Ornitorrinco"}};
```
<p>the prefered out come of this would be to have them printend out like e.g</p>
```Phill Garcia
Kim Gimena
etc...
```
<p>Now I was able to do this by catching the ArrayIndexOutOfBoundsException exception and it works and the output is:</p>
```name Phil Garcia
name Kim Gimena
name Phil Basinger
name Perry Ornitorrinco
```
<p>Which is great but I wondered if there was a way to do this without having to catch the exception? I've been searching to make this cleaner but wasn't able to do so.</p>
<p>Code at the moment:</p>
<pre class="lang-java prettyprint-override"><code>public static void robo2() {
    String[][] ladrones2 = {
            {"Phil", "Kim", "Phil", "Perry"},
            {"Garcia", "Gimena", "Basinger", "Ornitorrinco"}};

    try {
        for (int i = 0; i < ladrones2.length; i++) {
            for (int j = 0; j < ladrones2[i].length; j++) {
                System.out.println("name: " + ladrones2[i][j] + " " + ladrones2[i + 1][j]);
            }
        }
    } catch (ArrayIndexOutOfBoundsException e) {
        System.out.println("");
    }
}
</code>```

as you can see I used in the inner for loop a +1 on the i variable which in turn throws the exception.

Any ideas? I would like just to keep this way of working at the moment with 2 forloops due to being new to Java.

答:
If you are sure that ladrones2 array always has 2 rows, then below code would be simpler:

public static void main(String[] args) {
    String[][] ladrones2 = {
            {"Phil", "Kim", "Phil", "Perry"},
            {"Garcia", "Gimena", "Basinger", "Ornitorrinco"}};

    for (int i = 0; i < ladrones2[0].length; i++) {
        System.out.println("name: " + ladrones2[0][i] + " " + ladrones2[1][i]);
    }
}
```

Body:
I have this 2d array of the first row being first names and the second being last names.

String[][] ladrones2 = {
        {"Phil", "Kim", "Phil", "Perry"},
        {"Garcia", "Gimena", "Basinger", "Ornitorrinco"}};

the prefered out come of this would be to have them printend out like e.g

Phill Garcia
Kim Gimena
etc...

Now I was able to do this by catching the ArrayIndexOutOfBoundsException exception and it works and the output is:

name Phil Garcia
name Kim Gimena
name Phil Basinger
name Perry Ornitorrinco

Which is great but I wondered if there was a way to do this without having to catch the exception? I've been searching to make this cleaner but wasn't able to do so.

Code at the moment:

public static void robo2() {
    String[][] ladrones2 = {
            {"Phil", "Kim", "Phil", "Perry"},
            {"Garcia", "Gimena", "Basinger", "Ornitorrinco"}};

    try {
        for (int i = 0; i < ladrones2.length; i++) {
            for (int j = 0; j < ladrones2[i].length; j++) {
                System.out.println("name: " + ladrones2[i][j] + " " + ladrones2[i + 1][j]);
            }
        }
    } catch (ArrayIndexOutOfBoundsException e) {
        System.out.println("");
    }
}

as you can see I used in the inner for loop a +1 on the i variable which in turn throws the exception.

Any ideas? I would like just to keep this way of working at the moment with 2 forloops due to being new to Java.


问:
Library providing various hash algorithms (MD5, SHA1, SHA256, etc) in Java?
Is there a simple library out there for Java in a Maven repository that will give me simple, one-liner hash methods for the popular hash functions such as MD5, SHA1, SHA256, and SHA512? I'd really hate to have to reinvent the wheel to do this. </p>

Body: It's built-in: java.security.MessageDigest


问:
How to show About dialog?
Hello I see this video from flutter team https://www.youtube.com/watch?v=YFCSODyFxbE&t=0s
and when trying to add aboutdialog . error showing in under name . is anyone try this widget?</p>

答:
Call this method to view the dialog.

```<code>void _showDialog() {
  showAboutDialog(
    context: context,
    applicationName: 'Flutter',
    applicationIcon: FlutterLogo(),
    applicationVersion: '1.0.0',
    children: [
      Text('This is an About Dialog in Flutter'),
    ]
  );
}
</code>```

Title: How to show About dialog?

Body:
Call this method to view the dialog.

void _showDialog() {
  showAboutDialog(
    context: context,
    applicationName: 'Flutter',
    applicationIcon: FlutterLogo(),
    applicationVersion: '1.0.0',
    children: [
      Text('This is an About Dialog in Flutter'),
    ]
  );
}


答:
You want currentNode to be a reference pointer to the current node, so I think in insert() you need to replace:

```<code>Node *currentNode = list;
</code>```

and:

```<code>currentNode = currentNode->next;
</code>```

and:

```<code>currentNode->next = new;
</code>```

with:

```<code>Node **currentNode = &list;
</code>```

and:

```<code>currentNode = &(currentNode->next);
</code>```

and:

```<code>*(currentNode->next) = new;
</code>```

In retrieve() you don't need a reference pointer (as you're not changing data), just a regular pointer. So replace:

```<code>Node *current = list;
</code>```

with:

```<code>Node current = list;
</code>```

Your compiler probably warned you about assigning mismatching types.

Also you're mixing char* strings and references to single chars (which aren't strings as they won't have the NULL terminator).
For example:

```<code>char b = 'b';
insert(&b);
</code>```

should be:

```<code>char* b = "b";
insert(b);
</code>```

Title: How can I insert elements in an alphabetically sorted list in C?

Body:
You want currentNode to be a reference pointer to the current node, so I think in insert() you need to replace:

Node *currentNode = list;

and:

currentNode = currentNode->next;

and:

currentNode->next = new;

with:

Node **currentNode = &list;

and:

currentNode = &(currentNode->next);

and:

*(currentNode->next) = new;

In retrieve() you don't need a reference pointer (as you're not changing data), just a regular pointer. So replace:

Node *current = list;

with:

Node current = list;

Your compiler probably warned you about assigning mismatching types.

Also you're mixing char* strings and references to single chars (which aren't strings as they won't have the NULL terminator).
For example:

char b = 'b';
insert(&b);

should be:

char* b = "b";
insert(b);


问:
How to enforce global uniqueness in a User table in CosmosDB
I need to create a User table that at minimum looks like this:

```<code>public class User
{
  public Guid Id {get; set;}
  public string Username {get; set;}
  public string EmailAddress {get; set;}
  public DateTime CreatedOn {get; set;}
}
</code>```

I'm currently writing all data to CosmosDB (SQL API). The problem is I need to add a unique index policy to Username and EmailAddress across all users. Since CosmosDB is designed with scaling out in mind, I'd need to partition this container. If I do so, I cannot enforce uniqueness across partitions.

Currently, my partition key is Id. If I change my partition key to Username or EmailAddress, I fear that changing these fields can potentially result in users being deleted (e.g. delete old username and insert new username would be two separate transactions if the usernames belong to different partitions, which means there is no atomicity.).

Is there a CosmosDB solution to this problem that I cannot think of? I can move this part to SQL Server, but I'll end up maintaining a large table over time. Also, since I'm using Azure Functions for server processing, shipping with EF DLLs makes the app size unnecessarily large.

答: Make a synthetic partition key of UserName_EmailAddress and it will be unique.

Body:
I need to create a User table that at minimum looks like this:

public class User
{
  public Guid Id {get; set;}
  public string Username {get; set;}
  public string EmailAddress {get; set;}
  public DateTime CreatedOn {get; set;}
}

I'm currently writing all data to CosmosDB (SQL API). The problem is I need to add a unique index policy to Username and EmailAddress across all users. Since CosmosDB is designed with scaling out in mind, I'd need to partition this container. If I do so, I cannot enforce uniqueness across partitions.

Currently, my partition key is Id. If I change my partition key to Username or EmailAddress, I fear that changing these fields can potentially result in users being deleted (e.g. delete old username and insert new username would be two separate transactions if the usernames belong to different partitions, which means there is no atomicity.).

Is there a CosmosDB solution to this problem that I cannot think of? I can move this part to SQL Server, but I'll end up maintaining a large table over time. Also, since I'm using Azure Functions for server processing, shipping with EF DLLs makes the app size unnecessarily large.


问:
meeting can not be found in the calendar of organizer
I am trying to send outlook meeting invite (outlook version 2013) using ical4j 1.0.4 and javax mail 1.5.0 libraries.

I followed this article - How to send an iCal meeting request using Java Mail, and receive the response and i was able to send outlook meeting invite.

But organizer is not receiving the calendar invite.

If i send meeting invite from my email id to myself, i receive the event but it says "meeting can not be found in the calendar".

All Attendees receive the event and they can accept/decline and also see entry in their calendar.

Is there any way to get meeting added to organizer's calendar ?

答:
If you want to create a meeting in the organizer calendar I'd suggest automating Outlook from your Java-based application. You may consider using the Ole automation technology for automating Outlook, for example:

```<code>import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.ole.win32.OLE;
import org.eclipse.swt.ole.win32.OleAutomation;
import org.eclipse.swt.ole.win32.OleClientSite;
import org.eclipse.swt.ole.win32.OleFrame;
import org.eclipse.swt.ole.win32.Variant;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class OutlookMail {
    public static void main(String[] args) {
        sendEMail();
    }

    public static void sendEMail() {
        Display display = new Display();
        Shell shell = new Shell(display);
        OleFrame frame = new OleFrame(shell, SWT.NONE);

        // This should start outlook if it is not running yet
//      OleClientSite site = new OleClientSite(frame, SWT.NONE, "OVCtl.OVCtl");
//      site.doVerb(OLE.OLEIVERB_INPLACEACTIVATE);

        // Now get the outlook application
        OleClientSite site2 = new OleClientSite(frame, SWT.NONE, "Outlook.Application");
        OleAutomation outlook = new OleAutomation(site2);

        OleAutomation mail = invoke(outlook, "CreateItem", 0 /* Mail item */).getAutomation();

        setProperty(mail, "BodyFormat", 2 /* HTML */);
        setProperty(mail, "Subject", "My test subject");
//      setProperty(mail, "From", "my@sender.org");
        setProperty(mail, "To", "<John Doe> my@recipient.org");
        setProperty(mail, "HtmlBody", "<html><body>This is an <b>HTML</b> test body.</body></html>");

//      if (null != attachmentPaths) {
//          for (String attachmentPath : attachmentPaths) {
//              File file = new File(attachmentPath);
//              if (file.exists()) {
//                  OleAutomation attachments = getProperty(mail, "Attachments");
//                  invoke(attachments, "Add", attachmentPath);
//              }
//          }
//      }

        invoke(mail, "Display" /* or "Send" */);

    }

    private static OleAutomation getProperty(OleAutomation auto, String name) {
        Variant varResult = auto.getProperty(property(auto, name));
        if (varResult != null && varResult.getType() != OLE.VT_EMPTY) {
            OleAutomation result = varResult.getAutomation();
            varResult.dispose();
            return result;
        }
        return null;
    }

    private static Variant invoke(OleAutomation auto, String command,
            String value) {
        return auto.invoke(property(auto, command),
                new Variant[] { new Variant(value) });
    }

    private static Variant invoke(OleAutomation auto, String command) {
        return auto.invoke(property(auto, command));
    }

    private static Variant invoke(OleAutomation auto, String command, int value) {
        return auto.invoke(property(auto, command),
                new Variant[] { new Variant(value) });
    }

    private static boolean setProperty(OleAutomation auto, String name,
            String value) {
        return auto.setProperty(property(auto, name), new Variant(value));
    }

    private static boolean setProperty(OleAutomation auto, String name,
            int value) {
        return auto.setProperty(property(auto, name), new Variant(value));
    }

    private static int property(OleAutomation auto, String name) {
        return auto.getIDsOfNames(new String[] { name })[0];
    }
}
</code>```

See How to create an E-Mail in Outlook and make it visible for the User for more information.

The sequence of property and method calls from the Outlook object model you can find in the following articles:

How To: Create a new Outlook Appointment item

How To: Create a new recurring Outlook Appointment item

Body:
If you want to create a meeting in the organizer calendar I'd suggest automating Outlook from your Java-based application. You may consider using the Ole automation technology for automating Outlook, for example:

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.ole.win32.OLE;
import org.eclipse.swt.ole.win32.OleAutomation;
import org.eclipse.swt.ole.win32.OleClientSite;
import org.eclipse.swt.ole.win32.OleFrame;
import org.eclipse.swt.ole.win32.Variant;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class OutlookMail {
    public static void main(String[] args) {
        sendEMail();
    }

    public static void sendEMail() {
        Display display = new Display();
        Shell shell = new Shell(display);
        OleFrame frame = new OleFrame(shell, SWT.NONE);

        // This should start outlook if it is not running yet
//      OleClientSite site = new OleClientSite(frame, SWT.NONE, "OVCtl.OVCtl");
//      site.doVerb(OLE.OLEIVERB_INPLACEACTIVATE);

        // Now get the outlook application
        OleClientSite site2 = new OleClientSite(frame, SWT.NONE, "Outlook.Application");
        OleAutomation outlook = new OleAutomation(site2);

        OleAutomation mail = invoke(outlook, "CreateItem", 0 /* Mail item */).getAutomation();

        setProperty(mail, "BodyFormat", 2 /* HTML */);
        setProperty(mail, "Subject", "My test subject");
//      setProperty(mail, "From", "my@sender.org");
        setProperty(mail, "To", "<John Doe> my@recipient.org");
        setProperty(mail, "HtmlBody", "<html><body>This is an <b>HTML</b> test body.</body></html>");

//      if (null != attachmentPaths) {
//          for (String attachmentPath : attachmentPaths) {
//              File file = new File(attachmentPath);
//              if (file.exists()) {
//                  OleAutomation attachments = getProperty(mail, "Attachments");
//                  invoke(attachments, "Add", attachmentPath);
//              }
//          }
//      }

        invoke(mail, "Display" /* or "Send" */);

    }

    private static OleAutomation getProperty(OleAutomation auto, String name) {
        Variant varResult = auto.getProperty(property(auto, name));
        if (varResult != null && varResult.getType() != OLE.VT_EMPTY) {
            OleAutomation result = varResult.getAutomation();
            varResult.dispose();
            return result;
        }
        return null;
    }

    private static Variant invoke(OleAutomation auto, String command,
            String value) {
        return auto.invoke(property(auto, command),
                new Variant[] { new Variant(value) });
    }

    private static Variant invoke(OleAutomation auto, String command) {
        return auto.invoke(property(auto, command));
    }

    private static Variant invoke(OleAutomation auto, String command, int value) {
        return auto.invoke(property(auto, command),
                new Variant[] { new Variant(value) });
    }

    private static boolean setProperty(OleAutomation auto, String name,
            String value) {
        return auto.setProperty(property(auto, name), new Variant(value));
    }

    private static boolean setProperty(OleAutomation auto, String name,
            int value) {
        return auto.setProperty(property(auto, name), new Variant(value));
    }

    private static int property(OleAutomation auto, String name) {
        return auto.getIDsOfNames(new String[] { name })[0];
    }
}

See How to create an E-Mail in Outlook and make it visible for the User for more information.

The sequence of property and method calls from the Outlook object model you can find in the following articles:

How To: Create a new Outlook Appointment item

How To: Create a new recurring Outlook Appointment item


问:
Retrieving group of particular contact
I want to retrieve the contact details along with the group which it belongs to. I got the code to list all the contact groups in the phone.

```<code>Cursor groupC = getContentResolver().query(
    ContactsContract.Groups.CONTENT_URI, null, null, null, null);

while (groupC.moveToNext()) {
    String groupid =
        groupC.getString(groupC.getColumnIndex(ContactsContract.Groups._ID));
    Log.e("myTag", groupid);
    String grouptitle =
        groupC .getString(groupC.getColumnIndex(ContactsContract.Groups.TITLE));
    Log.e("myTag", grouptitle);
}
groupC.close();
</code>```

Then I tried to query for a particular contact by using its id but it always shows There is no such column....

```<code>Cursor groupC = getContentResolver().query(
    ContactsContract.Groups.CONTENT_URI,
    null,
    ContactsContract.Contacts._ID+"= ?",
    new String[]{id},
    null);
</code>```

where id is

```<code>Cursor cur = cr.query(
    ContactsContract.Contacts.CONTENT_URI,
    null,
    null,
    null,
    null);
id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
</code>```

How to query the group using a particular contact id?

答:
I found the answer.we should pass the raw contact-id and the correct mime type.

```<code>  String where = ContactsContract.Data.RAW_CONTACT_ID
            + "="
            + Integer.parseInt(id)
            + " AND "
            + ContactsContract.Data.MIMETYPE
            + "='"
            + ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE
            + "'";

    Cursor cursor = ctx
            .getContentResolver()
            .query(ContactsContract.Data.CONTENT_URI, null, where, null,
                    null);
    startManagingCursor(cursor);
    Log.e("Count is:", ""+ cursor.getCount());
    while (cursor.moveToNext()) {
        groupid = cursor
                .getString(cursor.getColumnIndex(ContactsContract.Data.DATA1));
        Log.e("groupid", groupid);
        builder.append(groupid);

    }String where = ContactsContract.Data.RAW_CONTACT_ID
            + "="
            + Integer.parseInt(id)
            + " AND "
            + ContactsContract.Data.MIMETYPE
            + "='"
            + ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE
            + "'";

    Cursor cursor = ctx
            .getContentResolver()
            .query(ContactsContract.Data.CONTENT_URI, null, where, null,
                    null);
    startManagingCursor(cursor);
    Log.e("Count is:", ""+ cursor.getCount());
    while (cursor.moveToNext()) {
        groupid = cursor
                .getString(cursor.getColumnIndex(ContactsContract.Data.DATA1));
        Log.e("groupid", groupid);
        break;
    }
</code>```

A contact may be in more than one group,here it retrivr its first group pnly.

I think this may be useful to somebody...

Title: Retrieving group of particular contact

Body:
I want to retrieve the contact details along with the group which it belongs to. I got the code to list all the contact groups in the phone.

Cursor groupC = getContentResolver().query(
    ContactsContract.Groups.CONTENT_URI, null, null, null, null);

while (groupC.moveToNext()) {
    String groupid =
        groupC.getString(groupC.getColumnIndex(ContactsContract.Groups._ID));
    Log.e("myTag", groupid);
    String grouptitle =
        groupC .getString(groupC.getColumnIndex(ContactsContract.Groups.TITLE));
    Log.e("myTag", grouptitle);
}
groupC.close();

Then I tried to query for a particular contact by using its id but it always shows There is no such column....

Cursor groupC = getContentResolver().query(
    ContactsContract.Groups.CONTENT_URI,
    null,
    ContactsContract.Contacts._ID+"= ?",
    new String[]{id},
    null);

where id is

Cursor cur = cr.query(
    ContactsContract.Contacts.CONTENT_URI,
    null,
    null,
    null,
    null);
id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));

How to query the group using a particular contact id?

Body:
I found the answer.we should pass the raw contact-id and the correct mime type.

  String where = ContactsContract.Data.RAW_CONTACT_ID
            + "="
            + Integer.parseInt(id)
            + " AND "
            + ContactsContract.Data.MIMETYPE
            + "='"
            + ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE
            + "'";

    Cursor cursor = ctx
            .getContentResolver()
            .query(ContactsContract.Data.CONTENT_URI, null, where, null,
                    null);
    startManagingCursor(cursor);
    Log.e("Count is:", ""+ cursor.getCount());
    while (cursor.moveToNext()) {
        groupid = cursor
                .getString(cursor.getColumnIndex(ContactsContract.Data.DATA1));
        Log.e("groupid", groupid);
        builder.append(groupid);

    }String where = ContactsContract.Data.RAW_CONTACT_ID
            + "="
            + Integer.parseInt(id)
            + " AND "
            + ContactsContract.Data.MIMETYPE
            + "='"
            + ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE
            + "'";

    Cursor cursor = ctx
            .getContentResolver()
            .query(ContactsContract.Data.CONTENT_URI, null, where, null,
                    null);
    startManagingCursor(cursor);
    Log.e("Count is:", ""+ cursor.getCount());
    while (cursor.moveToNext()) {
        groupid = cursor
                .getString(cursor.getColumnIndex(ContactsContract.Data.DATA1));
        Log.e("groupid", groupid);
        break;
    }

A contact may be in more than one group,here it retrivr its first group pnly.

I think this may be useful to somebody...


问:
Is Pycharm not finding PIL?
I get an error "No module named PIL" when I use this code:

```<code>from PIL import ImageTk
</code>```

I have uninstalled and installed Pillow already, but the error still pops up.
Maybe Pycharm just isn't finding PIL?

答: I got the solution, I needed to uninstall Pillow, in PyCharm press Ctrl+Alt+S, and add Pillow as a package, not PIL.</p>

Title: Is Pycharm not finding PIL?

Body:
I get an error "No module named PIL" when I use this code:

from PIL import ImageTk

I have uninstalled and installed Pillow already, but the error still pops up.
Maybe Pycharm just isn't finding PIL?


问:
How to capture Json from web site using c#
I have a paid subscription to Seeking Alpha and have a cookkie which enables me to get full data from https://seekingalpha.com/symbol/AAPL/financials-data?period_type=quarterly&statement_type=income-statement&order_type=latest_left&is_pro=True

I'd like to collect JSON response using C#

Below is my horrible code

```<code>        string cookie = "my super secret cookie string";

        var request = new RestRequest(Method.GET);
        request.AddHeader("content-type", "application/json");
        request.AddHeader("Accept", "*/*");
        request.AddHeader("User-Agent","Mozilla/5.0");
        request.AddHeader("X-Requested-With", "XMLHttpRequest");
        string url = "https://seekingalpha.com/symbol/AAPL/financials-data?period_type=quarterly&statement_type=income-statement&order_type=latest_left&is_pro=True";

                    request.AddParameter("cookie", cookie, ParameterType.Cookie);

        var client = new RestClient(url);

        var queryResult = client.Execute(request);

        Console.WriteLine(queryResult.Content);
</code>```

How can I get it to return JSON to me? I am getting something but not the JSON I want

答:
After poking around for a bit I figured it out. For the benefit of all:</p>

```<code>    private bool FinancialStatement(string symbol, string statement, string period)
    {
        var target = $"{BASE_URL}{symbol}/financials-data?period_type={period}&statement_type={statement}&order_type=latest_left&is_pro=True";

        var client = new RestClient(target);

        client.Timeout = -1;
        var request = new RestRequest(Method.GET);
        request.AddHeader("Cookie", MACHINE_COOKIE);
        IRestResponse response = client.Execute(request);
        dynamic responseObj;
        try
        {
            responseObj = JsonConvert.DeserializeObject(response.Content);
        }
        catch (Exception)
        {
            return false;
        }

        return response.IsSuccessful;
    }
</code>```

Body:
I have a paid subscription to Seeking Alpha and have a cookkie which enables me to get full data from https://seekingalpha.com/symbol/AAPL/financials-data?period_type=quarterly&statement_type=income-statement&order_type=latest_left&is_pro=True

I'd like to collect JSON response using C#

Below is my horrible code

        string cookie = "my super secret cookie string";

        var request = new RestRequest(Method.GET);
        request.AddHeader("content-type", "application/json");
        request.AddHeader("Accept", "*/*");
        request.AddHeader("User-Agent","Mozilla/5.0");
        request.AddHeader("X-Requested-With", "XMLHttpRequest");
        string url = "https://seekingalpha.com/symbol/AAPL/financials-data?period_type=quarterly&statement_type=income-statement&order_type=latest_left&is_pro=True";

                    request.AddParameter("cookie", cookie, ParameterType.Cookie);

        var client = new RestClient(url);

        var queryResult = client.Execute(request);

        Console.WriteLine(queryResult.Content);

How can I get it to return JSON to me? I am getting something but not the JSON I want

Body:
After poking around for a bit I figured it out. For the benefit of all:

    private bool FinancialStatement(string symbol, string statement, string period)
    {
        var target = $"{BASE_URL}{symbol}/financials-data?period_type={period}&statement_type={statement}&order_type=latest_left&is_pro=True";

        var client = new RestClient(target);

        client.Timeout = -1;
        var request = new RestRequest(Method.GET);
        request.AddHeader("Cookie", MACHINE_COOKIE);
        IRestResponse response = client.Execute(request);
        dynamic responseObj;
        try
        {
            responseObj = JsonConvert.DeserializeObject(response.Content);
        }
        catch (Exception)
        {
            return false;
        }

        return response.IsSuccessful;
    }


问:
How to capture the event when WPF combobox item is click, or selected by Enter key?
I had tried this for few hours, but it's not working.

I have a combobox, with a few items in there, generated dynamically like a search box.

Now I want to capture an event, when user click on the dropdown menu item, or click on the dropdown menu item.

How to achieve this? I tried to set mouse/keyboard event handler on Combobox, but it only works on the combobox's textbox, not in the dropdown list.

Thanks.

Edit:
I forgot to mention that I has custom DataTemplate on my Combobox. I tried another approach which set the event in ComboBox.ItemContainerStyle.

I tried PreviewKeyDown, but it is not captured. Any idea?

答:
Try setting an event of type DropDownClosed and capture that.

I tested it in my program and it seems to be called just before closing combobox dropdown.

I refer you to this question for further information on this.


问:
Azure Function occasionally still runs old code after deployment
Occasionally after deploying the latest bits to an azure function it still is running the older version of the function.  Here is the build of the .NET core azure function and deployment code.  Ideas for what is causing this.  No failures are seen in the deployment process and it only happens occasionally.  I've tried adding a restart step for the azure function to no avail.  As a temporary work around I am completely deleting the azure function and re-creating it in the build process but this is less than ideal.

// ARM for function

```<code>    {
  "apiVersion": "2015-08-01",
  "type": "Microsoft.Web/sites",
  "name": "[variables('functionAppName')]",
  "location": "[parameters('location')]",
  "kind": "functionapp",
  "dependsOn": [
    "[resourceId('Microsoft.Web/serverfarms', variables('hostingPlanName'))]",
    "[resourceId('Microsoft.Storage/storageAccounts', variables('storageAccountName'))]",
    "[resourceId('Microsoft.Storage/storageAccounts', parameters('storageAccounts_calculationartifacts_name'))]"
  ],
  "properties": {
    "serverFarmId": "[resourceId('Microsoft.Web/serverfarms', variables('hostingPlanName'))]",
    "siteConfig": {
      "appSettings": [
        {
          "name": "AzureWebJobsStorage",
          "value": "[concat('DefaultEndpointsProtocol=https;AccountName=', variables('storageAccountName'), ';AccountKey=', listKeys(variables('storageAccountid'),'2015-05-01-preview').key1)]"
        },
        {
            "name": "AzureWebJobsDashboard",
            "value": "[concat('DefaultEndpointsProtocol=https;AccountName=', variables('storageAccountName'), ';AccountKey=', listKeys(variables('storageAccountid'),'2015-05-01-preview').key1)]"
        },
        {
          "name": "WEBSITE_CONTENTAZUREFILECONNECTIONSTRING",
          "value": "[concat('DefaultEndpointsProtocol=https;AccountName=', variables('storageAccountName'), ';AccountKey=', listKeys(variables('storageAccountid'),'2015-05-01-preview').key1)]"
        },
        {
          "name": "WEBSITE_CONTENTSHARE",
          "value": "[toLower(variables('functionAppName'))]"
        },
        {
          "name": "FUNCTIONS_EXTENSION_VERSION",
          "value": "~3"
        },
        {
          "name": "WEBSITE_NODE_DEFAULT_VERSION",
          "value": "~10"
        },
        {
          "name": "APPINSIGHTS_INSTRUMENTATIONKEY",
          "value": "[reference(resourceId('microsoft.insights/components/', variables('applicationInsightsName')), '2015-05-01').InstrumentationKey]"
        },
        {
          "name": "FUNCTIONS_WORKER_RUNTIME",
          "value": "[variables('functionWorkerRuntime')]"
        },
        {
          "name": "WEBSITE_ENABLE_SYNC_UPDATE_SITE",
          "value": "true",
          "slotSetting": false
        }
      ]
    }
  }
}
</code>```

// yaml build step

```<code>- task: DotNetCoreCLI@2
  displayName: Build
  inputs:
    command: 'build'
    projects: |
      **/$(myProject).csproj
    arguments: --output $(System.DefaultWorkingDirectory)/publish_output --configuration Release
</code>```

// yaml deploy step

```<code>      - task: AzureFunctionApp@1
        displayName: 'Azure functions app deploy'
        inputs:
          azureSubscription: '$(azureSubscription)'
          appType: functionApp
          appName: $(myAppName)
          package: '$(Pipeline.Workspace)/drop/$(Build.BuildId).zip'
</code>```

答:
It could be that your functions are long running. A call to the function will run the version of the code that was available when the function was called.

Scenario 1:

T0: Call comes in and V1 of the function starts running

T1: V2 of the function is deployed

T2: Call completes using V1 of the function

Scenario 2:

T0: V1 of the function is running

T1: Deployment of V2 starts

T2: Call comes in, since deployment of V2 is not complete V1 responds

If the function is still responding with V1 several minutes after the deploy, then something else is wrong.

Body:
Occasionally after deploying the latest bits to an azure function it still is running the older version of the function.  Here is the build of the .NET core azure function and deployment code.  Ideas for what is causing this.  No failures are seen in the deployment process and it only happens occasionally.  I've tried adding a restart step for the azure function to no avail.  As a temporary work around I am completely deleting the azure function and re-creating it in the build process but this is less than ideal.

// ARM for function

    {
  "apiVersion": "2015-08-01",
  "type": "Microsoft.Web/sites",
  "name": "[variables('functionAppName')]",
  "location": "[parameters('location')]",
  "kind": "functionapp",
  "dependsOn": [
    "[resourceId('Microsoft.Web/serverfarms', variables('hostingPlanName'))]",
    "[resourceId('Microsoft.Storage/storageAccounts', variables('storageAccountName'))]",
    "[resourceId('Microsoft.Storage/storageAccounts', parameters('storageAccounts_calculationartifacts_name'))]"
  ],
  "properties": {
    "serverFarmId": "[resourceId('Microsoft.Web/serverfarms', variables('hostingPlanName'))]",
    "siteConfig": {
      "appSettings": [
        {
          "name": "AzureWebJobsStorage",
          "value": "[concat('DefaultEndpointsProtocol=https;AccountName=', variables('storageAccountName'), ';AccountKey=', listKeys(variables('storageAccountid'),'2015-05-01-preview').key1)]"
        },
        {
            "name": "AzureWebJobsDashboard",
            "value": "[concat('DefaultEndpointsProtocol=https;AccountName=', variables('storageAccountName'), ';AccountKey=', listKeys(variables('storageAccountid'),'2015-05-01-preview').key1)]"
        },
        {
          "name": "WEBSITE_CONTENTAZUREFILECONNECTIONSTRING",
          "value": "[concat('DefaultEndpointsProtocol=https;AccountName=', variables('storageAccountName'), ';AccountKey=', listKeys(variables('storageAccountid'),'2015-05-01-preview').key1)]"
        },
        {
          "name": "WEBSITE_CONTENTSHARE",
          "value": "[toLower(variables('functionAppName'))]"
        },
        {
          "name": "FUNCTIONS_EXTENSION_VERSION",
          "value": "~3"
        },
        {
          "name": "WEBSITE_NODE_DEFAULT_VERSION",
          "value": "~10"
        },
        {
          "name": "APPINSIGHTS_INSTRUMENTATIONKEY",
          "value": "[reference(resourceId('microsoft.insights/components/', variables('applicationInsightsName')), '2015-05-01').InstrumentationKey]"
        },
        {
          "name": "FUNCTIONS_WORKER_RUNTIME",
          "value": "[variables('functionWorkerRuntime')]"
        },
        {
          "name": "WEBSITE_ENABLE_SYNC_UPDATE_SITE",
          "value": "true",
          "slotSetting": false
        }
      ]
    }
  }
}

// yaml build step

- task: DotNetCoreCLI@2
  displayName: Build
  inputs:
    command: 'build'
    projects: |
      **/$(myProject).csproj
    arguments: --output $(System.DefaultWorkingDirectory)/publish_output --configuration Release

// yaml deploy step

      - task: AzureFunctionApp@1
        displayName: 'Azure functions app deploy'
        inputs:
          azureSubscription: '$(azureSubscription)'
          appType: functionApp
          appName: $(myAppName)
          package: '$(Pipeline.Workspace)/drop/$(Build.BuildId).zip'


问:
Merge git repository in subdirectory
I'd like to merge a remote git repository in my working git repository as a subdirectory of it. I'd like the resulting repository to contain the merged history of the two repositories and also that each file of the merged-in repository retain its history as it was in the remote repository. I tried using the subtree strategy as mentioned in How to use the subtree merge strategy, but after following that procedure, although the resulting repository contains indeed the merged history of the two repositories, individual files coming from the remote one haven't retained their history (`git log' on any of them just shows a message "Merged branch...").

Also I don't want to use submodules because I do not want the two combined git repositories to be separate anymore.

Is it possible to merge a remote git repository in another one as a subdirectory with individual files coming from the remote repository retaining their history?

Thanks very much for any help.

EDIT:
I'm currently trying out a solution that uses git filter-branch to rewrite the merged-in repository history. It does seem to work, but I need to test it some more. I'll return to report on my findings.

EDIT 2:
In hope I make myself more clear I give the exact commands I used with git's subtree strategy, which result in apparent loss of history of the files of the remote repository.
Let A be the git repo I'm currently working in and B the git repo I'd like to incorporate into A as a subdirectory of it. It did the following:

```<code>git remote add -f B <url-of-B>
git merge -s ours --no-commit B/master
git read-tree --prefix=subdir/Iwant/to/put/B/in/ -u B/master
git commit -m "Merge B as subdirectory in subdir/Iwant/to/put/B/in."
</code>```

After these commands and going into directory subdir/Iwant/to/put/B/in, I see all files of B, but git log on any one of them shows just  the commit message "Merge B as subdirectory in subdir/Iwant/to/put/B/in." Their file history as it is in B is lost.

What seems to work (since I'm a beginner on git I may be wrong) is the following:

```<code>git remote add -f B <url-of-B>
git checkout -b B_branch B/master  # make a local branch following B's master
git filter-branch --index-filter \
   'git ls-files -s | sed "s-\t\"*-&subdir/Iwant/to/put/B/in/-" |
        GIT_INDEX_FILE=$GIT_INDEX_FILE.new \
                git update-index --index-info &&
        mv "$GIT_INDEX_FILE.new" "$GIT_INDEX_FILE"' HEAD
git checkout master
git merge B_branch
</code>```

The command above for filter-branch is taken from git help filter-branch, in which I only changed the subdir path.

答:
Say you want to merge repository a into b (I'm assuming they're located alongside one another):

```<code>cd a
git filter-repo --to-subdirectory-filter a
cd ..
cd b
git remote add a ../a
git fetch a
git merge --allow-unrelated-histories a/master
git remote remove a
</code>```

For this you need git-filter-repo installed (filter-branch is discouraged).

An example of merging 2 big repositories, putting one of them into a subdirectory: https://gist.github.com/x-yuri/9890ab1079cf4357d6f269d073fd9731

More on it here.

Title: Merge git repository in subdirectory

Body:
I'd like to merge a remote git repository in my working git repository as a subdirectory of it. I'd like the resulting repository to contain the merged history of the two repositories and also that each file of the merged-in repository retain its history as it was in the remote repository. I tried using the subtree strategy as mentioned in How to use the subtree merge strategy, but after following that procedure, although the resulting repository contains indeed the merged history of the two repositories, individual files coming from the remote one haven't retained their history (`git log' on any of them just shows a message "Merged branch...").

Also I don't want to use submodules because I do not want the two combined git repositories to be separate anymore.

Is it possible to merge a remote git repository in another one as a subdirectory with individual files coming from the remote repository retaining their history?

Thanks very much for any help.

EDIT:
I'm currently trying out a solution that uses git filter-branch to rewrite the merged-in repository history. It does seem to work, but I need to test it some more. I'll return to report on my findings.

EDIT 2:
In hope I make myself more clear I give the exact commands I used with git's subtree strategy, which result in apparent loss of history of the files of the remote repository.
Let A be the git repo I'm currently working in and B the git repo I'd like to incorporate into A as a subdirectory of it. It did the following:

git remote add -f B <url-of-B>
git merge -s ours --no-commit B/master
git read-tree --prefix=subdir/Iwant/to/put/B/in/ -u B/master
git commit -m "Merge B as subdirectory in subdir/Iwant/to/put/B/in."

After these commands and going into directory subdir/Iwant/to/put/B/in, I see all files of B, but git log on any one of them shows just  the commit message "Merge B as subdirectory in subdir/Iwant/to/put/B/in." Their file history as it is in B is lost.

What seems to work (since I'm a beginner on git I may be wrong) is the following:

git remote add -f B <url-of-B>
git checkout -b B_branch B/master  # make a local branch following B's master
git filter-branch --index-filter \
   'git ls-files -s | sed "s-\t\"*-&subdir/Iwant/to/put/B/in/-" |
        GIT_INDEX_FILE=$GIT_INDEX_FILE.new \
                git update-index --index-info &&
        mv "$GIT_INDEX_FILE.new" "$GIT_INDEX_FILE"' HEAD
git checkout master
git merge B_branch

The command above for filter-branch is taken from git help filter-branch, in which I only changed the subdir path.

Body:
Say you want to merge repository a into b (I'm assuming they're located alongside one another):

cd a
git filter-repo --to-subdirectory-filter a
cd ..
cd b
git remote add a ../a
git fetch a
git merge --allow-unrelated-histories a/master
git remote remove a

For this you need git-filter-repo installed (filter-branch is discouraged).

An example of merging 2 big repositories, putting one of them into a subdirectory: https://gist.github.com/x-yuri/9890ab1079cf4357d6f269d073fd9731

More on it here.


问:
Almost all the cloud service providers have 99.95% of data available on the cloud. What will happen if the whole region sinks in an earthquake?
I'm just asking this question to satisfy my curiosity on cloud development. There's one thing in common in the cloud when comes to data availability, 99.95% of data is subject to be available even during downtime. I want just to know what will happen for example if the entire region sinks in a earthquake.

I understand the fact that there's continous data backup on the cloud storages. are those storages reside in a region or not?

答:
To give a couple of examples:

Amazon S3 is provided on a regional level. That means that when an S3 bucket is created, AWS automatically uses the different Availability Zones in that region to keep the data available.

In the catastrophic case where all the AZs in a region were to be destroyed, then that data will be lost.  For that, S3 offers Cross-Region replication where objects are copied across Amazon S3 buckets in different AWS Regions.

Google Cloud Storage is a also a regional service with multi-AZ availability. Google also offers special geo-redundancy in the form of multi-regional and dual-regional Cloud Storage locations. The USA, for example is designated as a multi-region across all its data centers, while Finland and the Netherlands are a specific pair in a dual-region:


问:
Python ElementTree generate not well formed XML file with special character '\x0b'
I used ElementTree to generate xml with special character of '\x0b', then use minidom to parse it. It will throw not well-formed error.

import xml.etree.ElementTree as ET
from xml.dom import minidom
root = ET.Element('root')
root.text='\x0b'
xml = ET.tostring(root, 'UTF-8')
print(xml)
pretty_tree = minidom.parseString(xml)
```

<p><strong>Generated XML</strong>: <code><root>\x0b</root></code> </p>

<p><strong>Error</strong>: </p>

```Traceback (most recent call last):
  File "testXml.py", line 7, in <module>
    pretty_tree = minidom.parseString(xml)
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/xml/dom/minidom.py", line 1968, in parseString
    return expatbuilder.parseString(string)
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/xml/dom/expatbuilder.py", line 925, in parseString
    return builder.parseString(string)
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/xml/dom/expatbuilder.py", line 223, in parseString
    parser.Parse(string, True)
xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 6
```

答:
As a workaround for myself, I wrote a helper method to clean the restricted chars before saving to XML model:

def clean(str):
  return re.sub(r'[^\u0009\u000A\u000D\u0020-\uD7FF\uE000-\uFFFD\u10000-\u10FFF]+', '', str)
```

Body:
I used ElementTree to generate xml with special character of '\x0b', then use minidom to parse it. It will throw not well-formed error.

import xml.etree.ElementTree as ET
from xml.dom import minidom
root = ET.Element('root')
root.text='\x0b'
xml = ET.tostring(root, 'UTF-8')
print(xml)
pretty_tree = minidom.parseString(xml)

Generated XML: <root>\x0b</root>

Error:

Traceback (most recent call last):
  File "testXml.py", line 7, in <module>
    pretty_tree = minidom.parseString(xml)
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/xml/dom/minidom.py", line 1968, in parseString
    return expatbuilder.parseString(string)
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/xml/dom/expatbuilder.py", line 925, in parseString
    return builder.parseString(string)
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/xml/dom/expatbuilder.py", line 223, in parseString
    parser.Parse(string, True)
xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 6