问:
Typescript: Use SET of interface property used by a class when only one property is changed?
I have an interface (which resembles the database structure) as such:

```<code>export interface Body {
    health: number;
    height: number;
    hairlength: number;
}
</code>```

and a class as following

```<code>export class Person {
    private _body: Body;
    private _name: string;
    private _age: number;
    constructor()....

    get body(): Body {
        return this._body
    }
}
</code>```

is there a way to use get/set on the body interface inside the class when only one property is changed from outside the class, e.g.:

```<code>    set body.hairlength(n: number) {
        // Do some stuff
    }
</code>```

so a haircutter could use:

```<code>static performHairCut(p: Person) {
    p.body.hairlength -= 10
}
</code>```

With this idea I want to seperate repeatedly updating properties from "occasional" ones

答:
Instead of returning Body object directly you can return object containing getters/setters like:

```<code>export interface Body {
    health: number;
    height: number;
    hairlength: number;
}

export class Person {
    private _body!: Body;

    constructor() { }

    get body(): Body {
        const that = this;

        return {
            get health() {
                return that._body.health;
            },
            set health(newValue: number) {
                that.body.health = newValue
            },
            get height() {
                return that._body.height;
            },
            set height(newValue: number) {
                that.body.height = newValue
            },
            get hairlength() {
                return that._body.hairlength;
            },
            set hairlength(newValue: number) {
                that.body.hairlength = newValue
            }
        }
    }
}
</code>```

However, I don't recommend this approach. In my opinion code like this is obscure and can get messy very quickly with bigger interfaces (especially if they contain nested structures). You should check out ES6 proxies.

Body:
I have an interface (which resembles the database structure) as such:

export interface Body {
    health: number;
    height: number;
    hairlength: number;
}

and a class as following

export class Person {
    private _body: Body;
    private _name: string;
    private _age: number;
    constructor()....

    get body(): Body {
        return this._body
    }
}

is there a way to use get/set on the body interface inside the class when only one property is changed from outside the class, e.g.:

    set body.hairlength(n: number) {
        // Do some stuff
    }

so a haircutter could use:

static performHairCut(p: Person) {
    p.body.hairlength -= 10
}

With this idea I want to seperate repeatedly updating properties from "occasional" ones

Body:
Instead of returning Body object directly you can return object containing getters/setters like:

export interface Body {
    health: number;
    height: number;
    hairlength: number;
}

export class Person {
    private _body!: Body;

    constructor() { }

    get body(): Body {
        const that = this;

        return {
            get health() {
                return that._body.health;
            },
            set health(newValue: number) {
                that.body.health = newValue
            },
            get height() {
                return that._body.height;
            },
            set height(newValue: number) {
                that.body.height = newValue
            },
            get hairlength() {
                return that._body.hairlength;
            },
            set hairlength(newValue: number) {
                that.body.hairlength = newValue
            }
        }
    }
}

However, I don't recommend this approach. In my opinion code like this is obscure and can get messy very quickly with bigger interfaces (especially if they contain nested structures). You should check out ES6 proxies.


来源: stackexchange

