问:
Using Higher order functions instead of two loops
I wanted to use higher order functions such as Map, Filter, Reduce.

My problem is I have an array which is not organised so I had to perform a loop operation to get the result I wanted. An array has two fields one is _id and totalCount which is an array the length will be minimum 0 to 3.

The totalCount each iteration consists of two fields one is orderstatus and another is total I want to perform a normal if else condition if orderstatus is "Merchant" or "driver" or "user" I want to take that iterated total and store it in my array like MerchantCount.

This is my code:

```<code>var arr = [{
   _id: "2017-12-08",
   totalcount: [{
     orderstatus: "MERCHANT",
     total: 1
   }]
 },
 {
   _id: "2017-12-02",
   totalcount: [{
     orderstatus: "USER",
     total: 2
   }]
 },
 {
   _id: "2017-12-06",
   totalcount: [{
     orderstatus: "DRIVER",
     total: 1
   }]
 },
 {
   _id: "2017-12-07",
   totalcount: [{
     orderstatus: "MERCHANT",
     total: 3
   }]
 },
 {
   _id: "2017-12-04",
   totalcount: [{
       orderstatus: "DRIVER",
       total: 1
     },
     {
       orderstatus: "MERCHANT",
       total: 2
     },
     {
       orderstatus: "USER",
       total: 1
     }
   ]
 }
]
</code>```

The loop am performing:

```<code>for (let i = 0; i < recentUserCount.length; i++) {
  for (let j = 0; j < recentUserCount[i].totalcount.length; j++) {
    if (recentUserCount[i].totalcount[j].usertype == "DRIVER") {
      recentUserCount[i].DRIVERCount = recentUserCount[i].totalcount[j].total;
    } else if (recentUserCount[i].totalcount[j].usertype == "USER") {
      recentUserCount[i].USERCount = recentUserCount[i].totalcount[j].total;
    } else if (recentUserCount[i].totalcount[j].usertype == "MERCHANT") {
      recentUserCount[i].MERCHANTCount = recentUserCount[i].totalcount[j].total;
    }
  }
}
</code>```

The result will be roughly like below:

```<code>    0 : {_id: "2017-12-08", totalcount: Array(1), MERCHANTCount: 3, $$hashKey: "object:316"}
    1 : {_id: "2017-12-07", totalcount: Array(1), MERCHANTCount: 3, $$hashKey: "object:317"}
    2 : {_id: "2017-12-06", totalcount: Array(1), DRIVERCount: 1, $$hashKey: "object:318"}
    3 : {_id: "2017-12-04", totalcount: Array(3), DRIVERCount: 1, MERCHANTCount: 2, USERCount: 1, …}
</code>```

I want the same operation to be performed using Map/Filter or Reduce method.

答:
You could shrink it to two nested forEach loops and take orderstatus as part of the new property.

var totalReference = { MERCHANT: 'MERCHANTCount', USER: 'USERCount', DRIVER: 'DRIVERCount' },
    array = [{ _id: "2017-12-08", totalcount: [{ orderstatus: "MERCHANT", total: 1 }] }, { _id: "2017-12-02", totalcount: [{ orderstatus: "USER", total: 2 }] }, { _id: "2017-12-06", totalcount: [{ orderstatus: "DRIVER", total: 1 }] }, { _id: "2017-12-07", totalcount: [{ orderstatus: "MERCHANT", total: 3 }] }, { _id: "2017-12-04", totalcount: [{ orderstatus: "DRIVER", total: 1 }, { orderstatus: "MERCHANT", total: 2 }, { orderstatus: "USER", total: 1 }] }];

array.forEach(function (o) {
    o.totalcount.forEach(function (p) {
        if (totalReference[p.orderstatus]) {
            o[totalReference[p.orderstatus]] = p.total;
         }
    });
});

console.log(array);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I wanted to use higher order functions such as Map, Filter, Reduce.

My problem is I have an array which is not organised so I had to perform a loop operation to get the result I wanted. An array has two fields one is _id and totalCount which is an array the length will be minimum 0 to 3.

The totalCount each iteration consists of two fields one is orderstatus and another is total I want to perform a normal if else condition if orderstatus is "Merchant" or "driver" or "user" I want to take that iterated total and store it in my array like MerchantCount.

This is my code:

var arr = [{
   _id: "2017-12-08",
   totalcount: [{
     orderstatus: "MERCHANT",
     total: 1
   }]
 },
 {
   _id: "2017-12-02",
   totalcount: [{
     orderstatus: "USER",
     total: 2
   }]
 },
 {
   _id: "2017-12-06",
   totalcount: [{
     orderstatus: "DRIVER",
     total: 1
   }]
 },
 {
   _id: "2017-12-07",
   totalcount: [{
     orderstatus: "MERCHANT",
     total: 3
   }]
 },
 {
   _id: "2017-12-04",
   totalcount: [{
       orderstatus: "DRIVER",
       total: 1
     },
     {
       orderstatus: "MERCHANT",
       total: 2
     },
     {
       orderstatus: "USER",
       total: 1
     }
   ]
 }
]

The loop am performing:

for (let i = 0; i < recentUserCount.length; i++) {
  for (let j = 0; j < recentUserCount[i].totalcount.length; j++) {
    if (recentUserCount[i].totalcount[j].usertype == "DRIVER") {
      recentUserCount[i].DRIVERCount = recentUserCount[i].totalcount[j].total;
    } else if (recentUserCount[i].totalcount[j].usertype == "USER") {
      recentUserCount[i].USERCount = recentUserCount[i].totalcount[j].total;
    } else if (recentUserCount[i].totalcount[j].usertype == "MERCHANT") {
      recentUserCount[i].MERCHANTCount = recentUserCount[i].totalcount[j].total;
    }
  }
}

The result will be roughly like below:

    0 : {_id: "2017-12-08", totalcount: Array(1), MERCHANTCount: 3, $$hashKey: "object:316"}
    1 : {_id: "2017-12-07", totalcount: Array(1), MERCHANTCount: 3, $$hashKey: "object:317"}
    2 : {_id: "2017-12-06", totalcount: Array(1), DRIVERCount: 1, $$hashKey: "object:318"}
    3 : {_id: "2017-12-04", totalcount: Array(3), DRIVERCount: 1, MERCHANTCount: 2, USERCount: 1, …}

I want the same operation to be performed using Map/Filter or Reduce method.

Body:
You could shrink it to two nested forEach loops and take orderstatus as part of the new property.

var totalReference = { MERCHANT: 'MERCHANTCount', USER: 'USERCount', DRIVER: 'DRIVERCount' },
    array = [{ _id: "2017-12-08", totalcount: [{ orderstatus: "MERCHANT", total: 1 }] }, { _id: "2017-12-02", totalcount: [{ orderstatus: "USER", total: 2 }] }, { _id: "2017-12-06", totalcount: [{ orderstatus: "DRIVER", total: 1 }] }, { _id: "2017-12-07", totalcount: [{ orderstatus: "MERCHANT", total: 3 }] }, { _id: "2017-12-04", totalcount: [{ orderstatus: "DRIVER", total: 1 }, { orderstatus: "MERCHANT", total: 2 }, { orderstatus: "USER", total: 1 }] }];

array.forEach(function (o) {
    o.totalcount.forEach(function (p) {
        if (totalReference[p.orderstatus]) {
            o[totalReference[p.orderstatus]] = p.total;
         }
    });
});

console.log(array);

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


来源: stackexchange

问:
Branch from master or branch from branch?
I'm working on a branch (feature1) which is branched from master.
Feature1 branch has many commits and a lot work has been done.

```<code>----------- Master
   \---------------- Feature1
</code>```

A colleague needs to do some work that is closely related to branch feature1.

Should the colleague branch off from master or feature1?

Let's say the colleague branches off from feature1 and creates feature1_addon, and work continues in parallel between these two branches. The work continues for weeks in parallel.

```<code>----------- Master
   \---------------- Feature1
            \----Feature1_addon
</code>```

Eventually these two branches (feature1 & feature1_addon) must be merged into master, how should this be done without losing any work?

答:
The technical answer is that it doesn't matter to git where branches are made.  You can make them from whatever commit (reachable from whatever branch(es)) gives you access to the version of the code you need to modify.  Each branch can be merged into any other branch more-or-less independently.

"More-or-less" independently because many people have misconceptions about the relationship between commit and branch that would lead them to think that the merges are not independent.  Consider:

```<code>X -- x -- x -- x -- x <--(master)
      \
       A -- B -- C -- o -- o <--(feature1)
                  \
                   D -- E -- F <--(feature1_addon)
</code>```

Now you could merge feature1 to master, and you probably know exactly what to expect.

Even if you haven't yet merged feature1 to master, you can merge feature1_addon to master.  But if you do, it will bring in A, B, C, D, E, and F - not merely D thru F - because A thru C are in the history of feature1_addon but are not yet in the history of master.  So even though you may think of A thru C as "part of the feature branch", git sees them as both "reachable from feature1" and "reachable from feature1_addon", no more belonging to one than the other.

