问:
Delete function always selects same ID - blog - Codeigniter
So, I have been trying to get this delete function to work now for a while.

At the bottom of the foreach I have a delete function. The funtion itself does work, however it always selects the post id of 1.

View

```<code><div><?php foreach($posts as $post) : ?>
<hr>
<h3><?php echo $post['title']; ?></h3>
<div class="row">
    <div class="col-md-3">
        <img class="post-thumb" src="<?php echo site_url(); ?>posts/image/<?php echo $post['post_image']; ?>">
    </div>
    <div class="col-md-9">
        <small class="post-date">Posted on: <?php echo $post['created_at']; ?> in <strong><?php echo $post['name']; ?></strong></small><br>
    <?php echo word_limiter($post['body'], 60); ?>
    <br><br>
    <p><a class="btn btn-default" href="<?php echo site_url('/posts/'.$post['slug']); ?>">Read More</a></p>
    </div>
</div>
<?php echo form_open('/posts/delete/'.$post['id']); ?>
    <input type="submit" value="Delete" class="btn btn-danger">
</form>
</code>```

Controller

```<code>public function posts($offset = 0){

  // Pagination Config
  $config['base_url'] = base_url() . 'admins/posts/';
  $config['total_rows'] = $this->db->count_all('posts');
  $config['per_page'] = 10;
  $config['uri_segment'] = 3;
  $config['attributes'] = array('class' => 'pagination-link');

  // Init Pagination
  $this->pagination->initialize($config);

  $data['title'] = 'Latest Posts';

  $data['posts'] = $this->post_model->get_posts(FALSE, $config['per_page'], $offset);

    $this->load->view('templates/header');
    $this->load->view('admins/posts', $data);
    $this->load->view('templates/footer');
}
</code>```

Model

```<code>public function delete_post($id){
  $image_file_name = $this->db->select('post_image')->get_where('posts', array('id' => $id))->row()->post_image;
  $cwd = getcwd(); // save the current working directory
  $image_file_path = $cwd."\\assets\\images\\posts\\";
  chdir($image_file_path);
  unlink($image_file_name);
  chdir($cwd); // Restore the previous working directory
  $this->db->where('id', $id);
  $this->db->delete('posts');
  return true;
}
</code>```

EDIT:
get_posts in model

```<code>public function get_posts($slug = FALSE, $limit = FALSE, $offset = FALSE){
  if($limit){
    $this->db->limit($limit, $offset);
  }
  if($slug === FALSE){
    $this->db->order_by('posts.id', 'DESC');
    $this->db->join('categories', 'categories.id = posts.category_id');
    $query = $this->db->get('posts');
    return $query->result_array();
  }

  $query = $this->db->get_where('posts', array('slug' => $slug));
  return $query->row_array();
}
</code>```

The function does run and I get a confirmation message, so the only thing I am really confused about is the Id.
The whole thing is written using the CodeIgniter Framework.

答:
Check your get_post model properly. From what you have, it looks like your query will get it's id from the category table.

Try this instead

```<code> public function get_posts($slug = FALSE, $limit = FALSE, $offset = FALSE){
      if($limit){
        $this->db->limit($limit, $offset);
      }
      if($slug === FALSE){
        $this->db->select('posts.id AS id, posts.slug, posts.body, posts.created_at');
        $this->db->from('posts, categories');
        $this->db->where('categories.id = posts.category_id');
        $query = $this->db->get();
        return $query->result_array();
      }

      $query = $this->db->get_where('posts', array('slug' => $slug));
      return $query->result_array();
    }
</code>```

Updating your join to LEFT JOIN or simple use WHERE

Body:
So, I have been trying to get this delete function to work now for a while.

At the bottom of the foreach I have a delete function. The funtion itself does work, however it always selects the post id of 1.

View

<?php foreach($posts as $post) : ?>

<?php echo $post['title']; ?>

        <img class="post-thumb" src="<?php echo site_url(); ?>posts/image/<?php echo $post['post_image']; ?>">

        Posted on: <?php echo $post['created_at']; ?> in <?php echo $post['name']; ?>

    <?php echo word_limiter($post['body'], 60); ?>

<a class="btn btn-default" href="<?php echo site_url('/posts/'.$post['slug']); ?>">Read More

<?php echo form_open('/posts/delete/'.$post['id']); ?>
    <input type="submit" value="Delete" class="btn btn-danger">
</form>

Controller

public function posts($offset = 0){

  // Pagination Config
  $config['base_url'] = base_url() . 'admins/posts/';
  $config['total_rows'] = $this->db->count_all('posts');
  $config['per_page'] = 10;
  $config['uri_segment'] = 3;
  $config['attributes'] = array('class' => 'pagination-link');

  // Init Pagination
  $this->pagination->initialize($config);

  $data['title'] = 'Latest Posts';

  $data['posts'] = $this->post_model->get_posts(FALSE, $config['per_page'], $offset);

    $this->load->view('templates/header');
    $this->load->view('admins/posts', $data);
    $this->load->view('templates/footer');
}

Model

public function delete_post($id){
  $image_file_name = $this->db->select('post_image')->get_where('posts', array('id' => $id))->row()->post_image;
  $cwd = getcwd(); // save the current working directory
  $image_file_path = $cwd."\\assets\\images\\posts\\";
  chdir($image_file_path);
  unlink($image_file_name);
  chdir($cwd); // Restore the previous working directory
  $this->db->where('id', $id);
  $this->db->delete('posts');
  return true;
}

EDIT:
get_posts in model

public function get_posts($slug = FALSE, $limit = FALSE, $offset = FALSE){
  if($limit){
    $this->db->limit($limit, $offset);
  }
  if($slug === FALSE){
    $this->db->order_by('posts.id', 'DESC');
    $this->db->join('categories', 'categories.id = posts.category_id');
    $query = $this->db->get('posts');
    return $query->result_array();
  }

  $query = $this->db->get_where('posts', array('slug' => $slug));
  return $query->row_array();
}

The function does run and I get a confirmation message, so the only thing I am really confused about is the Id.
The whole thing is written using the CodeIgniter Framework.

Body:
Check your get_post model properly. From what you have, it looks like your query will get it's id from the category table.

Try this instead

 public function get_posts($slug = FALSE, $limit = FALSE, $offset = FALSE){
      if($limit){
        $this->db->limit($limit, $offset);
      }
      if($slug === FALSE){
        $this->db->select('posts.id AS id, posts.slug, posts.body, posts.created_at');
        $this->db->from('posts, categories');
        $this->db->where('categories.id = posts.category_id');
        $query = $this->db->get();
        return $query->result_array();
      }

      $query = $this->db->get_where('posts', array('slug' => $slug));
      return $query->result_array();
    }

Updating your join to LEFT JOIN or simple use WHERE


来源: stackexchange

问:
r identify two populations in scatterplot
I am comparing two rasters with a simple scatter plot of cell-by-cell plot, and find that I have two seemingly different populations:

Now I am trying to extract the locations of each of these populations (by isolating the row IDs, e.g.) so I can see where they fall in the rasters and maybe understand why I get this behavior.    Here is a reproducible example:

X <- seq(1,1000,1)

Z <- runif(1000, 1, 2)

A = c(1.2 * X * Z + 100)

B = c(0.6 * X * Z )

df = data.frame(X = c(X,X), Y = c(A,B))

plot(df$X,df$Y)

Also, my original data has some 1,000,000 rows, so the solution needs to support a large data frame as well.
Any ideas on how I can isolate each of these groups?

Thanks

答:
Spectral Clustering is useful in identifying clusters of points that has a clear boundary. A great advantage is that it is unsupervised, i.e. not relying much on human judgement, although the method is slow and some hyperparameters (e.g. number of clusters) need to be supplied.

Below is the code for clustering. The code takes about a few minutes in your case.

```<code>library(kernlab)
specc_df <- specc(as.matrix(df),centers = 2)
plot(df, col = specc_df)
</code>```

The result is an obvious plot of two clusters of points.

ContentLicense: CC BY-SA 3.0

Body:
Spectral Clustering is useful in identifying clusters of points that has a clear boundary. A great advantage is that it is unsupervised, i.e. not relying much on human judgement, although the method is slow and some hyperparameters (e.g. number of clusters) need to be supplied.

Below is the code for clustering. The code takes about a few minutes in your case.

library(kernlab)
specc_df <- specc(as.matrix(df),centers = 2)
plot(df, col = specc_df)

The result is an obvious plot of two clusters of points.


问:
php class extend approch vs static approch,which one is better
Approch 1：

```<code>class Storage extends SaeStorage {
public function save($data,$name){
    if (! $this->write ( ST_DOMAIN, $name, $data )){
        $error_message =    $this->errmsg();
        $result['error'] = $error_message;
        return $result;
    }else{
        $url = $this->getUrl ( ST_DOMAIN, $name );
        return $url;
    }
}
</code>```

}

approach 2：

```<code>class Storage  {
public static  function save($data,$name){
    $SaeStorage = new SaeStorage();
    if (! $SaeStorage->write ( ST_DOMAIN, $name, $data )){
        $error_message =    $this->errmsg();
        $result['error'] = $error_message;
        return $result;
    }else{
        $url = $SaeStorage->getUrl ( ST_DOMAIN, $name );
        return $url;
    }
}
</code>```

}

答:
Depends on what do you mean by better. I'm keeping performance out of question as the difference in performance between the two approaches will be very minimal (if at all there is any) and can be ignored.

Then it is entirely a design question. Things for which you need to find answers are:

Do you want your clients to seamlessly replace SaeStorage with Storage, and SaeStorage is a special type of Storage? If yes then extend otherwise don't.

Is SaeStorage just a behavior? For example Storage is a storage device and the way they save things varies. SaeStorage is just one of the ways you save things. Then use second approach, which is kind of a strategy pattern.

Even if SaeStorage is a special storage you might want to use strategy pattern to decouple behavior from interface.

ContentLicense: CC BY-SA 2.5

Body:
Approch 1：

class Storage extends SaeStorage {
public function save($data,$name){
    if (! $this->write ( ST_DOMAIN, $name, $data )){
        $error_message =    $this->errmsg();
        $result['error'] = $error_message;
        return $result;
    }else{
        $url = $this->getUrl ( ST_DOMAIN, $name );
        return $url;
    }
}

}

approach 2：