问:
add legend and smoothing to a graph
I am going to plot these curves with the legend, however, the legend does not appear. Does anyone know how I can bring it ... also is it possible to make the plots neater and smoother? (the data for each plot is 165, ... is it possible to plot the average of each 16 data (i.e. we do not have 165 data anymore, we will have 10 data?
here is the code:

```<code>ggplot() +
  geom_ribbon(data=file1, aes(x = No., ymax = A1_10 + S1_10, ymin = A1_10 - S1_10),alpha = 0.20, fill=cl[1])+
  geom_line(data = file1, aes(x = No., y = A1_10), colour="red")+
  geom_ribbon(data=file1, aes(x = No., ymax = A2_10 + S2_10, ymin = A2_10 - S2_10),alpha = 0.20, fill=cl[3])+
  geom_line(data = file1, aes(x = No., y = A2_10), colour=cl[3])+
  geom_ribbon(data=file1, aes(x = No., ymax = A3_10 + S3_10, ymin = A3_10 - S3_10),alpha = 0.20, fill=cl[11])+
  geom_line(data = file1, aes(x = No., y = A3_10), colour=cl[11])+
  geom_ribbon(data=file1, aes(x = No., ymax = A5_10 + S5_10, ymin = A5_10 - S5_10),alpha = 0.20, fill=cl[8])+
  geom_line(data = file1, aes(x = No., y = A5_10), colour=cl[8])+
  geom_ribbon(data=file1, aes(x = No., ymax = A6_10 + S6_10, ymin = A6_10 - S6_10),alpha = 0.20, fill=cl[12])+
  geom_line(data = file1, aes(x = No., y = A6_10), colour=cl[8])+
  geom_ribbon(data=file1, aes(x = No., ymax = A7_10 + S7_10, ymin = A7_10 - S7_10),alpha = 0.20, fill=cl[18])+
  geom_line(data = file1, aes(x = No., y = A7_10), colour=cl[8])+
  xlab("Number")+ylab("Value")+
  theme(legend.position="bottom")
</code>```

答:
In order to get a legend, you can either add show.legend = TRUE in each geom_line but the result should be quite messy.

A better way of using ggplot is to reshape your data into a longer format. As, you did not provide reproducible example of your dataset in your question, I create a dummy example (provided below) with 7 columns, one containing number from 1 to 165 and 3 columns with a value and 3 column with a (fake) standard deviation.

For reshaping your dataframe, I used pivot_longer and pivot_wider function from tidyr package in order to obtain one column for "Number", one column for "y" values, one column for "s" values and one column for categorical values:

library(tidyr)
library(dplyr)
df %>% pivot_longer(-No, names_to = "var", values_to = "val") %>%
  mutate(Col = sub("\\d","",var), var = sub("\\w","",var)) %>%
  pivot_wider(names_from = Col, values_from = val)

# A tibble: 495 x 4
      No var        y      s
   <int> <chr>  <dbl>  <dbl>
 1     1 1      2.28   1.14
 2     1 2      5.02   2.01
 3     1 3      2.14   0.427
 4     2 1      2.57   1.28
 5     2 2      5.06   2.02
 6     2 3      2.07   0.413
 7     3 1     -0.201 -0.100
 8     3 2      4.42   1.77
 9     3 3      1.32   0.264
10     4 1      0.562  0.281
# … with 485 more rows
```

<p>Now, you can pass that and add the code for plotting using <code>ggplot2</code>:</p>

<pre class="lang-r prettyprint-override"><code>library(tidyr)
library(dplyr)
library(ggplot2)
df %>% pivot_longer(-No, names_to = "var", values_to = "val") %>%
  mutate(Col = sub("\\d","",var), var = sub("\\w","",var)) %>%
  pivot_wider(names_from = Col, values_from = val) %>%
  ggplot(aes(x = No, y = y, color = as.factor(var)))+
  geom_line()+
  geom_ribbon(aes(ymin = y-s, ymax= y+s, fill = as.factor(var)), alpha = 0.2)+
  scale_color_manual(values = c("red","blue","orange"))+
  scale_fill_manual(values = c("red","blue","orange"))+
  theme(legend.position = "bottom")
</code>```

Now, you can see, that you don't need to repeat geom_line and geom_ribbon for each initial variable and you get your legend that you can further personalize.

Regarding the second question, we can average your dataframe for each 16 data by using cut function. However, as you have 165 number, you will get 11 groups and not 10. Based the previous code, you can do:

library(tidyr)
library(dplyr)
df %>% mutate(Group = cut(No, breaks = c(seq(1,165,by  = 16),165), include.lowest = TRUE, label = 1:11)) %>%
  pivot_longer(-c(No, Group), names_to = "var", values_to = "val") %>%
  mutate(Col = sub("\\d","",var), var = sub("\\w","",var)) %>%
  group_by(Group, var, Col) %>%
  summarise(Mean = mean(val)) %>%
  pivot_wider(names_from = Col, values_from = Mean)

# A tibble: 33 x 4
# Groups:   Group, var [33]
   Group var       s     y
   <fct> <chr> <dbl> <dbl>
 1 1     1     0.384 0.768
 2 1     2     1.54  3.86
 3 1     3     0.432 2.16
 4 2     1     0.331 0.662
 5 2     2     1.57  3.94
 6 2     3     0.454 2.27
 7 3     1     0.639 1.28
 8 3     2     1.71  4.26
 9 3     3     0.403 2.01
10 4     1     0.355 0.710
# … with 23 more rows
```

<p>And similarly to get the plot, you can do:</p>

<pre class="lang-r prettyprint-override"><code>library(tidyr)
library(dplyr)
library(ggplot2)
df %>% mutate(Group = cut(No, breaks = c(seq(1,165,by  = 16),165), include.lowest = TRUE, label  = 1:11)) %>%
  pivot_longer(-c(No, Group), names_to = "var", values_to = "val") %>%
  mutate(Col = sub("\\d","",var), var = sub("\\w","",var)) %>%
  group_by(Group, var, Col) %>%
  summarise(Mean = mean(val)) %>%
  pivot_wider(names_from = Col, values_from = Mean) %>%
  ggplot(.,aes(x = as.numeric(Group), y = y, color = as.factor(var), fill = as.factor(var)))+
  geom_line()+
  geom_ribbon(alpha = 0.2, aes(ymin = y-s, ymax = y+s))+
  scale_x_continuous(breaks = 1:11)+
  scale_color_manual(values = c("red","blue","orange"))+
  scale_fill_manual(values = c("red","blue","orange"))+
  theme(legend.position = "bottom")
</code>```

Does it answer your question ?

If not, please provide a reproducible example of your dataset by following this tutorial: How to make a great R reproducible example

Reproducible example

df <- data.frame(No = 1:165,
                 y1 = rnorm(165,1,1),
                 y2 = rnorm(165,4,1),
                 y3 = rnorm(165,2,1))
df <- df %>% mutate(s1 = y1*0.5, s2 = y2*0.4, s3 = y3*0.2)
```

ContentLicense: CC BY-SA 4.0

Title: add legend and smoothing to a graph

Body:
I am going to plot these curves with the legend, however, the legend does not appear. Does anyone know how I can bring it ... also is it possible to make the plots neater and smoother? (the data for each plot is 165, ... is it possible to plot the average of each 16 data (i.e. we do not have 165 data anymore, we will have 10 data?
here is the code:

ggplot() +
  geom_ribbon(data=file1, aes(x = No., ymax = A1_10 + S1_10, ymin = A1_10 - S1_10),alpha = 0.20, fill=cl[1])+
  geom_line(data = file1, aes(x = No., y = A1_10), colour="red")+
  geom_ribbon(data=file1, aes(x = No., ymax = A2_10 + S2_10, ymin = A2_10 - S2_10),alpha = 0.20, fill=cl[3])+
  geom_line(data = file1, aes(x = No., y = A2_10), colour=cl[3])+
  geom_ribbon(data=file1, aes(x = No., ymax = A3_10 + S3_10, ymin = A3_10 - S3_10),alpha = 0.20, fill=cl[11])+
  geom_line(data = file1, aes(x = No., y = A3_10), colour=cl[11])+
  geom_ribbon(data=file1, aes(x = No., ymax = A5_10 + S5_10, ymin = A5_10 - S5_10),alpha = 0.20, fill=cl[8])+
  geom_line(data = file1, aes(x = No., y = A5_10), colour=cl[8])+
  geom_ribbon(data=file1, aes(x = No., ymax = A6_10 + S6_10, ymin = A6_10 - S6_10),alpha = 0.20, fill=cl[12])+
  geom_line(data = file1, aes(x = No., y = A6_10), colour=cl[8])+
  geom_ribbon(data=file1, aes(x = No., ymax = A7_10 + S7_10, ymin = A7_10 - S7_10),alpha = 0.20, fill=cl[18])+
  geom_line(data = file1, aes(x = No., y = A7_10), colour=cl[8])+
  xlab("Number")+ylab("Value")+
  theme(legend.position="bottom")

Body:
In order to get a legend, you can either add show.legend = TRUE in each geom_line but the result should be quite messy.

A better way of using ggplot is to reshape your data into a longer format. As, you did not provide reproducible example of your dataset in your question, I create a dummy example (provided below) with 7 columns, one containing number from 1 to 165 and 3 columns with a value and 3 column with a (fake) standard deviation.

For reshaping your dataframe, I used pivot_longer and pivot_wider function from tidyr package in order to obtain one column for "Number", one column for "y" values, one column for "s" values and one column for categorical values:

library(tidyr)
library(dplyr)
df %>% pivot_longer(-No, names_to = "var", values_to = "val") %>%
  mutate(Col = sub("\\d","",var), var = sub("\\w","",var)) %>%
  pivot_wider(names_from = Col, values_from = val)

# A tibble: 495 x 4
      No var        y      s
   <int> <chr>  <dbl>  <dbl>
 1     1 1      2.28   1.14
 2     1 2      5.02   2.01
 3     1 3      2.14   0.427
 4     2 1      2.57   1.28
 5     2 2      5.06   2.02
 6     2 3      2.07   0.413
 7     3 1     -0.201 -0.100
 8     3 2      4.42   1.77
 9     3 3      1.32   0.264
10     4 1      0.562  0.281
# … with 485 more rows

Now, you can pass that and add the code for plotting using ggplot2:

library(tidyr)
library(dplyr)
library(ggplot2)
df %>% pivot_longer(-No, names_to = "var", values_to = "val") %>%
  mutate(Col = sub("\\d","",var), var = sub("\\w","",var)) %>%
  pivot_wider(names_from = Col, values_from = val) %>%
  ggplot(aes(x = No, y = y, color = as.factor(var)))+
  geom_line()+
  geom_ribbon(aes(ymin = y-s, ymax= y+s, fill = as.factor(var)), alpha = 0.2)+
  scale_color_manual(values = c("red","blue","orange"))+
  scale_fill_manual(values = c("red","blue","orange"))+
  theme(legend.position = "bottom")

Now, you can see, that you don't need to repeat geom_line and geom_ribbon for each initial variable and you get your legend that you can further personalize.

Regarding the second question, we can average your dataframe for each 16 data by using cut function. However, as you have 165 number, you will get 11 groups and not 10. Based the previous code, you can do:

library(tidyr)
library(dplyr)
df %>% mutate(Group = cut(No, breaks = c(seq(1,165,by  = 16),165), include.lowest = TRUE, label = 1:11)) %>%
  pivot_longer(-c(No, Group), names_to = "var", values_to = "val") %>%
  mutate(Col = sub("\\d","",var), var = sub("\\w","",var)) %>%
  group_by(Group, var, Col) %>%
  summarise(Mean = mean(val)) %>%
  pivot_wider(names_from = Col, values_from = Mean)

# A tibble: 33 x 4
# Groups:   Group, var [33]
   Group var       s     y
   <fct> <chr> <dbl> <dbl>
 1 1     1     0.384 0.768
 2 1     2     1.54  3.86
 3 1     3     0.432 2.16
 4 2     1     0.331 0.662
 5 2     2     1.57  3.94
 6 2     3     0.454 2.27
 7 3     1     0.639 1.28
 8 3     2     1.71  4.26
 9 3     3     0.403 2.01
10 4     1     0.355 0.710
# … with 23 more rows

And similarly to get the plot, you can do:

library(tidyr)
library(dplyr)
library(ggplot2)
df %>% mutate(Group = cut(No, breaks = c(seq(1,165,by  = 16),165), include.lowest = TRUE, label  = 1:11)) %>%
  pivot_longer(-c(No, Group), names_to = "var", values_to = "val") %>%
  mutate(Col = sub("\\d","",var), var = sub("\\w","",var)) %>%
  group_by(Group, var, Col) %>%
  summarise(Mean = mean(val)) %>%
  pivot_wider(names_from = Col, values_from = Mean) %>%
  ggplot(.,aes(x = as.numeric(Group), y = y, color = as.factor(var), fill = as.factor(var)))+
  geom_line()+
  geom_ribbon(alpha = 0.2, aes(ymin = y-s, ymax = y+s))+
  scale_x_continuous(breaks = 1:11)+
  scale_color_manual(values = c("red","blue","orange"))+
  scale_fill_manual(values = c("red","blue","orange"))+
  theme(legend.position = "bottom")

Does it answer your question ?

If not, please provide a reproducible example of your dataset by following this tutorial: How to make a great R reproducible example

Reproducible example

df <- data.frame(No = 1:165,
                 y1 = rnorm(165,1,1),
                 y2 = rnorm(165,4,1),
                 y3 = rnorm(165,2,1))
df <- df %>% mutate(s1 = y1*0.5, s2 = y2*0.4, s3 = y3*0.2)


问:
Generating anchors with PyYAML.dump()?
I'd like to be able to generate anchors in the YAML generated by PyYAML's dump() function. Is there a way to do this? Ideally the anchors would have the same name as the YAML nodes.

Example:

```<code>import yaml
yaml.dump({'a': [1,2,3]})
'a: [1, 2, 3]\n'
</code>```

What I'd like to be able to do is generate YAML like:

```<code>import yaml
yaml.dump({'a': [1,2,3]})
'a: &a [1, 2, 3]\n'
</code>```

Can I write a custom emitter or dumper to do this? Is there another way?

答:
I couldn't get @beeb's answer to run at all, so I went ahead and tried to generailize @aaa90210's answer

import yaml

class _CustomAnchor(yaml.Dumper):
  anchor_tags = {}
  def __init__(self,*args,**kwargs):
    super().__init__(*args,**kwargs)
    self.new_anchors = {}
    self.anchor_next = None
  def anchor_node(self, node):
    if self.anchor_next is not None:
      self.new_anchors[node] = self.anchor_next
      self.anchor_next = None
    if isinstance(node.value, str) and node.value in self.anchor_tags:
      self.anchor_next = self.anchor_tags[node.value]

    super().anchor_node(node)

    if self.new_anchors:
      self.anchors.update(self.new_anchors)
      self.new_anchors.clear()
def CustomAnchor(tags):
  return type('CustomAnchor', (_CustomAnchor,), {'anchor_tags': tags})

print(yaml.dump(foo, Dumper=CustomAnchor({'a': 'a_name'})))
```

This does not offer a way to differentiate between two nodes with the same name value, that would require a yaml equivalent of XML's xpath, which I do not see in pyyaml :(

The Class factory CustomAnchor lets you pass in a dictionary of anchors base on node values. {value: anchor_name}

ContentLicense: CC BY-SA 3.0

Title: Generating anchors with PyYAML.dump()?

Body:
I'd like to be able to generate anchors in the YAML generated by PyYAML's dump() function. Is there a way to do this? Ideally the anchors would have the same name as the YAML nodes.

Example:

import yaml
yaml.dump({'a': [1,2,3]})
'a: [1, 2, 3]\n'

What I'd like to be able to do is generate YAML like:

import yaml
yaml.dump({'a': [1,2,3]})
'a: &a [1, 2, 3]\n'

Can I write a custom emitter or dumper to do this? Is there another way?

Body:
I couldn't get @beeb's answer to run at all, so I went ahead and tried to generailize @aaa90210's answer

import yaml

class _CustomAnchor(yaml.Dumper):
  anchor_tags = {}
  def __init__(self,*args,**kwargs):
    super().__init__(*args,**kwargs)
    self.new_anchors = {}
    self.anchor_next = None
  def anchor_node(self, node):
    if self.anchor_next is not None:
      self.new_anchors[node] = self.anchor_next
      self.anchor_next = None
    if isinstance(node.value, str) and node.value in self.anchor_tags:
      self.anchor_next = self.anchor_tags[node.value]

    super().anchor_node(node)

    if self.new_anchors:
      self.anchors.update(self.new_anchors)
      self.new_anchors.clear()
def CustomAnchor(tags):
  return type('CustomAnchor', (_CustomAnchor,), {'anchor_tags': tags})

print(yaml.dump(foo, Dumper=CustomAnchor({'a': 'a_name'})))

This does not offer a way to differentiate between two nodes with the same name value, that would require a yaml equivalent of XML's xpath, which I do not see in pyyaml :(

The Class factory CustomAnchor lets you pass in a dictionary of anchors base on node values. {value: anchor_name}


问:
"no such table" exception
In Django I added models into models.py. After manage.py makemigrations, manage.py migrate raised this exception:

django.db.utils.OperationalError: no such table: auth_test_usertranslatorprofile

I removed all old migrations and run makemigrations and migrate again which seemed to work. It didn't help because when I click User customer profiles of User translator profiles it raises exception:

```<code>Request Method: GET
Request URL: http://127.0.0.1:8000/admin/auth_test/usertranslatorprofile/

Django Version: 1.8.7
Python Version: 2.7.10
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'auth_test')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.security.SecurityMiddleware')

Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in wrapper
  618.                 return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapped_view
  110.                     response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
  57.         response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\contrib\admin\sites.py" in inner
  233.             return view(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapper
  34.             return bound_func(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapped_view
  110.                     response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in bound_func
  30.                 return func.__get__(self, type(self))(*args2, **kwargs2)
File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in changelist_view
  1550.                 self.list_max_show_all, self.list_editable, self)
File "C:\Python27\lib\site-packages\django\contrib\admin\views\main.py" in __init__
  82.         self.get_results(request)
File "C:\Python27\lib\site-packages\django\contrib\admin\views\main.py" in get_results
  177.         result_count = paginator.count
File "C:\Python27\lib\site-packages\django\core\paginator.py" in _get_count
  72.                 self._count = self.object_list.count()
File "C:\Python27\lib\site-packages\django\db\models\query.py" in count
  318.         return self.query.get_count(using=self.db)
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in get_count
  466.         number = obj.get_aggregation(using, ['__count'])['__count']
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in get_aggregation
  447.         result = compiler.execute_sql(SINGLE)
File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
  840.             cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\utils.py" in execute
  79.             return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\utils.py" in execute
  64.                 return self.cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\utils.py" in __exit__
  98.                 six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Python27\lib\site-packages\django\db\backends\utils.py" in execute
  64.                 return self.cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\sqlite3\base.py" in execute
  318.         return Database.Cursor.execute(self, query, params)

Exception Type: OperationalError at /admin/auth_test/usertranslatorprofile/
Exception Value: no such table: auth_test_usertranslatorprofile
</code>```

models.py:

```<code>from django.db import models
from django.contrib.auth.models import User

class Language(models.Model):
    shortcut = models.CharField(max_length=6)
    name = models.CharField(max_length=50)
    price_per_sign = models.FloatField()

class UserTranslatorProfile(models.Model):
    user = models.OneToOneField(User)
    languages = models.ManyToManyField(Language)
    price_per_word = models.FloatField()

class UserCustomerProfile(models.Model):
    user = models.OneToOneField(User)
</code>```

admin.py:

```<code>from django import forms
from .models import Language
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class FreelancerRegistrationForm(forms.Form):
    language = forms.ModelChoiceField(queryset=Language.objects.all().order_by('shortcut'))
</code>```

What is the problem?

答:
Follow this steps to get fixed this issue.

```<code>python manage.py migrate --fake APPNAME zero
</code>```

This will make your migration to fake. Now you can run the migrate script

```<code>python manage.py migrate APPNAME
</code>```

OR

```<code>python manage.py migrate
</code>```

Tables will be created and you solved your problem.. Cheers!!!

Title: "no such table" exception

Body:
In Django I added models into models.py. After manage.py makemigrations, manage.py migrate raised this exception:

django.db.utils.OperationalError: no such table: auth_test_usertranslatorprofile

I removed all old migrations and run makemigrations and migrate again which seemed to work. It didn't help because when I click User customer profiles of User translator profiles it raises exception:

Request Method: GET
Request URL: http://127.0.0.1:8000/admin/auth_test/usertranslatorprofile/

Django Version: 1.8.7
Python Version: 2.7.10
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'auth_test')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.security.SecurityMiddleware')

Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in wrapper
  618.                 return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapped_view
  110.                     response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
  57.         response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\contrib\admin\sites.py" in inner
  233.             return view(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapper
  34.             return bound_func(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapped_view
  110.                     response = view_func(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\utils\decorators.py" in bound_func
  30.                 return func.__get__(self, type(self))(*args2, **kwargs2)
File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in changelist_view
  1550.                 self.list_max_show_all, self.list_editable, self)
File "C:\Python27\lib\site-packages\django\contrib\admin\views\main.py" in __init__
  82.         self.get_results(request)
File "C:\Python27\lib\site-packages\django\contrib\admin\views\main.py" in get_results
  177.         result_count = paginator.count
File "C:\Python27\lib\site-packages\django\core\paginator.py" in _get_count
  72.                 self._count = self.object_list.count()
File "C:\Python27\lib\site-packages\django\db\models\query.py" in count
  318.         return self.query.get_count(using=self.db)
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in get_count
  466.         number = obj.get_aggregation(using, ['__count'])['__count']
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py" in get_aggregation
  447.         result = compiler.execute_sql(SINGLE)
File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
  840.             cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\utils.py" in execute
  79.             return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\utils.py" in execute
  64.                 return self.cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\utils.py" in __exit__
  98.                 six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Python27\lib\site-packages\django\db\backends\utils.py" in execute
  64.                 return self.cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\sqlite3\base.py" in execute
  318.         return Database.Cursor.execute(self, query, params)

Exception Type: OperationalError at /admin/auth_test/usertranslatorprofile/
Exception Value: no such table: auth_test_usertranslatorprofile

models.py:

from django.db import models
from django.contrib.auth.models import User

class Language(models.Model):
    shortcut = models.CharField(max_length=6)
    name = models.CharField(max_length=50)
    price_per_sign = models.FloatField()

class UserTranslatorProfile(models.Model):
    user = models.OneToOneField(User)
    languages = models.ManyToManyField(Language)
    price_per_word = models.FloatField()

class UserCustomerProfile(models.Model):
    user = models.OneToOneField(User)

admin.py:

from django import forms
from .models import Language
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class FreelancerRegistrationForm(forms.Form):
    language = forms.ModelChoiceField(queryset=Language.objects.all().order_by('shortcut'))

What is the problem?

Body:
Follow this steps to get fixed this issue.

python manage.py migrate --fake APPNAME zero

This will make your migration to fake. Now you can run the migrate script

python manage.py migrate APPNAME

OR

python manage.py migrate

Tables will be created and you solved your problem.. Cheers!!!


问:
C thread pool efficiency

Possible Duplicate:

  How many threads is too many?

I have a large for loop, in which I want each item to be passed to a function on a thread. I have a thread pool of a certain size, and I want to reuse the threads. What is the most efficient way to do this?

What would be the most efficient size for the thread pool? Or at least what is the best way to figure it out?

```<code>pthread_t thread_id[10];

int i;
for(i = 0; i < 10000000; i++) {
   pthread_create(thread_id[?], NULL, threadFunc, params[i]);
}
</code>```

答:
If all you want is to parallelize a large for loop with independent iterations, maybe you can use OpenMP.

```<code>int i;
#pragma omp parallel for
for(i = 0; i < 10000000; i++) {
    // the body of your loop
}
</code>```

You can select different schedule options and other parameters to tune behavior, including the number of threads if you need; by default, OpenMP will create as many threads as there are hardware contexts available, and divide the work in equal proportion between all threads.

Title: C thread pool efficiency

Body:
Possible Duplicate:

  How many threads is too many?

I have a large for loop, in which I want each item to be passed to a function on a thread. I have a thread pool of a certain size, and I want to reuse the threads. What is the most efficient way to do this?

What would be the most efficient size for the thread pool? Or at least what is the best way to figure it out?

pthread_t thread_id[10];

int i;
for(i = 0; i < 10000000; i++) {
   pthread_create(thread_id[?], NULL, threadFunc, params[i]);
}

Body:
If all you want is to parallelize a large for loop with independent iterations, maybe you can use OpenMP.

int i;
#pragma omp parallel for
for(i = 0; i < 10000000; i++) {
    // the body of your loop
}

You can select different schedule options and other parameters to tune behavior, including the number of threads if you need; by default, OpenMP will create as many threads as there are hardware contexts available, and divide the work in equal proportion between all threads.


问:
How to Close a Connection When Using Jupyter SQL Magic?
I'm using SQL Magic to connect to a db2 instance. However, I can't seem to find the syntax anywhere on how to close the connection when I'm done querying the database.</p>

答: You can also restart the kernel.</p>

Body: You can also restart the kernel.


问:
Selenium vs HtmlUnit?
I am trying to understand testing framework better and been looking into Selenium. I've used HTMLUnit before, mainly when I needed to scrape some information off website or the likes.

In the context of writing test automation, what's the advantage / disadvantages of Selenium vs HTMLUnit? Looks to me Selenium is more complicated to set up than HTMLUnit, although at the same time there's a HTMLUnitDriver for Selenium which I think behave the exact same way as in HTMLUnit itself?

Selenium obviously provides more robust framework, it has the Selenium RC for pararel testing, it also has different browser drivers that can be used - although when you used the browser drivers, the test will actually open/close a browser application rather than headless.

May be I am not understanding Selenium correctly. Some directions and pointers would be great!

On another note - a separate question - I am also looking at doing automated testing on mobile browser, I see that Selenium has an IPhoneDriver for it, but then this is not a headless testing either as it requires actual iOS simulator.

Is there anyway to do headless testing on mobile sites? Would changing user-agent be sufficient? I've seen a couple posts around changing user-agent that seem to have their own challenges, eg. Set user-agent in Selenium RC

Thanks a lot!

答: In my experience, HtmlUnit does a fine job with browsing automation, but might get a bit buggy when dealing with Javascript. I actually came to a case in which I wasn't able to automate an image download with HtmlUnit, and had to turn to Selenium, which performed beyond my expectations. The case is actually registered in an SO thread.</p>

Title: Selenium vs HtmlUnit?


问:
Execute a plugin in Marketing List in Microsoft Dynamics 365
When someone add multiples members (contacts, account, etc) to the Marketing List (entity name "list") I need execute a plugin. Now, I register the plugin with the "Plugin Registration Tool" on this messages (with entity "none") and I got:

Message: AddListMembers:
Don't execute. In this, I set entity "list" too, but nothing change.

Message: AddListMember:
Don't execute.

Message: AddMember:
Executed two times (I add two contact in one time). Almost!!

Message: AddMembers:
Don't execute.

Message: Update:
Don't execute.

Message: Associate:
Don't execute.

How I can known what message is the correct or what is the name for the correct message?

答:
Guido's answer in the Dynamics community forum clearly explains what we need to know:

AddMember is called when a single record is added to the marketing
  list

AddListMembers is called when multiple records are added to the
  marketing list

PLEASE NOTE that when you add members to a marketing list using
  certain ways (for example using advanced find query if I remember
  correctly) that message is not triggered.


问:
oracle 12c - select string after last occurrence of a character
I have below string:

```<code>ThisSentence.ShouldBe.SplitAfterLastPeriod.Sentence
</code>```

So I want to select Sentence since it is the string after the last period. How can I do this?

答:
```<code>select
  substr(
    'ThisSentence.ShouldBe.SplitAfterLastPeriod.Sentence',
    INSTR(
      'ThisSentence.ShouldBe.SplitAfterLastPeriod.Sentence',
      '.',
      -1
    )+1
  )
from dual;
</code>```

Body:
I have below string:

ThisSentence.ShouldBe.SplitAfterLastPeriod.Sentence

So I want to select Sentence since it is the string after the last period. How can I do this?


问:
Use of stroke-dashoffset
I have an arrow that I want to animate so I read about animations and I noticed I can achieve this with css keyframes and svg.

So basically I want to draw an arrow from 0 to 100%, so I have a path like:

```<code> <path class="showUp" fill="#4C9FDC" stroke="#000000" stroke-width= "0" d="M165.15 204.15l-4.49-4.49c-2.13-2.13-5.59-2.14-7.72-.01l-.01.01c-2.13 2.13-2.14 5.59-.01 7.72l.01.01 9.09 9.09a4.418 4.418 0 0 0 6.24 0l50.28-50.28c2.12-2.1 2.13-5.53.03-7.65l-.03-.03c-2.13-2.13-5.59-2.14-7.72-.01l-.01.01-45.66 45.63z"/>
</code>```

And I want to animate with stroke like:

```<code>@keyframes Arrow {
 from {
    stroke-dashoffset: 1000;
  }
  to {
    stroke-dashoffset: 0;
  }
}

.showUp {
  stroke-dasharray: 1000;
  stroke-dashoffset: 1000;
  animation: Arrow 5s linear forwards;
}
</code>```

CodePen

But it just doing nothing. What am I doing wrong there? Regards

答:
Line drawing animations can be achieved in several ways:

Changing the stroke-dashoffset parameters from the maximum equal to the line length to zero:

body{
  background-color: #272727;
}

@keyframes Arrow {
 from {
    stroke-dashoffset: 196;
  }
  to {
    stroke-dashoffset: 0;
  }
}
@keyframes Arrow_Fill {
 from {
    fill: #d3d3d3 ;
  }
  to {
    fill: #FF0000;
  }
}

.showUp {
  stroke-dasharray: 196;
  stroke-dashoffset: 196;
  animation: Arrow 2s linear forwards, Arrow_Fill 1.4s linear 2s forwards;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 792 366.94">

  <path class="showUp" fill="#4C9FDC" stroke="#FF0000" stroke-width= "4" stroke-linecap="round" d="M165.15 204.15l-4.49-4.49c-2.13-2.13-5.59-2.14-7.72-.01l-.01.01c-2.13 2.13-2.14 5.59-.01 7.72l.01.01 9.09 9.09a4.418 4.418 0 0 0 6.24 0l50.28-50.28c2.12-2.1 2.13-5.53.03-7.65l-.03-.03c-2.13-2.13-5.59-2.14-7.72-.01l-.01.01-45.66 45.63z"/>

</svg></code>```

By changing the stroke-dasharray parameters from zero dash and maximum gap to maximum stroke dash  and a gap of zero:

```<code>@keyframes Arrow {
 from {
    stroke-dasharray: 0,196;
  }
  to {
    stroke-dasharray: 196,0;
  }
}
</code>```

body{
  background-color: #151515;
}

@keyframes Arrow {
 from {
    stroke-dasharray: 0,196;
  }
  to {
    stroke-dasharray: 196,0;
  }
}
@keyframes Arrow_Fill {
 from {
    fill: #4C9FDC ;
  }
  to {
    fill: #AAD000;
  }
}

.showUp {
  stroke-dasharray: 0,196;
  animation: Arrow 2s linear forwards, Arrow_Fill 1.4s linear 2s forwards;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 792 366.94">

  <path class="showUp" fill="#4C9FDC" stroke="#AAD000" stroke-width= "2" stroke-linecap="round" d="M165.15 204.15l-4.49-4.49c-2.13-2.13-5.59-2.14-7.72-.01l-.01.01c-2.13 2.13-2.14 5.59-.01 7.72l.01.01 9.09 9.09a4.418 4.418 0 0 0 6.24 0l50.28-50.28c2.12-2.1 2.13-5.53.03-7.65l-.03-.03c-2.13-2.13-5.59-2.14-7.72-.01l-.01.01-45.66 45.63z"/></code>```

Drawing two lines from one midpoint:

body{
  background-color: #151515;
}

@keyframes Arrow {
 from {
    stroke-dasharray: 0,98 0,98 ;
  }
  to {
    stroke-dasharray: 0,0 196,0;
  }
}

@keyframes Arrow_Fill {
 from {
    fill: #4C9FDC ;
  }
  to {
    fill: #AAD000;
  }
}

.showUp {
  stroke-dasharray: 0,98 0,98;
  stroke-dashoffset:75;
  animation: Arrow 2s linear forwards, Arrow_Fill 1.4s linear 2s forwards
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 792 366.94">

  <path class="showUp" fill="#4C9FDC" stroke="#FF0000" stroke-width= "2"  d="M165.15 204.15l-4.49-4.49c-2.13-2.13-5.59-2.14-7.72-.01l-.01.01c-2.13 2.13-2.14 5.59-.01 7.72l.01.01 9.09 9.09a4.418 4.418 0 0 0 6.24 0l50.28-50.28c2.12-2.1 2.13-5.53.03-7.65l-.03-.03c-2.13-2.13-5.59-2.14-7.72-.01l-.01.01-45.66 45.63z"/>

</svg></code>```

Dotted line drawing use  animation of the mask:

.container{

  background-color: #151515;
  width:100vw;
  height:100vh;
}

@keyframes Arrow {
 from {
    stroke-dasharray: 196,0;
  }
  to {
    stroke-dasharray: 0,196;
  }
}

.showUp {
  stroke-dasharray: 196,0;
  stroke-dashoffset:75;
  animation: Arrow 4s linear forwards;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<svg xmlns="http://www.w3.org/2000/svg" width="100%"  viewBox="0 0 792 366.94">

    <defs>
 <mask id="msk1">
    <rect width="100%" height="100%" fill="white" />
   <path class="showUp" fill="white" stroke="black" stroke-width= "1"  d="M165.15 204.15l-4.49-4.49c-2.13-2.13-5.59-2.14-7.72-.01l-.01.01c-2.13 2.13-2.14 5.59-.01 7.72l.01.01 9.09 9.09a4.418 4.418 0 0 0 6.24 0l50.28-50.28c2.12-2.1 2.13-5.53.03-7.65l-.03-.03c-2.13-2.13-5.59-2.14-7.72-.01l-.01.01-45.66 45.63z"/>
 </mask>
 </defs>
  <path  mask="url(#msk1)" fill="#4C9FDC" stroke="greenyellow" stroke-width= "3" stroke-dasharray="4 2" d="M165.15 204.15l-4.49-4.49c-2.13-2.13-5.59-2.14-7.72-.01l-.01.01c-2.13 2.13-2.14 5.59-.01 7.72l.01.01 9.09 9.09a4.418 4.418 0 0 0 6.24 0l50.28-50.28c2.12-2.1 2.13-5.53.03-7.65l-.03-.03c-2.13-2.13-5.59-2.14-7.72-.01l-.01.01-45.66 45.63z"/>

</svg>
</div></code>```

Title: Use of stroke-dashoffset

Body:
I have an arrow that I want to animate so I read about animations and I noticed I can achieve this with css keyframes and svg.

So basically I want to draw an arrow from 0 to 100%, so I have a path like:

 <path class="showUp" fill="#4C9FDC" stroke="#000000" stroke-width= "0" d="M165.15 204.15l-4.49-4.49c-2.13-2.13-5.59-2.14-7.72-.01l-.01.01c-2.13 2.13-2.14 5.59-.01 7.72l.01.01 9.09 9.09a4.418 4.418 0 0 0 6.24 0l50.28-50.28c2.12-2.1 2.13-5.53.03-7.65l-.03-.03c-2.13-2.13-5.59-2.14-7.72-.01l-.01.01-45.66 45.63z"/>

And I want to animate with stroke like:

@keyframes Arrow {
 from {
    stroke-dashoffset: 1000;
  }
  to {
    stroke-dashoffset: 0;
  }
}

.showUp {
  stroke-dasharray: 1000;
  stroke-dashoffset: 1000;
  animation: Arrow 5s linear forwards;
}

CodePen

But it just doing nothing. What am I doing wrong there? Regards

Body:
Line drawing animations can be achieved in several ways:

Changing the stroke-dashoffset parameters from the maximum equal to the line length to zero:

body{
  background-color: #272727;
}

@keyframes Arrow {
 from {
    stroke-dashoffset: 196;
  }
  to {
    stroke-dashoffset: 0;
  }
}
@keyframes Arrow_Fill {
 from {
    fill: #d3d3d3 ;
  }
  to {
    fill: #FF0000;
  }
}

.showUp {
  stroke-dasharray: 196;
  stroke-dashoffset: 196;
  animation: Arrow 2s linear forwards, Arrow_Fill 1.4s linear 2s forwards;

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 792 366.94">

  <path class="showUp" fill="#4C9FDC" stroke="#FF0000" stroke-width= "4" stroke-linecap="round" d="M165.15 204.15l-4.49-4.49c-2.13-2.13-5.59-2.14-7.72-.01l-.01.01c-2.13 2.13-2.14 5.59-.01 7.72l.01.01 9.09 9.09a4.418 4.418 0 0 0 6.24 0l50.28-50.28c2.12-2.1 2.13-5.53.03-7.65l-.03-.03c-2.13-2.13-5.59-2.14-7.72-.01l-.01.01-45.66 45.63z"/>

</svg>

By changing the stroke-dasharray parameters from zero dash and maximum gap to maximum stroke dash  and a gap of zero:

@keyframes Arrow {
 from {
    stroke-dasharray: 0,196;
  }
  to {
    stroke-dasharray: 196,0;
  }
}

body{
  background-color: #151515;
}

@keyframes Arrow {
 from {
    stroke-dasharray: 0,196;
  }
  to {
    stroke-dasharray: 196,0;
  }
}
@keyframes Arrow_Fill {
 from {
    fill: #4C9FDC ;
  }
  to {
    fill: #AAD000;
  }
}

.showUp {
  stroke-dasharray: 0,196;
  animation: Arrow 2s linear forwards, Arrow_Fill 1.4s linear 2s forwards;
}

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 792 366.94">

  <path class="showUp" fill="#4C9FDC" stroke="#AAD000" stroke-width= "2" stroke-linecap="round" d="M165.15 204.15l-4.49-4.49c-2.13-2.13-5.59-2.14-7.72-.01l-.01.01c-2.13 2.13-2.14 5.59-.01 7.72l.01.01 9.09 9.09a4.418 4.418 0 0 0 6.24 0l50.28-50.28c2.12-2.1 2.13-5.53.03-7.65l-.03-.03c-2.13-2.13-5.59-2.14-7.72-.01l-.01.01-45.66 45.63z"/>

Drawing two lines from one midpoint:

body{
  background-color: #151515;
}

@keyframes Arrow {
 from {
    stroke-dasharray: 0,98 0,98 ;
  }
  to {
    stroke-dasharray: 0,0 196,0;
  }
}

@keyframes Arrow_Fill {
 from {
    fill: #4C9FDC ;
  }
  to {
    fill: #AAD000;
  }
}

.showUp {
  stroke-dasharray: 0,98 0,98;
  stroke-dashoffset:75;
  animation: Arrow 2s linear forwards, Arrow_Fill 1.4s linear 2s forwards
}

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 792 366.94">

  <path class="showUp" fill="#4C9FDC" stroke="#FF0000" stroke-width= "2"  d="M165.15 204.15l-4.49-4.49c-2.13-2.13-5.59-2.14-7.72-.01l-.01.01c-2.13 2.13-2.14 5.59-.01 7.72l.01.01 9.09 9.09a4.418 4.418 0 0 0 6.24 0l50.28-50.28c2.12-2.1 2.13-5.53.03-7.65l-.03-.03c-2.13-2.13-5.59-2.14-7.72-.01l-.01.01-45.66 45.63z"/>

</svg>

Dotted line drawing use  animation of the mask:

.container{

  background-color: #151515;
  width:100vw;
  height:100vh;
}

@keyframes Arrow {
 from {
    stroke-dasharray: 196,0;
  }
  to {
    stroke-dasharray: 0,196;
  }
}

.showUp {
  stroke-dasharray: 196,0;
  stroke-dashoffset:75;
  animation: Arrow 4s linear forwards;
}

<div class="container">
<svg xmlns="http://www.w3.org/2000/svg" width="100%"  viewBox="0 0 792 366.94">

    <defs>
 <mask id="msk1">
    <rect width="100%" height="100%" fill="white" />
   <path class="showUp" fill="white" stroke="black" stroke-width= "1"  d="M165.15 204.15l-4.49-4.49c-2.13-2.13-5.59-2.14-7.72-.01l-.01.01c-2.13 2.13-2.14 5.59-.01 7.72l.01.01 9.09 9.09a4.418 4.418 0 0 0 6.24 0l50.28-50.28c2.12-2.1 2.13-5.53.03-7.65l-.03-.03c-2.13-2.13-5.59-2.14-7.72-.01l-.01.01-45.66 45.63z"/>
 </mask>
 </defs>
  <path  mask="url(#msk1)" fill="#4C9FDC" stroke="greenyellow" stroke-width= "3" stroke-dasharray="4 2" d="M165.15 204.15l-4.49-4.49c-2.13-2.13-5.59-2.14-7.72-.01l-.01.01c-2.13 2.13-2.14 5.59-.01 7.72l.01.01 9.09 9.09a4.418 4.418 0 0 0 6.24 0l50.28-50.28c2.12-2.1 2.13-5.53.03-7.65l-.03-.03c-2.13-2.13-5.59-2.14-7.72-.01l-.01.01-45.66 45.63z"/>

</svg>
</div>


问:
R- Every Other Number of a Sequence Negative
I'm trying to generate a series of vectors to calculate the approx. value of Pi using this formula given:
Pi = 4 (1- (1/3) + (1/5) -(1/7)...
for 7 terms.
I made a sequence for the denominator values as such

```<code>number.terms3c <-7
seq.vec3c <- seq(from = 1, by = 2 , length.out = number.terms3c)
</code>```

and would then use that vector to get the reciprocals with

```<code>recip.vec3c <- (1/ seq.vec3c)
</code>```

But in order to sum them, I was thinking I needed to get every other value to be negative (hence the alternating + and - values.

Is there a simple code I can learn to do this?

答:
You can use rep to create what you want to multiply by.

```<code>> recip.vec3c * rep(c(1,-1), length.out = number.terms3c)
[1]  1.00000000 -0.33333333  0.20000000 -0.14285714  0.11111111 -0.09090909
[7]  0.07692308
</code>```

with that said... I only used that to avoid the warning.  If you don't particularly care about that you can be fast and loose with the vector recycling that R does and just multiply by c(1, -1).

```<code>> recip.vec3c * c(1, -1)
[1]  1.00000000 -0.33333333  0.20000000 -0.14285714  0.11111111 -0.09090909
[7]  0.07692308
Warning message:
In recip.vec3c * c(1, -1) :
  longer object length is not a multiple of shorter object length
</code>```

Body:
I'm trying to generate a series of vectors to calculate the approx. value of Pi using this formula given:
Pi = 4 (1- (1/3) + (1/5) -(1/7)...
for 7 terms.
I made a sequence for the denominator values as such

number.terms3c <-7
seq.vec3c <- seq(from = 1, by = 2 , length.out = number.terms3c)

and would then use that vector to get the reciprocals with

recip.vec3c <- (1/ seq.vec3c)

But in order to sum them, I was thinking I needed to get every other value to be negative (hence the alternating + and - values.

Is there a simple code I can learn to do this?

Body:
You can use rep to create what you want to multiply by.

> recip.vec3c * rep(c(1,-1), length.out = number.terms3c)
[1]  1.00000000 -0.33333333  0.20000000 -0.14285714  0.11111111 -0.09090909
[7]  0.07692308

with that said... I only used that to avoid the warning.  If you don't particularly care about that you can be fast and loose with the vector recycling that R does and just multiply by c(1, -1).

> recip.vec3c * c(1, -1)
[1]  1.00000000 -0.33333333  0.20000000 -0.14285714  0.11111111 -0.09090909
[7]  0.07692308
Warning message:
In recip.vec3c * c(1, -1) :
  longer object length is not a multiple of shorter object length


问:
Static field initialization order (C#) - can someone explain this snippet?
I am a C++ programmer learning C#. I am currently reading C#4.0 in a Nutshell.

I have come accross this statement/snipet on page 74:

Static field initializers run in the
  order in which the fields are
  declared. The following example
  illustrates this: X is initialized to
  0 and Y is initialized to 3.

```<code>class Foo
{
    public static int X = Y; // 0
    public static int Y = 3; // 3
}
</code>```

I dont understand how X can be assigned the value in Y, without Y being first declared. Am I missing something here?

As an aside, coming from a C++ background, I tend to use the term ctor for constructor - however, I haven't yet come accross the term in C# - is the term ctor also used in the C# world?

[Edit]

A further example on the same page (in the book mentioned earlier) is this:

```<code>class Program
{
    static void Main() { Console.WriteLine (Foo.X); } // 3
}
class Foo
{
    public static Foo Instance = new Foo();
    public static int X = 3;
    Foo() { Console.WriteLine (X); } // 0
}
</code>```

The book states (for the example above):

The example prints 0 followed by 3
  because the field initializer that
  instantiates a Foo executes before X
  is initialized to 3:

I have some further questions w.r.t the examples.

Both examples appear under the section entitled Static constructors and field initialization order however, the code examples dont show a static ctor - atleast, not one that I can easily recognise. I was expecting a static ctor to have the same name as the class, be parameterless and be preceeded by the 'static' keyword. So I dont see how the examples relate to the section heading. What am I missing here?

In the second example, the (non static) ctor prints out the value of X - which had explicitly been assigned the value of 3 in the previous line - and yet, the output printed out is 0. Why?!

答:
Field declaration doesn't need to be in the order of dependency.

That is, you can use Y above where you declare Y.

The initialization, however, goes like this:

X is initialized first, grabs its value from Y, which is uninitialized, and thus 0 (the default value for an int)

Y is initialized to 3.

Body:
I am a C++ programmer learning C#. I am currently reading C#4.0 in a Nutshell.

I have come accross this statement/snipet on page 74:

Static field initializers run in the
  order in which the fields are
  declared. The following example
  illustrates this: X is initialized to
  0 and Y is initialized to 3.

class Foo
{
    public static int X = Y; // 0
    public static int Y = 3; // 3
}

I dont understand how X can be assigned the value in Y, without Y being first declared. Am I missing something here?

As an aside, coming from a C++ background, I tend to use the term ctor for constructor - however, I haven't yet come accross the term in C# - is the term ctor also used in the C# world?

[Edit]

A further example on the same page (in the book mentioned earlier) is this:

class Program
{
    static void Main() { Console.WriteLine (Foo.X); } // 3
}
class Foo
{
    public static Foo Instance = new Foo();
    public static int X = 3;
    Foo() { Console.WriteLine (X); } // 0
}

The book states (for the example above):

The example prints 0 followed by 3
  because the field initializer that
  instantiates a Foo executes before X
  is initialized to 3:

I have some further questions w.r.t the examples.

Both examples appear under the section entitled Static constructors and field initialization order however, the code examples dont show a static ctor - atleast, not one that I can easily recognise. I was expecting a static ctor to have the same name as the class, be parameterless and be preceeded by the 'static' keyword. So I dont see how the examples relate to the section heading. What am I missing here?

In the second example, the (non static) ctor prints out the value of X - which had explicitly been assigned the value of 3 in the previous line - and yet, the output printed out is 0. Why?!


问:
Issues upgrading from Angular 8 to Angular 9
I'm following the steps in Angular's official updating guide, but am experiencing an issue that doesn't yield many results when I try to look it up.

After the update completes, I see this output:

```<code>Your project has been updated to Angular version 9!
For more info, please see: https://v9.angular.io/guide/updating-to-version-9
</code>```

When I run ng serve, I get this output:

```<code>Schema validation failed with the following errors:
  Data path ".browserTarget" should match pattern "^[^:\s]+:[^:\s]+(:[^\s]+)?$".
</code>```

In angular.json, my serve configuration looks like this:

```<code>    "serve": {
      "builder": "@angular-devkit/build-angular:dev-server",
      "options": {
        "browserTarget": "My Application:build"
      },
</code>```

Here are my dependencies and devDependencies in package.json:

```<code>"dependencies": {
    "@angular-devkit/build-angular": "~0.900.0-rc.12",
    "@angular-devkit/core": "^9.0.0-rc.12",
    "@angular/animations": "^9.0.0-rc.12",
    "@angular/cdk": "^9.0.0-rc.9",
    "@angular/cli": "^9.0.0-rc.12",
    "@angular/common": "^9.0.0-rc.12",
    "@angular/compiler": "^9.0.0-rc.12",
    "@angular/compiler-cli": "^9.0.0-rc.12",
    "@angular/core": "^9.0.0-rc.12",
    "@angular/flex-layout": "8.0.0-beta.27",
    "@angular/forms": "^9.0.0-rc.12",
    "@angular/material": "^9.0.0-rc.9",
    "@angular/material-moment-adapter": "^9.0.0-rc.9",
    "@angular/platform-browser": "^9.0.0-rc.12",
    "@angular/platform-browser-dynamic": "^9.0.0-rc.12",
    "@angular/platform-server": "^9.0.0-rc.12",
    "@angular/router": "^9.0.0-rc.12",
    "@angular/service-worker": "^9.0.0-rc.12",
    "@busacca/ng-pick-datetime": "^8.0.1",
    "@sentry/browser": "^5.4.0",
    "@types/stripe": "^6.25.8",
    "@w11k/ngx-componentdestroyed": "^4.1.4",
    "angular-mentions": "^0.9.1",
    "angular-token": "^7.0.1",
    "angular2-actioncable": "^6.0.2",
    "angular2-json2csv": "1.1.2",
    "angular2-jsonapi": "^7.0.0",
    "aws-sdk": "^2.493.0",
    "browser-image-compression": "^1.0.6",
    "calendar-utils": "0.0.7",
    "convert-keys": "^1.3.4",
    "core-js": "^2.4.1",
    "d3": "^4.13.0",
    "fs": "0.0.2",
    "immutable": "~3.8.2",
    "jshint": "^2.10.2",
    "jspdf": "~1.4.1",
    "jspdf-autotable": "~3.0.13",
    "libphonenumber-js": "^1.7.24",
    "lodash": "^4.17.13",
    "logrocket": "^0.6.20",
    "moment": "2.24.0",
    "net": "^1.0.2",
    "ng-intercom": "8.0.0",
    "ng-sidebar": "~9.1.1",
    "ng2-validation": "~4.2.0",
    "ngx-image-compress": "^8.0.3",
    "ngx-pipes": "~2.5.0",
    "randomvin": "0.0.1",
    "rxjs": "^6.5.4",
    "saturn-datepicker": "^7.4.0",
    "simple-web-notification": "^1.0.32",
    "tls": "0.0.1",
    "tslib": "^1.10.0",
    "typescript": "~3.7.5",
    "uuid": "~3.3.2",
    "vin-generator": "^1.0.1",
    "vin-validator": "^1.0.0",
    "vindec-validator": "^1.1.3",
    "weather-icons": "^1.3.2",
    "webpack": "^4.29.6",
    "xml2js": "^0.4.19",
    "yargs": "^13.2.4",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular/language-service": "^9.0.0-rc.12",
    "@sentry/webpack-plugin": "^1.6.2",
    "@types/jasmine": "^3.3.12",
    "@types/node": "^12.11.1",
    "codelyzer": "^5.1.2",
    "husky": "^3.0.9",
    "jasmine-core": "^3.3.0",
    "jasmine-marbles": "^0.4.1",
    "jasmine-reporters": "^2.3.2",
    "jasmine-spec-reporter": "^4.2.1",
    "karma": "^4.0.1",
    "karma-chrome-launcher": "^2.2.0",
    "karma-cli": "^2.0.0",
    "karma-coverage-istanbul-reporter": "~2.0.5",
    "karma-jasmine": "^2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "karma-junit-reporter": "^1.2.0",
    "karma-parallel": "^0.3.1",
    "lint-staged": "^9.4.3",
    "ng-bullet": "^1.0.3",
    "prettier": "^1.19.1",
    "protractor": "^5.4.2",
    "protractor-screenshot-reporter": "0.0.5",
    "rxjs-tslint": "^0.1.7",
    "ts-node": "~8.0.3",
    "tslint": "^5.20.1",
    "tslint-config-prettier": "^1.18.0",
    "tslint-plugin-prettier": "^2.0.1",
    "webpack-bundle-analyzer": "^3.4.1",
    "webpack-cyclic-dependency-checker": "0.0.1"
  },
</code>```

I haven't been able to find any information on why this is happening. I'd love some help here!

答:
Remove spaces from your project name in angular.json, and update all references to the project name. So replace "My Application" everywhere with "MyApplication" (only use characters that a valid for identifiers in javascript, and "space" isn't one of them).

```<code>...
  "projects": {
    "MyApplication": {
      "projectType": "application",

...

        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "MyApplication:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "MyApplication:build:production"
            }
          }
...

  "defaultProject": "MyApplication"
</code>```

etc...

Body:
I'm following the steps in Angular's official updating guide, but am experiencing an issue that doesn't yield many results when I try to look it up.

After the update completes, I see this output:

Your project has been updated to Angular version 9!
For more info, please see: https://v9.angular.io/guide/updating-to-version-9

When I run ng serve, I get this output:

Schema validation failed with the following errors:
  Data path ".browserTarget" should match pattern "^[^:\s]+:[^:\s]+(:[^\s]+)?$".

In angular.json, my serve configuration looks like this:

    "serve": {
      "builder": "@angular-devkit/build-angular:dev-server",
      "options": {
        "browserTarget": "My Application:build"
      },

Here are my dependencies and devDependencies in package.json:

"dependencies": {
    "@angular-devkit/build-angular": "~0.900.0-rc.12",
    "@angular-devkit/core": "^9.0.0-rc.12",
    "@angular/animations": "^9.0.0-rc.12",
    "@angular/cdk": "^9.0.0-rc.9",
    "@angular/cli": "^9.0.0-rc.12",
    "@angular/common": "^9.0.0-rc.12",
    "@angular/compiler": "^9.0.0-rc.12",
    "@angular/compiler-cli": "^9.0.0-rc.12",
    "@angular/core": "^9.0.0-rc.12",
    "@angular/flex-layout": "8.0.0-beta.27",
    "@angular/forms": "^9.0.0-rc.12",
    "@angular/material": "^9.0.0-rc.9",
    "@angular/material-moment-adapter": "^9.0.0-rc.9",
    "@angular/platform-browser": "^9.0.0-rc.12",
    "@angular/platform-browser-dynamic": "^9.0.0-rc.12",
    "@angular/platform-server": "^9.0.0-rc.12",
    "@angular/router": "^9.0.0-rc.12",
    "@angular/service-worker": "^9.0.0-rc.12",
    "@busacca/ng-pick-datetime": "^8.0.1",
    "@sentry/browser": "^5.4.0",
    "@types/stripe": "^6.25.8",
    "@w11k/ngx-componentdestroyed": "^4.1.4",
    "angular-mentions": "^0.9.1",
    "angular-token": "^7.0.1",
    "angular2-actioncable": "^6.0.2",
    "angular2-json2csv": "1.1.2",
    "angular2-jsonapi": "^7.0.0",
    "aws-sdk": "^2.493.0",
    "browser-image-compression": "^1.0.6",
    "calendar-utils": "0.0.7",
    "convert-keys": "^1.3.4",
    "core-js": "^2.4.1",
    "d3": "^4.13.0",
    "fs": "0.0.2",
    "immutable": "~3.8.2",
    "jshint": "^2.10.2",
    "jspdf": "~1.4.1",
    "jspdf-autotable": "~3.0.13",
    "libphonenumber-js": "^1.7.24",
    "lodash": "^4.17.13",
    "logrocket": "^0.6.20",
    "moment": "2.24.0",
    "net": "^1.0.2",
    "ng-intercom": "8.0.0",
    "ng-sidebar": "~9.1.1",
    "ng2-validation": "~4.2.0",
    "ngx-image-compress": "^8.0.3",
    "ngx-pipes": "~2.5.0",
    "randomvin": "0.0.1",
    "rxjs": "^6.5.4",
    "saturn-datepicker": "^7.4.0",
    "simple-web-notification": "^1.0.32",
    "tls": "0.0.1",
    "tslib": "^1.10.0",
    "typescript": "~3.7.5",
    "uuid": "~3.3.2",
    "vin-generator": "^1.0.1",
    "vin-validator": "^1.0.0",
    "vindec-validator": "^1.1.3",
    "weather-icons": "^1.3.2",
    "webpack": "^4.29.6",
    "xml2js": "^0.4.19",
    "yargs": "^13.2.4",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular/language-service": "^9.0.0-rc.12",
    "@sentry/webpack-plugin": "^1.6.2",
    "@types/jasmine": "^3.3.12",
    "@types/node": "^12.11.1",
    "codelyzer": "^5.1.2",
    "husky": "^3.0.9",
    "jasmine-core": "^3.3.0",
    "jasmine-marbles": "^0.4.1",
    "jasmine-reporters": "^2.3.2",
    "jasmine-spec-reporter": "^4.2.1",
    "karma": "^4.0.1",
    "karma-chrome-launcher": "^2.2.0",
    "karma-cli": "^2.0.0",
    "karma-coverage-istanbul-reporter": "~2.0.5",
    "karma-jasmine": "^2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "karma-junit-reporter": "^1.2.0",
    "karma-parallel": "^0.3.1",
    "lint-staged": "^9.4.3",
    "ng-bullet": "^1.0.3",
    "prettier": "^1.19.1",
    "protractor": "^5.4.2",
    "protractor-screenshot-reporter": "0.0.5",
    "rxjs-tslint": "^0.1.7",
    "ts-node": "~8.0.3",
    "tslint": "^5.20.1",
    "tslint-config-prettier": "^1.18.0",
    "tslint-plugin-prettier": "^2.0.1",
    "webpack-bundle-analyzer": "^3.4.1",
    "webpack-cyclic-dependency-checker": "0.0.1"
  },

I haven't been able to find any information on why this is happening. I'd love some help here!

Body:
Remove spaces from your project name in angular.json, and update all references to the project name. So replace "My Application" everywhere with "MyApplication" (only use characters that a valid for identifiers in javascript, and "space" isn't one of them).

...
  "projects": {
    "MyApplication": {
      "projectType": "application",

...

        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "MyApplication:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "MyApplication:build:production"
            }
          }
...

  "defaultProject": "MyApplication"

etc...


问:
How can I check in javascript if it's day time or night time on the client?
Using date-nfs, how can I check if new Date() is between 8am and 8pm?

答: You don't need to use external libraries, you can simply get the current hour by new Date().getHours(), and check if it's more then 20 or less then 8.


问:
Conversion of string to dictionary
I have captured a string from a REST get request and have placed it in a variable. The string is:

```<code> {"name":"na1mailboxarchive","objectCount":49564710,"dataBytes":36253526882451},{"name":"na1mailboxarchive2","objectCount":17616567,"dataBytes":13409204616615}
</code>```

I am trying to convert it to a dictionary so I can increment through it and capture the bucket name, size and object count. I have tried eval()

```<code>bucket_dict = eval(bucket_info)
</code>```

but the program errors out with a:

```<code>Traceback (most recent call last):
  File "./test.py", line 83, in <module>
    for k,b in bucket_dict.items():
AttributeError: 'tuple' object has no attribute 'items'
</code>```

When I print the value of bucket_dict I get:

```<code>({'name': 'na1mailboxarchive', 'objectCount': 49564710, 'dataBytes': 36253526882451}, {'name': 'na1mailboxarchive2', 'objectCount': 17616567, 'dataBytes': 13409204616615})
</code>```

I think the foul up is the () at the beginning and the end of the dictionary. Nothing else I have tried works either.

答:
I got it figured out.

Firstly the json return from the REST API get is badly formatted. I will take that up with the vendor. Secondly I used some iof the infrmation form @PrashantKumar and @MisterMiyagi to sus out the issue I was having. In my original code I had loaded the list with:

```<code>bucket_info = [acct_string[acct_string_start+11:acct_len-4]]
</code>```

The variable was capturing the leading "[" and trailing "]" as a part of the string. Once I removed them then the list behaved correctly and I now can work with it. Thank you for the information and the trail markers.

Title: Conversion of string to dictionary

Body:
I have captured a string from a REST get request and have placed it in a variable. The string is:

 {"name":"na1mailboxarchive","objectCount":49564710,"dataBytes":36253526882451},{"name":"na1mailboxarchive2","objectCount":17616567,"dataBytes":13409204616615}

I am trying to convert it to a dictionary so I can increment through it and capture the bucket name, size and object count. I have tried eval()

bucket_dict = eval(bucket_info)

but the program errors out with a:

Traceback (most recent call last):
  File "./test.py", line 83, in <module>
    for k,b in bucket_dict.items():
AttributeError: 'tuple' object has no attribute 'items'

When I print the value of bucket_dict I get:

({'name': 'na1mailboxarchive', 'objectCount': 49564710, 'dataBytes': 36253526882451}, {'name': 'na1mailboxarchive2', 'objectCount': 17616567, 'dataBytes': 13409204616615})

I think the foul up is the () at the beginning and the end of the dictionary. Nothing else I have tried works either.

Body:
I got it figured out.

Firstly the json return from the REST API get is badly formatted. I will take that up with the vendor. Secondly I used some iof the infrmation form @PrashantKumar and @MisterMiyagi to sus out the issue I was having. In my original code I had loaded the list with:

bucket_info = [acct_string[acct_string_start+11:acct_len-4]]

The variable was capturing the leading "[" and trailing "]" as a part of the string. Once I removed them then the list behaved correctly and I now can work with it. Thank you for the information and the trail markers.


问:
Why the value of "count" is showig 1 instead of 2?
In my below code I was trying to find the number of words that are in between "-", so I used string.Equals(), but it is not working. And just incrementing the value of "count" in the print section.</p>

```<code>static void Main()
{
    int count=0, i;
    string inputString = "Anupam-Datta";
    Console.WriteLine(inputString.Length);
    for(i = 0; i < inputString.Length; i++)
    {
        if(inputString[i].Equals("-"))
            count++;
    }
    Console.WriteLine("Number of words: {0}", ++count);
}
</code>```

答:
If you need the number of words, which are separated by the char "-", try this:</p>

```<code>public static void Main()
{
    string s = "Anupam-Datta";
    int count = s.Split('-').Count();
    Console.WriteLine($"Numer of words: {count}.");
}
</code>```

Body:
In my below code I was trying to find the number of words that are in between "-", so I used string.Equals(), but it is not working. And just incrementing the value of "count" in the print section.

static void Main()
{
    int count=0, i;
    string inputString = "Anupam-Datta";
    Console.WriteLine(inputString.Length);
    for(i = 0; i < inputString.Length; i++)
    {
        if(inputString[i].Equals("-"))
            count++;
    }
    Console.WriteLine("Number of words: {0}", ++count);
}

Body:
If you need the number of words, which are separated by the char "-", try this:

public static void Main()
{
    string s = "Anupam-Datta";
    int count = s.Split('-').Count();
    Console.WriteLine($"Numer of words: {count}.");
}


答: getHours() on the date object will be an integer between 0 and 23. So you could check if it's between 8 and 20

Title: How can I check in javascript if it's day time or night time on the client?

Body: Using date-nfs, how can I check if new Date() is between 8am and 8pm?


问:
MongoDB Custom Serializer not setting properties
Whenever using a custom serializer it sets the property value correctly in the database but the property on the object remains the default value.

Custom Serializer:

```<code>public class RngSerializer : SerializerBase<int>
{
    public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, int value)
    {
        var rng = new Random().Next(0, 100);
        Console.WriteLine($"Generated rng {rng}");
        context.Writer.WriteInt32(rng);
    }
}
</code>```

The object:

```<code>public class Entity
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }

    [BsonSerializer(typeof(RngSerializer))]
    public int RngProp { get; set; }
}
</code>```

The code that does the inserting:

```<code>var entity = new Entity();
collection.InsertOne(entity);
Console.WriteLine($"Inserted Id {entity.Id}, Rng {entity.RngProp}");
</code>```

You can see that the serializer is called corrected, the value is also set when I check the object in the database. However, the driver doesn't seem to correctly set the property.

Generated rng 32

Inserted Id 5e4ade582c509931f4467e38, Rng 0

答:
I found a solution by triggering the Serializer before the Insert happens like this;

```<code>        var bson = entity.ToBson();
        var hydrated = BsonSerializer.Deserialize<Entity>(bson);
        collection.InsertOne(hydrated);
        hydrated.Id = entity.Id;
</code>```

And changing the Serializer accordingly to;

```<code>public class RngSerializer : SerializerBase<int>
{
    #region Overrides of SerializerBase<int>

    public override int Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
    {
        return context.Reader.ReadInt32();
    }

    #endregion

    public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, int value)
    {
        //This part is important otherwise it will call the rng twice, once when the ToBson() is called and once when inserting.
        if (value == 0)
        {
            var rng = new Random().Next(0, 100);
            Console.WriteLine($"Generated rng {rng}");
            context.Writer.WriteInt32(rng);
        }
        else
        {
            context.Writer.WriteInt32(value);
        }
    }
}
</code>```

It might not be the most elegant way with the double serialization, but it gives me the expected results.

Body:
Whenever using a custom serializer it sets the property value correctly in the database but the property on the object remains the default value.

Custom Serializer:

public class RngSerializer : SerializerBase<int>
{
    public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, int value)
    {
        var rng = new Random().Next(0, 100);
        Console.WriteLine($"Generated rng {rng}");
        context.Writer.WriteInt32(rng);
    }
}

The object:

public class Entity
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }

    [BsonSerializer(typeof(RngSerializer))]
    public int RngProp { get; set; }
}

The code that does the inserting:

var entity = new Entity();
collection.InsertOne(entity);
Console.WriteLine($"Inserted Id {entity.Id}, Rng {entity.RngProp}");

You can see that the serializer is called corrected, the value is also set when I check the object in the database. However, the driver doesn't seem to correctly set the property.

Generated rng 32

Inserted Id 5e4ade582c509931f4467e38, Rng 0

Body:
I found a solution by triggering the Serializer before the Insert happens like this;

        var bson = entity.ToBson();
        var hydrated = BsonSerializer.Deserialize<Entity>(bson);
        collection.InsertOne(hydrated);
        hydrated.Id = entity.Id;

And changing the Serializer accordingly to;

public class RngSerializer : SerializerBase<int>
{
    #region Overrides of SerializerBase<int>

    public override int Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
    {
        return context.Reader.ReadInt32();
    }

    #endregion

    public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, int value)
    {
        //This part is important otherwise it will call the rng twice, once when the ToBson() is called and once when inserting.
        if (value == 0)
        {
            var rng = new Random().Next(0, 100);
            Console.WriteLine($"Generated rng {rng}");
            context.Writer.WriteInt32(rng);
        }
        else
        {
            context.Writer.WriteInt32(value);
        }
    }
}

It might not be the most elegant way with the double serialization, but it gives me the expected results.


问:
How to sum two rows by a simple condition in a data frame
I'd like to sum rows 2 by 2, in order to study the lag of certain variable.

Suppose that I have the following the data base:

```<code>> SE eggs
  4  2.0
  6  4.0
  7 10.0
  8  0.5
  5  1.0
  1  3.0
  2  6.0
  3  9.0
</code>```

So, I expected to obtain the following, where eggsare the sum of the indexes "SE"'s:

```<code>> df
    SE2    eggs
  "4+5"    3
  "6+7"    14
  "8+1"    3.5
  "2+3"    15
</code>```

Where

```<code>df = data.frame(SE=c(4,6,7,8,5,1,2,3),eggs = c(2,4,10,0.5,1,3,6,9))
</code>```

Obs.: Don't mater the order of the data frame, but I need to start from certain number (in this case, number 4), and then take the next number, in this case, number 5, and keep this logic. After SE 6+7, SE 8+1, SE 2+3...

Any hint on how can I do that?

答:
Match c(4:8, 1:3) to SE using the match indexes to index into eggs, reshape into a 2x4 matrix and sum each column.

```<code>k <- 4   # starting index
nr <- nrow(df)  # no of rows in df

with(df, colSums(matrix(eggs[match(c(k:nr, seq_len(k-1)), SE)], 2)))
## [1] 3.0 14.0  3.5 15.0
</code>```

Body:
I'd like to sum rows 2 by 2, in order to study the lag of certain variable.

Suppose that I have the following the data base:

> SE eggs
  4  2.0
  6  4.0
  7 10.0
  8  0.5
  5  1.0
  1  3.0
  2  6.0
  3  9.0

So, I expected to obtain the following, where eggsare the sum of the indexes "SE"'s:

> df
    SE2    eggs
  "4+5"    3
  "6+7"    14
  "8+1"    3.5
  "2+3"    15

Where

df = data.frame(SE=c(4,6,7,8,5,1,2,3),eggs = c(2,4,10,0.5,1,3,6,9))

Obs.: Don't mater the order of the data frame, but I need to start from certain number (in this case, number 4), and then take the next number, in this case, number 5, and keep this logic. After SE 6+7, SE 8+1, SE 2+3...

Any hint on how can I do that?

Body:
Match c(4:8, 1:3) to SE using the match indexes to index into eggs, reshape into a 2x4 matrix and sum each column.

k <- 4   # starting index
nr <- nrow(df)  # no of rows in df

with(df, colSums(matrix(eggs[match(c(k:nr, seq_len(k-1)), SE)], 2)))
## [1] 3.0 14.0  3.5 15.0


问:
I have a vector that has pointers to elements from 2 subtypes accessed via an interface. Can't seem to re-arrange the vector
I'm working on a really over engineered matrix calculator for school and hit a brick wall with the very last function I need. The full version of the transpose() is supposed to re-arrange my matrix and to switch columns and rows around.

I posted this question earlier with a snippet but was asked to write a minimum reproducable sample. This isn't very "minimum" but I tried.

So. I have a std::vector<std::unique_ptr<Interface>> that can hold objects of types Sub1 and Sub2.

In the full version I have a class that bypasses Interface and works fine since it only holds Sub2 objects.

However I can't seem to get it to work when there are multiple types in the vector. Nothing I've tried in the past few hours has done anything.

```<code>#include <iostream>
#include "main.h"
#include <memory>
#include <utility>
#include <vector>
#include <sstream>

//this is the one that won't work
Super Super::transpose() const {
    Super newMatrix = *this;
    int i = 1;
    for(auto& elem : elements){
        *elem = *newMatrix.elements[i];
        i--;
    }
return *this;
}

int main() {
    std::vector<std::unique_ptr<Interface>> newMatrix;
    newMatrix.push_back(std::unique_ptr<Sub1>(new Sub1('x')));
    newMatrix.push_back(std::unique_ptr<Sub2>(new Sub2(1)));
    Super mtx(std::move(newMatrix),2 );
    std::cout << mtx << std::endl;
    mtx.transpose();
    std::cout << mtx;
    return 0;
}

//busywork from here on
Super::Super(std::vector<std::unique_ptr<Interface>> matrix, int pN){
    elements = std::move(matrix);
    n = pN;
}

std::unique_ptr<Interface> Sub1::clone() const {
    char newVal = val;
    return std::unique_ptr<Sub1>(new Sub1(newVal));
}

std::unique_ptr<Interface> Sub2::clone() const {
    int newVal = i;
    return std::unique_ptr<Sub2>(new Sub2(newVal));
}

Sub1::Sub1(char pVal) {
    val = pVal;
}

Sub2::Sub2(int pI) {
    i = pI;
}

std::string Sub1::toString() const {
    std::stringstream ss;
    ss << val;
    return ss.str();
}

std::string Sub2::toString() const {
    std::stringstream ss;
    ss << i;
    return ss.str();
}

std::ostream &operator<<(std::ostream &os, const Super &matrix) {
    os << "[";
    int i = 0;
    for (auto &elem : matrix.elements) {
        os << elem->toString();
        if (i < matrix.n - 1) {
            os << ",";
        }
        i++;
    }
    os << "]";
    return os;
}

Super::Super(const Super &matrix) {
    n = matrix.n;
    for (auto &elem : matrix.elements) {
        std::unique_ptr<Interface> newElem = elem->clone();
        elements.push_back(std::move(newElem));
    }
}
</code>```

And heres the header

```<code>#ifndef EXAMPLE_MAIN_H
#define EXAMPLE_MAIN_H

#include <memory>
#include <vector>

class Interface{
public:
    virtual ~Interface() = default;
    virtual std::unique_ptr<Interface> clone() const = 0;
    virtual std::string toString() const = 0;
};

class Super{
private:
    std::vector<std::unique_ptr<Interface>> elements;
    int n = 2;
public:
    Super(std::vector<std::unique_ptr<Interface>> elements, int n);
    Super(const Super &matrix);
    Super transpose() const;
    friend std::ostream &operator<<(std::ostream &os, const Super &matrix);
};

class Sub1: public Interface{
private:
    char val;
public:
    Sub1(char pVal);
    std::string toString() const override;
    std::unique_ptr<Interface> clone() const override;
};

class Sub2: public Interface{
private:
    int i;
public:
    Sub2(int pI);
    std::string toString() const override;
    std::unique_ptr<Interface> clone() const override;
};

std::ostream &operator<<(std::ostream &os, const Super &matrix);

#endif //EXAMPLE_MAIN_H
</code>```

答:
I came up with this hideous thing to fix it. I'd have liked it to to transpose the matrix nicely in it's place but it looks like it isn's happening tonight. So instead im creating a new object.  </p>

```<code>Super::Super(Super &&matrix) {
   elements = std::move(matrix.elements);
   n = matrix.n;
}

//this was the one that wouldn't work
Super Super::transpose() const {
    Super newMatrix = *this;
    Super anotherOne = *this;
    anotherOne.elements.clear();
    for(int i = 1; i > -1; i--){
        anotherOne.elements.push_back(std::move(newMatrix.elements[i]));
    }
    return anotherOne;
 }

int main() {
    std::vector<std::unique_ptr<Interface>> newMatrix;
   newMatrix.push_back(std::unique_ptr<Sub1>(new Sub1('x')));
   newMatrix.push_back(std::unique_ptr<Sub2>(new Sub2(1)));
   Super mtx(std::move(newMatrix),2 );
   std::cout << mtx << std::endl;
   Super aa(std::move(mtx.transpose()));
   std::cout << aa;
   return 0;
}
</code>```

Body:
I'm working on a really over engineered matrix calculator for school and hit a brick wall with the very last function I need. The full version of the transpose() is supposed to re-arrange my matrix and to switch columns and rows around.

I posted this question earlier with a snippet but was asked to write a minimum reproducable sample. This isn't very "minimum" but I tried.

So. I have a std::vector<std::unique_ptr<Interface>> that can hold objects of types Sub1 and Sub2.

In the full version I have a class that bypasses Interface and works fine since it only holds Sub2 objects.

However I can't seem to get it to work when there are multiple types in the vector. Nothing I've tried in the past few hours has done anything.

#include <iostream>
#include "main.h"
#include <memory>
#include <utility>
#include <vector>
#include <sstream>

//this is the one that won't work
Super Super::transpose() const {
    Super newMatrix = *this;
    int i = 1;
    for(auto& elem : elements){
        *elem = *newMatrix.elements[i];
        i--;
    }
return *this;
}

int main() {
    std::vector<std::unique_ptr<Interface>> newMatrix;
    newMatrix.push_back(std::unique_ptr<Sub1>(new Sub1('x')));
    newMatrix.push_back(std::unique_ptr<Sub2>(new Sub2(1)));
    Super mtx(std::move(newMatrix),2 );
    std::cout << mtx << std::endl;
    mtx.transpose();
    std::cout << mtx;
    return 0;
}

//busywork from here on
Super::Super(std::vector<std::unique_ptr<Interface>> matrix, int pN){
    elements = std::move(matrix);
    n = pN;
}

std::unique_ptr<Interface> Sub1::clone() const {
    char newVal = val;
    return std::unique_ptr<Sub1>(new Sub1(newVal));
}

std::unique_ptr<Interface> Sub2::clone() const {
    int newVal = i;
    return std::unique_ptr<Sub2>(new Sub2(newVal));
}

Sub1::Sub1(char pVal) {
    val = pVal;
}

Sub2::Sub2(int pI) {
    i = pI;
}

std::string Sub1::toString() const {
    std::stringstream ss;
    ss << val;
    return ss.str();
}

std::string Sub2::toString() const {
    std::stringstream ss;
    ss << i;
    return ss.str();
}

std::ostream &operator<<(std::ostream &os, const Super &matrix) {
    os << "[";
    int i = 0;
    for (auto &elem : matrix.elements) {
        os << elem->toString();
        if (i < matrix.n - 1) {
            os << ",";
        }
        i++;
    }
    os << "]";
    return os;
}

Super::Super(const Super &matrix) {
    n = matrix.n;
    for (auto &elem : matrix.elements) {
        std::unique_ptr<Interface> newElem = elem->clone();
        elements.push_back(std::move(newElem));
    }
}

And heres the header

#ifndef EXAMPLE_MAIN_H
#define EXAMPLE_MAIN_H

#include <memory>
#include <vector>

class Interface{
public:
    virtual ~Interface() = default;
    virtual std::unique_ptr<Interface> clone() const = 0;
    virtual std::string toString() const = 0;
};

class Super{
private:
    std::vector<std::unique_ptr<Interface>> elements;
    int n = 2;
public:
    Super(std::vector<std::unique_ptr<Interface>> elements, int n);
    Super(const Super &matrix);
    Super transpose() const;
    friend std::ostream &operator<<(std::ostream &os, const Super &matrix);
};

class Sub1: public Interface{
private:
    char val;
public:
    Sub1(char pVal);
    std::string toString() const override;
    std::unique_ptr<Interface> clone() const override;
};

class Sub2: public Interface{
private:
    int i;
public:
    Sub2(int pI);
    std::string toString() const override;
    std::unique_ptr<Interface> clone() const override;
};

std::ostream &operator<<(std::ostream &os, const Super &matrix);

#endif //EXAMPLE_MAIN_H

Body:
I came up with this hideous thing to fix it. I'd have liked it to to transpose the matrix nicely in it's place but it looks like it isn's happening tonight. So instead im creating a new object.

Super::Super(Super &&matrix) {
   elements = std::move(matrix.elements);
   n = matrix.n;
}

//this was the one that wouldn't work
Super Super::transpose() const {
    Super newMatrix = *this;
    Super anotherOne = *this;
    anotherOne.elements.clear();
    for(int i = 1; i > -1; i--){
        anotherOne.elements.push_back(std::move(newMatrix.elements[i]));
    }
    return anotherOne;
 }

int main() {
    std::vector<std::unique_ptr<Interface>> newMatrix;
   newMatrix.push_back(std::unique_ptr<Sub1>(new Sub1('x')));
   newMatrix.push_back(std::unique_ptr<Sub2>(new Sub2(1)));
   Super mtx(std::move(newMatrix),2 );
   std::cout << mtx << std::endl;
   Super aa(std::move(mtx.transpose()));
   std::cout << aa;
   return 0;
}


问:
function is overriding variable declared in other scope
I have to functions both using i as an iterator.
One function is using the other.
I thought local Variables cant be changed by other scopes.
But now "i" is changed after the "createOptions" function.
Is it possible that the value is passed by the object?</p>

```<code>    function createOptions(array) {
       var optionArray = [];
       for (i=0;i<array.length;i++) {
         var option = $("<option></option").text(array[i]);
         $(option).attr("value", array[i]);
         optionArray.push(option);
       }
       return optionArray;
     }

     function buildForm(players) {
       var form = $("<form></form>");
       for (i=0; i<4; i++) {
         var playernumber = "player " + (i+1).toString();
         var select = $("<select></select>").attr({
          "id" : playernumber,
          "onchange" : "addNewPlayer(this)"
         });
         var selectPlayerOption = $("<option></option>").text("-- select Player --");
         $(selectPlayerOption).attr({
           "disabled" : true,
           "selected" : true
         })
         var newPlayerOption = $("<option></option>").text("New Player");
         var playerOptions = createOptions(players);
         console.log(playerOptions.j);
         $(select).append(selectPlayerOption, newPlayerOption, playerOptions);
         $(form).append(select);
       }
       $("#maincontent").append(form);
     }
</code>```

答:
that is normal your function buildForm is using i as an iterator and when CreateOption is called inside buildForm function it value is reassigned to 0 because of this line for (i=0;i<array.length;i++) in createOption function.
So unless you want to use i in both functions i suggest to use two differents iterators i and j for example

Body:
I have to functions both using i as an iterator.
One function is using the other.
I thought local Variables cant be changed by other scopes.
But now "i" is changed after the "createOptions" function.
Is it possible that the value is passed by the object?

    function createOptions(array) {
       var optionArray = [];
       for (i=0;i<array.length;i++) {
         var option = $("<option></option").text(array[i]);
         $(option).attr("value", array[i]);
         optionArray.push(option);
       }
       return optionArray;
     }

     function buildForm(players) {
       var form = $("<form></form>");
       for (i=0; i<4; i++) {
         var playernumber = "player " + (i+1).toString();
         var select = $("<select></select>").attr({
          "id" : playernumber,
          "onchange" : "addNewPlayer(this)"
         });
         var selectPlayerOption = $("<option></option>").text("-- select Player --");
         $(selectPlayerOption).attr({
           "disabled" : true,
           "selected" : true
         })
         var newPlayerOption = $("<option></option>").text("New Player");
         var playerOptions = createOptions(players);
         console.log(playerOptions.j);
         $(select).append(selectPlayerOption, newPlayerOption, playerOptions);
         $(form).append(select);
       }
       $("#maincontent").append(form);
     }


问:
Adding a "New Button" option on Access form
Please forgive me if this question is too vague or extensive.  I have limited experience with Access, SQL, and VBA and have a problem at work that I just can't solve.  I'm trying to add a "new button" button to the user interface on our Access database.

I would like it to maybe bring up another form that allows you to input a query you want to make into a quick link on the home page.  Obviously this would only be accessible to certain users but I can handle that part.

I don't necessarily need the code written, just an idea of where to start.  So far all I've been able to do is hard code a new query or link into a button each team I want to make one.  I want this process to be simplified so that anybody can make a button even if they don't know how to use Access very well.

Again, any help would be greatly appreciated and feel free to tell me to get lost if this is too vast or general a question.

答:
```<code>I would like it to maybe bring up another form that allows you to input a query
</code>```

The above seems very confusing. You are asking how a form can be used or launched or displayed to allow the user to add a new record. Then you toss in this VERY unrelated concept of some query? What does some query have to do with adding a new record?

If you want to add a new record, and you are in a form that is displaying current records, then behind the button, you can execute this line of code to jump to a new record ready for data entry:

```<code>DoCmd.GoToRecord , , acNewRec
</code>```

So, that is one line of code.

If you want to launch an existing form and have it start out with a new clean fresh record, then use this:

```<code>DoCmd.OpenForm "frmCustomers", , , , acFormAdd
</code>```

The above will launch the given from in "add mode" and thus you are again on a new fresh record ready for data entry.

The issue(s) of some query etc. for the user What does that have to do with wanting the user to add a new record? So that part does not seem to apply to the basic idea of presenting a form with a new record which allows the user to add that record in question.

You have to explain what all the hub bub about this magic query issue but to jump a form to a new record for the user? Just use the first line of code behind a button.

And if you need to launch a form in "add mode", then use the 2nd example one line of code behind the button in question. None of this has really anything to do with some "query" in regards to you wanting the user to add a new record. You can expand on what you mean by some user query, but you have several options to jump an existing form to a new record, or launch a form in "add mode" to allow adding of a record. In these cases, you don't need nor want to write or deal with some SQL query.

Body:
I would like it to maybe bring up another form that allows you to input a query

The above seems very confusing. You are asking how a form can be used or launched or displayed to allow the user to add a new record. Then you toss in this VERY unrelated concept of some query? What does some query have to do with adding a new record?

If you want to add a new record, and you are in a form that is displaying current records, then behind the button, you can execute this line of code to jump to a new record ready for data entry:

DoCmd.GoToRecord , , acNewRec

So, that is one line of code.

If you want to launch an existing form and have it start out with a new clean fresh record, then use this:

DoCmd.OpenForm "frmCustomers", , , , acFormAdd

The above will launch the given from in "add mode" and thus you are again on a new fresh record ready for data entry.

The issue(s) of some query etc. for the user What does that have to do with wanting the user to add a new record? So that part does not seem to apply to the basic idea of presenting a form with a new record which allows the user to add that record in question.

You have to explain what all the hub bub about this magic query issue but to jump a form to a new record for the user? Just use the first line of code behind a button.

And if you need to launch a form in "add mode", then use the 2nd example one line of code behind the button in question. None of this has really anything to do with some "query" in regards to you wanting the user to add a new record. You can expand on what you mean by some user query, but you have several options to jump an existing form to a new record, or launch a form in "add mode" to allow adding of a record. In these cases, you don't need nor want to write or deal with some SQL query.


问:
Just trying out to check whether the value is present in array or not
I am trying to write a function in jQuery.

var arr1 = ["Jcob", "Pete", "Fin", "John"];
var str = $("#fname").val();
if (jQuery.inArray(str, arr1))
  $("#lname").text("Bob");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="fname" name="fname">
<input type="text" id="lname" name="lname"></code>```

Please check my fiddle here

What it will do it the user will give the value in the first input box the jQuery function will check if the value is present in that array it will fill the second input box with the given text.

答:
Three things:

You need to add an event listener to the first input to constantly keep checking when someone inputs something.

Before selecting elements in the DOM, make sure the DOM is ready.

You don't need jQuery at all here. Like most things, very easy to do without jQuery.

const names = [ "Jcob", "Pete", "Fin", "John" ];
document.addEventListener('DOMContentLoaded', function() {
  const fname = document.getElementById('fname');
  const lname = document.getElementById('lname');
  fname.addEventListener('input', function(event) {
    lname.value = names.includes(fname.value) ? 'Bob' : '';
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="fname" name="fname">
<input type="text" id="lname" name="lname"></code>```

If you insist on jQuery (which I do strongly recommend you shouldn't until you are proficient with the native DOM API):

const names = [ "Jcob", "Pete", "Fin", "John" ];
$(document).ready(function() {
  const $fname = $('#fname');
  const $lname = $('#lname');
  $fname.on('input', function(event) {
    if ($.inArray($fname.val(), names) > -1) {
      $lname.val('Bob');
    } else {
      $lname.val('');
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="fname" name="fname">
<input type="text" id="lname" name="lname"></code>```

Body:
I am trying to write a function in jQuery.

var arr1 = ["Jcob", "Pete", "Fin", "John"];
var str = $("#fname").val();
if (jQuery.inArray(str, arr1))
  $("#lname").text("Bob");

<input type="text" id="fname" name="fname">
<input type="text" id="lname" name="lname">

Please check my fiddle here

What it will do it the user will give the value in the first input box the jQuery function will check if the value is present in that array it will fill the second input box with the given text.

Body:
Three things:

You need to add an event listener to the first input to constantly keep checking when someone inputs something.

Before selecting elements in the DOM, make sure the DOM is ready.

You don't need jQuery at all here. Like most things, very easy to do without jQuery.

const names = [ "Jcob", "Pete", "Fin", "John" ];
document.addEventListener('DOMContentLoaded', function() {
  const fname = document.getElementById('fname');
  const lname = document.getElementById('lname');
  fname.addEventListener('input', function(event) {
    lname.value = names.includes(fname.value) ? 'Bob' : '';
  });
});

<input type="text" id="fname" name="fname">
<input type="text" id="lname" name="lname">

If you insist on jQuery (which I do strongly recommend you shouldn't until you are proficient with the native DOM API):

const names = [ "Jcob", "Pete", "Fin", "John" ];
$(document).ready(function() {
  const $fname = $('#fname');
  const $lname = $('#lname');
  $fname.on('input', function(event) {
    if ($.inArray($fname.val(), names) > -1) {
      $lname.val('Bob');
    } else {
      $lname.val('');
    }
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="fname" name="fname">
<input type="text" id="lname" name="lname">


问:
Use placeholders in YAML
Is there a way to use placeholders in YAML like this:</p>
```<code>foo: &FOO
    <<propname>>:
        type: number
        default: <<default>>

bar:
    - *FOO
       propname: "some_prop"
       default: "some default"
</code>```

答:
With Yglu Structural Templating, your example can be written:

```<code>foo: !()
  !? $.propname:
     type: number
     default: !? $.default

bar:
  !apply .foo:
    propname: "some_prop"
    default: "some default"
</code>```

Disclaimer: I am the author of Yglu.

Title: Use placeholders in YAML

Body:
Is there a way to use placeholders in YAML like this:

foo: &FOO
    <<propname>>:
        type: number
        default: <<default>>

bar:
    - *FOO
       propname: "some_prop"
       default: "some default"

Body:
With Yglu Structural Templating, your example can be written:

foo: !()
  !? $.propname:
     type: number
     default: !? $.default

bar:
  !apply .foo:
    propname: "some_prop"
    default: "some default"

Disclaimer: I am the author of Yglu.