问:
Rate-limiting and count-limiting events in RxJS v5, but also allowing pass-through
I have a bunch of events to send up to a service. But the requests are rate limited and each request has a count limit:

1 request per second: bufferTime(1000)

100 event items per request: bufferCount(100)

The problem is, I am not sure how to combine them in a way that makes sense.

Allowing pass-through

Complicating this further, I need to make sure that events go through instantaneously if we don't hit either limit.

For example, I don't want it to actually wait for 100 event items before letting it go through if it's only one single event during a non-busy time.

Legacy API

I also found that there was a bufferWithTimeOrCount that existed in RxJS v4, although I am not sure how I'd use that even if I had it.

Test playground

Here is a JSBin I made for you to test your solution:

http://jsbin.com/fozexehiba/1/edit?js,console,output

Any help would be greatly appreciated.

答:
I've modified the answer I gave to this question to support your use case of adding a limited number of values (i.e. events) to pending requests.

The comments within should explain how it works.

Because you need to keep a record of the requests that have been made within the rate limit period, I don't believe that it's possible to use the bufferTime and bufferCount operators to do what you want - a scan is required so that you can maintain that state within the observable.

function rateLimit(source, period, valuesPerRequest, requestsPerPeriod = 1) {

  return source
    .scan((requests, value) => {

      const now = Date.now();
      const since = now - period;

      // Keep a record of all requests made within the last period. If the
      // number of requests made is below the limit, the value can be
      // included in an immediate request. Otherwise, it will need to be
      // included in a delayed request.

      requests = requests.filter((request) => request.until > since);
      if (requests.length >= requestsPerPeriod) {

        const leastRecentRequest = requests[0];
        const mostRecentRequest = requests[requests.length - 1];

        // If there is a request that has not yet been made, append the
        // value to that request if the number of values in that request's
        // is below the limit. Otherwise, another delayed request will be
        // required.

        if (
          (mostRecentRequest.until > now) &&
          (mostRecentRequest.values.length < valuesPerRequest)
        ) {

          mostRecentRequest.values.push(value);

        } else {

          // until is the time until which the value should be delayed.

          const until = leastRecentRequest.until + (
            period * Math.floor(requests.length / requestsPerPeriod)
          );

          // concatMap is used below to guarantee the values are emitted
          // in the same order in which they are received, so the delays
          // are cumulative. That means the actual delay is the difference
          // between the until times.

          requests.push({
            delay: (mostRecentRequest.until < now) ?
              (until - now) :
              (until - mostRecentRequest.until),
            until,
            values: [value]
          });
        }

      } else {

        requests.push({
          delay: 0,
          until: now,
          values: [value]
        });
      }
      return requests;

    }, [])

    // Emit only the most recent request.

    .map((requests) => requests[requests.length - 1])

    // If multiple values are added to the request, it will be emitted
    // mulitple times. Use distinctUntilChanged so that concatMap receives
    // the request only once.

    .distinctUntilChanged()
    .concatMap((request) => {

      const observable = Rx.Observable.of(request.values);
      return request.delay ? observable.delay(request.delay) : observable;
    });
}

const start = Date.now();
rateLimit(
  Rx.Observable.range(1, 250),
  1000,
  100,
  1
).subscribe((values) => console.log(
  `Request with ${values.length} value(s) at T+${Date.now() - start}`
));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

```

Body:
I've modified the answer I gave to this question to support your use case of adding a limited number of values (i.e. events) to pending requests.

The comments within should explain how it works.

Because you need to keep a record of the requests that have been made within the rate limit period, I don't believe that it's possible to use the bufferTime and bufferCount operators to do what you want - a scan is required so that you can maintain that state within the observable.

function rateLimit(source, period, valuesPerRequest, requestsPerPeriod = 1) {

  return source
    .scan((requests, value) => {

      const now = Date.now();
      const since = now - period;

      // Keep a record of all requests made within the last period. If the
      // number of requests made is below the limit, the value can be
      // included in an immediate request. Otherwise, it will need to be
      // included in a delayed request.

      requests = requests.filter((request) => request.until > since);
      if (requests.length >= requestsPerPeriod) {

        const leastRecentRequest = requests[0];
        const mostRecentRequest = requests[requests.length - 1];

        // If there is a request that has not yet been made, append the
        // value to that request if the number of values in that request's
        // is below the limit. Otherwise, another delayed request will be
        // required.

        if (
          (mostRecentRequest.until > now) &&
          (mostRecentRequest.values.length < valuesPerRequest)
        ) {

          mostRecentRequest.values.push(value);

        } else {

          // until is the time until which the value should be delayed.

          const until = leastRecentRequest.until + (
            period * Math.floor(requests.length / requestsPerPeriod)
          );

          // concatMap is used below to guarantee the values are emitted
          // in the same order in which they are received, so the delays
          // are cumulative. That means the actual delay is the difference
          // between the until times.

          requests.push({
            delay: (mostRecentRequest.until < now) ?
              (until - now) :
              (until - mostRecentRequest.until),
            until,
            values: [value]
          });
        }

      } else {

        requests.push({
          delay: 0,
          until: now,
          values: [value]
        });
      }
      return requests;

    }, [])

    // Emit only the most recent request.

    .map((requests) => requests[requests.length - 1])

    // If multiple values are added to the request, it will be emitted
    // mulitple times. Use distinctUntilChanged so that concatMap receives
    // the request only once.

    .distinctUntilChanged()
    .concatMap((request) => {

      const observable = Rx.Observable.of(request.values);
      return request.delay ? observable.delay(request.delay) : observable;
    });
}

const start = Date.now();
rateLimit(
  Rx.Observable.range(1, 250),
  1000,
  100,
  1
).subscribe((values) => console.log(
  `Request with ${values.length} value(s) at T+${Date.now() - start}`
));

.as-console-wrapper { max-height: 100% !important; top: 0; }

<script src="https://unpkg.com/rxjs@5/bundles/Rx.min.js"></script>


来源: stackexchange

问:
How to populate a Combobox with items and one textbox
I have two ComboBoxes, based on the selection of the first, the seconds gets populated.

How to make the second ComboBox act or display a TextBox when Other is selected in first one, so user can enter numbers/letters.

 C#

```<code> public class MyViewModel
 {
     public ICommand UpdateCommand { get; private set; }

     private ObservableCollection<string> _Veh = new ObservableCollection<string>();

     private ObservableCollection<string> _VehTypes = new ObservableCollection<string>();
     private ObservableCollection<string> _cars = new ObservableCollection<string>();
     private ObservableCollection<string> _planes = new ObservableCollection<string>();

     public ObservableCollection<string> Veh
     {
         get { return _Veh; }
         set { SetProperty(ref _Veh, value); }
     }

     public ObservableCollection<string> VehTypes
     {
         get { return _VehTypes; }
         set { SetProperty(ref _VehTypes, value); }
     }

     public MyViewModel()
     {
         UpdateCommand = new DelegateCommand<object>(OnUpdate);

         _Veh.Add("Cars");
         _Veh.Add("Planes");
         _Veh.Add("Other");

         _Cars.Add("GM");
         _Cars.Add("BMW");
         _Cars.Add("Toyota");
         _Cars.Add("Honda");

         _planes.Add("AirBus");
         _planes.Add("Boing");
    }

    private void OnUpdate(object myobj)
    {
        _VehTypes.Clear();
        // Add new vehTypes based on _cars and _planes
    }
}
</code>```

 wpf

```<code><ComboBox Name="ComboVeh" ItemsSource="{Binding Veh}" >
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectionChanged">
            <i:InvokeCommandAction Command="{Binding UpdateCommand}"
                                                       CommandParameter="{Binding SelectedValue, ElementName=ComboVeh}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</ComboBox>