Regardless of the order or timing of merges, you should not be concerned about losing work.

You should be concerned about merge conflicts, though, for which reason your branch model (creating potentially-long-lived branches that don't interact until they're finally merged together) is not generally thought of as a best practice.

So the non-technical answer is, while you can branch and merge however you want, you might want to think some more about it.

Exactly what branch strategy would be best for your situation is not something I can determine.  I've found gitflow to be very useful, but it is somewhat heavy-weight if there are just two of you, and it assumes an agile workflow (meaning branches represent small units of work that are merged in pretty frequently).

If you prefer to have long-lived lines of development, you should at least consider periodically merging them into one another, so that they don't diverge too much.  Conflicts will then be merged in manageable doses, and less conflicts will be created than if you develop each thread in isolation.

ContentLicense: CC BY-SA 3.0

Body:
I'm working on a branch (feature1) which is branched from master.
Feature1 branch has many commits and a lot work has been done.

----------- Master
   \---------------- Feature1

A colleague needs to do some work that is closely related to branch feature1.

Should the colleague branch off from master or feature1?

Let's say the colleague branches off from feature1 and creates feature1_addon, and work continues in parallel between these two branches. The work continues for weeks in parallel.

----------- Master
   \---------------- Feature1
            \----Feature1_addon

Eventually these two branches (feature1 & feature1_addon) must be merged into master, how should this be done without losing any work?

Body:
The technical answer is that it doesn't matter to git where branches are made.  You can make them from whatever commit (reachable from whatever branch(es)) gives you access to the version of the code you need to modify.  Each branch can be merged into any other branch more-or-less independently.

"More-or-less" independently because many people have misconceptions about the relationship between commit and branch that would lead them to think that the merges are not independent.  Consider:

X -- x -- x -- x -- x <--(master)
      \
       A -- B -- C -- o -- o <--(feature1)
                  \
                   D -- E -- F <--(feature1_addon)

Now you could merge feature1 to master, and you probably know exactly what to expect.

Even if you haven't yet merged feature1 to master, you can merge feature1_addon to master.  But if you do, it will bring in A, B, C, D, E, and F - not merely D thru F - because A thru C are in the history of feature1_addon but are not yet in the history of master.  So even though you may think of A thru C as "part of the feature branch", git sees them as both "reachable from feature1" and "reachable from feature1_addon", no more belonging to one than the other.

Regardless of the order or timing of merges, you should not be concerned about losing work.

You should be concerned about merge conflicts, though, for which reason your branch model (creating potentially-long-lived branches that don't interact until they're finally merged together) is not generally thought of as a best practice.

So the non-technical answer is, while you can branch and merge however you want, you might want to think some more about it.

Exactly what branch strategy would be best for your situation is not something I can determine.  I've found gitflow to be very useful, but it is somewhat heavy-weight if there are just two of you, and it assumes an agile workflow (meaning branches represent small units of work that are merged in pretty frequently).

If you prefer to have long-lived lines of development, you should at least consider periodically merging them into one another, so that they don't diverge too much.  Conflicts will then be merged in manageable doses, and less conflicts will be created than if you develop each thread in isolation.


问:
How do you edit the settings you entered when you registered your Facebook app?
How do you edit the settings you entered when you registered your Facebook app?
I need to change the base url and cannot for the life of me figure it out navigating the site.
Someone must know where this is accessible.

Edit:
Hmmm, guess I have been going to the right place, right now I just get
'An error occurred with Developer. Please try again later.'

答:
http://www.facebook.com/developers

Find your app on the right, then go to Edit Settings.

ContentLicense: CC BY-SA 2.5


问:
how can a function check for null in typescript?
in typescript 2.6 I want to write a function that does a null check. When I enable strict null-checks, typescript 2.6 complains about the following code. (Note that when using the null check directly works)

edited: corrected notNullOrUndefined since it didn't check for foo

```<code>interface A {
  foo: string | undefined;
}
const notNullOrUndefined = (a: A): boolean => {
  return a.foo != null;
}
const len = (a: A): number => {
  //if (a.foo != null) {
  if (notNullOrUndefined(a)){
    return a.foo.length;
  }
  return 0;
}
</code>```

here is the example to play with: example

What's the typescript way to solve this?

答:
You need to check both a and a.foo. This code, for example, will work even when strict null checking is not enabled:

```<code>const len = (a: A): number => {
  if (a != null && a.foo != null){
    return a.foo.length;
  }
  return 0;
}
</code>```

If you do have strict null checking enabled you already know that a is not undefined and then you can just use your commented out line:

```<code>const len = (a: A): number => {
  if (a.foo != null){
    return a.foo.length;
  }
  return 0;
}
</code>```

If you want to perform the test in a separate function then you should make that function a type assertion. You could for example remove the undefined from the type of foo but use Partial anywhere that you don't know whether or not foo is present:

```<code>interface A {
  foo: string;
}
const notNullOrUndefined = (a: Partial<A>): a is A => {
  return a != null && a.foo != null;
}
const len = (a: Partial<A>): number => {
  if (notNullOrUndefined(a)){
    return a.foo.length;
  }
  return 0;
}
</code>```

Body:
in typescript 2.6 I want to write a function that does a null check. When I enable strict null-checks, typescript 2.6 complains about the following code. (Note that when using the null check directly works)

edited: corrected notNullOrUndefined since it didn't check for foo

interface A {
  foo: string | undefined;
}
const notNullOrUndefined = (a: A): boolean => {
  return a.foo != null;
}
const len = (a: A): number => {
  //if (a.foo != null) {
  if (notNullOrUndefined(a)){
    return a.foo.length;
  }
  return 0;
}

here is the example to play with: <a href="https://www.typescriptlang.org/play/#src=interface%20A%20%7B%0D%0A%20%20foo%3A%20string%20%7C%20undefined%3B%0D%0A%7D%0D%0Aconst%20notNullOrUndefined%20%3D%20(a%3A%20A)%3A%20boolean%20%3D%3E%20%7B%0D%0A%20%20return%20a.foo%20!%3D%20null%3B%0D%0A%7D%0D%0Aconst%20len%20%3D%20(a%3A%20A)%3A%20number%20%3D%3E%20%7B%0D%0A%20%20%2F%2Fif%20(a.foo%20!%3D%20null)%20%7B%0D%0A%20%20if%20(notNullOrUndefined(a))%7B%0D%0A%20%20%20%20return%20a.foo.length%3B%0D%0A%20%20%7D%0D%0A%20%20return%200%3B%0D%0A%7D%20" rel="nofollow noreferrer">example

What's the typescript way to solve this?

Body:
You need to check both a and a.foo. This code, for example, will work even when strict null checking is not enabled:

const len = (a: A): number => {
  if (a != null && a.foo != null){
    return a.foo.length;
  }
  return 0;
}

If you do have strict null checking enabled you already know that a is not undefined and then you can just use your commented out line:

const len = (a: A): number => {
  if (a.foo != null){
    return a.foo.length;
  }
  return 0;
}

If you want to perform the test in a separate function then you should make that function a type assertion. You could for example remove the undefined from the type of foo but use Partial<A> anywhere that you don't know whether or not foo is present:

interface A {
  foo: string;
}
const notNullOrUndefined = (a: Partial<A>): a is A => {
  return a != null && a.foo != null;
}
const len = (a: Partial<A>): number => {
  if (notNullOrUndefined(a)){
    return a.foo.length;
  }
  return 0;
}


问:
How to show elements of a list using `<*ngIf>` and enum variable
I have a list mad with angular, and I want to show elements of this list, with an enum variable. For example if enum = 0 than it shows all elements, if enum = 1 it shows only elements with list.status = true and if enum = 2 it shows only elements wiht list.status = false.

```<code><ul class="list" style="list-style-type:none">
    <div>
      <li *ngFor="let list of currentList">
        <div>
          <input type="checkbox" class="stat" (click)="status(list)" [(checked)]="list.status" />
          <span class="task">{{list.task}}</span>
          <button class="listBtn" (click)="edit(list)">EDIT</button>
          <button class="listBtn" (click)="remove(list)">REMOVE</button>
        </div>
      </li>
    </div>
  </ul>
</code>```

答:
You would need a method which returns a boolean after doing the check, something like

```<code>public checkEnum( list: any ): boolean {
  if ( enum == 0 ) {
   return true;
  }
  if ( enum == 1 && list.status == true ) {
   return true;
  }
  if ( enum == 2 && list.status == false ) {
   return true;
  }
  return false;
}
</code>```

and then in the template:

```<code>    <div *ngIf="checkEnum(list)">
      <input type="checkbox" class="stat" (click)="status(list)" [(checked)]="list.status" />
      <span class="task">{{list.task}}</span>
      <button class="listBtn" (click)="edit(list)">EDIT</button>
      <button class="listBtn" (click)="remove(list)">REMOVE</button>
    </div>
</code>```