class Storage  {
public static  function save($data,$name){
    $SaeStorage = new SaeStorage();
    if (! $SaeStorage->write ( ST_DOMAIN, $name, $data )){
        $error_message =    $this->errmsg();
        $result['error'] = $error_message;
        return $result;
    }else{
        $url = $SaeStorage->getUrl ( ST_DOMAIN, $name );
        return $url;
    }
}

}


问:
Side-by-side boxplots with Pandas
I need to plot comparison of five variable, stored in pandas dataframe. I used an example from here, it worked, but now I need to change the axes and titles, but I'm struggling to do so.

Here is my data:

```<code>df1.groupby('cls').head()
Out[171]:
   sensitivity  specificity  accuracy       ppv       auc       cls
0     0.772091     0.824487  0.802966  0.799290  0.863700       sig
1     0.748931     0.817238  0.776366  0.785910  0.859041       sig
2     0.774016     0.805909  0.801975  0.789840  0.853132       sig
3     0.826670     0.730071  0.795715  0.784150  0.850024       sig
4     0.781112     0.803839  0.824709  0.791530  0.863411       sig
0     0.619048     0.748290  0.694969  0.686138  0.713899  baseline
1     0.642348     0.702076  0.646216  0.674683  0.712632  baseline
2     0.567344     0.765410  0.710650  0.665614  0.682502  baseline
3     0.644046     0.733645  0.754621  0.683485  0.734299  baseline
4     0.710077     0.653871  0.707933  0.684313  0.732997  baseline
</code>```

Here is my code:

```<code>>> fig, axes = plt.subplots(ncols=5, figsize=(12, 5), sharey=True)
>> df1.query("cls in ['sig', 'baseline']").boxplot(by='cls', return_type='axes', ax=axes)
</code>```

And the resulting pictures are:

How to:

change the title ('Boxplot groupped by cls')

get rid of annoying [cls] plotted along the horizontal line

reorder the plotted categories as they appear in df1? (first sensitivity, followed by speci...)

答:
I suggest using seaborn

Here is an example that might help you:

Imports

```<code>import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
</code>```

Make data

```<code>data = {'sensitivity' : np.random.normal(loc = 0, size = 10),
        'specificity' : np.random.normal(loc = 0, size = 10),
        'accuracy' : np.random.normal(loc = 0, size = 10),
        'ppv' : np.random.normal(loc = 0, size = 10),
        'auc' : np.random.normal(loc = 0, size = 10),
        'cls' : ['sig', 'sig', 'sig', 'sig', 'sig', 'baseline', 'baseline', 'baseline', 'baseline', 'baseline']}

df = pd.DataFrame(data)
df
</code>```

Seaborn has a nifty tool called factorplot that creates a grid of subplots where the rows/cols are built with your data. To be able to do this, we need to "melt" the df into a more usable shape.

```<code>df_melt = df.melt(id_vars = 'cls',
                  value_vars = ['accuracy',
                                'auc',
                                'ppv',
                                'sensitivity',
                                'specificity'],
                  var_name = 'columns')
</code>```

Now we can create the factorplot using the col "columns".

```<code>a = sns.factorplot(data = df_melt,
                   x = 'cls',
                   y = 'value',
                   kind = 'box', # type of plot
                   col = 'columns',
                   col_order = ['sensitivity', # custom order of boxplots
                                'specificity',
                                'accuracy',
                                'ppv',
                                'auc']).set_titles('{col_name}') # remove 'column = ' part of title

plt.show()
</code>```

You can also just use Seaborn's boxplot.

```<code>b = sns.boxplot(data = df_melt,
                hue = 'cls', # different colors for different 'cls'
                x = 'columns',
                y = 'value',
                order = ['sensitivity', # custom order of boxplots
                         'specificity',
                         'accuracy',
                         'ppv',
                         'auc'])

sns.plt.title('Boxplot grouped by cls') # You can change the title here
plt.show()
</code>```

This will give you the same plot but all in one figure instead of subplots. It also allows you to change the title of the figure with one line. Unfortunately I can't find a way to remove the 'columns' subtitle but hopefully this will get you what you need.

EDIT

To view the plots sideways:
Factorplot
Swap your x and y values, change col = 'columns' to row = 'columns', change col_order = [...] to row_order = [...], and change '{col_name}' to '{row_name}' like so

```<code>a1 = sns.factorplot(data = df_melt,
                    x = 'value',
                    y = 'cls',
                    kind = 'box', # type of plot
                    row = 'columns',
                    row_order = ['sensitivity', # custom order of boxplots
                                 'specificity',
                                 'accuracy',
                                 'ppv',
                                 'auc']).set_titles('{row_name}') # remove 'column = ' part of title

plt.show()
</code>```

Boxplot
Swap your x and y values then add the parameter orient = 'h' like so

```<code>b1 = sns.boxplot(data = df_melt,
                 hue = 'cls',
                 x = 'value',
                 y = 'columns',
                 order = ['sensitivity', # custom order of boxplots
                         'specificity',
                         'accuracy',
                         'ppv',
                         'auc'],
                 orient = 'h')

sns.plt.title('Boxplot grouped by cls')
plt.show()
</code>```

Title: Side-by-side boxplots with Pandas

Body:
I need to plot comparison of five variable, stored in pandas dataframe. I used an example from here, it worked, but now I need to change the axes and titles, but I'm struggling to do so.

Here is my data:

df1.groupby('cls').head()
Out[171]:
   sensitivity  specificity  accuracy       ppv       auc       cls
0     0.772091     0.824487  0.802966  0.799290  0.863700       sig
1     0.748931     0.817238  0.776366  0.785910  0.859041       sig
2     0.774016     0.805909  0.801975  0.789840  0.853132       sig
3     0.826670     0.730071  0.795715  0.784150  0.850024       sig
4     0.781112     0.803839  0.824709  0.791530  0.863411       sig
0     0.619048     0.748290  0.694969  0.686138  0.713899  baseline
1     0.642348     0.702076  0.646216  0.674683  0.712632  baseline
2     0.567344     0.765410  0.710650  0.665614  0.682502  baseline
3     0.644046     0.733645  0.754621  0.683485  0.734299  baseline
4     0.710077     0.653871  0.707933  0.684313  0.732997  baseline

Here is my code:

>> fig, axes = plt.subplots(ncols=5, figsize=(12, 5), sharey=True)
>> df1.query("cls in ['sig', 'baseline']").boxplot(by='cls', return_type='axes', ax=axes)

And the resulting pictures are:

How to:

change the title ('Boxplot groupped by cls')

get rid of annoying [cls] plotted along the horizontal line

reorder the plotted categories as they appear in df1? (first sensitivity, followed by speci...)

Body:
I suggest using seaborn

Here is an example that might help you:

Imports

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns

Make data

data = {'sensitivity' : np.random.normal(loc = 0, size = 10),
        'specificity' : np.random.normal(loc = 0, size = 10),
        'accuracy' : np.random.normal(loc = 0, size = 10),
        'ppv' : np.random.normal(loc = 0, size = 10),
        'auc' : np.random.normal(loc = 0, size = 10),
        'cls' : ['sig', 'sig', 'sig', 'sig', 'sig', 'baseline', 'baseline', 'baseline', 'baseline', 'baseline']}

df = pd.DataFrame(data)
df

Seaborn has a nifty tool called factorplot that creates a grid of subplots where the rows/cols are built with your data. To be able to do this, we need to "melt" the df into a more usable shape.

df_melt = df.melt(id_vars = 'cls',
                  value_vars = ['accuracy',
                                'auc',
                                'ppv',
                                'sensitivity',
                                'specificity'],
                  var_name = 'columns')

Now we can create the factorplot using the col "columns".

a = sns.factorplot(data = df_melt,
                   x = 'cls',
                   y = 'value',
                   kind = 'box', # type of plot
                   col = 'columns',
                   col_order = ['sensitivity', # custom order of boxplots
                                'specificity',
                                'accuracy',
                                'ppv',
                                'auc']).set_titles('{col_name}') # remove 'column = ' part of title

plt.show()

You can also just use Seaborn's boxplot.

b = sns.boxplot(data = df_melt,
                hue = 'cls', # different colors for different 'cls'
                x = 'columns',
                y = 'value',
                order = ['sensitivity', # custom order of boxplots
                         'specificity',
                         'accuracy',
                         'ppv',
                         'auc'])

sns.plt.title('Boxplot grouped by cls') # You can change the title here
plt.show()

This will give you the same plot but all in one figure instead of subplots. It also allows you to change the title of the figure with one line. Unfortunately I can't find a way to remove the 'columns' subtitle but hopefully this will get you what you need.

EDIT

To view the plots sideways:
Factorplot
Swap your x and y values, change col = 'columns' to row = 'columns', change col_order = [...] to row_order = [...], and change '{col_name}' to '{row_name}' like so

a1 = sns.factorplot(data = df_melt,
                    x = 'value',
                    y = 'cls',
                    kind = 'box', # type of plot
                    row = 'columns',
                    row_order = ['sensitivity', # custom order of boxplots
                                 'specificity',
                                 'accuracy',
                                 'ppv',
                                 'auc']).set_titles('{row_name}') # remove 'column = ' part of title

plt.show()

Boxplot
Swap your x and y values then add the parameter orient = 'h' like so

b1 = sns.boxplot(data = df_melt,
                 hue = 'cls',
                 x = 'value',
                 y = 'columns',
                 order = ['sensitivity', # custom order of boxplots
                         'specificity',
                         'accuracy',
                         'ppv',
                         'auc'],
                 orient = 'h')

sns.plt.title('Boxplot grouped by cls')
plt.show()


问:
How to create recurring event .ics file using ical4j in java?
This is the sample code for creating .ics file using java for normal event.

```<code>    Calendar calendar = new Calendar();
    calendar.getProperties().add(new ProdId("-//Ben Fortuna//iCal4j 1.0//EN"));
    calendar.getProperties().add(Version.VERSION_2_0);
    calendar.getProperties().add(CalScale.GREGORIAN);

    java.util.Calendar cal = java.util.Calendar.getInstance();
    cal.set(java.util.Calendar.MONTH, java.util.Calendar.DECEMBER);
    cal.set(java.util.Calendar.DAY_OF_MONTH, 25);
    // initialise as an all-day event..
    VEvent christmas = new VEvent(new Date(cal.getTime()), "Christmas Day");
    // Generate a UID for the event..
    UidGenerator ug = new UidGenerator("1");
    christmas.getProperties().add(ug.generateUid());
    calendar.getComponents().add(christmas);

    ServletOutputStream fout = response.getOutputStream();
    CalendarOutputter outputter = new CalendarOutputter();
    outputter.output(calendar, fout);
</code>```