<ComboBox Name="ComboVehTypes" ItemsSource="{Binding VehTypes}"/>
</code>```

答:
Your goal can be achieved by following:

Add a new 'TextBox' (this will handle the text when "Other" is selected in first dropdown) in your view.

Bind the Visibility property of both - second dropdown and this new TextBox from ViewModel and make them visible accordingly.

Like, if 'Other' is selected in first dropdown set 'Visibility' of second dropdown to 'Collapsed' and 'Visibility' of TextBox to 'Visible' else vice-versa.

So, at once only one element will be visible to user - either second dropdown or a TextBox based on the selection in first dropdown.

You are already handling second dropdown selection so all you need is to bind the 'Text' property of new TextBox from ViewModel so if 'Other' is selected in first dropdown you can use that Text (entered by user in TextBox) for further manipulation or to store in DB.

Hope, this helps.

ContentLicense: CC BY-SA 3.0

Body:
I have two ComboBoxes, based on the selection of the first, the seconds gets populated.

How to make the second ComboBox act or display a TextBox when Other is selected in first one, so user can enter numbers/letters.

 C#

 public class MyViewModel
 {
     public ICommand UpdateCommand { get; private set; }

     private ObservableCollection<string> _Veh = new ObservableCollection<string>();

     private ObservableCollection<string> _VehTypes = new ObservableCollection<string>();
     private ObservableCollection<string> _cars = new ObservableCollection<string>();
     private ObservableCollection<string> _planes = new ObservableCollection<string>();

     public ObservableCollection<string> Veh
     {
         get { return _Veh; }
         set { SetProperty(ref _Veh, value); }
     }

     public ObservableCollection<string> VehTypes
     {
         get { return _VehTypes; }
         set { SetProperty(ref _VehTypes, value); }
     }

     public MyViewModel()
     {
         UpdateCommand = new DelegateCommand<object>(OnUpdate);

         _Veh.Add("Cars");
         _Veh.Add("Planes");
         _Veh.Add("Other");

         _Cars.Add("GM");
         _Cars.Add("BMW");
         _Cars.Add("Toyota");
         _Cars.Add("Honda");

         _planes.Add("AirBus");
         _planes.Add("Boing");
    }

    private void OnUpdate(object myobj)
    {
        _VehTypes.Clear();
        // Add new vehTypes based on _cars and _planes
    }
}

 wpf

<ComboBox Name="ComboVeh" ItemsSource="{Binding Veh}" >

</ComboBox>

<ComboBox Name="ComboVehTypes" ItemsSource="{Binding VehTypes}"/>


问:
swift XCTAssertEquals succeeded with Optional
I have this succeeded test:

```<code>func testProfileFieldValue() {
   let realm = try! Realm()
   let vs = ["name":"n"]
   createOrUpdate(realm: realm, value: vs)
   let profile = realm.objects(Profile.self).first
   XCTAssertEqual("n", profile?.name)
}
private func createOrUpdate(realm:Realm, value: Any = [:]) {
    try! realm.write() {
      realm.create(Profile.self,value:value,update: true)
    }
}
</code>```

Why did this test succeed? "n" is not an optional. If i try to assert:

```<code> XCTAssertEqual("nf", profile?.name)
</code>```

I get this failure message from Xcode:

XCTAssertEqual failed: ("Optional("nf")") is not equal to
  ("Optional("n")")

Why "nf" is and Optional?

thx

答:
What's happening with

```<code>XCTAssertEqual("nf", profile?.name)
</code>```

is the compiler sees that the second expression evaluates to an optional String. It then implicitly converts the first expression to an optional, in order to do the comparison. This is why the failure message shows both sides as Optional.

Body:
I have this succeeded test:

func testProfileFieldValue() {
   let realm = try! Realm()
   let vs = ["name":"n"]
   createOrUpdate(realm: realm, value: vs)
   let profile = realm.objects(Profile.self).first
   XCTAssertEqual("n", profile?.name)
}
private func createOrUpdate(realm:Realm, value: Any = [:]) {
    try! realm.write() {
      realm.create(Profile.self,value:value,update: true)
    }
}

Why did this test succeed? "n" is not an optional. If i try to assert:

 XCTAssertEqual("nf", profile?.name)

I get this failure message from Xcode:

XCTAssertEqual failed: ("Optional("nf")") is not equal to
  ("Optional("n")")

Why "nf" is and Optional?

thx

Body:
What's happening with

XCTAssertEqual("nf", profile?.name)

is the compiler sees that the second expression evaluates to an optional String. It then implicitly converts the first expression to an optional, in order to do the comparison. This is why the failure message shows both sides as Optional.

ContentLicense: CC BY-SA 4.0


问:
How to set http headers for static files?
I use gin-gonic's r.Static("files", "./files") to serve all files in the files directory. Is there a way to set headers for these file requests so I can allow CORS?

答:
There is an official Gin middleware providing this functionality.

A Good starting template (from their examples)

```<code>func main() {
    router := gin.Default()
    // - No origin allowed by default
    // - GET,POST, PUT, HEAD methods
    // - Credentials share disabled
    // - Preflight requests cached for 12 hours
    config := cors.DefaultConfig()
    config.AllowOrigins = []string{"http://google.com"}
    config.AddAllowOrigins("http://facebook.com")
    // config.AllowOrigins == []string{"http://google.com", "http://facebook.com"}

    router.Use(cors.New(config))
    router.Run()
}
</code>```

Body:
There is an official Gin middleware providing this functionality.

A Good starting template (from their examples)

func main() {
    router := gin.Default()
    // - No origin allowed by default
    // - GET,POST, PUT, HEAD methods
    // - Credentials share disabled
    // - Preflight requests cached for 12 hours
    config := cors.DefaultConfig()
    config.AllowOrigins = []string{"http://google.com"}
    config.AddAllowOrigins("http://facebook.com")
    // config.AllowOrigins == []string{"http://google.com", "http://facebook.com"}

    router.Use(cors.New(config))
    router.Run()
}


问:
Regular expression to validate an Australian bank BSB number (XXX-XXX)?
I am trying to come up with a regex for validating a BSB number which is in the format of 3 digits, a dash, and 3 digits (e.g. 123-456).

I thought /[1-9]{3}-{1}[1-9]{3}/ would work, but it doesn't. Can someone show me which regex I need to match the BSB format?

答:
Zero is in fact allowed for BSB codes, and the dash is optional. I would probably use /\d{3}-?\d{3}/, or /[0-9]{3}-?[0-9]{3}/. That said, your given regex should definitely match a number like 123-456, so if it's not I would investigate that (e.g. are the /'s part of the regex?).

A failing code snippet would be extremely helpful here, in many cases @Phil's regex would be more correct. As the question is given it's hard to tell.


问:
fatal error: openssl/rsa.h: No such file or directory
I got this error when I executed g++ mycode.cpp, and this .cpp file include a line #include<openssl/rsa.h>. Now, I know the error's reason, and I have tow plan to resolve it:

I can add the openssl path to /etc/profile,

or I also can copy openssl folder to /usr/include, so I did the first plan, like this:

```<code>CPLUS_INCLUDE_PATH=$CPLUS_INCLUDE_PATH:/mylib

export CPLUS_INCLUDE_PATH
</code>```

(my openssl folder's path is /mylib/openssl)

and I got this error again.

Then I try second plan, and it passed complie,(like this /usr/include/openssl).

Now, my problem is,

why the header ("openssl/rsa.h") can be found under /usr/include/ but can not be found under /mylib/, even I had add the path(/mylib) to /etc/profile?

答:
To install OpenSSL on Debian, Ubuntu, or other derivative versions:

$ sudo apt-get install libssl-dev

To install the OpenSSL development kit on Fedora, CentOS, or RHEL:

$ sudo yum install openssl-devel

After installation, try to recompile the program.

Body:
I got this error when I executed g++ mycode.cpp, and this .cpp file include a line #include<openssl/rsa.h>. Now, I know the error's reason, and I have tow plan to resolve it:

I can add the openssl path to /etc/profile,

or I also can copy openssl folder to /usr/include, so I did the first plan, like this:

CPLUS_INCLUDE_PATH=$CPLUS_INCLUDE_PATH:/mylib

export CPLUS_INCLUDE_PATH

(my openssl folder's path is /mylib/openssl)

and I got this error again.

Then I try second plan, and it passed complie,(like this /usr/include/openssl).

Now, my problem is,

why the header ("openssl/rsa.h") can be found under /usr/include/ but can not be found under /mylib/, even I had add the path(/mylib) to /etc/profile?


问:
Spliting on every character except for preserved substring
Given the string

```<code>word = "These"
</code>```

that contains the tuple

```<code>pair = ("h", "e")
</code>```

the aim is to replace the word such that it splits on all character except for the pair tuple, i.e. output:

```<code>('T', 'he', 's', 'e')
</code>```

I've tried:

```<code>word = 'These'
pair = ('h', 'e')
first, second = pair
pair_str = ''.join(pair)
pair_str = pair_str.replace('\\','\\\\')
pattern = re.compile(r'(?<!\S)' + re.escape(first + ' ' + second) + r'(?!\S)')
new_word = ' '.join(word)
new_word = pattern.sub(pair_str, new_word)
result = tuple(new_word.split())
</code>```

Note that sometimes the pair tuple can contain slashes, backslashes or any other escape characters, thus the replace and escape in the above regex.

Is there a simpler way to achieve the same string replacement?

EDITED

Specifics from comments:

And is there a distinction between when both characters in the pair are unique and when they aren't?

Nope, they should be treated the same way.

答:
Match instead of splitting:

```<code>pattern = re.escape(''.join(pair)) + '|.'
result = tuple(re.findall(pattern, word))
</code>```

The pattern is <pair>|., which matches the pair if possible and a single character* otherwise.

You can also do this without regular expressions:

```<code>import itertools

non_pairs = word.split(''.join(pair))
result = [(''.join(pair),)] * (2 * len(non_pairs) - 1)
result[::2] = non_pairs
result = tuple(itertools.chain(*result))
</code>```

* It doesn’t match newlines, though; if you have those, pass re.DOTALL as a third argument to re.findall.

Body:
Given the string

word = "These"

that contains the tuple

pair = ("h", "e")

the aim is to replace the word such that it splits on all character except for the pair tuple, i.e. output:

('T', 'he', 's', 'e')

I've tried:

word = 'These'
pair = ('h', 'e')
first, second = pair
pair_str = ''.join(pair)
pair_str = pair_str.replace('\\','\\\\')
pattern = re.compile(r'(?<!\S)' + re.escape(first + ' ' + second) + r'(?!\S)')
new_word = ' '.join(word)
new_word = pattern.sub(pair_str, new_word)
result = tuple(new_word.split())

Note that sometimes the pair tuple can contain slashes, backslashes or any other escape characters, thus the replace and escape in the above regex.

Is there a simpler way to achieve the same string replacement?

EDITED

Specifics from comments:

And is there a distinction between when both characters in the pair are unique and when they aren't?

Nope, they should be treated the same way.

Body:
Match instead of splitting:

pattern = re.escape(''.join(pair)) + '|.'
result = tuple(re.findall(pattern, word))

The pattern is <pair>|., which matches the pair if possible and a single character* otherwise.

You can also do this without regular expressions:

import itertools

non_pairs = word.split(''.join(pair))
result = [(''.join(pair),)] * (2 * len(non_pairs) - 1)
result[::2] = non_pairs
result = tuple(itertools.chain(*result))

* It doesn’t match newlines, though; if you have those, pass re.DOTALL as a third argument to re.findall.


问:
genuine bulk email solution for support system
I have a support system for my clients where we send a ton's of reply to their support tickets, every day. We are using google suite as official email solution and many times we encounter the per day limit issue.

We have looked for our own SMTP server option but due to high manageability concern, we are looking for third party services.

I have checked Amazon SES, mailgun and mailchimp but I am still not conveyance for long term solution. The service provider must be "trusted" in terms of security and spamming and should not be blocked due to customer email policies.

Any suggestion please.

答: In my experience the best solution that satisfies all your requirements would be sparkpost. It's the best cost effective and reliable third party solution according to my personal experience. </p>


问:
Ruby Elegant Way to Return Min/Max if Value Outside Range
So I am writing a program to model a process and need to calculate fees. The logic is that if the fee amount is less than a minimum use the minimum and if the fee amount is greater than the maximum use the maximum.

I can of course make this happen on multiple lines but would be interested to know if there is a more elegant way to do this in Ruby.

```<code>fee_amount = <whatever logic I need>
if fee_amount < min return min
if fee_amount > max return max
return fee_amount
</code>```

答:
```<code># stabby lambda function:
map = ->(val, min, max) { [min, val, max].sort[1] }