See if it helps.

Body:
I have a list mad with angular, and I want to show elements of this list, with an enum variable. For example if enum = 0 than it shows all elements, if enum = 1 it shows only elements with list.status = true and if enum = 2 it shows only elements wiht list.status = false.

          <input type="checkbox" class="stat" (click)="status(list)" [(checked)]="list.status" />
          {{list.task}}
          <button class="listBtn" (click)="edit(list)">EDIT</button>
          <button class="listBtn" (click)="remove(list)">REMOVE</button>

Body:
You would need a method which returns a boolean after doing the check, something like

public checkEnum( list: any ): boolean {
  if ( enum == 0 ) {
   return true;
  }
  if ( enum == 1 && list.status == true ) {
   return true;
  }
  if ( enum == 2 && list.status == false ) {
   return true;
  }
  return false;
}

and then in the template:

    <div *ngIf="checkEnum(list)">
      <input type="checkbox" class="stat" (click)="status(list)" [(checked)]="list.status" />
      <span class="task">{{list.task}}</span>
      <button class="listBtn" (click)="edit(list)">EDIT</button>
      <button class="listBtn" (click)="remove(list)">REMOVE</button>
    </div>

See if it helps.


问:
Does Google Analytics for Cordova still work?
I have noticed that if you try configuring Google Analytics for a mobile app - it points you to Firebase Analytics.

Can Google Analytics still be used for a Cordova app?  If yes - shall it set as separate web property to track?  What should be the site URL?

答: The website doesn't matter when configuring your GA property. You can use the web libraries like gtag.js or analytics.js just fine. Type mywebsite.com in the field, it simply doesn't matter.</p>


问:
local site is automatically on https on chrome
I had an update on my computer ( ubuntu) and now my host that i had in local is not working anymore :
This site can’t be reached
www.site.dev refused to connect.
Try:

Checking the connection
Checking the proxy and the firewall
ERR_CONNECTION_REFUSED

This same url works on firefox and postman for my api so I am a bit lost!

答:
Forcing HTTPS is a new feature of chrome. More on it here.

Apparently, it cannot be disabled. One workaround is changing your .dev domain to .test, .local or similar.


问:
Reactjs setState() does not immediately mutate this.state, How should I fix it?
I need to set a state in my code, but since setState() does not immediately mutate this.state I'm trying to do it in a call back. But can't figure out the correct syntax for it. Below is the code. After user press a button the update() method is called. There are these two states: this.state.tmp and this.state.rec. this.state.rec is a MAP, and it's a copy of this.props.rec. I need to compare the new value of this.state.rec and this.props.rec (calling it patch) and run a api call.

this.state.rec should have the changes so: on line #2, first I create rec. it gets the new value from this.state.tmp and then I need to update this.state.rec with  this new value. But obviously the updated is not getting the value the way it is now. Can someone please tell me how to fix it?

```<code>update(event)
{
    event.preventDefault();
    const rec = this.state.rec.set('something', this.state.tmp);
    let updated = this.setState({rec}, () => {
            return this.state.rec.toJS();
    });
    console.log("updated = ", updated)
    const original = this.props.rec.get('data').toJS();
    const patch = compare(original, updated);
    ....
}
</code>```

答:
Use something like this

```<code>    this.setState(function(state, props) {
    //You can write your logic here to decide to
    //make api call or not.
    return {
    newValue : state.newValue + 1,
    newAttribute: state.newAttribute - 1,
    newValueFromProps: props.newValue,
    }
})
</code>```

Please let me know it that worked for you

Body:
I need to set a state in my code, but since setState() does not immediately mutate this.state I'm trying to do it in a call back. But can't figure out the correct syntax for it. Below is the code. After user press a button the update() method is called. There are these two states: this.state.tmp and this.state.rec. this.state.rec is a MAP, and it's a copy of this.props.rec. I need to compare the new value of this.state.rec and this.props.rec (calling it patch) and run a api call.

this.state.rec should have the changes so: on line #2, first I create rec. it gets the new value from this.state.tmp and then I need to update this.state.rec with  this new value. But obviously the updated is not getting the value the way it is now. Can someone please tell me how to fix it?

update(event)
{
    event.preventDefault();
    const rec = this.state.rec.set('something', this.state.tmp);
    let updated = this.setState({rec}, () => {
            return this.state.rec.toJS();
    });
    console.log("updated = ", updated)
    const original = this.props.rec.get('data').toJS();
    const patch = compare(original, updated);
    ....
}

Body:
Use something like this

    this.setState(function(state, props) {
    //You can write your logic here to decide to
    //make api call or not.
    return {
    newValue : state.newValue + 1,
    newAttribute: state.newAttribute - 1,
    newValueFromProps: props.newValue,
    }
})

Please let me know it that worked for you


答:
EDIT: updated to reflect fixing a typo in question: The question is a little confusing, since your notNullOrUndefined() doesn't check a.foo at all, so it's not surprising that those would be different.

Note that with --strictNullChecks on, you have defined len() so that the a parameter is an A, and therefore cannot be null or undefined.  So you don't have to check a itself inside the len() function implementation; instead you need to make sure that anything you pass to len() is a valid A.   So notNullOrUndefined() is kind of a bad name, since you're checking the foo value of the parameter, not the parameter itself.  Feel free to change it to something like fooPropertyIsNotNull(); I will leave it for now.

The main issue here is that TypeScript recognizes that if (a.foo != null) { ... } is a type guard, and narrows a.foo to string inside the { ... } clause.  But type guards do not propagate out of functions automatically, so TypeScript doesn't understand that notNullOrUndefined() itself acts as a type guard.

Luckily, this issue is common enough that TypeScript provides user-defined type guards: if you have a function that returns a boolean which narrows the type of one of its parameters, you can change the boolean return type to a type predicate, using the x is T syntax.  Here it is for notNullOrUndefined():

```<code>const notNullOrUndefined = (a: A): a is { foo: string } => {
  return a.foo != null;
}
</code>```

So the function signature says: if you pass in an A, it will return a boolean value.  If it returns true, then the passed-in parameter is narrowed to { foo: string }.  Now you will get no errors, as you wanted:

```<code>interface A {
  foo: string | undefined;
}
const notNullOrUndefined = (a: A): a is { foo: string } => {
  return a.foo != null; // checking a.foo
}
const len = (a: A): number => {
  if (notNullOrUndefined(a)){
    return a.foo.length; // okay
  }
  return 0;
}
</code>```

Hope that helps, good luck!

Title: how can a function check for null in typescript?

Body:
EDIT: updated to reflect fixing a typo in question: The question is a little confusing, since your notNullOrUndefined() doesn't check a.foo at all, so it's not surprising that those would be different.

Note that with --strictNullChecks on, you have defined len() so that the a parameter is an A, and therefore cannot be null or undefined.  So you don't have to check a itself inside the len() function implementation; instead you need to make sure that anything you pass to len() is a valid A.   So notNullOrUndefined() is kind of a bad name, since you're checking the foo value of the parameter, not the parameter itself.  Feel free to change it to something like fooPropertyIsNotNull(); I will leave it for now.

The main issue here is that TypeScript recognizes that if (a.foo != null) { ... } is a type guard, and narrows a.foo to string inside the { ... } clause.  But type guards do not propagate out of functions automatically, so TypeScript doesn't understand that notNullOrUndefined() itself acts as a type guard.

Luckily, this issue is common enough that TypeScript provides user-defined type guards: if you have a function that returns a boolean which narrows the type of one of its parameters, you can change the boolean return type to a type predicate, using the x is T syntax.  Here it is for notNullOrUndefined():

const notNullOrUndefined = (a: A): a is { foo: string } => {
  return a.foo != null;
}

So the function signature says: if you pass in an A, it will return a boolean value.  If it returns true, then the passed-in parameter is narrowed to { foo: string }.  Now you will get no errors, as you wanted:

interface A {
  foo: string | undefined;
}
const notNullOrUndefined = (a: A): a is { foo: string } => {
  return a.foo != null; // checking a.foo
}
const len = (a: A): number => {
  if (notNullOrUndefined(a)){
    return a.foo.length; // okay
  }
  return 0;
}

Hope that helps, good luck!


问:
Automatically convert bunch of commands to command1 && command2

I'm running commands in bash like this:
</p>

```<code>cd path &&
service service1 stop &&
(run some scripts) &&
service service1 start &&
service service2 restart
</code>```

<p>
Is there any tool which would run commands without "&&" at end like it would be there? Now I'm just adding "&&" with replace function in text editor, I know i can write simple script which would do that automatically but if there is tool for that in repo it would be great.
</p>

答:
&& lets you do something based on whether the previous command completed successfully. It may be used to chain commands, so that the next command runs only if the previous succedded.
If this is Your goal, there is a simpler way. If You want to run the next command only if the previous one succedded, You may want to use:

set -euo pipefail

If any of the commands fail (return with a non-zero status), than the script will stop.

From http://tldp.org/LDP/abs/html/options.html :

- set -e -> Abort script at first error, when a command exits with non-zero status (except in until or while loops, if-tests, list constructs)

- set -u -> Attempt to use undefined variable outputs error message, and forces an exit

- set -o pipefail -> Causes a pipeline to return the exit status of the last command in the pipe that returned a non-zero return value.

( Every shell script that i write, starts with a set -euo pipefail. It is a good practice. )

ContentLicense: CC BY-SA 4.0

Body:
I'm running commands in bash like this:

cd path &&
service service1 stop &&
(run some scripts) &&
service service1 start &&
service service2 restart

Is there any tool which would run commands without "&&" at end like it would be there? Now I'm just adding "&&" with replace function in text editor, I know i can write simple script which would do that automatically but if there is tool for that in repo it would be great.


问:
How to uncheck the checkcolumn of perticular row in Ext grid
I have a grid which has a column of checkboxes. I have used xtype checkcolumn

for this. follow fiddle here: https://fiddle.sencha.com/#view/editor&fiddle/2ano

Now I want to uncheck checkbox at perticular(in this case 2nd) row on click of given button. I tried getting them using xtypes but no luck.

finally I found a workaround.

```<code>store.getAt(1).data.active = false;
grid.getView().refresh();
</code>```

It works but not sure if its the correct way to do so.
I will be glad for any suggestions.
Thank you.

答:
One way as per your code.

You can use this methods of grid store store.each(),  store.clearFilter() and store.filter('active',true).

In this FIDDLE, you can check here uncheck checked columns using record.set('active',false).

```<code>var store = Ext.create('Ext.data.Store', {
    fields: ['name', 'email', 'phone', 'active'],
    data: [{
        name: 'Lisa',
        email: 'lisa@simpsons.com',
        phone: '555-111-1224',
        active: false
    }, {
        name: 'Bart',
        email: 'bart@simpsons.com',
        phone: '555-222-1234',
        active: true
    }, {
        name: 'Homer',
        email: 'homer@simpsons.com',
        phone: '555-222-1244',
        active: false
    }, {
        name: 'Marge',
        email: 'marge@simpsons.com',
        phone: '555-222-1254',
        active: false
    }]
});

Ext.create('Ext.grid.Panel', {
    title: 'Simpsons',
    itemId: 'test',
    renderTo: Ext.getBody(),
    store: store,
    buttons: [{
        text: 'Un check',
        handler: function () {
            var store = this.up('grid').getStore();
            store.clearFilter();
            store.filter('active', true);
            store.each(function (rec) {
                rec.set('active', false);
            });
            store.clearFilter();
        }
    }],
    columns: [{
        text: 'Name',
        dataIndex: 'name'
    }, {
        text: 'Email',
        dataIndex: 'email',
        flex: 1
    }, {
        text: 'Phone',
        dataIndex: 'phone'
    }, {
        xtype: 'checkcolumn',
        text: 'Active',
        dataIndex: 'active'
    }]
});
</code>```

Another way as per your code.

You can use selModel  and selType configs for grid.

In this FIDDLE, I have created a demo using selType and selModel config. it will help you or guide you more about grid checkbox selection.

```<code>Ext.create('Ext.grid.Panel', {
        title: 'Simpsons',
        store: store,
        id: 'testGrid',
        columns: [{
            text: 'Name',
            dataIndex: 'name'
        }, {
            text: 'Email',
            dataIndex: 'email',
            flex: 1
        }, {
            text: 'Phone',
            dataIndex: 'phone'
        }],
        renderTo: Ext.getBody(),
        selModel: {
            checkOnly: false,
            //injectCheckbox: 'last',
            mode: 'SIMPLE'
        },
        selType: 'checkboxmodel',
        buttons: [{
            text: 'Select All',
            handler: function () {
                Ext.getCmp('testGrid').getSelectionModel().selectAll();
            }
        }, {
            text: 'Deselect All',
            handler: function () {
                Ext.getCmp('testGrid').getSelectionModel().deselectAll();
            }
        }]
    });
</code>```

Body:
I have a grid which has a column of checkboxes. I have used xtype checkcolumn

for this. follow fiddle here: https://fiddle.sencha.com/#view/editor&fiddle/2ano

Now I want to uncheck checkbox at perticular(in this case 2nd) row on click of given button. I tried getting them using xtypes but no luck.

finally I found a workaround.

store.getAt(1).data.active = false;
grid.getView().refresh();

It works but not sure if its the correct way to do so.
I will be glad for any suggestions.
Thank you.

Body:
One way as per your code.

You can use this methods of grid store store.each(),  store.clearFilter() and store.filter('active',true).

In this FIDDLE, you can check here uncheck checked columns using record.set('active',false).

var store = Ext.create('Ext.data.Store', {
    fields: ['name', 'email', 'phone', 'active'],
    data: [{
        name: 'Lisa',
        email: 'lisa@simpsons.com',
        phone: '555-111-1224',
        active: false
    }, {
        name: 'Bart',
        email: 'bart@simpsons.com',
        phone: '555-222-1234',
        active: true
    }, {
        name: 'Homer',
        email: 'homer@simpsons.com',
        phone: '555-222-1244',
        active: false
    }, {
        name: 'Marge',
        email: 'marge@simpsons.com',
        phone: '555-222-1254',
        active: false
    }]
});

Ext.create('Ext.grid.Panel', {
    title: 'Simpsons',
    itemId: 'test',
    renderTo: Ext.getBody(),
    store: store,
    buttons: [{
        text: 'Un check',
        handler: function () {
            var store = this.up('grid').getStore();
            store.clearFilter();
            store.filter('active', true);
            store.each(function (rec) {
                rec.set('active', false);
            });
            store.clearFilter();
        }
    }],
    columns: [{
        text: 'Name',
        dataIndex: 'name'
    }, {
        text: 'Email',
        dataIndex: 'email',
        flex: 1
    }, {
        text: 'Phone',
        dataIndex: 'phone'
    }, {
        xtype: 'checkcolumn',
        text: 'Active',
        dataIndex: 'active'
    }]
});

Another way as per your code.

You can use selModel  and selType configs for grid.

In this FIDDLE, I have created a demo using selType and selModel config. it will help you or guide you more about grid checkbox selection.

Ext.create('Ext.grid.Panel', {
        title: 'Simpsons',
        store: store,
        id: 'testGrid',
        columns: [{
            text: 'Name',
            dataIndex: 'name'
        }, {
            text: 'Email',
            dataIndex: 'email',
            flex: 1
        }, {
            text: 'Phone',
            dataIndex: 'phone'
        }],
        renderTo: Ext.getBody(),
        selModel: {
            checkOnly: false,
            //injectCheckbox: 'last',
            mode: 'SIMPLE'
        },
        selType: 'checkboxmodel',
        buttons: [{
            text: 'Select All',
            handler: function () {
                Ext.getCmp('testGrid').getSelectionModel().selectAll();
            }
        }, {
            text: 'Deselect All',
            handler: function () {
                Ext.getCmp('testGrid').getSelectionModel().deselectAll();
            }
        }]
    });


问:
Display of screen is pushed down xamarin.forms android
Weirdly my display of screen is pushed down for only the MainPage thereafter display fits the screen as it should. I've tried deleting the page and re-adding it but that didn't work either. Does anyone know what could be causing this and how to fix it?

Here's what it looks like: The black space at the top should not be there

MainPage.xaml

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="LoyaltyWorx.Views.MainPage"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:LoyaltyWorx.Views.Converters"
    xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
    prism:ViewModelLocator.AutowireViewModel="True"
    >
    <ContentPage.Resources>
        <ResourceDictionary>
            <local:InvertBooleanConverter x:Key="InvertBooleanConverter" />
        </ResourceDictionary>
    </ContentPage.Resources>
    <Grid>
        <Image Source="bk3.jpg" Aspect="AspectFill"/>
        <StackLayout VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
        <StackLayout Orientation="Horizontal" VerticalOptions="Start">
            <!-- top controls -->
        </StackLayout>
        <StackLayout VerticalOptions="CenterAndExpand">
            <!-- middle controls -->
            <BoxView HeightRequest="430"></BoxView>
            <Button Text="Continue with Facebook" x:Name="LoginBtn" BackgroundColor="#4867aa" TextColor="White" FontFamily="Klavika" HorizontalOptions="CenterAndExpand" Clicked="LoginBtn_Clicked" />
            <Button Text="Continue with Google  " Command="{Binding GoogleLoginCommand}" BackgroundColor="#d34836" TextColor="White" FontFamily="Klavika" HorizontalOptions="CenterAndExpand"/>
        </StackLayout>
        <StackLayout Orientation="Horizontal" VerticalOptions="End" HorizontalOptions="Center">
            <!-- bottom controls -->
            <Frame OutlineColor="White" HorizontalOptions="StartAndExpand">
                <StackLayout Orientation="Horizontal" VerticalOptions="End" HorizontalOptions="Center">
                    <!-- bottom controls -->
                    <StackLayout Grid.Row="1" Orientation="Horizontal" Spacing="0">
                        <Label
                               Text="Terms and conditions"
                              FontSize="13"
                            TextColor="#71757a"
                            FontAttributes="Bold"
                            x:Name="LblTerms"/>
                        <Label
                            Text=" and"
                            FontSize="13"
                            TextColor="#71757a"
                            />

                        <Label
                               Text=" privacy policy"
                            FontSize="13"
                            TextColor="#71757a"
                            FontAttributes="Bold"
                            x:Name="LblPrivacy"/>
                    </StackLayout>

                </StackLayout>
            </Frame>
        </StackLayout>
    </StackLayout>
    </Grid>