答:
Lets say your recurrence pattern is

```<code>String recurrencePattern = "FREQ=MONTHLY;INTERVAL=1;BYDAY=SU;BYSETPOS=1;COUNT=5"
</code>```

then you can add recurrence information in your current event in this way.

```<code>VEvent christmas = new VEvent(new Date(cal.getTime()), "Christmas Day");
christmas.getProperties().add(new RRule(recurrencePattern));
</code>```

Body:
This is the sample code for creating .ics file using java for normal event.

    Calendar calendar = new Calendar();
    calendar.getProperties().add(new ProdId("-//Ben Fortuna//iCal4j 1.0//EN"));
    calendar.getProperties().add(Version.VERSION_2_0);
    calendar.getProperties().add(CalScale.GREGORIAN);

    java.util.Calendar cal = java.util.Calendar.getInstance();
    cal.set(java.util.Calendar.MONTH, java.util.Calendar.DECEMBER);
    cal.set(java.util.Calendar.DAY_OF_MONTH, 25);
    // initialise as an all-day event..
    VEvent christmas = new VEvent(new Date(cal.getTime()), "Christmas Day");
    // Generate a UID for the event..
    UidGenerator ug = new UidGenerator("1");
    christmas.getProperties().add(ug.generateUid());
    calendar.getComponents().add(christmas);

    ServletOutputStream fout = response.getOutputStream();
    CalendarOutputter outputter = new CalendarOutputter();
    outputter.output(calendar, fout);

Body:
Lets say your recurrence pattern is

String recurrencePattern = "FREQ=MONTHLY;INTERVAL=1;BYDAY=SU;BYSETPOS=1;COUNT=5"

then you can add recurrence information in your current event in this way.

VEvent christmas = new VEvent(new Date(cal.getTime()), "Christmas Day");
christmas.getProperties().add(new RRule(recurrencePattern));


问:
Angular cross-service communication
I have a statistics application. On the left side of my page I have list of themes, on the top - list of groups. The main part contains statistics items related to both theme and group.

Also I have several services which provide business logic for my application. For simplicity let's talk about three of them: ThemeSerivce, GroupService and StatisticsService.

End users could manipulate lists of themes and groups (add or remove items) and I have to recalculate statistics after each change. In this application I use Subjects and Subsription from rx.js to track such kind of changes.

So, in my components I could write something like this:

for GroupComponent

```<code> removeGroup() {
        this.groupService.removeGroup(this.group);
        this.statisticsService.updateStatistics();
      }
</code>```

for ThemeComponent

```<code>removeTheme() {
    this.themeService.removeTheme(this.theme);
    this.statisticsService.updateStatistics();
  }
</code>```

But logically these components don't have to know about statistics. Of course I can move dependency of StatisticsService into ThemeService and GroupService, but then I will have to call statisticsService.updateStatistics() in every method which changes collection of themes or groups. That's why I want to implement direct cross-service communication with subscription.

And finally my questions:

Is it a good idea at all?

If it's ok, what is the best way to implement it?
When I use Subscription in components, I register it in ngOnInit() method and unsubscribe in ngOnDestroy() to prevent memory leaks.
Could I subscribe it in service's constructor? And when or where should I unsubscribe? Or maybe it's not necessary when I register my services as provider on App module level?

答:
StatisticsService should subscribe to the list of themes and groups.  Your individual components should only subscribe to their respective services (ThemeComponent to ThemeService, Group to Group etc).

For simplicity, I'll just focus on the ThemeService but GroupService is similar.  ThemeService should have an internal Subject when remove is called, the Subject will next a value (probably the entire new list).

StatisticsService will subscribe to the ThemeService observable and recalculate after change.  It will look something like this

```<code>/* theme.service.ts */
@Injectable()
export class ThemeService {
    private _list$ = new Subject<ThemeList>();

    get list(): Observable<ThemeList> {
        return this._list$.asObservable();
    }

    set list(newList: ThemeList) {
       this._list$.next(newList);
    }
}

/* statistics.service.ts */
@Injectable()
export class StatisticsService {
    private _calculation$ = new Subject<StatisticResult>();

    constructor(private themeService: ThemeService) {
        themeService.list.subscribe((themeList: ThemeList) => this.updateCalculation(themeList));
    }

    get calculation(): Observable<StatisticResult> {
        return this._calculation$.asObservable();
    }

    updateCalculation(newData: ThemeList | GroupList) {
        // ... do stuff
        this._calculation.next(statisticResult);
    }
}

/* statistics.component.ts */
@Component({
  selector: 'statistics',
  template: '<p>{{ statisticResult$ | async }}</p>'
})
export class StatisticsComponent {
    statisticResult$: Observable<StatisticResult>;

    constructor(private statisticsService: StatisticsService) {
        this.statisticResult$ = statisticsService.calculation;
    }
}
</code>```

Title: Angular cross-service communication

Body:
I have a statistics application. On the left side of my page I have list of themes, on the top - list of groups. The main part contains statistics items related to both theme and group.

Also I have several services which provide business logic for my application. For simplicity let's talk about three of them: ThemeSerivce, GroupService and StatisticsService.

End users could manipulate lists of themes and groups (add or remove items) and I have to recalculate statistics after each change. In this application I use Subjects and Subsription from rx.js to track such kind of changes.

So, in my components I could write something like this:

for GroupComponent

 removeGroup() {
        this.groupService.removeGroup(this.group);
        this.statisticsService.updateStatistics();
      }

for ThemeComponent

removeTheme() {
    this.themeService.removeTheme(this.theme);
    this.statisticsService.updateStatistics();
  }

But logically these components don't have to know about statistics. Of course I can move dependency of StatisticsService into ThemeService and GroupService, but then I will have to call statisticsService.updateStatistics() in every method which changes collection of themes or groups. That's why I want to implement direct cross-service communication with subscription.

And finally my questions:

Is it a good idea at all?

If it's ok, what is the best way to implement it?
When I use Subscription in components, I register it in ngOnInit() method and unsubscribe in ngOnDestroy() to prevent memory leaks.
Could I subscribe it in service's constructor? And when or where should I unsubscribe? Or maybe it's not necessary when I register my services as provider on App module level?

Body:
StatisticsService should subscribe to the list of themes and groups.  Your individual components should only subscribe to their respective services (ThemeComponent to ThemeService, Group to Group etc).

For simplicity, I'll just focus on the ThemeService but GroupService is similar.  ThemeService should have an internal Subject when remove is called, the Subject will next a value (probably the entire new list).

StatisticsService will subscribe to the ThemeService observable and recalculate after change.  It will look something like this

/* theme.service.ts */
@Injectable()
export class ThemeService {
    private _list$ = new Subject<ThemeList>();

    get list(): Observable<ThemeList> {
        return this._list$.asObservable();
    }

    set list(newList: ThemeList) {
       this._list$.next(newList);
    }
}

/* statistics.service.ts */
@Injectable()
export class StatisticsService {
    private _calculation$ = new Subject<StatisticResult>();

    constructor(private themeService: ThemeService) {
        themeService.list.subscribe((themeList: ThemeList) => this.updateCalculation(themeList));
    }

    get calculation(): Observable<StatisticResult> {
        return this._calculation$.asObservable();
    }

    updateCalculation(newData: ThemeList | GroupList) {
        // ... do stuff
        this._calculation.next(statisticResult);
    }
}

/* statistics.component.ts */
@Component({
  selector: 'statistics',
  template: '<p>{{ statisticResult$ | async }}</p>'
})
export class StatisticsComponent {
    statisticResult$: Observable<StatisticResult>;

    constructor(private statisticsService: StatisticsService) {
        this.statisticResult$ = statisticsService.calculation;
    }
}


问:
Why does this function fail when I use this regular expression?
I have been practicing getting more comfortable with the use of regular expressions, but I am having a really hard time understanding why this function I wrote does not work. I wrote a simple function to count the number of duplicate letters in a word, which seems to work sometimes, but doesn't work all the time.

```<code>function duplicates(str){
    try{
        return str.match(/(.)\1+/ig).length;
    }catch(e){
        return 0;
    }
}
</code>```

According to what I have researched this statement should look through the string, find a letter (or multiple letters) that repeat more than once ignoring case, and return the length of the matched letters. If no matching letters occur it will return 0. It works correctly for some strings, but not all. Here's what I have been getting:

```<code>duplicates("abcdef") -> 0      #should return 0
duplicates("Aabccdef") -> 2    #should return 2
duplicates("Mississippi") -> 3 #should return 3
duplicates("Indivisible") -> 0 #should return 1
duplicates("abcabcabc") -> 0   #should return 3
</code>```

Upon further inspection, it would seem that when I ran "Mississippi", I got the expected number 3, however when I added .toString() in replacement of .length to see what the expression was counting I got:

```<code>ss,ss,pp
</code>```

There are no i's counted and there should be. It would also seem that the i's were not counted in "Indivisible" either and did not indicate any repeated letters in "abcabcabc". It seems that it can not count non-consecutive repeats, but I can't figure out why. I am sure it is my misunderstanding of how regular expressions work, since I am new to them, but if anyone would shed some light on why this is happening, that would be awesome!

Edit: Is there a way to do this with RegEx, or do I need to use a loop?

答:
You are near to achieve it but since you are looking for recent captured character immediately after capturing it you can't count characters which are not neighbors.

The idea would be using a positive lookahead to find repeating characters, then omit duplicate characters to leave unique characters in order to count them. The regex:

```<code>(.)(?=.*\1)
</code>```

ES6:

function duplicates($str) {
    return [...new Set($str.toLowerCase().match(/(.)(?=.*\1)/g))].length;
}

console.log(duplicates("abcdef"));
console.log(duplicates("Aabccdef"));
console.log(duplicates("Mississippi"));
console.log(duplicates("Indivisible"));
console.log(duplicates("abcabcabc"));```
</div>
</div>
</p>

<h2>ES5:</h2>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function _unique(value, index, self) {
    return self.indexOf(value) === index;
}

function duplicates($str) {
    return ($str.toLowerCase().match(/(.)(?=.*\1)/g) || Array()).filter(_unique).length;
}

console.log(duplicates("abcdef"));
console.log(duplicates("Aabccdef"));
console.log(duplicates("Mississippi"));
console.log(duplicates("Indivisible"));
console.log(duplicates("abcabcabc"));</code>```

Body:
I have been practicing getting more comfortable with the use of regular expressions, but I am having a really hard time understanding why this function I wrote does not work. I wrote a simple function to count the number of duplicate letters in a word, which seems to work sometimes, but doesn't work all the time.