# call stabby function:
map.call(2.5, 1, 3)
=> 2.5
# or shorter:
map[2.5, 1, 3]
=> 2.5
</code>```

Body:
So I am writing a program to model a process and need to calculate fees. The logic is that if the fee amount is less than a minimum use the minimum and if the fee amount is greater than the maximum use the maximum.

I can of course make this happen on multiple lines but would be interested to know if there is a more elegant way to do this in Ruby.

fee_amount = <whatever logic I need>
if fee_amount < min return min
if fee_amount > max return max
return fee_amount


问:
Group Value and display data from different table
I have the following problem. I am trying to display total duration and workouts for a phase. I also want on the same time query a related table that stores the exercises for each workouts and displays how many exercises are in this phase:

The text output would be:

```<code>Phase 1
Duration: 268
Workouts: 6
Exercises: 17

Phase 2
Duration: 245
Workouts: 6
Exercises: 22
</code>```

etc

```<code>table rk_workouts
id | phase | workout | duration
 1 |     1 |       1 |       45
 2 |     1 |       2 |       49
 3 |     1 |       3 |       48
 4 |     1 |       4 |       41
 5 |     1 |       5 |       42
 6 |     1 |       6 |       43
 7 |     2 |       1 |       41
 8 |     2 |       2 |       40
 9 |     2 |       3 |       41
10 |     2 |       4 |       40
11 |     2 |       5 |       43
12 |     2 |       6 |       40
13 |     3 |       1 |       45
14 |     3 |       2 |       40
15 |     3 |       3 |       40
16 |     3 |       4 |       43
17 |     3 |       5 |       47

table rk_exercises

id | workout_id | workout_name
 1 |          1 | exercise 1
 2 |          1 | exercise 2
 3 |          1 | exercise 3
 4 |          1 | exercise 4
 5 |          1 | exercise 5
 6 |          1 | exercise 6
 7 |          1 | exercise 7
 8 |          2 | exercise 1
 9 |          2 | exercise 2
10 |          2 | exercise 3
11 |          2 | exercise 4
12 |          2 | exercise 5
13 |          2 | exercise 6
14 |          3 | exercise 1
15 |          3 | exercise 2
16 |          3 | exercise 3
17 |          3 | exercise 4
etc
</code>```

I am querying the following:

```<code>$this->db->qry = "SELECT
                    a.phase,
                    SUM(a.duration) as duration,
                    COUNT(a.workout) as workouts,
                    COUNT(b.id) as exercises
                FROM
                    rk_workouts a
                JOIN
                    rk_exercises b
                ON
                    a.workout=b.workout_id
                WHERE
                    a.category_id = '".$catid."'
                GROUP BY
                    a.phase
                ORDER BY
                    a.phase ASC";