</ContentPage>
</code>```

App.cs

```<code>public partial class App : PrismApplication
    {

        public App(IPlatformInitializer initializer = null) : base(initializer) { }

        protected override void OnInitialized()
        {
            InitializeComponent();
            SetMainPage();
            NavigationService.NavigateAsync("NavigationPage/MainPage?title=Hello%20from%20Xamarin.Forms");
        }

        protected override void RegisterTypes()
        {
            Container.RegisterTypeForNavigation<NavigationPage>();
            Container.RegisterTypeForNavigation<MainPage>();
        }

        private void SetMainPage()
        {
            if (!string.IsNullOrEmpty(Helpers.Settings.Usertoken))
            {
                Application.Current.MainPage = (new Profile());
            }
            else
            {
                MainPage = new NavigationPage(new MainPage())
                { BarBackgroundColor = Color.FromHex("#393b3d") };

            }
        }

        public async static Task NavigateToSMS()
        {
            await Application.Current.MainPage.Navigation.PushAsync(new SMS());
        }

        public static void NavigateToProfile()
        {
            Application.Current.MainPage = (new InvalidLogin());
        }
        public static void NavigateToVerified()
        {
            Application.Current.MainPage = (new Profile());
        }

        protected override void OnStart()
        {
            // Handle when your app starts
        }

        protected override void OnSleep()
        {
            // Handle when your app sleeps
        }

        protected override void OnResume()
        {
            // Handle when your app resumes
        }
    }
</code>```

答:
You have your MainPage wrapped in a NavigationPage that by default shows the NavigationBar. You can turn it off in your cs code or in your MainPage.xaml

cs

```<code>var mainPage = new MainPage();
MainPage = new NavigationPage(mainPage);
NavigationPage.SetHasNavigationBar(mainPage, false);
</code>```

xaml

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="LoyaltyWorx.Views.MainPage"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:LoyaltyWorx.Views.Converters"
    xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
    prism:ViewModelLocator.AutowireViewModel="True"
    NavigationPage.HasNavigationBar="False">
</code>```

Body:
Weirdly my display of screen is pushed down for only the MainPage thereafter display fits the screen as it should. I've tried deleting the page and re-adding it but that didn't work either. Does anyone know what could be causing this and how to fix it?

Here's what it looks like: The black space at the top should not be there

MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="LoyaltyWorx.Views.MainPage"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:LoyaltyWorx.Views.Converters"
    xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
    prism:ViewModelLocator.AutowireViewModel="True"
    >
    <ContentPage.Resources>
        <ResourceDictionary>
            <local:InvertBooleanConverter x:Key="InvertBooleanConverter" />
        </ResourceDictionary>
    </ContentPage.Resources>
    <Grid>
        <Image Source="bk3.jpg" Aspect="AspectFill"/>
        <StackLayout VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
        <StackLayout Orientation="Horizontal" VerticalOptions="Start">

        </StackLayout>
        <StackLayout VerticalOptions="CenterAndExpand">

            <BoxView HeightRequest="430"></BoxView>
            <Button Text="Continue with Facebook" x:Name="LoginBtn" BackgroundColor="#4867aa" TextColor="White" FontFamily="Klavika" HorizontalOptions="CenterAndExpand" Clicked="LoginBtn_Clicked" />
            <Button Text="Continue with Google  " Command="{Binding GoogleLoginCommand}" BackgroundColor="#d34836" TextColor="White" FontFamily="Klavika" HorizontalOptions="CenterAndExpand"/>
        </StackLayout>
        <StackLayout Orientation="Horizontal" VerticalOptions="End" HorizontalOptions="Center">

            <Frame OutlineColor="White" HorizontalOptions="StartAndExpand">
                <StackLayout Orientation="Horizontal" VerticalOptions="End" HorizontalOptions="Center">

                    <StackLayout Grid.Row="1" Orientation="Horizontal" Spacing="0">

                    </StackLayout>

                </StackLayout>
            </Frame>
        </StackLayout>
    </StackLayout>
    </Grid>
</ContentPage>

App.cs

public partial class App : PrismApplication
    {

        public App(IPlatformInitializer initializer = null) : base(initializer) { }

        protected override void OnInitialized()
        {
            InitializeComponent();
            SetMainPage();
            NavigationService.NavigateAsync("NavigationPage/MainPage?title=Hello%20from%20Xamarin.Forms");
        }

        protected override void RegisterTypes()
        {
            Container.RegisterTypeForNavigation<NavigationPage>();
            Container.RegisterTypeForNavigation<MainPage>();
        }

        private void SetMainPage()
        {
            if (!string.IsNullOrEmpty(Helpers.Settings.Usertoken))
            {
                Application.Current.MainPage = (new Profile());
            }
            else
            {
                MainPage = new NavigationPage(new MainPage())
                { BarBackgroundColor = Color.FromHex("#393b3d") };

            }
        }

        public async static Task NavigateToSMS()
        {
            await Application.Current.MainPage.Navigation.PushAsync(new SMS());
        }

        public static void NavigateToProfile()
        {
            Application.Current.MainPage = (new InvalidLogin());
        }
        public static void NavigateToVerified()
        {
            Application.Current.MainPage = (new Profile());
        }

        protected override void OnStart()
        {
            // Handle when your app starts
        }

        protected override void OnSleep()
        {
            // Handle when your app sleeps
        }

        protected override void OnResume()
        {
            // Handle when your app resumes
        }
    }

Body:
You have your MainPage wrapped in a NavigationPage that by default shows the NavigationBar. You can turn it off in your cs code or in your MainPage.xaml

cs

var mainPage = new MainPage();
MainPage = new NavigationPage(mainPage);
NavigationPage.SetHasNavigationBar(mainPage, false);

xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="LoyaltyWorx.Views.MainPage"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:LoyaltyWorx.Views.Converters"
    xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
    prism:ViewModelLocator.AutowireViewModel="True"
    NavigationPage.HasNavigationBar="False">


问:
Create a column in Pandas by summing and multiplying the previous value in the column
I think that my problem is best illustrated with an example.

The following are the columns I have as inputs.

```<code>Month       Monthly_Interest    Payment_Shortfall      Amount_In_Arrears
1               0.1             20
2               0.1             100
3               0.1             105
4               0.1             50
5               0.1             5
6               0.1             30
7               0.1             70
</code>```

This is the output that I need.

```<code>Month       Monthly_Interest    Payment_Shortfall      Amount_In_Arrears
1               0.1             20                     20.00
2               0.1             100                    122.00
3               0.1             105                    239.20
4               0.1             50                     313.12
5               0.1             5                      349.43
6               0.1             30                     414.38
7               0.1             70                     525.81
</code>```

This is a loan which is being underpaid each month by the Payment_Shortfall.

The Payment_Shortfall builds up each month to form the Amount_In_Arrears.

Interest is charged on the Amount_In_Arrears as at the previous month and is added to the current month's Amount_In_Arrears.

In other words: Amount_In_Arrears =  Payment_Shortfall + Amount_In_Arrears(previous month) + Amount_In_Arrears(previous month) * Monthly_Interest

For example, for month 2:  Amount_in_Arrears = 100 + 20 + 20 * 0.1 = 122 and for month 3: Amount_in_Arrears = 105 + 122 + 122 * 0.1 = 239.20

I have been trying to do this in Pandas and I just can't seem to figure it out. I will need to apply it to a fairly large dataframe (about 3 million rows), so efficiency is a consideration.

My data have a number of loans like this, so I will also need the solution to reset (probably using the groupby() function), however, I think it's best to deal with one issue at a time.

Many thanks in advance for any help!