function duplicates(str){
    try{
        return str.match(/(.)\1+/ig).length;
    }catch(e){
        return 0;
    }
}

According to what I have researched this statement should look through the string, find a letter (or multiple letters) that repeat more than once ignoring case, and return the length of the matched letters. If no matching letters occur it will return 0. It works correctly for some strings, but not all. Here's what I have been getting:

duplicates("abcdef") -> 0      #should return 0
duplicates("Aabccdef") -> 2    #should return 2
duplicates("Mississippi") -> 3 #should return 3
duplicates("Indivisible") -> 0 #should return 1
duplicates("abcabcabc") -> 0   #should return 3

Upon further inspection, it would seem that when I ran "Mississippi", I got the expected number 3, however when I added .toString() in replacement of .length to see what the expression was counting I got:

ss,ss,pp

There are no i's counted and there should be. It would also seem that the i's were not counted in "Indivisible" either and did not indicate any repeated letters in "abcabcabc". It seems that it can not count non-consecutive repeats, but I can't figure out why. I am sure it is my misunderstanding of how regular expressions work, since I am new to them, but if anyone would shed some light on why this is happening, that would be awesome!

Edit: Is there a way to do this with RegEx, or do I need to use a loop?

Body:
You are near to achieve it but since you are looking for recent captured character immediately after capturing it you can't count characters which are not neighbors.

The idea would be using a positive lookahead to find repeating characters, then omit duplicate characters to leave unique characters in order to count them. The regex:

(.)(?=.*\1)

ES6:

function duplicates($str) {
    return [...new Set($str.toLowerCase().match(/(.)(?=.*\1)/g))].length;
}

console.log(duplicates("abcdef"));
console.log(duplicates("Aabccdef"));
console.log(duplicates("Mississippi"));
console.log(duplicates("Indivisible"));
console.log(duplicates("abcabcabc"));

ES5:

function _unique(value, index, self) {
    return self.indexOf(value) === index;
}

function duplicates($str) {
    return ($str.toLowerCase().match(/(.)(?=.*\1)/g) || Array()).filter(_unique).length;
}

console.log(duplicates("abcdef"));
console.log(duplicates("Aabccdef"));
console.log(duplicates("Mississippi"));
console.log(duplicates("Indivisible"));
console.log(duplicates("abcabcabc"));


问:
How can I get the request body using HttpClient when uploading a file?
I'm using HttpClient to upload files to an API that requires the Content-MD5 header. How can I get the full request body from HttpClient before sending it so I can run MD5 on the content and use that in the request header? Note that I also need to include the headers in between the multipart form data, i.e. Content-Disposition and all other headers that are in each part.

I'm using the code below, taken from this answer.

```<code>private System.IO.Stream Upload(string url, string param1, Stream fileStream, byte [] fileBytes)
{
    HttpContent stringContent = new StringContent(param1);
    HttpContent fileStreamContent = new StreamContent(fileStream);
    HttpContent bytesContent = new ByteArrayContent(fileBytes);
    using (var client = new HttpClient())
    using (var formData = new MultipartFormDataContent())
    {
        formData.Add(stringContent, "param1", "param1");
        formData.Add(fileStreamContent, "file1", "file1");
        formData.Add(bytesContent, "file2", "file2");
        var response = client.PostAsync(url, formData).Result;
        if (!response.IsSuccessStatusCode)
        {
            return null;
        }
        return response.Content.ReadAsStreamAsync().Result;
    }
}
</code>```

答:
The generic way to handle this sort of with HttpClient is to use a HttpMessageHandler as you might other work to do e.g. adding authorization headers, signing the message etc.

I've also re-written this using Task based syntax as it's more ideomatic HttpClient - the caller can call .Result as needed.

```<code>private await Task<System.IO.Stream> Upload(string url, string param1, Stream fileStream, byte[] fileBytes)
{
    HttpContent stringContent = new StringContent(param1);
    HttpContent fileStreamContent = new StreamContent(fileStream);
    HttpContent bytesContent = new ByteArrayContent(fileBytes);

    var handler = new HttpClientHandler();
    var md5Handler = new RequestContentMd5Handler();
    md5Handler.InnerHandler = handler;

    using (HttpClient client = new HttpClient(md5Handler))
    {
        using (MultipartFormDataContent formData = new MultipartFormDataContent())
        {
            formData.Add(stringContent, "param1", "param1");
            formData.Add(fileStreamContent, "file1", "file1");
            formData.Add(bytesContent, "file2", "file2");

            using (var response = await client.PostAsync(url, formData))
            {
                if (!response.IsSuccessStatusCode)
                {
                    return null;
                }

                return await response.Content.ReadAsStreamAsync();
            }
        }
    }
}
</code>```

Also, it's generally poor practice to re-create the HttpClient on each request (see What is the overhead of creating a new HttpClient per call in a WebAPI client? etc), but I've left that here in keeping with the style of the question.

Here's the handler used...

```<code>/// <summary>
/// Handler to assign the MD5 hash value if content is present
/// </summary>
public class RequestContentMd5Handler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (request.Content == null)
        {
            return await base.SendAsync(request, cancellationToken);
        }

        await request.Content.AssignMd5Hash();

        var response = await base.SendAsync(request, cancellationToken);

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

And the extensions methods...

```<code>    /// <summary>
    /// Compute and assign the MD5 hash of the content.
    /// </summary>
    /// <param name="httpContent"></param>
    /// <returns></returns>
    public static async Task AssignMd5Hash(this HttpContent httpContent)
    {
        var hash = await httpContent.ComputeMd5Hash();

        httpContent.Headers.ContentMD5 = hash;
    }

    /// <summary>
    /// Compute the MD5 hash of the content.
    /// </summary>
    /// <param name="httpContent"></param>
    /// <returns></returns>
    public static async Task<byte[]> ComputeMd5Hash(this HttpContent httpContent)
    {
        using (var md5 = MD5.Create())
        {
            var content = await httpContent.ReadAsStreamAsync();
            var hash = md5.ComputeHash(content);
            return hash;
        }
    }
</code>```

Makes it easy to unit test the various parts.

Body:
I'm using HttpClient to upload files to an API that requires the Content-MD5 header. How can I get the full request body from HttpClient before sending it so I can run MD5 on the content and use that in the request header? Note that I also need to include the headers in between the multipart form data, i.e. Content-Disposition and all other headers that are in each part.

I'm using the code below, taken from this answer.

private System.IO.Stream Upload(string url, string param1, Stream fileStream, byte [] fileBytes)
{
    HttpContent stringContent = new StringContent(param1);
    HttpContent fileStreamContent = new StreamContent(fileStream);
    HttpContent bytesContent = new ByteArrayContent(fileBytes);
    using (var client = new HttpClient())
    using (var formData = new MultipartFormDataContent())
    {
        formData.Add(stringContent, "param1", "param1");
        formData.Add(fileStreamContent, "file1", "file1");
        formData.Add(bytesContent, "file2", "file2");
        var response = client.PostAsync(url, formData).Result;
        if (!response.IsSuccessStatusCode)
        {
            return null;
        }
        return response.Content.ReadAsStreamAsync().Result;
    }
}

Body:
The generic way to handle this sort of with HttpClient is to use a HttpMessageHandler as you might other work to do e.g. adding authorization headers, signing the message etc.

I've also re-written this using Task based syntax as it's more ideomatic HttpClient - the caller can call .Result as needed.

private await Task<System.IO.Stream> Upload(string url, string param1, Stream fileStream, byte[] fileBytes)
{
    HttpContent stringContent = new StringContent(param1);
    HttpContent fileStreamContent = new StreamContent(fileStream);
    HttpContent bytesContent = new ByteArrayContent(fileBytes);

    var handler = new HttpClientHandler();
    var md5Handler = new RequestContentMd5Handler();
    md5Handler.InnerHandler = handler;

    using (HttpClient client = new HttpClient(md5Handler))
    {
        using (MultipartFormDataContent formData = new MultipartFormDataContent())
        {
            formData.Add(stringContent, "param1", "param1");
            formData.Add(fileStreamContent, "file1", "file1");
            formData.Add(bytesContent, "file2", "file2");

            using (var response = await client.PostAsync(url, formData))
            {
                if (!response.IsSuccessStatusCode)
                {
                    return null;
                }

                return await response.Content.ReadAsStreamAsync();
            }
        }
    }
}

Also, it's generally poor practice to re-create the HttpClient on each request (see What is the overhead of creating a new HttpClient per call in a WebAPI client? etc), but I've left that here in keeping with the style of the question.

Here's the handler used...

/// <summary>
/// Handler to assign the MD5 hash value if content is present
/// </summary>
public class RequestContentMd5Handler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (request.Content == null)
        {
            return await base.SendAsync(request, cancellationToken);
        }

        await request.Content.AssignMd5Hash();

        var response = await base.SendAsync(request, cancellationToken);

        return response;
    }
}

And the extensions methods...

    /// <summary>
    /// Compute and assign the MD5 hash of the content.
    /// </summary>
    /// <param name="httpContent"></param>
    /// <returns></returns>
    public static async Task AssignMd5Hash(this HttpContent httpContent)
    {
        var hash = await httpContent.ComputeMd5Hash();

        httpContent.Headers.ContentMD5 = hash;
    }

    /// <summary>
    /// Compute the MD5 hash of the content.
    /// </summary>
    /// <param name="httpContent"></param>
    /// <returns></returns>
    public static async Task<byte[]> ComputeMd5Hash(this HttpContent httpContent)
    {
        using (var md5 = MD5.Create())
        {
            var content = await httpContent.ReadAsStreamAsync();
            var hash = md5.ComputeHash(content);
            return hash;
        }
    }

Makes it easy to unit test the various parts.


问:
Counting lowercase with regex
I am trying to count the number of lower case characters in a string using regex.  I think I am missing something blindingly obvious but can't figure out what!  It is for an old classic ASP page.

```<code><%
Password="abcd123"
Set myRegExp = New RegExp
myRegExp.Pattern = "(.*[a-z].*)"
Response.Write myRegExp.Execute(Password).Count
%>
</code>```

The script returns 1 rather than 4.

答:
I think the following is what you want to do.

Password="abcd123"
Set myRegExp = New RegExp
myRegExp.Global = True ' This is required to get all matches
myRegExp.Pattern = "[a-z]"
Response.Write myRegExp.Execute(Password).Count
```