</code>```

I then insert the result into an array:

```<code>$rlt = $this->db->_result();
if(count($rlt) > 0){
    $new_arr = array();
    foreach($rlt as $dta){
        $new_arr["Phases"][] = array(
            "phase"=>$dta['phase'],
            "duration" => $dta['duration'],
            "workouts" => $dta['workouts'],
            "exercises" => $dta['exercises']
        );
    }
</code>```

The result of my array output is not what I expected. I am trying to get the following output:

```<code>{
    "Phases": [{
        "phase": "1",
        "duration": "268",
        "workouts": "6",
        "exercises": "17"
    }]
}
</code>```

But I get the following:

```<code>{
    "Phases": [{
        "phase": "1",
        "duration": "1788",
        "workouts": "40",
        "exercises": "40"
    }]
}
</code>```

I am most certain my query is very wrong and wonder if someone could help me out or point me into the right direction. If need to, I can provide full table data.

Thank you for any help and time.

答:
The new query I am using is before running the main query is:

```<code>$this->db->qry = "SELECT id FROM rk_workouts";
$mainSQL = $this->db->_execute();
$rlt = $this->db->_result();
  while ($row = mysqli_fetch_assoc($mainSQL)) {
    $this->db->qry = "SELECT COUNT(id) as exercises, workout_id FROM rk_exercises WHERE workout_id = '".$row['id']."' ";
    $subSQL = $this->db->_execute();
      while ($row = mysqli_fetch_assoc($subSQL)) {
        $this->db->qry = "UPDATE rk_workouts SET exercises = '".$row['exercises']."' WHERE id = ".$row['workout_id'];
      $this->db->_execute();
   }
}
</code>```

I added an extra column to the rk_workouts Table to store the result of the COUNT(id).

The nain query on my rk_workouts table looks like this:

```<code>$this->db->qry = "SELECT phase, SUM(duration) as duration, COUNT(workout) as workouts, SUM(exercises) as exercises FROM rk_workouts WHERE category_id = '".$catid."' GROUP by phase ORDER BY phase ASC";
</code>```

The result of my JSON output is now:

```<code>{
  "Phases": [
    {
      "phase": "1",
      "duration": "268",
      "workouts": "6",
      "exercises": "40"
    },
    {
      "phase": "2",
      "duration": "245",
      "workouts": "6",
      "exercises": "39"
    },
    {
      "phase": "3",
      "duration": "215",
      "workouts": "5",
      "exercises": "32"
    },
    {
      "phase": "4",
      "duration": "225",
      "workouts": "5",
      "exercises": "25"
    },
    {
      "phase": "5",
      "duration": "138",
      "workouts": "3",
      "exercises": "24"
    },
    {
      "phase": "6",
      "duration": "616",
      "workouts": "11",
      "exercises": "80"
    }
  ]
}
</code>```

This is exactly what I needed for my iOS project.
Thank you for everyone involved.

Body:
I have the following problem. I am trying to display total duration and workouts for a phase. I also want on the same time query a related table that stores the exercises for each workouts and displays how many exercises are in this phase:

The text output would be:

Phase 1
Duration: 268
Workouts: 6
Exercises: 17

Phase 2
Duration: 245
Workouts: 6
Exercises: 22

etc

table rk_workouts
id | phase | workout | duration
 1 |     1 |       1 |       45
 2 |     1 |       2 |       49
 3 |     1 |       3 |       48
 4 |     1 |       4 |       41
 5 |     1 |       5 |       42
 6 |     1 |       6 |       43
 7 |     2 |       1 |       41
 8 |     2 |       2 |       40
 9 |     2 |       3 |       41
10 |     2 |       4 |       40
11 |     2 |       5 |       43
12 |     2 |       6 |       40
13 |     3 |       1 |       45
14 |     3 |       2 |       40
15 |     3 |       3 |       40
16 |     3 |       4 |       43
17 |     3 |       5 |       47

table rk_exercises

id | workout_id | workout_name
 1 |          1 | exercise 1
 2 |          1 | exercise 2
 3 |          1 | exercise 3
 4 |          1 | exercise 4
 5 |          1 | exercise 5
 6 |          1 | exercise 6
 7 |          1 | exercise 7
 8 |          2 | exercise 1
 9 |          2 | exercise 2
10 |          2 | exercise 3
11 |          2 | exercise 4
12 |          2 | exercise 5
13 |          2 | exercise 6
14 |          3 | exercise 1
15 |          3 | exercise 2
16 |          3 | exercise 3
17 |          3 | exercise 4
etc

I am querying the following:

$this->db->qry = "SELECT
                    a.phase,
                    SUM(a.duration) as duration,
                    COUNT(a.workout) as workouts,
                    COUNT(b.id) as exercises
                FROM
                    rk_workouts a
                JOIN
                    rk_exercises b
                ON
                    a.workout=b.workout_id
                WHERE
                    a.category_id = '".$catid."'
                GROUP BY
                    a.phase
                ORDER BY
                    a.phase ASC";

I then insert the result into an array:

$rlt = $this->db->_result();
if(count($rlt) > 0){
    $new_arr = array();
    foreach($rlt as $dta){
        $new_arr["Phases"][] = array(
            "phase"=>$dta['phase'],
            "duration" => $dta['duration'],
            "workouts" => $dta['workouts'],
            "exercises" => $dta['exercises']
        );
    }

The result of my array output is not what I expected. I am trying to get the following output:

{
    "Phases": [{
        "phase": "1",
        "duration": "268",
        "workouts": "6",
        "exercises": "17"
    }]
}

But I get the following:

{
    "Phases": [{
        "phase": "1",
        "duration": "1788",
        "workouts": "40",
        "exercises": "40"
    }]
}

I am most certain my query is very wrong and wonder if someone could help me out or point me into the right direction. If need to, I can provide full table data.

Thank you for any help and time.

Body:
The new query I am using is before running the main query is:

$this->db->qry = "SELECT id FROM rk_workouts";
$mainSQL = $this->db->_execute();
$rlt = $this->db->_result();
  while ($row = mysqli_fetch_assoc($mainSQL)) {
    $this->db->qry = "SELECT COUNT(id) as exercises, workout_id FROM rk_exercises WHERE workout_id = '".$row['id']."' ";
    $subSQL = $this->db->_execute();
      while ($row = mysqli_fetch_assoc($subSQL)) {
        $this->db->qry = "UPDATE rk_workouts SET exercises = '".$row['exercises']."' WHERE id = ".$row['workout_id'];
      $this->db->_execute();
   }
}

I added an extra column to the rk_workouts Table to store the result of the COUNT(id).

The nain query on my rk_workouts table looks like this:

$this->db->qry = "SELECT phase, SUM(duration) as duration, COUNT(workout) as workouts, SUM(exercises) as exercises FROM rk_workouts WHERE category_id = '".$catid."' GROUP by phase ORDER BY phase ASC";

The result of my JSON output is now:

{
  "Phases": [
    {
      "phase": "1",
      "duration": "268",
      "workouts": "6",
      "exercises": "40"
    },
    {
      "phase": "2",
      "duration": "245",
      "workouts": "6",
      "exercises": "39"
    },
    {
      "phase": "3",
      "duration": "215",
      "workouts": "5",
      "exercises": "32"
    },
    {
      "phase": "4",
      "duration": "225",
      "workouts": "5",
      "exercises": "25"
    },
    {
      "phase": "5",
      "duration": "138",
      "workouts": "3",
      "exercises": "24"
    },
    {
      "phase": "6",
      "duration": "616",
      "workouts": "11",
      "exercises": "80"
    }
  ]
}

This is exactly what I needed for my iOS project.
Thank you for everyone involved.


问:
Prevent or remove an extra Series Y-axis Point from being added to Chart?
How can I remove or prevent the '120' Y-axis Point from being added to my column Chart? I only want to show data within 0 to 100.

See screenshot below:

This is my code that creates the chart (System.Windows.Forms.DataVisualization.Charting):

```<code>        Chart chart = new Chart();

        string[] xAxis1 = { "a", "b", "c", "d", "e", "f" };
        decimal[] yAxis1 = { 0, 20, 40, 60, 80, 100 };
        string[] xAxis2 = { "a", "b", "c", "d", "e", "f" };
        decimal[] yAxis2 = { 0, 20, 40, 60, 80, 100 };
        string[] xAxis3 = { "a", "b", "c", "d", "e", "f" };
        decimal[] yAxis3 = { 0, 20, 40, 60, 80, 100 };

        chart.Series.Add("Benchmark");
        chart.Series[0].ChartType = SeriesChartType.Column;
        chart.Series[0].Points.DataBindXY(xAxis1, yAxis1);
        chart.Series[0].Color = Color.Blue;

        chart.Series.Add("Current");
        chart.Series[1].ChartType = SeriesChartType.Column;
        chart.Series[1].Points.DataBindXY(xAxis2, yAxis2);
        chart.Series[1].Color = Color.Maroon;

        chart.Series.Add("Recommended");
        chart.Series[2].ChartType = SeriesChartType.Column;
        chart.Series[2].Points.DataBindXY(xAxis3, yAxis3);
        chart.Series[2].Color = Color.LawnGreen;

        // Chart area
        ChartArea area = new ChartArea();
        chart.ChartAreas.Add(area);

        // Chart Legend
        Legend legend = new Legend();
        legend.Docking = Docking.Bottom;
        chart.Legends.Add(legend);

        // Chart Size
        chart.Size = new Size(500, 350);
</code>```

Thank you.

答: Try chart.ChartAreas[0].AxisY.Maximum = 100; - jstreet.

Body:
How can I remove or prevent the '120' Y-axis Point from being added to my column Chart? I only want to show data within 0 to 100.

See screenshot below:

This is my code that creates the chart (System.Windows.Forms.DataVisualization.Charting):

        Chart chart = new Chart();

        string[] xAxis1 = { "a", "b", "c", "d", "e", "f" };
        decimal[] yAxis1 = { 0, 20, 40, 60, 80, 100 };
        string[] xAxis2 = { "a", "b", "c", "d", "e", "f" };
        decimal[] yAxis2 = { 0, 20, 40, 60, 80, 100 };
        string[] xAxis3 = { "a", "b", "c", "d", "e", "f" };
        decimal[] yAxis3 = { 0, 20, 40, 60, 80, 100 };

        chart.Series.Add("Benchmark");
        chart.Series[0].ChartType = SeriesChartType.Column;
        chart.Series[0].Points.DataBindXY(xAxis1, yAxis1);
        chart.Series[0].Color = Color.Blue;

        chart.Series.Add("Current");
        chart.Series[1].ChartType = SeriesChartType.Column;
        chart.Series[1].Points.DataBindXY(xAxis2, yAxis2);
        chart.Series[1].Color = Color.Maroon;

        chart.Series.Add("Recommended");
        chart.Series[2].ChartType = SeriesChartType.Column;
        chart.Series[2].Points.DataBindXY(xAxis3, yAxis3);
        chart.Series[2].Color = Color.LawnGreen;

        // Chart area
        ChartArea area = new ChartArea();
        chart.ChartAreas.Add(area);

        // Chart Legend
        Legend legend = new Legend();
        legend.Docking = Docking.Bottom;
        chart.Legends.Add(legend);

        // Chart Size
        chart.Size = new Size(500, 350);

Thank you.


问:
Overloading a route one and two variables in Rails 4
I recently upgraded from rails 3 to rails 4 on one of our legacy apps, the problem is that rails 4 doesn't allow the same path name on two URLs even if they take a different number of arguments.

E.g. we used to do this:

```<code>  get "object/:id/data/:dataid" => "object#data", as: :object_data
  get "object/:id/data/:dataid/:extra" => "object#data", as: :object_data
</code>```

but in rails 4 having two object_data_paths is not allowed. I'm wanting to accomplish the same thing as before. It seems like one method would be to call the second one something new, but use the same method, i.e.:

get "object/:id/data/:dataid/:extra" => "object#data", as: :object_data_extra

But this does seem like a worse solution than before. Any other ways I can do this? Thoughts on why we have to do this?

答:
There are two solutions. The first is to use an optional path segment:

```<code>get "object/:id/data/:dataid(/:extra)" => "object#data", as: :object_data
</code>```

The other is to wrap it in a helper:

```<code>get "object/:id/data/:dataid"        => "object#data", as: :object_data_1
get "object/:id/data/:dataid/:extra" => "object#data", as: :object_data_2

# And in application_helpers.rb or somewhere similar

def object_data_path(id, dataid, extra=nil)
  if extra
    object_data_2_path(id, dataid, extra)
  else
    object_data_1_path(id, dataid)
  end
end
</code>```

Body:
I recently upgraded from rails 3 to rails 4 on one of our legacy apps, the problem is that rails 4 doesn't allow the same path name on two URLs even if they take a different number of arguments.

E.g. we used to do this:

  get "object/:id/data/:dataid" => "object#data", as: :object_data
  get "object/:id/data/:dataid/:extra" => "object#data", as: :object_data

but in rails 4 having two object_data_paths is not allowed. I'm wanting to accomplish the same thing as before. It seems like one method would be to call the second one something new, but use the same method, i.e.:

get "object/:id/data/:dataid/:extra" => "object#data", as: :object_data_extra

But this does seem like a worse solution than before. Any other ways I can do this? Thoughts on why we have to do this?

Body:
There are two solutions. The first is to use an optional path segment:

get "object/:id/data/:dataid(/:extra)" => "object#data", as: :object_data

The other is to wrap it in a helper:

get "object/:id/data/:dataid"        => "object#data", as: :object_data_1
get "object/:id/data/:dataid/:extra" => "object#data", as: :object_data_2

# And in application_helpers.rb or somewhere similar

def object_data_path(id, dataid, extra=nil)
  if extra
    object_data_2_path(id, dataid, extra)
  else
    object_data_1_path(id, dataid)
  end
end


问:
How can I maintain consistency in a 2-way object relationship in JavaScript?
If I have a 2-way relationship between 2 objects, such that A relates to B and B relates to A, how can I keep this consistent such that the 2 objects will always refer back to each other?

I'm struggling to put my very simple problem into words, so here's a very simple example. I start with Husband and Wife:

```<code>function Husband() { this.wife; }
function Wife() { this.husband; }

var harry = new Husband();
var wendy = new Wife();

harry.wife = wendy;
wendy.husband = harry;
</code>```

Logically, if Harry's wife is Wendy, then Wendy's husband is Harry.

I need a way of keeping this relationship consistent. So I create a setter method on Husband and denote that the wife variable should be treated as private by prefixing with an underscore.

```<code>function Husband() {
    this._wife;
    this.setWife = function(wife) {
        this._wife = wife;
        wife.husband = this;
    }
}
</code>```

Describing this relationship is now simple and encourages consistency:

```<code>harry.setWife(wendy);
</code>```

Likewise, it would be nice to have the reverse option:

```<code>wendy.setHusband(harry);
</code>```

To do this I create a setHusband method on Wife, and tweak Husband as needed.

```<code>function Husband() {
    this._wife;
    this.setWife = function(wife) {
        this._wife = wife;
        // wife.husband = this; // <-- husband is now _husband (private)...
        wife.setHusband(this);  // <-- switching to a public method
    }
}

function Wife() {
    this._husband;
    this.setHusband = function(husband) {
        this._husband = husband;
        husband._wife = this;  // <-- Oops! _wife is private!
        husband.setWife(this); // <-- Oops! this results in an infinite loop!
    }
}
</code>```

At this point I run into a snag. My new setHusband method needs to be able to maintain consistency, but wife is now _wife (private), and calling setWife causes an infinite loop because they reciprocate each other.

I could create another set of methods like reallyJustSetHusband but that seems silly.

My conundrum isn't particular to JavaScript, but I've mentioned it in the question in case there's a particular approach needed.

What is the best way to achieve consistency between these 2 objects? Is there something I've overlooked?

Similar Pattern in the DOM

In the DOM, if you call parent.appendChild(child), then child.parentNode === parent. They are never inconsistent. If a parent has a child the child has the same parent. Other relationships such as nextSibling are also kept consistent.

答:
A simple way is to just check for redundant values and abort early:

```<code>function Husband() {
    this._wife;
    this.setWife = function(wife) {
        if(this._wife == wife) return; // prevents recursion
        this._wife = wife;
        wife.setHusband(this);
    }
}

function Wife() {
    this._husband;
    this.setHusband = function(husband) {
        if(this._husband == husband) return; // prevents recursion
        this._husband = husband;
        husband.setWife(this);
    }
}
</code>```

you could also use an external state manager (redux, sql, etc) with update events, or have direct properties that don't need setters and be careful about keeping the data updated.

Body:
If I have a 2-way relationship between 2 objects, such that A relates to B and B relates to A, how can I keep this consistent such that the 2 objects will always refer back to each other?

I'm struggling to put my very simple problem into words, so here's a very simple example. I start with Husband and Wife:

function Husband() { this.wife; }
function Wife() { this.husband; }

var harry = new Husband();
var wendy = new Wife();

harry.wife = wendy;
wendy.husband = harry;

Logically, if Harry's wife is Wendy, then Wendy's husband is Harry.

I need a way of keeping this relationship consistent. So I create a setter method on Husband and denote that the wife variable should be treated as private by prefixing with an underscore.

function Husband() {
    this._wife;
    this.setWife = function(wife) {
        this._wife = wife;
        wife.husband = this;
    }
}

Describing this relationship is now simple and encourages consistency:

harry.setWife(wendy);

Likewise, it would be nice to have the reverse option:

wendy.setHusband(harry);

To do this I create a setHusband method on Wife, and tweak Husband as needed.

function Husband() {
    this._wife;
    this.setWife = function(wife) {
        this._wife = wife;
        // wife.husband = this; // <-- husband is now _husband (private)...
        wife.setHusband(this);  // <-- switching to a public method
    }
}

function Wife() {
    this._husband;
    this.setHusband = function(husband) {
        this._husband = husband;
        husband._wife = this;  // <-- Oops! _wife is private!
        husband.setWife(this); // <-- Oops! this results in an infinite loop!
    }
}

At this point I run into a snag. My new setHusband method needs to be able to maintain consistency, but wife is now _wife (private), and calling setWife causes an infinite loop because they reciprocate each other.

I could create another set of methods like reallyJustSetHusband but that seems silly.

My conundrum isn't particular to JavaScript, but I've mentioned it in the question in case there's a particular approach needed.

What is the best way to achieve consistency between these 2 objects? Is there something I've overlooked?

Similar Pattern in the DOM

In the DOM, if you call parent.appendChild(child), then child.parentNode === parent. They are never inconsistent. If a parent has a child the child has the same parent. Other relationships such as nextSibling are also kept consistent.

Body:
A simple way is to just check for redundant values and abort early:

function Husband() {
    this._wife;
    this.setWife = function(wife) {
        if(this._wife == wife) return; // prevents recursion
        this._wife = wife;
        wife.setHusband(this);
    }
}

function Wife() {
    this._husband;
    this.setHusband = function(husband) {
        if(this._husband == husband) return; // prevents recursion
        this._husband = husband;
        husband.setWife(this);
    }
}

you could also use an external state manager (redux, sql, etc) with update events, or have direct properties that don't need setters and be careful about keeping the data updated.


问:
The simplest way to cut off unnecessary dots in octave/matlab
I have coordinates of dots (x,y) stored in 1206x2 matrix called data. The command plot(data(:,1),data(:,2)) gives that picture:

I've found maximums in my data with findpeaks command:

```<code>[pks,loc,smth] = findpeaks(data(:,2));
</code>```

And then plot them on previous graph:

```<code>plot(mod(:,1),mod(:,2),mod(loc,1),pks,'o')
</code>```

So, the question is: what is the simplest way to cut off maximums which I do not need, I mean the maximums below red line on this picture:

UPD:
The best way I've found by now is to use "MinPeakDistance" parameter.

答:
For the signal you've shown it's actually pretty straightforward. If I have some signal, similar to yours,

You can find the positive peaks where the sign of the derivative is equal to one

```<code>dy = [NaN, diff(y)];
pks = sign(dy) == 1;
t_pks = t(pks);
y_pks = y(pks);
</code>```

Body:
I have coordinates of dots (x,y) stored in 1206x2 matrix called data. The command plot(data(:,1),data(:,2)) gives that picture:

I've found maximums in my data with findpeaks command:

[pks,loc,smth] = findpeaks(data(:,2));

And then plot them on previous graph:

plot(mod(:,1),mod(:,2),mod(loc,1),pks,'o')

So, the question is: what is the simplest way to cut off maximums which I do not need, I mean the maximums below red line on this picture:

UPD:
The best way I've found by now is to use "MinPeakDistance" parameter.

Body:
For the signal you've shown it's actually pretty straightforward. If I have some signal, similar to yours,

You can find the positive peaks where the sign of the derivative is equal to one

dy = [NaN, diff(y)];
pks = sign(dy) == 1;
t_pks = t(pks);
y_pks = y(pks);


问:
is there a non brute force regex for matching 1st (x to y) characters of a word?
I have the following regex which works, in PERL, to find if the start of a word is contained in a string. I want it to be okay to find, say, divo but not dive. This is not too bad with brute force.

```<code>if ($a =~ /\b(div|divo|divor|divorc|divorce|divorces)\b/i)
{
  print "OK, I found the substring I needed.";
}
</code>```

In other words, if my program sees the start of "divorces" in a string, it flags that string as something I want to look at.

This is okay if I want to do this once, but I have a reason to do this multiple times with multiple words.

Is there a way to do this just with regexes, or would I have to do something like:

```<code>use strict;
use warnings;

while (my $str = <STDIN>)
{
  if (mymatch($str, "divorces", 3, 8))
  {
    print "Yay!\n";
  }
}

sub mymatch
{
  my $temp;
  for ($_[2]..$_[3])
  {
    $temp = substr($_[1], 0, $_);
    if ($_[0] =~ /\b$temp\b/i)
    {
      return 1;
    }
  }
  return 0;
}
</code>```

While being able to use a function like the above is acceptable to me, I have a feeling I'm missing a powerful advanced regex that might be helpful to me in the future as well.

Thanks for any and all help with this!

答:
It's easier if you turn things inside out. Instead of

```<code>"divo settlement talks" =~ /\b(div|divo|divor|divorc|divorce|divorces)\b/i
</code>```

let's do

```<code>"divorced" =~ /^(?:divo|settlement|talks)/i
</code>```

Code:

```<code>sub mymatch {
    my ($str, $targ, $min) = @_;
    my $max = length($targ);
    for my $word (grep { length($_) >= $min && length($_) <= $max } $str =~ /\w+/g) {
        return 1 if $targ =~ /^$word/i;
    }

    return 0;
}
</code>```

or

```<code>sub mymatch {
    my ($str, $targ, $min) = @_;
    my $max = length($targ);
    for my $word ($str =~ /\b\w{$min,$max}\b/g) {
        return 1 if $targ =~ /^$word/i;
    }

    return 0;
}
</code>```

or

```<code>sub mymatch {
    my ($str, $targ, $min) = @_;
    my $max = length($targ);
    my $pat = '^(?:' . join('|', $str =~ /\b\w{$min,$max}\b/g) . ')';
    return $targ =~ /$pat/i;
}
</code>```

Your way, while more complex, has the advantage of a building a regex that can search large amounts of text, and even multiple words at once.

```<code>sub build_pattern {
    my $min = shift;
    my @targs;
    for my $targ (@_) {
        push @targs, map { substr($targ, 0, $_) } $min..length($targ);
    }

    my $pat = join('|', @targs);
    return qr/\b(?:$pat)\b/i;
}

my $re = build_pattern(3, qw( divorced ... ));

$str =~ $re
</code>```

Body:
I have the following regex which works, in PERL, to find if the start of a word is contained in a string. I want it to be okay to find, say, divo but not dive. This is not too bad with brute force.

if ($a =~ /\b(div|divo|divor|divorc|divorce|divorces)\b/i)
{
  print "OK, I found the substring I needed.";
}

In other words, if my program sees the start of "divorces" in a string, it flags that string as something I want to look at.

This is okay if I want to do this once, but I have a reason to do this multiple times with multiple words.

Is there a way to do this just with regexes, or would I have to do something like:

use strict;
use warnings;

while (my $str = <STDIN>)
{
  if (mymatch($str, "divorces", 3, 8))
  {
    print "Yay!\n";
  }
}

sub mymatch
{
  my $temp;
  for ($_[2]..$_[3])
  {
    $temp = substr($_[1], 0, $_);
    if ($_[0] =~ /\b$temp\b/i)
    {
      return 1;
    }
  }
  return 0;
}

While being able to use a function like the above is acceptable to me, I have a feeling I'm missing a powerful advanced regex that might be helpful to me in the future as well.

Thanks for any and all help with this!

Body:
It's easier if you turn things inside out. Instead of

"divo settlement talks" =~ /\b(div|divo|divor|divorc|divorce|divorces)\b/i

let's do

"divorced" =~ /^(?:divo|settlement|talks)/i

Code:

sub mymatch {
    my ($str, $targ, $min) = @_;
    my $max = length($targ);
    for my $word (grep { length($_) >= $min && length($_) <= $max } $str =~ /\w+/g) {
        return 1 if $targ =~ /^$word/i;
    }

    return 0;
}

or

sub mymatch {
    my ($str, $targ, $min) = @_;
    my $max = length($targ);
    for my $word ($str =~ /\b\w{$min,$max}\b/g) {
        return 1 if $targ =~ /^$word/i;
    }

    return 0;
}

or

sub mymatch {
    my ($str, $targ, $min) = @_;
    my $max = length($targ);
    my $pat = '^(?:' . join('|', $str =~ /\b\w{$min,$max}\b/g) . ')';
    return $targ =~ /$pat/i;
}

Your way, while more complex, has the advantage of a building a regex that can search large amounts of text, and even multiple words at once.

sub build_pattern {
    my $min = shift;
    my @targs;
    for my $targ (@_) {
        push @targs, map { substr($targ, 0, $_) } $min..length($targ);
    }

    my $pat = join('|', @targs);
    return qr/\b(?:$pat)\b/i;
}

my $re = build_pattern(3, qw( divorced ... ));

$str =~ $re


问:
Problems extending my Django user model
I have a simple django app, and am trying to set up a custom Django User Model so that I can have users log in with their email field.  I think I set everything up well enough, its all fairly straightforward, however when trying to actually run the migrations I get this error:

```<code>django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency accounts.0001_initial
</code>```

Seems weird?

I'm having trouble understanding why it's having trouble understanding.

Heres the User model Im implementing

```<code>from __future__ import unicode_literals

from django.db import models
from django.core.mail import send_mail
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.base_user import AbstractBaseUser
from django.utils.translation import ugettext_lazy as _

from .managers import UserManager

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), unique=True)
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    display_name = models.CharField(_('display name'), max_length=30, blank=True)
    bio = models.TextField(blank=True)
    date_joined = models.DateTimeField(_('date joined'), auto_now_add=True)
    is_active = models.BooleanField(_('active'), default=True)
    avatar = models.ImageField(upload_to='avatars/', null=True, blank=True)