答:
As far as i know there is no efficient way to calculate this in plain pandas(But if there is, I'd very much like to know). I know of two options to get fast computations in python for this kind of task, cython (specially annotated python that is compiled to c) and numba (a just in time compiler for plain python).

Since i don't know much about cython I'll give you the example for numba.

For numba you write a separate function with a numba decorater. Numba plays nice with numpy but doesn't know pandas, therefore we have to feed numpy arrays into the function:

```<code>@numba.jit(nopython=True)
def compute_total_amount(interest, amount):
  n = len(interest)
  total_amount = np.empty(n)
  total_amount[0] = amount[0]
  for i in range(1,n):
    total_amount[i] = total_amount[i-1]*(1+interest[i])+amount[i]
  return total_amount

df['Amount_In_Arrears'] = compute_total_amount(df['Monthly_Interest'].values,\
                                               df['Payment_Shortfall'].values)

   Payment_Shortfall  Monthly_Interest  Amount_In_Arrears
0                 20               0.1           20.00000
1                100               0.1          122.00000
2                105               0.1          239.20000
3                 50               0.1          313.12000
4                  5               0.1          349.43200
5                 30               0.1          414.37520
6                 70               0.1          525.81272
</code>```

EDIT: Added timings for numba vs plain python (1m rows)

```<code>df= pd.DataFrame({'Payment_Shortfall':np.random.random(10**6)*10}))
df['Monthly_Interest'] = -0.01

def compute_total_amount_python(interest, amount):
  n = len(interest)
  total_amount = np.empty(n)
  total_amount[0] = amount[0]
  for i in range(1,n):
    total_amount[i] = total_amount[i-1]*(1+interest[i])+amount[i]
  return total_amount

%timeit compute_total_amount_python(df['Monthly_Interest'].values, df['Payment_Shortfall'].values)
729 ms ± 36.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit compute_total_amount(df['Monthly_Interest'].values, df['Payment_Shortfall'].values)
2.7 ms ± 62.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
</code>```

Body:
I think that my problem is best illustrated with an example.

The following are the columns I have as inputs.

Month       Monthly_Interest    Payment_Shortfall      Amount_In_Arrears
1               0.1             20
2               0.1             100
3               0.1             105
4               0.1             50
5               0.1             5
6               0.1             30
7               0.1             70

This is the output that I need.

Month       Monthly_Interest    Payment_Shortfall      Amount_In_Arrears
1               0.1             20                     20.00
2               0.1             100                    122.00
3               0.1             105                    239.20
4               0.1             50                     313.12
5               0.1             5                      349.43
6               0.1             30                     414.38
7               0.1             70                     525.81

This is a loan which is being underpaid each month by the Payment_Shortfall.

The Payment_Shortfall builds up each month to form the Amount_In_Arrears.

Interest is charged on the Amount_In_Arrears as at the previous month and is added to the current month's Amount_In_Arrears.

In other words: Amount_In_Arrears =  Payment_Shortfall + Amount_In_Arrears(previous month) + Amount_In_Arrears(previous month) * Monthly_Interest

For example, for month 2:  Amount_in_Arrears = 100 + 20 + 20 * 0.1 = 122 and for month 3: Amount_in_Arrears = 105 + 122 + 122 * 0.1 = 239.20

I have been trying to do this in Pandas and I just can't seem to figure it out. I will need to apply it to a fairly large dataframe (about 3 million rows), so efficiency is a consideration.

My data have a number of loans like this, so I will also need the solution to reset (probably using the groupby() function), however, I think it's best to deal with one issue at a time.

Many thanks in advance for any help!

Body:
As far as i know there is no efficient way to calculate this in plain pandas(But if there is, I'd very much like to know). I know of two options to get fast computations in python for this kind of task, cython (specially annotated python that is compiled to c) and numba (a just in time compiler for plain python).

Since i don't know much about cython I'll give you the example for numba.

For numba you write a separate function with a numba decorater. Numba plays nice with numpy but doesn't know pandas, therefore we have to feed numpy arrays into the function:

@numba.jit(nopython=True)
def compute_total_amount(interest, amount):
  n = len(interest)
  total_amount = np.empty(n)
  total_amount[0] = amount[0]
  for i in range(1,n):
    total_amount[i] = total_amount[i-1]*(1+interest[i])+amount[i]
  return total_amount

df['Amount_In_Arrears'] = compute_total_amount(df['Monthly_Interest'].values,\
                                               df['Payment_Shortfall'].values)

   Payment_Shortfall  Monthly_Interest  Amount_In_Arrears
0                 20               0.1           20.00000
1                100               0.1          122.00000
2                105               0.1          239.20000
3                 50               0.1          313.12000
4                  5               0.1          349.43200
5                 30               0.1          414.37520
6                 70               0.1          525.81272

EDIT: Added timings for numba vs plain python (1m rows)

df= pd.DataFrame({'Payment_Shortfall':np.random.random(10**6)*10}))
df['Monthly_Interest'] = -0.01

def compute_total_amount_python(interest, amount):
  n = len(interest)
  total_amount = np.empty(n)
  total_amount[0] = amount[0]
  for i in range(1,n):
    total_amount[i] = total_amount[i-1]*(1+interest[i])+amount[i]
  return total_amount

%timeit compute_total_amount_python(df['Monthly_Interest'].values, df['Payment_Shortfall'].values)
729 ms ± 36.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit compute_total_amount(df['Monthly_Interest'].values, df['Payment_Shortfall'].values)
2.7 ms ± 62.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)


答:
The link is: http://www.facebook.com/developers/editapp.php?app_id=[APP_ID]
You can navigate to this link starting from facebook.com/developers. The base URL can be edited inside the Facebook integration tab (on the left)</p>

Body:
How do you edit the settings you entered when you registered your Facebook app?
I need to change the base url and cannot for the life of me figure it out navigating the site.
Someone must know where this is accessible.

Edit:
Hmmm, guess I have been going to the right place, right now I just get
'An error occurred with Developer. Please try again later.'


问:
choosing camera for robot vision system
I am making a robot that navigates based on vision system . vision system use the colour of the object to navigate so how I choose my camera?

答:
If I can give you an advice, be careful on USB controlled cameras as you might quickly get into a bandwidth bottleneck. In other words, the size on the image you need to analyse might be so large that it won't fit on the USB bus (or won't be transmitted fast enough).

Here at work, we use ethernet for transmitting images across and I am also aware that the iCub robot sends images across ethernet as well to other desktop computers which do all the image-processing stuff (and people still complain that it is too slow).

That said, as many other mentioned, the right camera depends on what you want to do and how much you wish to spend. There do exist a lot of robots which perform colour based image processing but such images are also very heavy (3x area of image in pixel) and you might hit that bottleneck pretty fast.

Probably the first thing you want to clarify for yourself is the resolution of your camera. The higher the resolution the more information your algorithm will have (and the more computational CPU power you will need to process it), the lower the resolution the easier it is to process it quickly and the cheaper will be your system (no need of making ad-hoc boards for example).

An higher resolution and better CPU will not automatically give you a better robot if you use your data cleverly. The Nao robot, back in 2009, was using a 320x240 colour camera (like a old mobile phone) interfaced internally to a Geode microcontroller using integrated circuits. Despite the fact that the original image was subsampled, the robot was still able to play football. Of course the code was tightly optimised.

Title: choosing camera for robot vision system


问:
Nexmo restricted to sent messages globally
Currently, I am using a Test account to sent the messages and It is restricted me to sent the messages to only added numbers. I have to send messages globally to any number. How can I do this? Will this allow me to sent messages globally If I use a paid account?</p>

答:
When initially creating a Nexmo account you will be given €2 welcome credit.
At this stage, you are able to use our products on up to 10 destination numbers of your choice managed on the test numbers page and the text [FREE SMS DEMO, TEST MESSAGE] will be added to all SMS you send.

To enable full account features you will need to add credit to your account and make your first payment.