<p>But I have some suggestions for you.</p>

<ul>
<li><p>You can make your rule greedy with <code>+</code>. This will reduce the cycles.</p></li>
<li><p>You need to set <code>.Global</code> to <code>True</code> to get all matches, not only the first one.</p></li>
<li><p>With this approach you need to loop through the matches collection (returned from <code>myRegExp.Execute</code>) to find the right result.</p></li>
</ul>

<pre class="lang-vb prettyprint-override"><code>Password="abcd123fooBar"
Set myRegExp = New RegExp
myRegExp.Pattern = "[a-z]+"
myRegExp.Global = True
count = 0
For Each match In myRegExp.Execute(Password)
    count = count + match.Length
Next
Response.Write count 'prints 9
</code>```

And here's another way to the same.

This matches with all non-lowercase characters and removes them from the result string. You can then get the length by using Len function.

Password="abcd123fooBar"
Set myRegExp = New RegExp
myRegExp.Pattern = "[^a-z]+"
myRegExp.Global = True
count = Len(myRegExp.Replace(Password, ""))
Response.Write count 'prints 9
```

Title: Counting lowercase with regex

Body:
I am trying to count the number of lower case characters in a string using regex.  I think I am missing something blindingly obvious but can't figure out what!  It is for an old classic ASP page.

<%
Password="abcd123"
Set myRegExp = New RegExp
myRegExp.Pattern = "(.*[a-z].*)"
Response.Write myRegExp.Execute(Password).Count
%>

The script returns 1 rather than 4.

Body:
I think the following is what you want to do.

Password="abcd123"
Set myRegExp = New RegExp
myRegExp.Global = True ' This is required to get all matches
myRegExp.Pattern = "[a-z]"
Response.Write myRegExp.Execute(Password).Count

But I have some suggestions for you.

You can make your rule greedy with +. This will reduce the cycles.

You need to set .Global to True to get all matches, not only the first one.

With this approach you need to loop through the matches collection (returned from myRegExp.Execute) to find the right result.

Password="abcd123fooBar"
Set myRegExp = New RegExp
myRegExp.Pattern = "[a-z]+"
myRegExp.Global = True
count = 0
For Each match In myRegExp.Execute(Password)
    count = count + match.Length
Next
Response.Write count 'prints 9

And here's another way to the same.

This matches with all non-lowercase characters and removes them from the result string. You can then get the length by using Len function.

Password="abcd123fooBar"
Set myRegExp = New RegExp
myRegExp.Pattern = "[^a-z]+"
myRegExp.Global = True
count = Len(myRegExp.Replace(Password, ""))
Response.Write count 'prints 9


问:
android.view.InflateException - cannot find reason
This is my fragment inputtext_fragment.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<fragment
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/inputtextfragm"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <LinearLayout
        android:id="@+id/inputtext_layout"
        android:visibility="invisible"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        ...>

        ...

    </LinearLayout>
</fragment>
</code>```

inputText fragment in java:

```<code>package de.company.android.inputtext;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class InputTextFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        try {
            return inflater.inflate(R.layout.inputtext_fragment, container, false);
        }
        catch (Throwable t) {
            t.printStackTrace();
            return null;
        }
    }
}
</code>```

This is the activity layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/layout"
    tools:context="de.company.android.testview.MainActivity"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000">

    ...

    <fragment
        android:id="@+id/console"
        android:name="de.company.android.inputtext.InputTextFragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</RelativeLayout>
</code>```

I get the following error on launch, when the content view of the activity is set onCreate():

D/AndroidRuntime: Shutting down VM
  E/AndroidRuntime: FATAL EXCEPTION: main
                    Process: de.company.android.testview, PID: 573
                    java.lang.RuntimeException: Unable to start activity ComponentInfo{de.company.android.testview/de.company.android.testview.MainActivity}: android.view.InflateException: Binary XML file line #153: Binary XML file line #153: Error inflating class fragment
                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3319)
                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
                        at android.app.ActivityThread.access$1100(ActivityThread.java:229)
                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
                        at android.os.Handler.dispatchMessage(Handler.java:102)
                        at android.os.Looper.loop(Looper.java:148)
                        at android.app.ActivityThread.main(ActivityThread.java:7325)
                        at java.lang.reflect.Method.invoke(Native Method)
                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

Caused by: android.view.InflateException: Binary XML file line #153: Binary XML file line #153: Error inflating class fragment
                   ...

Caused by: java.lang.IllegalStateException: Fragment de.company.android.inputtext.InputTextFragment did not create a view.
                        at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2253)
                        at android.app.FragmentController.onCreateView(FragmentController.java:99)
                        at android.app.Activity.onCreateView(Activity.java:6085)
                        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:766)
                        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:716)
                        at android.view.LayoutInflater.rInflate(LayoutInflater.java:847)
                        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:810)
                        at android.view.LayoutInflater.inflate(LayoutInflater.java:527)
                        at android.view.LayoutInflater.inflate(LayoutInflater.java:429)
                        at android.view.LayoutInflater.inflate(LayoutInflater.java:380)
                        at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:479)
                        at android.app.Activity.setContentView(Activity.java:2400)
                        at de.company.android.testview.MainActivity.onCreate(MainActivity.java:1697)
                        at android.app.Activity.performCreate(Activity.java:6904)
                        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3266)
                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
                        at android.app.ActivityThread.access$1100(ActivityThread.java:229)
                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
                        at android.os.Handler.dispatchMessage(Handler.java:102)
                        at android.os.Looper.loop(Looper.java:148)
                        at android.app.ActivityThread.main(ActivityThread.java:7325)
                        at java.lang.reflect.Method.invoke(Native Method)
                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

This is the error logged inside catch:

```<code>W/System.err: android.view.InflateException: Binary XML file line #2: Binary XML file line #2: Error inflating class fragment
W/System.err:     at android.view.LayoutInflater.inflate(LayoutInflater.java:551)
W/System.err:     at android.view.LayoutInflater.inflate(LayoutInflater.java:429)
W/System.err:     at de.company.android.inputtext.InputTextFragment.onCreateView(InputTextFragment.java:23)
W/System.err:     at android.app.Fragment.performCreateView(Fragment.java:2281)
W/System.err:     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
W/System.err:     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1142)
W/System.err:     at android.app.FragmentManagerImpl.addFragment(FragmentManager.java:1246)
W/System.err:     at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2223)
W/System.err:     at android.app.FragmentController.onCreateView(FragmentController.java:99)
W/System.err:     at android.app.Activity.onCreateView(Activity.java:6085)
W/System.err:     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:766)
W/System.err:     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:716)
W/System.err:     at android.view.LayoutInflater.rInflate(LayoutInflater.java:847)
W/System.err:     at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:810)
W/System.err:     at android.view.LayoutInflater.inflate(LayoutInflater.java:527)
...
W/System.err: Caused by: java.lang.NullPointerException
W/System.err:     at java.lang.VMClassLoader.findLoadedClass(Native Method)
W/System.err:     at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:362)
W/System.err:     at java.lang.ClassLoader.loadClass(ClassLoader.java:499)
W/System.err:     at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
W/System.err:     at android.app.Fragment.instantiate(Fragment.java:620)
W/System.err:     at android.app.Fragment.instantiate(Fragment.java:598)
W/System.err:     at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2214)
W/System.err:     at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:192)
W/System.err:     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:766)
W/System.err:   ... 33 more
</code>```

I cannot find out what is wrong. The activity and the fragment are in different modules, but everything is configured right so that the de.company.android.inputtext utils are correctly referenced.

答:
Caused by: java.lang.IllegalStateException: Fragment de.company.android.inputtext.InputTextFragment did not create a view.

You can't return a null view in onCreateView.

ContentLicense: CC BY-SA 4.0

Body:
This is my fragment inputtext_fragment.xml:

<?xml version="1.0" encoding="utf-8"?>
<fragment
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/inputtextfragm"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <LinearLayout
        android:id="@+id/inputtext_layout"
        android:visibility="invisible"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        ...>

        ...

    </LinearLayout>
</fragment>

inputText fragment in java:

package de.company.android.inputtext;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class InputTextFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        try {
            return inflater.inflate(R.layout.inputtext_fragment, container, false);
        }
        catch (Throwable t) {
            t.printStackTrace();
            return null;
        }
    }
}

This is the activity layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/layout"
    tools:context="de.company.android.testview.MainActivity"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000">

    ...

    <fragment
        android:id="@+id/console"
        android:name="de.company.android.inputtext.InputTextFragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</RelativeLayout>

I get the following error on launch, when the content view of the activity is set onCreate():

D/AndroidRuntime: Shutting down VM
  E/AndroidRuntime: FATAL EXCEPTION: main
                    Process: de.company.android.testview, PID: 573
                    java.lang.RuntimeException: Unable to start activity ComponentInfo{de.company.android.testview/de.company.android.testview.MainActivity}: android.view.InflateException: Binary XML file line #153: Binary XML file line #153: Error inflating class fragment
                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3319)
                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
                        at android.app.ActivityThread.access$1100(ActivityThread.java:229)
                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
                        at android.os.Handler.dispatchMessage(Handler.java:102)
                        at android.os.Looper.loop(Looper.java:148)
                        at android.app.ActivityThread.main(ActivityThread.java:7325)
                        at java.lang.reflect.Method.invoke(Native Method)
                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

Caused by: android.view.InflateException: Binary XML file line #153: Binary XML file line #153: Error inflating class fragment
                   ...

Caused by: java.lang.IllegalStateException: Fragment de.company.android.inputtext.InputTextFragment did not create a view.
                        at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2253)
                        at android.app.FragmentController.onCreateView(FragmentController.java:99)
                        at android.app.Activity.onCreateView(Activity.java:6085)
                        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:766)
                        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:716)
                        at android.view.LayoutInflater.rInflate(LayoutInflater.java:847)
                        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:810)
                        at android.view.LayoutInflater.inflate(LayoutInflater.java:527)
                        at android.view.LayoutInflater.inflate(LayoutInflater.java:429)
                        at android.view.LayoutInflater.inflate(LayoutInflater.java:380)
                        at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:479)
                        at android.app.Activity.setContentView(Activity.java:2400)
                        at de.company.android.testview.MainActivity.onCreate(MainActivity.java:1697)
                        at android.app.Activity.performCreate(Activity.java:6904)
                        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3266)
                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
                        at android.app.ActivityThread.access$1100(ActivityThread.java:229)
                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
                        at android.os.Handler.dispatchMessage(Handler.java:102)
                        at android.os.Looper.loop(Looper.java:148)
                        at android.app.ActivityThread.main(ActivityThread.java:7325)
                        at java.lang.reflect.Method.invoke(Native Method)
                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