objects = UserManager()

USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []

class Meta:
    verbose_name = _('user')
    verbose_name_plural = _('users')

def get_full_name(self):
    '''
    Returns the first_name plus the last_name, with a space in between.
    '''
    full_name = '%s %s' % (self.first_name, self.last_name)
    return full_name.strip()

def get_short_name(self):
    '''
    Returns the short name for the user.
    '''
    return self.first_name

def email_user(self, subject, message, from_email=None, **kwargs):
    '''
    Sends an email to this User.
    '''
    send_mail(subject, message, from_email, [self.email], **kwargs)
</code>```

答:
"Using a custom user model when starting a project"

If you’re starting a new project, it’s highly recommended to set up a custom user model, even if the default User model is sufficient for you. This model behaves identically to the default user model, but you’ll be able to customize it in the future if the need arises." reference->django docs

Then you have to specify to setting.py that you are using a new user model (again before you migrate for the first time.)

```<code>from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    pass

# in settings.py

AUTH_USER_MODEL = 'myapp.MyUser'
</code>```

I highly recommend checking out the link above.

Now to solve your problem you can delete your migrations in your app path under the migrations directory and reset your database and follow the instructions above.

Changing user model mid project is difficult in django and requires manually editing your schema so since your project is for educational purposes just reset it

Title: Problems extending my Django user model

Body:
I have a simple django app, and am trying to set up a custom Django User Model so that I can have users log in with their email field.  I think I set everything up well enough, its all fairly straightforward, however when trying to actually run the migrations I get this error:

django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency accounts.0001_initial

Seems weird?

I'm having trouble understanding why it's having trouble understanding.

Heres the User model Im implementing

from __future__ import unicode_literals

from django.db import models
from django.core.mail import send_mail
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.base_user import AbstractBaseUser
from django.utils.translation import ugettext_lazy as _

from .managers import UserManager

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), unique=True)
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    display_name = models.CharField(_('display name'), max_length=30, blank=True)
    bio = models.TextField(blank=True)
    date_joined = models.DateTimeField(_('date joined'), auto_now_add=True)
    is_active = models.BooleanField(_('active'), default=True)
    avatar = models.ImageField(upload_to='avatars/', null=True, blank=True)

objects = UserManager()

USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []

class Meta:
    verbose_name = _('user')
    verbose_name_plural = _('users')

def get_full_name(self):
    '''
    Returns the first_name plus the last_name, with a space in between.
    '''
    full_name = '%s %s' % (self.first_name, self.last_name)
    return full_name.strip()

def get_short_name(self):
    '''
    Returns the short name for the user.
    '''
    return self.first_name

def email_user(self, subject, message, from_email=None, **kwargs):
    '''
    Sends an email to this User.
    '''
    send_mail(subject, message, from_email, [self.email], **kwargs)

Body:
"Using a custom user model when starting a project"

If you’re starting a new project, it’s highly recommended to set up a custom user model, even if the default User model is sufficient for you. This model behaves identically to the default user model, but you’ll be able to customize it in the future if the need arises." reference->django docs

Then you have to specify to setting.py that you are using a new user model (again before you migrate for the first time.)

from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    pass

# in settings.py

AUTH_USER_MODEL = 'myapp.MyUser'

I highly recommend checking out the link above.

Now to solve your problem you can delete your migrations in your app path under the migrations directory and reset your database and follow the instructions above.

Changing user model mid project is difficult in django and requires manually editing your schema so since your project is for educational purposes just reset it


问:
How to display server output in web page?
For example, in Jenkins, when you run a job, you can see the output of the job which is being ran in remote server in Jenkins's webpage, realtime.

In fact, I am writing a web page, when user click run, a program in server will be ran, and I would like to show the output(stdout/stderr) of the program to the user in this web page.

How to do that?

答:
Socket can solve your problem.

Socket.IO enables real-time bidirectional event-based communication.

Please refer more detail here:

https://socket.io/


问:
How are variables stored in memory in the Rails console?
How are variables stored in memory in the Rails console? Is there a key value store somewhere?

For example, when I open the Rails console with rails c, and type the following.

```<code>Running via Spring preloader in process 7854
Loading development environment (Rails 4.2.5)
2.3.0 :001 > thing = "car"
 => "car"