Once this is done you no longer need to:
Whitelist your destination numbers
Have the message [FREE SMS DEMO, TEST MESSAGE] attached to your SMS
(note: older accounts that have not yet made their first payment have the shorter wording [Nexmo DEMO] attached to SMS, instead of [FREE SMS DEMO, TEST MESSAGE]


答: setState(updater[, callback]) accepts a callback function as a second param, however, performing comparison of next and / or previous state within componentWillUpdate(nextProps, nextState) or componentDidUpdate(prevProps, prevState) appears to be more appropriate for your use case.

Title: Reactjs setState() does not immediately mutate this.state, How should I fix it?


问:
Get certificate details from java key store
Friends,

Problem Statement:
An external entity sends the serial number of a certificate to my system. And  using that serial number my system has to find out or fetch certificate details (Ex: by online downloading or by pre-load using Java Key Store) and use it for signature verification.

I could not find how to download certificate from online using serial number. But, I wouldn't ouch for even though it was, since you know why.

Instead, i would like to go with Java Key Store (JKS) and fetch certification details. But JKS expects alias name and password.

So, now do you suggest me to go to that external entity guy and ask him to send the certification details instead of serial number? if so is that security compliance? since we are working on Telecom domain using Remote Provisioning Architecture for Embedded UICC Technical Specification Versio 3.0.

答:
CAs only publish their root and intermediate certificates. The serial number is not usually used to download them, but a URL is included in the final issued certificates.

Summarizing: you can't find a certificate by serial number except if your CA has a specific service to download it, or you have a pre-provisioned list of the CA certificates, for example in a keystore.

Assuming you have a keystore with possible certificates, you can list all available aliases, load the certificate and check if serial number match the provided one. You do not need any password at all.

```<code> Enumeration enumeration = keystore.aliases();
 while(enumeration.hasMoreElements()) {
        String alias = (String)enumeration.nextElement();
        X509Certificate certificate = (X509Certificate) keystore.getCertificate(alias);
        BigInteger serialNumber = certificate.getSerialNumber()

    }
</code>```

Note that the serial number is not unique between different CAs

Body:
CAs only publish their root and intermediate certificates. The serial number is not usually used to download them, but a URL is included in the final issued certificates.

Summarizing: you can't find a certificate by serial number except if your CA has a specific service to download it, or you have a pre-provisioned list of the CA certificates, for example in a keystore.

Assuming you have a keystore with possible certificates, you can list all available aliases, load the certificate and check if serial number match the provided one. You do not need any password at all.

 Enumeration enumeration = keystore.aliases();
 while(enumeration.hasMoreElements()) {
        String alias = (String)enumeration.nextElement();
        X509Certificate certificate = (X509Certificate) keystore.getCertificate(alias);
        BigInteger serialNumber = certificate.getSerialNumber()

    }

Note that the serial number is not unique between different CAs


问:
disk I/O error with SQLite3 in Python 3 when writing to a database
i am a student just starting out with python, and i was tasked with creating a relational database management system. I think i came pretty far, but i seem to have hit a wall. This is my code:

```<code>import csv
import sqlite3

conn = sqlite3.connect('unfccc.db')
c = conn.cursor()

c.execute('''CREATE TABLE unfccc (
        Country TEXT,
        CodeCountryFormat TEXT,
        NamePollutant TEXT,
        NameYearSector TEXT,
        NameParent TEXT,
        Sector TEXT,
        CodeSector TEXT,
        CNUEDSPD TEXT
        )''')

def insert_row(Country, CodeCountryFormat, NamePollutant, NameYearSector, NameParent, Sector, CodeSector, CNUEDSPD):
    c.execute("INSERT INTO unfccc VALUES (?, ?, ?, ?, ?, ?, ?, ?)", (Country, CodeCountryFormat, NamePollutant, NameYearSector, NameParent, Sector, CodeSector, CNUEDSPD))
    conn.commit()

with open('UNFCCC_v20.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter='\t')

    counter = 0

    for row in readCSV:
        insert_row(row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7])
        counter = counter+1
        print('%d down, more to go' % counter)
conn.close()
</code>```

when i run it with line 4 directing the input towards :memory: it works perfectly and i have myself what i think is a relational database.

However, when i try to run the code like this, writing the data to a db file, i get this error:

```<code> File "<ipython-input-13-4c50216842bc>", line 19, in insert_row
    c.execute("INSERT INTO unfccc VALUES (?, ?, ?, ?, ?, ?, ?, ?)", (Country, CodeCountryFormat, NamePollutant, NameYearSector, NameParent, Sector, CodeSector, CNUEDSPD))

OperationalError: disk I/O error
</code>```

I've searched stackoverflow, and i've used google, but i don't think any of the cases i found match up to what i'm trying to do here (or i don't have the knowledge to figure out whats going on). One other thing i noticed about my code is that it inputs the data into memory super fast, but when i write to a db file it is really slow, it shouldn't be a hardware limit as i am using an SSD. Any help will be greatly appreciated!

答:
The answer was simple, i was working from my Google Drive directory on my personal computer, i was offline at the time of the error and the Backup and Sync program was not running therefore it took me a while to realize that i still don't have full permissions over the folder.

Moving my script and necessary files to a folder in my Documents fixed the error. Thanks for the help Marco and Josh!

Body:
i am a student just starting out with python, and i was tasked with creating a relational database management system. I think i came pretty far, but i seem to have hit a wall. This is my code:

import csv
import sqlite3

conn = sqlite3.connect('unfccc.db')
c = conn.cursor()

c.execute('''CREATE TABLE unfccc (
        Country TEXT,
        CodeCountryFormat TEXT,
        NamePollutant TEXT,
        NameYearSector TEXT,
        NameParent TEXT,
        Sector TEXT,
        CodeSector TEXT,
        CNUEDSPD TEXT
        )''')

def insert_row(Country, CodeCountryFormat, NamePollutant, NameYearSector, NameParent, Sector, CodeSector, CNUEDSPD):
    c.execute("INSERT INTO unfccc VALUES (?, ?, ?, ?, ?, ?, ?, ?)", (Country, CodeCountryFormat, NamePollutant, NameYearSector, NameParent, Sector, CodeSector, CNUEDSPD))
    conn.commit()

with open('UNFCCC_v20.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter='\t')

    counter = 0

    for row in readCSV:
        insert_row(row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7])
        counter = counter+1
        print('%d down, more to go' % counter)
conn.close()

when i run it with line 4 directing the input towards :memory: it works perfectly and i have myself what i think is a relational database.

However, when i try to run the code like this, writing the data to a db file, i get this error:

 File "<ipython-input-13-4c50216842bc>", line 19, in insert_row
    c.execute("INSERT INTO unfccc VALUES (?, ?, ?, ?, ?, ?, ?, ?)", (Country, CodeCountryFormat, NamePollutant, NameYearSector, NameParent, Sector, CodeSector, CNUEDSPD))

OperationalError: disk I/O error

I've searched stackoverflow, and i've used google, but i don't think any of the cases i found match up to what i'm trying to do here (or i don't have the knowledge to figure out whats going on). One other thing i noticed about my code is that it inputs the data into memory super fast, but when i write to a db file it is really slow, it shouldn't be a hardware limit as i am using an SSD. Any help will be greatly appreciated!


问:
How to configure Apache Kafka to sending data at specified time?
Lets consider the following abstaract schema of working Apache Kafka:

```<code>Poducers ->(Send messages) -> Apache Kafka -> (Resend to customers) -> Customers
</code>```

It is possible to configure Kafka to send messages to customers at the specified time?

The second question is it real to roll back message to Kafka from customer?

答:
As others have already replied, Kafka doesn't push messages to consumers but consumers pull messages from Kafka; it means that you need to write your consumer in order to pull messages from Kafka topic at specific times (or intervals).
About rollback what do you mean ? Maybe that consumer gets messages from Kafka but then it wants to re-read same messages later because errors happen during the first processing ? If yes, there are two aspects to consider about Kafka :

Kafka has a retention of the messages that can be configured (even for days), it means that when the consumer gets messages they are not deleted from the topic partition

instead when the consumer gets messages, it has to commit the offset so that it can trace what's the latest message read from the topic partition. This commit can be done automatically or manually so that you can commit the offset only if your process went well. In any case, you are able to re-wind the stream and decide to re-start reading the topic partition from a specific offset.

Body:
Lets consider the following abstaract schema of working Apache Kafka:

Poducers ->(Send messages) -> Apache Kafka -> (Resend to customers) -> Customers

It is possible to configure Kafka to send messages to customers at the specified time?

The second question is it real to roll back message to Kafka from customer?


问:
JavaScript: Compare dates in an array and sum the "price" for each month/year
I have a json file with multiple transactions with a date and a price attribute. Now I want to compare the dates and if they are in the same month and year I want to sum up the prices.

JSON:

```<code>transactions: [
{
  date: "2017-11-17",
  price: "28",
},
{
  ...
}
</code>```

JavaScript:

```<code>request.onload = function() {
  for(const transaction of request.response.transactions) {
    let year = new Date(transaction.date).getFullYear();
    let month = new Date(transaction.date).getMonth();

    console.log(year + ' ' + month);  // output: 2017-11 ...
  }
};
</code>```

I tried to loop over the json object but I struggle to find a solution to compare the dates.

答:
This solutions uses map to format your dates into year/month format for each object entry and then reduce to sum them by those separated dates.

const transactions = [
  {date:"2017-11-17", price: "28",},
  {date:"2017-12-17", price: "28",},
  {date:"2017-11-17", price: "20",},
  {date:"2017-12-17", price: "2",},
  {date:"2017-11-17", price: "58",},
  {date:"2017-11-17", price: "8",},
  {date:"2017-10-17", price: "30",},
  {date:"2018-11-17", price: "1",},
];

const mapper = single => {
  let d = single.date.split('-');
  let p = Number(single.price);
  return { year: d[0], month: d[1], price: p };
}

const reducer = (group, current) => {
  let i = group.findIndex(single => (single.year == current.year && single.month == current.month));
  if (i == -1) {
    return [ ...group, current ];
  }

  group[i].price += current.price;
  return group;
};

const sumPrices = transactions.map(mapper).reduce(reducer, []);
console.log(sumPrices);

  ```

Body:
I have a json file with multiple transactions with a date and a price attribute. Now I want to compare the dates and if they are in the same month and year I want to sum up the prices.

JSON:

transactions: [
{
  date: "2017-11-17",
  price: "28",
},
{
  ...
}

JavaScript:

request.onload = function() {
  for(const transaction of request.response.transactions) {
    let year = new Date(transaction.date).getFullYear();
    let month = new Date(transaction.date).getMonth();

    console.log(year + ' ' + month);  // output: 2017-11 ...
  }
};

I tried to loop over the json object but I struggle to find a solution to compare the dates.


问:
How can I check if an XMLHttpRequest to my public API is from my own webapp or from a third-party client (to ensure priority)?
Does anybody know of a way of checking on the API side if a XMLHttpRequest has been made from my own web-application (ie. from the JS I have written) or from a third-party application...

The problem, to me, seems to be that because the JS is run on the client and thus accessible to anyone I have no way of secretly communicating to the API server who I am. I think this is useful because otherwise I cannot prioritize requests from my own application over third-party clients in case of high usage.

I could obviously send some non-documented parameters but these can be spoofed.

Anybody with some ideas?

答:
If you do approve of third party clients accessing your API, perhaps you could provide them with a slightly different, rate-limited interface and document it well (so that it would be easier to use and thus actually be used by third-party clients).

One way to do this would be to have two different API URLs, for example:

/api?client=ThirdPartyAppName&... for third-party apps (you would encourage use of this URL)

/api?token=<number generated from hidden fields from the HTML page using obfuscated code>&... for your own JS

Note that as you mention, it is not possible to put a complete stop to reverse engineering of your own code. Although it can take longer, even compiled, binary code written in such languages as C++ can be reverse engineered, and that threatens any approach relying on secrecy.


答:
This is why I hate strictNullChecks at the moment. It does not support typechecking from within a function to 'bubble up' to where the check is called at.

```<code>if (a && a.foo) {
   return a.foo.length;
}
</code>```

works as expected. For me, wrapping the following in a function...

```<code>const hasFoo(a: A) => !!a && 'foo' in a && typeof a.foo === 'string';

...

if (hasFoo(a)) {
   return a.foo.length;
}

...
</code>```

...should work as the initial check. However, this is not the case.

A solution (and afaik the only one) is to use the new !. postfix expression. This claims that the value is indeed declared as the expected type.

```<code>if (hasFoo(a))
{
   return a.foo!.length;
}
</code>```

Body:
in typescript 2.6 I want to write a function that does a null check. When I enable strict null-checks, typescript 2.6 complains about the following code. (Note that when using the null check directly works)

edited: corrected notNullOrUndefined since it didn't check for foo

interface A {
  foo: string | undefined;
}
const notNullOrUndefined = (a: A): boolean => {
  return a.foo != null;
}
const len = (a: A): number => {
  //if (a.foo != null) {
  if (notNullOrUndefined(a)){
    return a.foo.length;
  }
  return 0;
}

here is the example to play with: <a href="https://www.typescriptlang.org/play/#src=interface%20A%20%7B%0D%0A%20%20foo%3A%20string%20%7C%20undefined%3B%0D%0A%7D%0D%0Aconst%20notNullOrUndefined%20%3D%20(a%3A%20A)%3A%20boolean%20%3D%3E%20%7B%0D%0A%20%20return%20a.foo%20!%3D%20null%3B%0D%0A%7D%0D%0Aconst%20len%20%3D%20(a%3A%20A)%3A%20number%20%3D%3E%20%7B%0D%0A%20%20%2F%2Fif%20(a.foo%20!%3D%20null)%20%7B%0D%0A%20%20if%20(notNullOrUndefined(a))%7B%0D%0A%20%20%20%20return%20a.foo.length%3B%0D%0A%20%20%7D%0D%0A%20%20return%200%3B%0D%0A%7D%20" rel="nofollow noreferrer">example

What's the typescript way to solve this?

Body:
This is why I hate strictNullChecks at the moment. It does not support typechecking from within a function to 'bubble up' to where the check is called at.

if (a && a.foo) {
   return a.foo.length;
}

works as expected. For me, wrapping the following in a function...

const hasFoo(a: A) => !!a && 'foo' in a && typeof a.foo === 'string';

...

if (hasFoo(a)) {
   return a.foo.length;
}

...

...should work as the initial check. However, this is not the case.

A solution (and afaik the only one) is to use the new !. postfix expression. This claims that the value is indeed declared as the expected type.

if (hasFoo(a))
{
   return a.foo!.length;
}


问:
Use component from another module
I have Angular 2.0.0 app generated with angular-cli.

When I create a component and add it to AppModule's declarations array it's all good, it works.

I decided to separate the components, so I created a TaskModule and a component TaskCard. Now I want to use the TaskCard in one of the components of the AppModule (the Board component).

AppModule:

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { BoardComponent } from './board/board.component';
import { LoginComponent } from './login/login.component';

import { MdButtonModule } from '@angular2-material/button';
import { MdInputModule } from '@angular2-material/input';
import { MdToolbarModule } from '@angular2-material/toolbar';

import { routing, appRoutingProviders} from './app.routing';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';

import { UserService  } from './services/user/user.service';
import { TaskModule } from './task/task.module';

@NgModule({
  declarations: [
    AppComponent,
    BoardComponent,// I want to use TaskCard in this component
    LoginComponent,
    PageNotFoundComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    MdButtonModule,
    MdInputModule,
    MdToolbarModule,
    routing,
    TaskModule // TaskCard is in this module
  ],
  providers: [UserService],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

TaskModule:

```<code>import { NgModule } from '@angular/core';
import { TaskCardComponent } from './task-card/task-card.component';

import { MdCardModule } from '@angular2-material/card';

@NgModule({
  declarations: [TaskCardComponent],
  imports: [MdCardModule],
  providers: []
})
export class TaskModule{}
</code>```

The whole project is available on https://github.com/evgdim/angular2 (kanban-board folder)

What am I missing? What do I have to do to use TaskCardComponent in BoardComponent?

答:
Note that in order to create a so called "feature module", you need to import CommonModule inside it. So, your module initialization code will look like this:

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { TaskCardComponent } from './task-card/task-card.component';
import { MdCardModule } from '@angular2-material/card';

@NgModule({
  imports: [
    CommonModule,
    MdCardModule
  ],
  declarations: [
    TaskCardComponent
  ],
  exports: [
    TaskCardComponent
  ]
})
export class TaskModule { }
</code>```

More information available here: https://angular.io/guide/ngmodule#create-the-feature-module

Title: Use component from another module

Body:
I have Angular 2.0.0 app generated with angular-cli.

When I create a component and add it to AppModule's declarations array it's all good, it works.

I decided to separate the components, so I created a TaskModule and a component TaskCard. Now I want to use the TaskCard in one of the components of the AppModule (the Board component).

AppModule:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { BoardComponent } from './board/board.component';
import { LoginComponent } from './login/login.component';

import { MdButtonModule } from '@angular2-material/button';
import { MdInputModule } from '@angular2-material/input';
import { MdToolbarModule } from '@angular2-material/toolbar';

import { routing, appRoutingProviders} from './app.routing';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';

import { UserService  } from './services/user/user.service';
import { TaskModule } from './task/task.module';

@NgModule({
  declarations: [
    AppComponent,
    BoardComponent,// I want to use TaskCard in this component
    LoginComponent,
    PageNotFoundComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    MdButtonModule,
    MdInputModule,
    MdToolbarModule,
    routing,
    TaskModule // TaskCard is in this module
  ],
  providers: [UserService],
  bootstrap: [AppComponent]
})
export class AppModule { }

TaskModule:

import { NgModule } from '@angular/core';
import { TaskCardComponent } from './task-card/task-card.component';

import { MdCardModule } from '@angular2-material/card';

@NgModule({
  declarations: [TaskCardComponent],
  imports: [MdCardModule],
  providers: []
})
export class TaskModule{}

The whole project is available on https://github.com/evgdim/angular2 (kanban-board folder)

What am I missing? What do I have to do to use TaskCardComponent in BoardComponent?

Body:
Note that in order to create a so called "feature module", you need to import CommonModule inside it. So, your module initialization code will look like this:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { TaskCardComponent } from './task-card/task-card.component';
import { MdCardModule } from '@angular2-material/card';

@NgModule({
  imports: [
    CommonModule,
    MdCardModule
  ],
  declarations: [
    TaskCardComponent
  ],
  exports: [
    TaskCardComponent
  ]
})
export class TaskModule { }

More information available here: https://angular.io/guide/ngmodule#create-the-feature-module


答:
you can use sed : sed ':a;N;$!ba;s/\n/ \&\& /g' < in.txt > out.txt

how it works is explained in this question.

Title: Automatically convert bunch of commands to command1 && command2