This is the error logged inside catch:

W/System.err: android.view.InflateException: Binary XML file line #2: Binary XML file line #2: Error inflating class fragment
W/System.err:     at android.view.LayoutInflater.inflate(LayoutInflater.java:551)
W/System.err:     at android.view.LayoutInflater.inflate(LayoutInflater.java:429)
W/System.err:     at de.company.android.inputtext.InputTextFragment.onCreateView(InputTextFragment.java:23)
W/System.err:     at android.app.Fragment.performCreateView(Fragment.java:2281)
W/System.err:     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
W/System.err:     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1142)
W/System.err:     at android.app.FragmentManagerImpl.addFragment(FragmentManager.java:1246)
W/System.err:     at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2223)
W/System.err:     at android.app.FragmentController.onCreateView(FragmentController.java:99)
W/System.err:     at android.app.Activity.onCreateView(Activity.java:6085)
W/System.err:     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:766)
W/System.err:     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:716)
W/System.err:     at android.view.LayoutInflater.rInflate(LayoutInflater.java:847)
W/System.err:     at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:810)
W/System.err:     at android.view.LayoutInflater.inflate(LayoutInflater.java:527)
...
W/System.err: Caused by: java.lang.NullPointerException
W/System.err:     at java.lang.VMClassLoader.findLoadedClass(Native Method)
W/System.err:     at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:362)
W/System.err:     at java.lang.ClassLoader.loadClass(ClassLoader.java:499)
W/System.err:     at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
W/System.err:     at android.app.Fragment.instantiate(Fragment.java:620)
W/System.err:     at android.app.Fragment.instantiate(Fragment.java:598)
W/System.err:     at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2214)
W/System.err:     at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:192)
W/System.err:     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:766)
W/System.err:   ... 33 more

I cannot find out what is wrong. The activity and the fragment are in different modules, but everything is configured right so that the de.company.android.inputtext utils are correctly referenced.


问:
Must an object's ctor and dtor be on the same thread?
With C++ RAII, the dtor gets called when the object goes out of scope. The mechanisms for multithreading always involve passing a callback to be run on a new thread. Thus, I don't think it's possible for an object to be constructed in one thread and destructed in another, since those would have to be different scopes. </p>

<p>Am I right about this? Or are there some cases where an objects ctor and dtor can be called in different threads? </p>

答:
The mechanisms for multithreading always involve passing a callback to be run on a new thread.

False. There's plenty of cases where you just need another thread to do stuff or manage something in the background but don't care about the status. Additionally, there are other signalling methods besides callbacks (just one example would be conditional variables).

Side note: a callback could be called on any thread, including the thread that you passed the callback to. It all depends on how you design the system. You don't have to make a new thread every time you invoke a callback (although that's one way to do it).

Thus, I don't think it's possible for an object to be constructed in one thread and destructed in another, since those would have to be different scopes.

False. Shared pointers allow pointers to objects to be passed around threads and once all references to the object are removed, then the object is destructed.

An example would be a networking thread that constructs an object to represent some message received from the network. That thread then puts that object on a shared queue and some other processing thread processes that message. Once the processing thread has completed, it can destruct the object and free the resources for other things.

Body:
With C++ RAII, the dtor gets called when the object goes out of scope. The mechanisms for multithreading always involve passing a callback to be run on a new thread. Thus, I don't think it's possible for an object to be constructed in one thread and destructed in another, since those would have to be different scopes.

Am I right about this? Or are there some cases where an objects ctor and dtor can be called in different threads?


问:
Bash to find files under directory and goto directory and compile
All 4gl files are located in their own directory under dir1. I need to compile these 4gl files to be 4ge. Normally I compile follow this step;
cd ~/dir1/file1/
build file1.4ge  # file locates in this folder is file1.4gl

But what if I need to create a loop script to find these 4gl files in each directory under dir1 and then change directory to the directory that found the file first, compile it using command "build file_name.4ge", then move to the next 4gl file. Can anybody help me with this? Thanks in advance.

答:
What about </p>

```<code>$ find ~/ -type f -name "*.4gl" -exec sh -c \ 'cd $(dirname $1);build $(basename $1 .4ge)' sh {} \;
</code>```

Body:
What about

$ find ~/ -type f -name "*.4gl" -exec sh -c \ 'cd $(dirname $1);build $(basename $1 .4ge)' sh {} \;


问:
RxJS: Disable refresh button for duration after clicked
I am new to RxJS and tried to do a simple demo that lets you refresh the data every one second.

I made a button and created a click stream from it.
The problem started when i wanted to make a stream that every button click emits false and after one second emits true once again.

For example - the initial state is true as we can refresh at start.
Once i clicked the button the new value should be false right after the click as we cant refresh further.

Lastly after one second passed - the value should be true once again.

I tried creating it and succeeded, but it looks terrible.
Any ideas hot to do it better and cleaner?
Another thing is I don't really know if it is even a good idea to use RxJS here as the easy regular way is to have a Boolean set to true and after I clicked set it to false and with setTimeout change it back to true.

Here is what i did:

```<code>// The stream of the button clicks.
$clicksStream
  // Change the click stream to the timed true false change.
  .switchMap(() => Observable
                    // Emit first value immediately and every 1 second after.
                    .timer(0, 1000)
                    // Map each one - 0 becomes false and others true.
                    .map(x => !!x)
                    // Take only first two items.
                    .take(2))
  // Always the start value is true.
  .startWith(true);
</code>```

答:
Handling async operations with rxjs is an excellent idea. It's what reactive programming is about and rxjs is good at doing it.

The beauty of the code you have produced is that it is pure. It doesn't depend on any external context.

Using the setTimeout and the good ol' boolean to change state will work of course but at the price of purity and functional programming. You would be doing imperative programming and side effects. And the semantic of the code wouldn't be the same

```<code>button.addEventListener("click", function refresh(event) {
  refreshData();
  setTimeout(renderButton, 1000, true)
  renderButton(false)
})
</code>```

The problem with that piece of code: it is very dependant on its context. For it to work you need to implement refreshData and renderButton. They also need to be accessible from that scope.

But you piece of code was totally standalone, you could copy/paste it elsewhere, it would still work.

The other problem is that the click handler function is responsible for way too many things (actually refreshing the data, rendering the new state of the button and launching the timeout. It's totally breaking the Single Responsibility Principle.

I hope I have helped you seeing the benefits of the code you have produced. It's actually pretty good, it's just a matter of getting used to it.

One simple simplification you could make would be using startWith and mapTo instead of the kind-of-hacky !!x :)

```<code>$clicksStream
  // Change the click stream to the timed true false change.
  .switchMap(() => Observable
                    // just a timer of 1000ms
                    .timer(1000)
                    // when it emits we just return true
                    .mapTo(true)
                    // Take only first two items.
                    .startWith(false)
  )
  // Always the start value is true.
  .startWith(true);
</code>```

Body:
I am new to RxJS and tried to do a simple demo that lets you refresh the data every one second.

I made a button and created a click stream from it.
The problem started when i wanted to make a stream that every button click emits false and after one second emits true once again.

For example - the initial state is true as we can refresh at start.
Once i clicked the button the new value should be false right after the click as we cant refresh further.

Lastly after one second passed - the value should be true once again.

I tried creating it and succeeded, but it looks terrible.
Any ideas hot to do it better and cleaner?
Another thing is I don't really know if it is even a good idea to use RxJS here as the easy regular way is to have a Boolean set to true and after I clicked set it to false and with setTimeout change it back to true.

Here is what i did:

// The stream of the button clicks.
$clicksStream
  // Change the click stream to the timed true false change.
  .switchMap(() => Observable
                    // Emit first value immediately and every 1 second after.
                    .timer(0, 1000)
                    // Map each one - 0 becomes false and others true.
                    .map(x => !!x)
                    // Take only first two items.
                    .take(2))
  // Always the start value is true.
  .startWith(true);

Body:
Handling async operations with rxjs is an excellent idea. It's what reactive programming is about and rxjs is good at doing it.

The beauty of the code you have produced is that it is pure. It doesn't depend on any external context.

Using the setTimeout and the good ol' boolean to change state will work of course but at the price of purity and functional programming. You would be doing imperative programming and side effects. And the semantic of the code wouldn't be the same

button.addEventListener("click", function refresh(event) {
  refreshData();
  setTimeout(renderButton, 1000, true)
  renderButton(false)
})

The problem with that piece of code: it is very dependant on its context. For it to work you need to implement refreshData and renderButton. They also need to be accessible from that scope.

But you piece of code was totally standalone, you could copy/paste it elsewhere, it would still work.

The other problem is that the click handler function is responsible for way too many things (actually refreshing the data, rendering the new state of the button and launching the timeout. It's totally breaking the Single Responsibility Principle.

I hope I have helped you seeing the benefits of the code you have produced. It's actually pretty good, it's just a matter of getting used to it.

One simple simplification you could make would be using startWith and mapTo instead of the kind-of-hacky !!x :)

$clicksStream
  // Change the click stream to the timed true false change.
  .switchMap(() => Observable
                    // just a timer of 1000ms
                    .timer(1000)
                    // when it emits we just return true
                    .mapTo(true)
                    // Take only first two items.
                    .startWith(false)
  )
  // Always the start value is true.
  .startWith(true);


问:
SQL: Add a new column based on CASE expression and looking up values from another table
I am trying to add a new column called Multiplier to an existing table called Trades. The row values of this column will depend on another column on the Trades table called Type. If the Type is anything other than "Equity", "Corp" or "Option, then the value needs to be looked up from another table called ContractSize. Lastly, I want the data type of the Multiplier column to be decimal (7,3). The code I had was:

```<code>ALTER TABLE Portfolio.Trades
ADD Multiplier decimal(7,3) AS
(
CASE
 WHEN Type = 'Equity' Then 1
 WHEN Type = 'Corp' Then 0.1
 WHEN Type = 'Option' Then 100
ELSE
 (SELECT ContractSize FROM Portfolio.ContractSize CS
 JOIN Portfolio.Trades T
 ON T.Identifier = CS.ContractSize)
)
</code>```

I am getting two errors on this code:

Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'AS'.

Msg 102, Level 15, State 1, Line 12
Incorrect syntax near ')'.

Some guidance is much appreciated.