2.3.0 :002 > thing
 => "car"
2.3.0 :003 >
</code>```

thing is persisted in memory for the duration of the session.

Apologies if this is a newbie question, but I'm been programming for a while and I still don't understand this.

答:
Rails console just uses IRB behind the scenes by autoloading your entire application.

IRB is nothing but a module that evaluates all your input immediately and stores the result inside its own module.

Body:
How are variables stored in memory in the Rails console? Is there a key value store somewhere?

For example, when I open the Rails console with rails c, and type the following.

Running via Spring preloader in process 7854
Loading development environment (Rails 4.2.5)
2.3.0 :001 > thing = "car"
 => "car"
2.3.0 :002 > thing
 => "car"
2.3.0 :003 >

thing is persisted in memory for the duration of the session.

Apologies if this is a newbie question, but I'm been programming for a while and I still don't understand this.


问:
JPA (Hibernate) and custom table prefixes
Is it possible to override table names in JPA/Hibernate in order to add a common prefix for all project entities? For instance to be able to prefix all JBPM 5 tables by "JBPM5_" prefix.

Example for the accepted answer:

```<code>public class JBPM5NamingStrategy extends ImprovedNamingStrategy {
   public String classToTableName(String className) {
      return StringHelper.unqualify(className);
   }
   public String propertyToColumnName(String propertyName) {
      return propertyName;
   }
   public String tableName(String tableName) {
      return "JBPM5_" + tableName;
   }
   public String columnName(String columnName) {
      return columnName;
   }
   public String propertyToTableName(String className, String propertyName) {
      return "JBPM5_" + classToTableName(className) + '_'
         + propertyToColumnName(propertyName);
   }
}
</code>```

答:
One way to rename all tables at once, is to implement your own namingStrategy (implementation of org.hibernate.cfg.NamingStrategy).

The NamingStrategy used is specified within persistence.xml by

```<code><property name="hibernate.ejb.naming_strategy"
          value="com.example.MyNamingStrategy" />
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Is it possible to override table names in JPA/Hibernate in order to add a common prefix for all project entities? For instance to be able to prefix all JBPM 5 tables by "JBPM5_" prefix.

Example for the accepted answer:

public class JBPM5NamingStrategy extends ImprovedNamingStrategy {
   public String classToTableName(String className) {
      return StringHelper.unqualify(className);
   }
   public String propertyToColumnName(String propertyName) {
      return propertyName;
   }
   public String tableName(String tableName) {
      return "JBPM5_" + tableName;
   }
   public String columnName(String columnName) {
      return columnName;
   }
   public String propertyToTableName(String className, String propertyName) {
      return "JBPM5_" + classToTableName(className) + '_'
         + propertyToColumnName(propertyName);
   }
}

Body:
One way to rename all tables at once, is to implement your own namingStrategy (implementation of org.hibernate.cfg.NamingStrategy).

The NamingStrategy used is specified within persistence.xml by

<property name="hibernate.ejb.naming_strategy"
          value="com.example.MyNamingStrategy" />


问:
Cant get required output from loop
I am trying to get a certain output pattern from the array but can't seem to get what I'm looking for and now sure why. Link is the desired output. Sorry if formatting is not good. Array size is inputted by the user.

```<code>public class A3_Q2 {

    int [][] pattern2 = new int[arraySize][arraySize];

    number = 1;
    int i;
    int j;
    int newNumber = arraySize-1;

    for (i = 0; i < arraySize; i++)

    {

        if (i == 0)
        {

            for (j = 0; j < arraySize; j++)
            {
                pattern2[i][j] = number;
                System.out.printf("%3d", pattern2[i][j]);
                number++;
            }

        }

        else
        {
            for(j = 0; j < i; j++)
            {
                pattern2[i][j] = number + newNumber;
                System.out.printf("%3d", pattern2[i][j]);
                newNumber++;
            }
            newNumber = arraySize-1;
            while(j < arraySize)
            {
                pattern2[i][j] = number;
                System.out.printf("%3d", pattern2[i][j]);
                number++;
                j++;
            }

        }
        System.out.println("");
   }
</code>```

Desired Output:

  1  2  3  4  5
 10  6  7  8  9
 14 15 11 12 13
 18 19 20 16 17
 22 23 24 25 21