答:
Every CASE statement must have a END keyword at the end of the condition. In this case it should be like this.</p>

```<code>ALTER TABLE Portfolio.Trades
ADD Multiplier decimal(7,3) AS
(
CASE
 WHEN Type = 'Equity' Then 1
 WHEN Type = 'Corp' Then 0.1
 WHEN Type = 'Option' Then 100
ELSE
 (SELECT ContractSize FROM Portfolio.ContractSize CS
 JOIN Portfolio.Trades T
 ON T.Identifier = CS.ContractSize)END
)
</code>```

Body:
I am trying to add a new column called Multiplier to an existing table called Trades. The row values of this column will depend on another column on the Trades table called Type. If the Type is anything other than "Equity", "Corp" or "Option, then the value needs to be looked up from another table called ContractSize. Lastly, I want the data type of the Multiplier column to be decimal (7,3). The code I had was:

ALTER TABLE Portfolio.Trades
ADD Multiplier decimal(7,3) AS
(
CASE
 WHEN Type = 'Equity' Then 1
 WHEN Type = 'Corp' Then 0.1
 WHEN Type = 'Option' Then 100
ELSE
 (SELECT ContractSize FROM Portfolio.ContractSize CS
 JOIN Portfolio.Trades T
 ON T.Identifier = CS.ContractSize)
)

I am getting two errors on this code:

Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'AS'.

Msg 102, Level 15, State 1, Line 12
Incorrect syntax near ')'.

Some guidance is much appreciated.

Body:
Every CASE statement must have a END keyword at the end of the condition. In this case it should be like this.

ALTER TABLE Portfolio.Trades
ADD Multiplier decimal(7,3) AS
(
CASE
 WHEN Type = 'Equity' Then 1
 WHEN Type = 'Corp' Then 0.1
 WHEN Type = 'Option' Then 100
ELSE
 (SELECT ContractSize FROM Portfolio.ContractSize CS
 JOIN Portfolio.Trades T
 ON T.Identifier = CS.ContractSize)END
)


问:
Dynamic variable assignment VBA
Ok so I have been struggling to figure out what the problem is with my assignment of my variables 'aveCellAdrs' & 'q'. Each suffers from the error: method 'Range' of object 'Global_' failed.

What I want the variables 'q' & 'aveCellAdrs' to do, is refer to the dynamic variable 'k' (k changes each time the loop goes through itself) and then get their new range from that.

Heres is my code:

```<code>             Dim i As Integer
             Dim j As Integer
             Dim k As Range
             Dim q As Range
             Dim tableRange2 As Range
             Dim total As Double
             Dim table2average As Double
             Dim aveCellAdrs As Range

For i = 1 To 20
    Set k = Range("B73").End(xlUp).Offset(i, 0) 'This finds the top-most cell as a starting point
            Set aveCellAdrs = Range(k).End(xlToRight)  'Used to enter the average found in the loops below to the correct cell
                 Set q = Range(k).End(xlToRight).Offset(0, -1)  'This finds the right-most cell in the row
                      Set table2Range2 = Range(k, q)  'Identifying the dynamic range to which we will calculate each rows' average
</code>```

Hopefully this makes sense. Here is the attached screenshot of the code block:

答:
braX is correct, in VBA range is an object, not a datatype.  When you enter:

```<code>Set table2Range2 = Range(k, q)
</code>```

what I think you're trying to do is to pass the left-most and right-most limits of the range to range() in order to set the range for table2Range2.  If that's the case, you want to pass the cell addresses (i.e. B2:E2), which is what range() expects to receive. What you're actually doing in your code above is trying to pass entire range object, which is causing range() to throw an error.

Here's what I would do:  start off by setting a range as reference point, create some string variables to hold the cell addresses at the corners of the range you're trying to create. Build that into a string and pass that to range() to set tablerange dynamically for each iteration of your loop.  Once you set a range you can use the .address method to grab the cell address.  See below:

```<code>Dim i As Integer
Dim startingPoint As Range
Dim rngStart As String
Dim rngEnd As String
Dim tableRange As Range

For i = 1 To 20
    Set startingPoint = Range("B73").End(xlUp).Offset(i, 0)
    rngStart = startingPoint.Address 'This finds the top-most cell as a starting point
    rngEnd = startingPoint.End(xlToRight).Offset(0, -1).Address 'This finds the right-most cell in the row
    Set tableRange = Range(rngStart & ":" & rngEnd)  'Identifying the dynamic range to which we will calculate each rows' average
Next
</code>```

Title: Dynamic variable assignment VBA

Body:
Ok so I have been struggling to figure out what the problem is with my assignment of my variables 'aveCellAdrs' & 'q'. Each suffers from the error: method 'Range' of object 'Global_' failed.

What I want the variables 'q' & 'aveCellAdrs' to do, is refer to the dynamic variable 'k' (k changes each time the loop goes through itself) and then get their new range from that.

Heres is my code:

             Dim i As Integer
             Dim j As Integer
             Dim k As Range
             Dim q As Range
             Dim tableRange2 As Range
             Dim total As Double
             Dim table2average As Double
             Dim aveCellAdrs As Range

For i = 1 To 20
    Set k = Range("B73").End(xlUp).Offset(i, 0) 'This finds the top-most cell as a starting point
            Set aveCellAdrs = Range(k).End(xlToRight)  'Used to enter the average found in the loops below to the correct cell
                 Set q = Range(k).End(xlToRight).Offset(0, -1)  'This finds the right-most cell in the row
                      Set table2Range2 = Range(k, q)  'Identifying the dynamic range to which we will calculate each rows' average

Hopefully this makes sense. Here is the attached screenshot of the code block:

Body:
braX is correct, in VBA range is an object, not a datatype.  When you enter:

Set table2Range2 = Range(k, q)

what I think you're trying to do is to pass the left-most and right-most limits of the range to range() in order to set the range for table2Range2.  If that's the case, you want to pass the cell addresses (i.e. B2:E2), which is what range() expects to receive. What you're actually doing in your code above is trying to pass entire range object, which is causing range() to throw an error.

Here's what I would do:  start off by setting a range as reference point, create some string variables to hold the cell addresses at the corners of the range you're trying to create. Build that into a string and pass that to range() to set tablerange dynamically for each iteration of your loop.  Once you set a range you can use the .address method to grab the cell address.  See below:

Dim i As Integer
Dim startingPoint As Range
Dim rngStart As String
Dim rngEnd As String
Dim tableRange As Range

For i = 1 To 20
    Set startingPoint = Range("B73").End(xlUp).Offset(i, 0)
    rngStart = startingPoint.Address 'This finds the top-most cell as a starting point
    rngEnd = startingPoint.End(xlToRight).Offset(0, -1).Address 'This finds the right-most cell in the row
    Set tableRange = Range(rngStart & ":" & rngEnd)  'Identifying the dynamic range to which we will calculate each rows' average
Next


问:
Append element from another page?
Given this HTML:

index.html:

```<code><div class="tile" data-tilename="test">
    <div class="tileHeader">Tile Name</div>
</div>
</code>```

tile-content.html:

```<code><div id="test-tile" class="tileContent">
       <!-- lots of stuff here. -->
</div>
</code>```

How can I arrive at the following?

```<code><div class="tile">
    <div class="tileHeader">Tile Name</div>
    <div class="tileContent">
       //lots of stuff here.
    </div>
</div>
</code>```

Currently all these are created dynamically, so here is my current code:

```<code>let $elTile = $('<div/>', {
    class: 'tile'
}).appendTo($elContainer);

let $elTileHeader = $('<div/>', {
    class: 'tileHeader',
    html: tile.header
}).appendTo($elTile);

let $elTileContent = $('<div>').load('tile-content.html #' + tile.name + '-tile');
$elTile.append($elTileContent);
</code>```

The last two lines above were inspired by this solution.  Unfortunately it adds an extra
 which I would like to avoid:

```<code><div class="tile">
    <div class="tileHeader">Tile Name</div>
    <div> <!-- I don't want this -->
        <div class="tileContent">
           <!-- lots of stuff here. -->
        </div>
    <div>
</div>
</code>```

How can I arrive at the desired solution?

There are a couple similar questions, but none that I found have solutions and my situation is slightly different (dynamically created elements).

答:
It's because you are creating that extra div by yourself here:

```<code>let $elTileContent = $('<div>').load(...)
</code>```

You should load the content, then prepend the header:

```<code>//create the tile and add it to the container
let $elTile = $('<div/>', {
    class: 'tile'
}).appendTo($elContainer);

//create the header but do not add it yet
let $elTileHeader = $('<div/>', {
    class: 'tileHeader',
    html: tile.header
})

//load the content into the tile
$elTile.load('tile-content.html #' + tile.name + '-tile', function(){
    //on the "complete" callback, prepend the header
    $elTile.prepend($elTileHeader);
});
</code>```

Happy Coding :)

Title: Append element from another page?

Body:
Given this HTML:

index.html:

Tile Name

tile-content.html:

How can I arrive at the following?

Tile Name

       //lots of stuff here.

Currently all these are created dynamically, so here is my current code:

let $elTile = $('
', {
    class: 'tile'
}).appendTo($elContainer);

let $elTileHeader = $('
', {
    class: 'tileHeader',
    html: tile.header
}).appendTo($elTile);

let $elTileContent = $('
').load('tile-content.html #' + tile.name + '-tile');
$elTile.append($elTileContent);

The last two lines above were inspired by this solution.  Unfortunately it adds an extra
 which I would like to avoid:

Tile Name

How can I arrive at the desired solution?

There are a couple similar questions, but none that I found have solutions and my situation is slightly different (dynamically created elements).

Body:
It's because you are creating that extra div by yourself here:

let $elTileContent = $('<div>').load(...)

You should load the content, then prepend the header:

//create the tile and add it to the container
let $elTile = $('<div/>', {
    class: 'tile'
}).appendTo($elContainer);

//create the header but do not add it yet
let $elTileHeader = $('<div/>', {
    class: 'tileHeader',
    html: tile.header
})

//load the content into the tile
$elTile.load('tile-content.html #' + tile.name + '-tile', function(){
    //on the "complete" callback, prepend the header
    $elTile.prepend($elTileHeader);
});

Happy Coding :)


问:
Implementing AJAX and database operations with Wicket
I'm trying to add AJAX to my project.

I have a link and a boolean variable named hasEngagement in my Wicket page. I want my link to produce a JavaScript informational warning if the boolean value is true, or perform a database operation otherwise. Here's my code:

```<code>Link myLink = new Link("mylink"){
     @Override
     onSubmit(){
     if(hasEngagement)
        //ajax operation
     else
        // database operation
     }
};
</code>```

答: Also you can assign your message to a Feedback message. And of course use AjaxLink</p>

Body:
I'm trying to add AJAX to my project.

I have a link and a boolean variable named hasEngagement in my Wicket page. I want my link to produce a JavaScript informational warning if the boolean value is true, or perform a database operation otherwise. Here's my code:

Link myLink = new Link("mylink"){
     @Override
     onSubmit(){
     if(hasEngagement)
        //ajax operation
     else
        // database operation
     }
};


问:
Dummy filters in Django
How do I make a dummy filter query in Django (a filter that is always matched) and an exclude query that is never matched.  The reason is because I have cases where my query is None, and in those cases I want to use a dummy filter.  This is the code:

```<code>MyModel.objects.filter(filterQuery).exclude(excludeQuery)
</code>```

In cases where filterQuery or excludeQuery is None I get an error, so I want to add the following conditional before that query:

```<code>if filterQuery == None: filterQuery = ???
if excludeQuery == None: excludeQuery = ???
MyModel.objects.filter(filterQuery).exclude(excludeQuery)
</code>```

答:
The best way is to use a dict, particularly if you have complex filters.

```<code>filterQuery = excludeQuery = {}

# optionally set the filters based on some logic
if 1==1:
  filterQuery['agent'] = 'John'

if 2==2:
  excludeQuery['user_id__in'] = [1, 2]

if 3==3:
  filterQuery['time__gte'] = timezone.now()

MyModel.objects.filter(**filterQuery).exclude(**excludeQuery)
</code>```

You could add some ifs like Shang suggested to see if you need to apply the filter or not, but I doubt there is much of a performance loss and this is much more readable.

Title: Dummy filters in Django

Body:
How do I make a dummy filter query in Django (a filter that is always matched) and an exclude query that is never matched.  The reason is because I have cases where my query is None, and in those cases I want to use a dummy filter.  This is the code:

MyModel.objects.filter(filterQuery).exclude(excludeQuery)

In cases where filterQuery or excludeQuery is None I get an error, so I want to add the following conditional before that query:

if filterQuery == None: filterQuery = ???
if excludeQuery == None: excludeQuery = ???
MyModel.objects.filter(filterQuery).exclude(excludeQuery)

Body:
The best way is to use a dict, particularly if you have complex filters.

filterQuery = excludeQuery = {}

# optionally set the filters based on some logic
if 1==1:
  filterQuery['agent'] = 'John'

if 2==2:
  excludeQuery['user_id__in'] = [1, 2]

if 3==3:
  filterQuery['time__gte'] = timezone.now()

MyModel.objects.filter(**filterQuery).exclude(**excludeQuery)

You could add some ifs like Shang suggested to see if you need to apply the filter or not, but I doubt there is much of a performance loss and this is much more readable.


问:
Is there a way to hook a script into Django's test server, so that it executes on each reload?
I have certain files that I want to be static on production but want to be able to write dynamically during development. So I would like to be able to execute a script to accomplish this each time the test server reloads, so that changes I have made will be taken into account, and the file gets updated. Is there any way to hook into the autoreloader to do this, or is this something I would need to do manually?</p>

答:
Ended up doing what was suggested here. In short, I just added the following to the end of urls.py.

```<code>from django.conf import settings

if settings.DEBUG:
    my_dev_reload_script()
</code>```

Thomas was close, but placing this in settings makes app references impossible. Putting it in urls ensures that apps are loaded.

Body:
Ended up doing what was suggested here. In short, I just added the following to the end of urls.py.

from django.conf import settings

if settings.DEBUG:
    my_dev_reload_script()

Thomas was close, but placing this in settings makes app references impossible. Putting it in urls ensures that apps are loaded.


问:
Can not get a styled anchor tag to display the proper height and width attributes for a simulated button in email on Outlook 2013 for Windows
My code does work properly in Outlook 15.33 for Mac. Buttons take the height and width of the linked text in the Windows version of Outlook. I have tried setting the buttons as  tags and  tags, but I have the same formatting issues on the Windows version of Outlook.</p>

```<code><table class="fullwidth260" border="0" width="215" cellspacing="0" cellpadding="5" align="left">
<tbody>
<tr>
<td valign="middle">
<a class="quickLinks" href="http://www.mba.org" style="display: flex; text-align: center; padding: 10px 20px 10px 20px; color: #496f8d; font-family: Arial, san-serif; size: 10pt; line-height: 1.2; border: 1px solid #c8d3dc; background-color: #e3e9ed; text-decoration: none; height: 60px; width: 160px; justify-content: center; flex-direction: column;">STATE RELATIONS ONLINE COMMUNITY</a>
</td>
</tr>
</tbody>
</table>
</code>```

答:
Your designing for email, not for the Web. Outlook non-Mac does not fully support the CSS attributes flex or padding.

Outlook is a major pain to get buttons to display correctly. I'd give you more advice, but you didn't post your existing code which makes it hard to make suggestions on how to offer better advice to fix your issues.

Good luck.

Body:
My code does work properly in Outlook 15.33 for Mac. Buttons take the height and width of the linked text in the Windows version of Outlook. I have tried setting the buttons as  tags and  tags, but I have the same formatting issues on the Windows version of Outlook.

STATE RELATIONS ONLINE COMMUNITY


问:
Official Windows C/C++ Compiler and C Libraries
I've been coding C/C++ in a Linux environment, and that has been a breeze (Open terminal > Vim > code > gcc > done). I'm trying to get into doing the same in Windows, and it hasn't been nearly as easy. I've gotten Vim to run out of terminal, as I do not like IDEs, thus I'm looking for a Windows compiler that I can work with via command-line.

My problem is that I can't find the official Windows compiler for C/C++, Microsoft support was useless, and MSDN keeps pointing me to Visual Studio. There are a plethora of questions here on SO, and the web about compilers for C/C++ on Windows, with suggestions like Dev-C++, but that comes with GCC. Visual Studio supports C/C++, and I would assume that compiler is the official one, but I've had no luck in finding just the compiler. The closest I've gotten is either the Windows SDK or Visual Studio Express 2015.

Additionally, I was told in the Stackoverflow C chat room, that C is no longer a subset of C++, so does that mean I need to find 2 compilers, one for C and one for C++?

I'm also trying to figure out where C/C++ libraries are. On Linux, they're already there. Is that the case with Windows, if not where do I find their C/C++ libraries?

I didn't expect it to be so difficult to get started, nor did I expect to get lost so quickly.

答:
The compiler is included with Visual Studio.  It is called "cl" and can be run from the command line. See these links for instructions:

Walkthrough: Compiling a Native C++ Program on the Command Line

Walkthrough: Compile a C program on the command line

They basically amount to "Open terminal > notepad > code > cl > done".  Not as hard as you're making it out to be.  I believe the instructions in those links also apply to the stand-alone build tools mentioned by the other answer.

There are better editors than notepad, and alternative compilers, but the question wasn't about editors, and cl is as close to an "official" compiler as you're going to get, so we won't get into that here.


问:
My 1:30 minute long WAV file is only playing for three seconds
I'm trying to play a .wav file in this code, but for some reason it only plays the minute-long song for about three seconds. Does anyone have any ideas why?</p>

```<code>private void btnPlayActionPerformed(java.awt.event.ActionEvent evt) {

   try {
        JFXPanel j = new JFXPanel();
        String uri = new File("04_Kensington_Chump (1).wav").toURI().toString();
        new MediaPlayer(new Media(uri)).play();
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(this, ex);
    }

}
</code>```

答:
You are creating a new media player in the method, and just leaving it there without storing it in a variable you can later access. This causes the garbage collector to pick it up.

Create a list to store all your media players so the garbage collector doesn't destroy them, and that should fix the problem

```<code>MediaPlayer player = new MediaPlayer(new Media(uri));
player.play();
someList.add(player);
</code>```

Then periodically clean the list when players are done playing the audio

Body:
I'm trying to play a .wav file in this code, but for some reason it only plays the minute-long song for about three seconds. Does anyone have any ideas why?

private void btnPlayActionPerformed(java.awt.event.ActionEvent evt) {

   try {
        JFXPanel j = new JFXPanel();
        String uri = new File("04_Kensington_Chump (1).wav").toURI().toString();
        new MediaPlayer(new Media(uri)).play();
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(this, ex);
    }

}

Body:
You are creating a new media player in the method, and just leaving it there without storing it in a variable you can later access. This causes the garbage collector to pick it up.

Create a list to store all your media players so the garbage collector doesn't destroy them, and that should fix the problem

MediaPlayer player = new MediaPlayer(new Media(uri));
player.play();
someList.add(player);

Then periodically clean the list when players are done playing the audio


问:
Design patterns to avoid
A lot of people seem to agree, that the Singleton pattern has a number of drawbacks and some even suggest avoiding the pattern entirely. There's an excellent discussion here. Please direct any comments about the Singleton pattern to that question.

My question: Are there other design patterns, that should be avoided or used with great care?

答: A complement to Spoike's post, Refactoring to Patterns is a good read.</p>

OwnerDisplayName: Brian Rasmussen

Title: Design patterns to avoid

LastEditorDisplayName: Joel Coehoorn

OwnerDisplayName: Adeel Ansari


问:
Can't clone public repo from within Dockerfile
I have the following line in my Dockerfile:

```<code>RUN git clone https://github.com/assafg/youtube-remote.git ./youtube-remote
</code>```

When executing sudo docker build -t 'yremote' .
I get the following error:

Cloning into './youtube-remote'... fatal: unable to access
  'https://github.com/assafg/youtube-remote.git/': Could not resolve
  host: github.com The command '/bin/sh -c git clone
  https://github.com/assafg/youtube-remote.git ./youtube-remote'
  returned a non-zero code: 128

Running clone command from command line works fine.

答: This is not a very scientific answer but sometimes docker restart helps especially in cases connected with docker network.</p>

Body:
I have the following line in my Dockerfile:

RUN git clone https://github.com/assafg/youtube-remote.git ./youtube-remote

When executing sudo docker build -t 'yremote' .
I get the following error:

Cloning into './youtube-remote'... fatal: unable to access
  'https://github.com/assafg/youtube-remote.git/': Could not resolve
  host: github.com The command '/bin/sh -c git clone
  https://github.com/assafg/youtube-remote.git ./youtube-remote'
  returned a non-zero code: 128

Running clone command from command line works fine.