```

This image shows the out-of-sequence cells highlighted:

答:
As I suggested in my comment, you're trying to do too many things at once, and that makes the logic (and logic errors) very hard to see.
Breaking each part into its own method can make things much easier.

All those loops and conditionals hid that there were only three tasks required:

Create grid.

Fill grid.

Print grid.

```<code>public static void main(final String[] args) {
    final int arraySize = 5;
    int[][] pattern = new int[arraySize][arraySize];
    fillPattern(pattern);
    printPattern(pattern);
    return;
}
</code>```

That weird non-sequential output means that "fill the grid" is actually too big a task for one method.

Filling a grid normally requires filling each row.
This grid also requires rotating each row's values one to the right...
one more than the previous row, that is.
That has nothing to do with filling a grid with rows, so it's some other method's problem.

(I could have foisted rowStartValue off onto the other method too, come to think of it.)

```<code>private static void fillPattern(int[][] pattern) {
    final int rowCount = pattern.length;
    for (int rowOffset = 0; rowOffset < rowCount; rowOffset++) {
        final int[] row = pattern[rowOffset];
        // Numbers in grid start at 1, not 0.
        final int rowStartValue = rowOffset * row.length + 1;
        fillRow(row, rowOffset, rowStartValue);
    }
    return;
}
</code>```

fillRow has to produce values and stuff them into row.
Producing the values is easy;
the only tricky part is deciding where to put them.

Picking the destination required only two operators, so I did it here.
Since no one wants to figure out what row[some / weird * math % here] means, I gave the calculation a name by saving it as the rowIndex variable.
If it had been any more complex, I would have moved the work to a rowIndex(...) method instead.

```<code>private static void fillRow(int[] row, final int offset, final int value) {
    for (int addend = 0; addend < row.length; addend++) {
        final int rowIndex = (offset + addend) % row.length;
        row[rowIndex] = value + addend;
    }
    return;
}
</code>```

Now that the grid is full, printing it is easy:

```<code>private static void printPattern(final int[][] pattern) {
    for (final int[] row : pattern) {
        for (final int element : row) {
            System.out.printf("%3d", element);
        }
        System.out.println();
    }
    return;
}
</code>```

Replacing variables like i and j with row and offset helped a lot, too.

Title: Cant get required output from loop

Body:
I am trying to get a certain output pattern from the array but can't seem to get what I'm looking for and now sure why. Link is the desired output. Sorry if formatting is not good. Array size is inputted by the user.

public class A3_Q2 {

    int [][] pattern2 = new int[arraySize][arraySize];

    number = 1;
    int i;
    int j;
    int newNumber = arraySize-1;

    for (i = 0; i < arraySize; i++)

    {

        if (i == 0)
        {

            for (j = 0; j < arraySize; j++)
            {
                pattern2[i][j] = number;
                System.out.printf("%3d", pattern2[i][j]);
                number++;
            }

        }

        else
        {
            for(j = 0; j < i; j++)
            {
                pattern2[i][j] = number + newNumber;
                System.out.printf("%3d", pattern2[i][j]);
                newNumber++;
            }
            newNumber = arraySize-1;
            while(j < arraySize)
            {
                pattern2[i][j] = number;
                System.out.printf("%3d", pattern2[i][j]);
                number++;
                j++;
            }

        }
        System.out.println("");
   }

Desired Output:

  1  2  3  4  5
 10  6  7  8  9
 14 15 11 12 13
 18 19 20 16 17
 22 23 24 25 21

This image shows the out-of-sequence cells highlighted:

Body:
As I suggested in my comment, you're trying to do too many things at once, and that makes the logic (and logic errors) very hard to see.
Breaking each part into its own method can make things much easier.

All those loops and conditionals hid that there were only three tasks required:

Create grid.

Fill grid.

Print grid.

public static void main(final String[] args) {
    final int arraySize = 5;
    int[][] pattern = new int[arraySize][arraySize];
    fillPattern(pattern);
    printPattern(pattern);
    return;
}

That weird non-sequential output means that "fill the grid" is actually too big a task for one method.

Filling a grid normally requires filling each row.
This grid also requires rotating each row's values one to the right...
one more than the previous row, that is.
That has nothing to do with filling a grid with rows, so it's some other method's problem.

(I could have foisted rowStartValue off onto the other method too, come to think of it.)

private static void fillPattern(int[][] pattern) {
    final int rowCount = pattern.length;
    for (int rowOffset = 0; rowOffset < rowCount; rowOffset++) {
        final int[] row = pattern[rowOffset];
        // Numbers in grid start at 1, not 0.
        final int rowStartValue = rowOffset * row.length + 1;
        fillRow(row, rowOffset, rowStartValue);
    }
    return;
}

fillRow has to produce values and stuff them into row.
Producing the values is easy;
the only tricky part is deciding where to put them.

Picking the destination required only two operators, so I did it here.
Since no one wants to figure out what row[some / weird * math % here] means, I gave the calculation a name by saving it as the rowIndex variable.
If it had been any more complex, I would have moved the work to a rowIndex(...) method instead.

private static void fillRow(int[] row, final int offset, final int value) {
    for (int addend = 0; addend < row.length; addend++) {
        final int rowIndex = (offset + addend) % row.length;
        row[rowIndex] = value + addend;
    }
    return;
}

Now that the grid is full, printing it is easy:

private static void printPattern(final int[][] pattern) {
    for (final int[] row : pattern) {
        for (final int element : row) {
            System.out.printf("%3d", element);
        }
        System.out.println();
    }
    return;
}

Replacing variables like i and j with row and offset helped a lot, too.


问:
app.config file is not giving connection properly
I am on a desktop application and retrieving the list of databases on a local server
by this function

```<code>/// <summary>
/// This function populates the databases list in the drop down after the user is connected.
/// </summary>
public void BindDBDropDown()

        {

        //Create the connection object
        SqlConnection sConnection = new SqlConnection("Server=192.168.10.3;DataBase=GoalPlanNew;User Id=gp;Password=gp");

        //To Open the connection.
        sConnection.Open();

        //Query to select the list of databases.
        string selectDatabaseNames = @"SELECT
                                            NAME
                                        FROM
                                            MASTER..SYSDATABASES";

        //Create the command object
        SqlCommand sCommand = new SqlCommand(selectDatabaseNames, sConnection);

        try
            {
            //Create the data set
            DataSet sDataset = new DataSet("master..sysdatabases");

            //Create the dataadapter object
            SqlDataAdapter sDataAdapter = new SqlDataAdapter(selectDatabaseNames, sConnection);
            sDataAdapter.TableMappings.Add("Table", "master..sysdatabases");

            //Fill the dataset
            sDataAdapter.Fill(sDataset);

            //Bind the database names in combobox
            DataViewManager dsv = sDataset.DefaultViewManager;

            //Provides the master mapping between the sourcr table and system.data.datatable
            cmbDatabases.DataSource = sDataset.Tables["master..sysdatabases"];
            cmbDatabases.DisplayMember = "NAME";
            cmbDatabases.ValueMember = ("NAME");
            }
        catch(Exception ex)
            {
            //All the exceptions are handled and written in the EventLog.
            EventLog logException = new EventLog("Application");
            logException.Source = "MFDBAnalyser";
            logException.WriteEntry(ex.Message);
            }
        finally
            {
            //If connection is not closed then close the connection
            if(sConnection.State != ConnectionState.Closed)
                {
                sConnection.Close();
                }
            }
        }
</code>```

This function is working fine if I am letting it to be hardcoded but when I tried to use the connection string declared in the app.config file as

```<code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="ConnectionString" value="Server=192.168.10.3;DataBase=GoalPlanNew;User Id=gp;Password=gp"/>
  </appSettings>
</configuration>
</code>```

Then it is not working...

What I need to do??

答:
Is the code you posted above using a separate class library to your main executable?

Is the app.config, where you added the appsetting, part of the class library project?

If yes to both those questions then the ConfigurationManager is not looking where you are expecting it to.  The framework will look to the app.config file for your executable (yourexesname.exe.config after compilation).  So if you move the app settings into there the code should work.

Body:
I am on a desktop application and retrieving the list of databases on a local server
by this function

///
/// This function populates the databases list in the drop down after the user is connected.
///
public void BindDBDropDown()

        {

        //Create the connection object
        SqlConnection sConnection = new SqlConnection("Server=192.168.10.3;DataBase=GoalPlanNew;User Id=gp;Password=gp");

        //To Open the connection.
        sConnection.Open();

        //Query to select the list of databases.
        string selectDatabaseNames = @"SELECT
                                            NAME
                                        FROM
                                            MASTER..SYSDATABASES";

        //Create the command object
        SqlCommand sCommand = new SqlCommand(selectDatabaseNames, sConnection);

        try
            {
            //Create the data set
            DataSet sDataset = new DataSet("master..sysdatabases");

            //Create the dataadapter object
            SqlDataAdapter sDataAdapter = new SqlDataAdapter(selectDatabaseNames, sConnection);
            sDataAdapter.TableMappings.Add("Table", "master..sysdatabases");

            //Fill the dataset
            sDataAdapter.Fill(sDataset);

            //Bind the database names in combobox
            DataViewManager dsv = sDataset.DefaultViewManager;

            //Provides the master mapping between the sourcr table and system.data.datatable
            cmbDatabases.DataSource = sDataset.Tables["master..sysdatabases"];
            cmbDatabases.DisplayMember = "NAME";
            cmbDatabases.ValueMember = ("NAME");
            }
        catch(Exception ex)
            {
            //All the exceptions are handled and written in the EventLog.
            EventLog logException = new EventLog("Application");
            logException.Source = "MFDBAnalyser";
            logException.WriteEntry(ex.Message);
            }
        finally
            {
            //If connection is not closed then close the connection
            if(sConnection.State != ConnectionState.Closed)
                {
                sConnection.Close();
                }
            }
        }

This function is working fine if I am letting it to be hardcoded but when I tried to use the connection string declared in the app.config file as

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="ConnectionString" value="Server=192.168.10.3;DataBase=GoalPlanNew;User Id=gp;Password=gp"/>
  </appSettings>
</configuration>

Then it is not working...

What I need to do??


问:
When are nested functions generally appropriate in JavaScript?
I am learning JavaScript through this website. The link is to the specific chapter that I'm reading right now.

In the book, the author talks about keeping the implementation details of a module on a local scope. He achieves it by doing:

```<code>var dayName = function() {
  var names = ["Sunday", "Monday", "Tuesday", "Wednesday",
               "Thursday", "Friday", "Saturday"];
  return function(number) {
    return names[number];
  };
}();
</code>```

I understand how this works, but I do not understand why he is doing it this way. Why wouldn't he just do...

```<code>function dayName(number) {
  var names = ["Sunday", "Monday", "Tuesday", "Wednesday",
               "Thursday", "Friday", "Saturday"];
  return names[number];
}
</code>```

...which to me looks like a much cleaner and readable code? Given his goal of keeping names within local scope, creating a nested lambda seems redundant.

Is there any real advantage to using the nested function in this case? Or is he using it just for educational purposes?

Thanks!

答:
You said:

I understand how this works, but I do not understand why he is doing it this way

If you do not understand why he is doing it this way then you don't really understand how it really works.

What you see in that example is a closure. And in my opinion this is a better introduction to closures than a lot of the introductory examples out there.

A closure is a bit like a global variable. When using a global variable a function access data outside its own scope. For example:

```<code>var x = 2;

function amplify (n) {
    return n * x; // here a function is using x which does not exist
                  // in the function's own scope
}
</code>```

Closures are similar, except that they are hidden in global scope. Every time an inner function access a variable form an outer function it does so using the same mechanism as how global variables work except that that variable is not visible form global scope. Let's now see a simple example similar to the one in your post:

```<code>var amplify;

function init () {
    var x = 2;
    amplify = function (n) { return n * x };
};
init();

console.log(amplify(5)); // prints 10
console.log(x); // syntax error
</code>```

So in this case, as in the code you posted, the variable x behaves like a global variable but is invisible in global scope. Just like global variables it is visible to all functions declared in the scope it's in. And because x is used by the amplify() function it is not freed or garbage collected when the init() function returns. And that is all what closures are about - this weird contradictory concept of private globals. Nothing more.

In this specific use-case the advantages are minimal. You save memory by not allocating the array each time you call the function but that's about it. But closures are much more powerful than that. You can for example share the same variables with multiple functions yet still hide it from global scope. For example:

```<code>var amplify;
var setFactor;
var getFactor;

function init () {
    var x = 2;

    amplify = function (n) { return n * x };
    setFactor = function (n) { x = n };
    getFactor = function () { return x };
};
init();

amplify(5); // returns 10
getFactor(); // returns 2
setFactor(4);
amplify(5); // returns 20
console.log(x); // still a syntax error
</code>```

As you can see. Closures allow you to capture and share data amongst related functions yet hide that data from all other functions. In a way, closures are almost functional equivalents to objects. So my guide of when to use closures is when you need modularisation but objects are overkill. The most common use-case for this is capturing state for callbacks. But caching (memoization), as shown by the example code you posted, is a good use-case as well.

Body:
I am learning JavaScript through this website. The link is to the specific chapter that I'm reading right now.

In the book, the author talks about keeping the implementation details of a module on a local scope. He achieves it by doing:

var dayName = function() {
  var names = ["Sunday", "Monday", "Tuesday", "Wednesday",
               "Thursday", "Friday", "Saturday"];
  return function(number) {
    return names[number];
  };
}();

I understand how this works, but I do not understand why he is doing it this way. Why wouldn't he just do...

function dayName(number) {
  var names = ["Sunday", "Monday", "Tuesday", "Wednesday",
               "Thursday", "Friday", "Saturday"];
  return names[number];
}

...which to me looks like a much cleaner and readable code? Given his goal of keeping names within local scope, creating a nested lambda seems redundant.

Is there any real advantage to using the nested function in this case? Or is he using it just for educational purposes?

Thanks!

Body:
You said:

I understand how this works, but I do not understand why he is doing it this way

If you do not understand why he is doing it this way then you don't really understand how it really works.

What you see in that example is a closure. And in my opinion this is a better introduction to closures than a lot of the introductory examples out there.

A closure is a bit like a global variable. When using a global variable a function access data outside its own scope. For example:

var x = 2;

function amplify (n) {
    return n * x; // here a function is using x which does not exist
                  // in the function's own scope
}

Closures are similar, except that they are hidden in global scope. Every time an inner function access a variable form an outer function it does so using the same mechanism as how global variables work except that that variable is not visible form global scope. Let's now see a simple example similar to the one in your post:

var amplify;

function init () {
    var x = 2;
    amplify = function (n) { return n * x };
};
init();

console.log(amplify(5)); // prints 10
console.log(x); // syntax error

So in this case, as in the code you posted, the variable x behaves like a global variable but is invisible in global scope. Just like global variables it is visible to all functions declared in the scope it's in. And because x is used by the amplify() function it is not freed or garbage collected when the init() function returns. And that is all what closures are about - this weird contradictory concept of private globals. Nothing more.

In this specific use-case the advantages are minimal. You save memory by not allocating the array each time you call the function but that's about it. But closures are much more powerful than that. You can for example share the same variables with multiple functions yet still hide it from global scope. For example:

var amplify;
var setFactor;
var getFactor;

function init () {
    var x = 2;

    amplify = function (n) { return n * x };
    setFactor = function (n) { x = n };
    getFactor = function () { return x };
};
init();

amplify(5); // returns 10
getFactor(); // returns 2
setFactor(4);
amplify(5); // returns 20
console.log(x); // still a syntax error

As you can see. Closures allow you to capture and share data amongst related functions yet hide that data from all other functions. In a way, closures are almost functional equivalents to objects. So my guide of when to use closures is when you need modularisation but objects are overkill. The most common use-case for this is capturing state for callbacks. But caching (memoization), as shown by the example code you posted, is a good use-case as well.


问:
C# null check chain in method call
I suppose method call chain below.

```<code>void DoSomething()
{
    ObjectA a = CreateA();
    if (a != null)
    {
        a.Foo();
    }
}

ObjectA CreateA()
{
    ObjectB b = CreateB();
    if (b != null)
    {
        ObjectA a = b.ToA();
        return a;
    }
    return null;
}
</code>```

If method call depth get deeper, null checking will be more overlapped.
Is there any good solution for this?

Modified

I changed example code. It can't solve my problem that change CreateA to constructor.
The problem is only unnecessary null check chaining overlapping.

```<code>void SetImage()
{
    UISprite image = GetSprite();
    if (image  != null)
    {
        image.spriteName = "hat";
    }
}

UISprite GetSprite()
{
    UISprite image = GetComponent<UISprite>();
    if (image  != null)
    {
        image.width = 100;
        image.height = 100;
        return image;
    }
    return null;
}
</code>```

答:
So, assuming you (or someone else) can't use the null-conditional operator, is there a good reason to be using this pattern of methods creating objects instead of constructors creating the objects? Constructors are guaranteed not to return null.

It looks like you have some conversion or nested object heirarchy, but no inheritance heirarchy where you could just fall back on polymorphism. Maybe a tool like AutoMapper could be useful to encode these ToX() methods in a consistent manner?

I'm not sure how "nested" this would be. Your CreateB() method is going to look exactly like your CreateA() code. You're not going to end up with a "pyramid," just a lot of identical methods.

```<code>ObjectB CreateB()
    {
        ObjectC c = CreateC();
        if (c != null)
        {
            ObjectB b = c.ToB();
            return b;
        }
        return null;
    }
</code>```

Most of the time, you're doing this in an environment where you don't control all the classes. In that case, writing your own conversion functions or AutoMapper (really, worth the time) is the best approach. But, if you own the class hierarchy you might implement an abstract class that will do most of the heavy lifting for you. But honestly, I would only write something like this if I had a really good reason (something more than I just wanted to fuck with people). I include this to demonstrate how much simpler life is if you just use a constructor, which is guaranteed not to return null;

```<code>public abstract class MyAbstractObject<Tobj> where TObj: MyAbstractObject, new()
{
    public static MyAbstractObject CreateObject()
    {
        Tobj subOb = new TObj();
        MyAbstractObject parent = subOb.ToObject();
        return parent;
    }
    public virtual TObj ToObject()
    {
        return CreateObject();
    }
}

public class ObjectD : MyAbstractObject<ObjectC> { }
public class ObjectC : MyAbstractObject<ObjectB> { }
public class ObjectB : MyAbstractObject<ObjectA> { }
public class ObjectA : MyAbstractObject<ObjectA>
{
    public override TObj ToObject()
    {
        return this;
    }
}

static void Main()
{
    ObjectA a = ObjectD.CreateObject();
}
</code>```

Title: C# null check chain in method call

Body:
I suppose method call chain below.

void DoSomething()
{
    ObjectA a = CreateA();
    if (a != null)
    {
        a.Foo();
    }
}

ObjectA CreateA()
{
    ObjectB b = CreateB();
    if (b != null)
    {
        ObjectA a = b.ToA();
        return a;
    }
    return null;
}

If method call depth get deeper, null checking will be more overlapped.
Is there any good solution for this?

Modified

I changed example code. It can't solve my problem that change CreateA to constructor.
The problem is only unnecessary null check chaining overlapping.

void SetImage()
{
    UISprite image = GetSprite();
    if (image  != null)
    {
        image.spriteName = "hat";
    }
}

UISprite GetSprite()
{
    UISprite image = GetComponent<UISprite>();
    if (image  != null)
    {
        image.width = 100;
        image.height = 100;
        return image;
    }
    return null;
}

Body:
So, assuming you (or someone else) can't use the null-conditional operator, is there a good reason to be using this pattern of methods creating objects instead of constructors creating the objects? Constructors are guaranteed not to return null.

It looks like you have some conversion or nested object heirarchy, but no inheritance heirarchy where you could just fall back on polymorphism. Maybe a tool like AutoMapper could be useful to encode these ToX() methods in a consistent manner?

I'm not sure how "nested" this would be. Your CreateB() method is going to look exactly like your CreateA() code. You're not going to end up with a "pyramid," just a lot of identical methods.

ObjectB CreateB()
    {
        ObjectC c = CreateC();
        if (c != null)
        {
            ObjectB b = c.ToB();
            return b;
        }
        return null;
    }

Most of the time, you're doing this in an environment where you don't control all the classes. In that case, writing your own conversion functions or AutoMapper (really, worth the time) is the best approach. But, if you own the class hierarchy you might implement an abstract class that will do most of the heavy lifting for you. But honestly, I would only write something like this if I had a really good reason (something more than I just wanted to fuck with people). I include this to demonstrate how much simpler life is if you just use a constructor, which is guaranteed not to return null;

public abstract class MyAbstractObject<Tobj> where TObj: MyAbstractObject, new()
{
    public static MyAbstractObject CreateObject()
    {
        Tobj subOb = new TObj();
        MyAbstractObject parent = subOb.ToObject();
        return parent;
    }
    public virtual TObj ToObject()
    {
        return CreateObject();
    }
}

public class ObjectD : MyAbstractObject<ObjectC> { }
public class ObjectC : MyAbstractObject<ObjectB> { }
public class ObjectB : MyAbstractObject<ObjectA> { }
public class ObjectA : MyAbstractObject<ObjectA>
{
    public override TObj ToObject()
    {
        return this;
    }
}

static void Main()
{
    ObjectA a = ObjectD.CreateObject();
}