问:
Comparing two integers without any comparison
Is it possible to find the greatest of two integers without any comparison? I found some  solutions:

```<code>if(!(a/b)) // if a is less than b then division result will be zero.
{
    cout << " b is greater than a";
}
else if (!(a-b)) // we know a is greater than or equal to b now.  check whether they are equal.
{
    cout << "a and b are equal";
}
else
    cout << "a is greater than b";
</code>```

But if(c) or if(!c) is a comparison to zero. In addition it doesn't work for negative numbers. In fact I need a solution that avoids any if statement. Instead I should use switch statements and arithmetic operators. ThanX.

答:
```<code>(!(a/b) ?  cout << " b is greater than a" : (!(b-a) ? cout << "a and b are equal" :  cout << "a is greater than b") :  cout << "a is greater than b");
</code>```

That gets a bit messy though

Edit: Is this homework?

OwnerDisplayName: kvphxga

Body:
Is it possible to find the greatest of two integers without any comparison? I found some  solutions:

if(!(a/b)) // if a is less than b then division result will be zero.
{
    cout << " b is greater than a";
}
else if (!(a-b)) // we know a is greater than or equal to b now.  check whether they are equal.
{
    cout << "a and b are equal";
}
else
    cout << "a is greater than b";

But if(c) or if(!c) is a comparison to zero. In addition it doesn't work for negative numbers. In fact I need a solution that avoids any if statement. Instead I should use switch statements and arithmetic operators. ThanX.

LastEditorDisplayName: kvphxga

Body:
(!(a/b) ?  cout << " b is greater than a" : (!(b-a) ? cout << "a and b are equal" :  cout << "a is greater than b") :  cout << "a is greater than b");

That gets a bit messy though

Edit: Is this homework?

OwnerDisplayName: fmsf

LastEditorDisplayName: fmsf


来源: stackexchange

问:
CSS using z-index doesn't place child element behind its parent
I am trying to make a drop down menu that slides from header.
I have a header and inside it I have some div with border-bottom 1px line and background-color. Inside this div I would like to place logo, searchbox some links and a user profile button. When this button is clicked I would like to drop down menu below this button. Unfortunately this dropdown menu appears in front of header and not slides from behind of header (obscuring the header background and bottom-border line). I have tried solution like below (it is simplified version).

header {
  position: relative;
  z-index: 5;
}

.dropdown {
  background-color: yellow;
  width: 100px;
  height: 100px;
  position: absolute;
  z-index: 1;
}

.background {
  position: absolute;
  background-color: #ccca;
  border-bottom: 1px solid black;
  width: 100%;
  height: 50px;
  z-index: 2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <div class="background">
    <div class="dropdown">
    </div>
  </div>
</header></code>```

I have tried many z-index configurations and none of them seems to work.
1. div.background with z-index 2, div.dropdown with z-index 1 or even -1
2. div.background without z-index and position, div.dropdown with z-index -1 (here dropdown was behind header but menu links stopped working and menu was also behind main content of webpage)

How can I make my div.dropdown to slide from behind the header bar with background and border bottom line? Isn't it possible to have this div.dropdown inside header div tree as the descendant element.

答:
Child elements cannot be displayed under their parent. Make the two divs seperate elements like this.

header {
 position:relative;
 z-index:5;
}
.dropdown {
 background-color: yellow;
 width: 100px;
 height: 100px;
 position: absolute;
  z-index: 1;
}
.background {
 position: absolute;
 background-color:#ccca;
 border-bottom: 1px solid black;
 width: 100%;
 height: 50px;
 z-index: 2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
</head>
<body>
<header>
  <div class="background"></div>
  <div class="dropdown"></div>
</header>
</body>
</html></code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to make a drop down menu that slides from header.
I have a header and inside it I have some div with border-bottom 1px line and background-color. Inside this div I would like to place logo, searchbox some links and a user profile button. When this button is clicked I would like to drop down menu below this button. Unfortunately this dropdown menu appears in front of header and not slides from behind of header (obscuring the header background and bottom-border line). I have tried solution like below (it is simplified version).

header {
  position: relative;
  z-index: 5;
}

.dropdown {
  background-color: yellow;
  width: 100px;
  height: 100px;
  position: absolute;
  z-index: 1;
}

.background {
  position: absolute;
  background-color: #ccca;
  border-bottom: 1px solid black;
  width: 100%;
  height: 50px;
  z-index: 2;
}

I have tried many z-index configurations and none of them seems to work.
1. div.background with z-index 2, div.dropdown with z-index 1 or even -1
2. div.background without z-index and position, div.dropdown with z-index -1 (here dropdown was behind header but menu links stopped working and menu was also behind main content of webpage)

How can I make my div.dropdown to slide from behind the header bar with background and border bottom line? Isn't it possible to have this div.dropdown inside header div tree as the descendant element.

Body:
Child elements cannot be displayed under their parent. Make the two divs seperate elements like this.

header {
 position:relative;
 z-index:5;
}
.dropdown {
 background-color: yellow;
 width: 100px;
 height: 100px;
 position: absolute;
  z-index: 1;
}
.background {
 position: absolute;
 background-color:#ccca;
 border-bottom: 1px solid black;
 width: 100%;
 height: 50px;
 z-index: 2;
}

<html>
<head>
</head>
<body>
<header>
  <div class="background"></div>
  <div class="dropdown"></div>
</header>
</body>
</html>


问:
Spreadsheet Gear #value when result.Number contains the correct return value
I am working on a project porting VBA code to C# for Spreadsheet Gear. My team has successfully ported around 150 custom Excel Add-in functions.  For one of the functions, our regression spreadsheet returns #value for 4 out of 148 function calls, with the remainder returning the expected result.  When I step through the code, everything functions as expected and the correct result gets written to result.Number, but resolves to #value in Spreadsheet Gear.  I'm totally baffled!  Please help me - I don't even know where to start.

The end of the function is as follows:

```<code>if (retval < 0)
{
     result.Text = UtilFuncs.ErrorNum(retval);
}
else
{
     result.Number = retval;
}
</code>```

retval contains the correct result returned from a call to a separate DLL. And when I hover over result.Number, it also contains the correct result.  But I get a #value.

I can provide more code if necessary.  My big question is why it works for all but 4 of them.

答:
Without a more concrete example, it's about impossible to provide a definitive answer to this.  I'll take a shot in the dark, though.

If you use IArguments methods like IArguments.GetNumber(...),
 GetLogical(...), etc., to access your custom function's arguments, you might read through the documentation for these.  For instance, see the following remark for GetLogical(...):

Non-logical arguments are converted to a logical value if possible.
Otherwise, false is returned by this method, and an internal flag is
set indicating that an error has occurred, causing the result of the
formula to be an error.

So if you pass in a non-boolean value into an argument where you are expecting a Boolean, your function may end up having this internal "error" flag being set and so result in a #VALUE! error being displayed for this cell, regardless of what you set the result object at the end of your method.

If this is the case, you can use the IArguments.ClearError(...) method to clear the error.

Body:
I am working on a project porting VBA code to C# for Spreadsheet Gear. My team has successfully ported around 150 custom Excel Add-in functions.  For one of the functions, our regression spreadsheet returns #value for 4 out of 148 function calls, with the remainder returning the expected result.  When I step through the code, everything functions as expected and the correct result gets written to result.Number, but resolves to #value in Spreadsheet Gear.  I'm totally baffled!  Please help me - I don't even know where to start.

The end of the function is as follows:

if (retval < 0)
{
     result.Text = UtilFuncs.ErrorNum(retval);
}
else
{
     result.Number = retval;
}

retval contains the correct result returned from a call to a separate DLL. And when I hover over result.Number, it also contains the correct result.  But I get a #value.

I can provide more code if necessary.  My big question is why it works for all but 4 of them.


问:
Angular 2/4 prevent user to leave component if changes not saved
I have this interface that i'm using to prevent the user to leave page

```<code>export interface ComponentCanDeactivate {
  canDeactivate: () => boolean;
}

@Injectable()
export class PendingChangesGuard implements CanDeactivate<ComponentCanDeactivate> {
  canDeactivate(component: ComponentCanDeactivate): boolean {
    return  component.canDeactivate() ?
     //code : //more code
  }
}
</code>```

In one of my component i have the following code

```<code>export class DashboardComponent implements ComponentCanDeactivate{
  @HostListener('window:beforeunload')
  canDeactivate(): boolean {
    return !this.isDirty;
  }
</code>```

My problem is that my component -> (component: ComponentCanDeactivate) from PendingChangesGuard  is always null so i get an error saying

Cannot call canDeactivate() of null

I also have this setup in my routing

```<code> path: 'dashboard',
        canDeactivate: [PendingChangesGuard],
        loadChildren: './views/dashboard/dashboard.module#DashboardModule'
</code>```

Can someone tell me what am i doing wrong?

答:
The issue was caused by lazy loading

Instead of having this in your app routing:

```<code>path: 'dashboard',
        canDeactivate: [PendingChangesGuard], <-- causing issue
        loadChildren: './views/dashboard/dashboard.module#DashboardModule'
</code>```

You need to remove the canDeactive from the app routing and move it to the module routing.

```<code>const routes: Routes = [
  {
    path: '',
    component: DashboardComponent,
    canDeactivate: [ PendingChangesGuard ]
  }
</code>```

Body:
I have this interface that i'm using to prevent the user to leave page

export interface ComponentCanDeactivate {
  canDeactivate: () => boolean;
}

@Injectable()
export class PendingChangesGuard implements CanDeactivate<ComponentCanDeactivate> {
  canDeactivate(component: ComponentCanDeactivate): boolean {
    return  component.canDeactivate() ?
     //code : //more code
  }
}

In one of my component i have the following code

export class DashboardComponent implements ComponentCanDeactivate{
  @HostListener('window:beforeunload')
  canDeactivate(): boolean {
    return !this.isDirty;
  }

My problem is that my component -> (component: ComponentCanDeactivate) from PendingChangesGuard  is always null so i get an error saying

Cannot call canDeactivate() of null

I also have this setup in my routing

 path: 'dashboard',
        canDeactivate: [PendingChangesGuard],
        loadChildren: './views/dashboard/dashboard.module#DashboardModule'

Can someone tell me what am i doing wrong?

Body:
The issue was caused by lazy loading

Instead of having this in your app routing:

path: 'dashboard',
        canDeactivate: [PendingChangesGuard], <-- causing issue
        loadChildren: './views/dashboard/dashboard.module#DashboardModule'

You need to remove the canDeactive from the app routing and move it to the module routing.

const routes: Routes = [
  {
    path: '',
    component: DashboardComponent,
    canDeactivate: [ PendingChangesGuard ]
  }


问:
Not matched rows in B join with some row in A
Example data:

```<code>Table1     Table2
x | y      x | y
-----      -----
1 | A      1 | A
1 | B      1 | D
1 | C      2 | M
1 | null   2 | N
2 | M      2 | M
2 | N      1 | A
</code>```

I want to count number of x's in Table2 and join it with Table1. But in Table2 I can have y's which doesn't match to y's in Table1. In this case I want to join them with row with null in y column in Table1.
In an example Table2.1-D should be joined with Tabl1.1-null

For given example I expect the result:

```<code>x | y    | count
-----------------
1 | A    | 2
1 | B    | 0
1 | C    | 0
1 | null | 1 (because D doesn't match to anything else in Table1)
2 | M    | 2
2 | N    | 1
</code>```

答:
There are multiple ways to solve this problem and the best one for you really depends on the data, the number of rows and resulting performance.

One of the ways would be doing the operation for everything but null from the Table1 and then UNION-ing with the null row.

For your given example I assume that the combination of x and y values in both Table1 and Table2 is always unique. You'll need additional grouping if it's not.

```<code>SELECT
    t1.x,
    t1.y,
    COUNT(*) as [count]
FROM
    Table1 t1
    INNER JOIN Table2 t2 ON t1.y = t2.y
WHERE
    t1.y IS NOT NULL
GROUP BY
    t1.x, t1.y
UNION ALL
SELECT
    t1.x,
    NULL as y,
    t2missingFromt1.[count]
FROM
    Table1 t1
    CROSS APPLY (
        SELECT
             COUNT(x) as [count]
        FROM
             Table2 t2
        WHERE NOT EXISTS (SELECT 1 FROM Table1 tbl1 WHERE tbl1.y = t2.y)
    ) t2missingFromt1
WHERE
    t1.y IS NULL
</code>```

Body:
Example data:

Table1     Table2
x | y      x | y
-----      -----
1 | A      1 | A
1 | B      1 | D
1 | C      2 | M
1 | null   2 | N
2 | M      2 | M
2 | N      1 | A

I want to count number of x's in Table2 and join it with Table1. But in Table2 I can have y's which doesn't match to y's in Table1. In this case I want to join them with row with null in y column in Table1.
In an example Table2.1-D should be joined with Tabl1.1-null

For given example I expect the result:

x | y    | count
-----------------
1 | A    | 2
1 | B    | 0
1 | C    | 0
1 | null | 1 (because D doesn't match to anything else in Table1)
2 | M    | 2
2 | N    | 1

Body:
There are multiple ways to solve this problem and the best one for you really depends on the data, the number of rows and resulting performance.

One of the ways would be doing the operation for everything but null from the Table1 and then UNION-ing with the null row.

For your given example I assume that the combination of x and y values in both Table1 and Table2 is always unique. You'll need additional grouping if it's not.

SELECT
    t1.x,
    t1.y,
    COUNT(*) as [count]
FROM
    Table1 t1
    INNER JOIN Table2 t2 ON t1.y = t2.y
WHERE
    t1.y IS NOT NULL
GROUP BY
    t1.x, t1.y
UNION ALL
SELECT
    t1.x,
    NULL as y,
    t2missingFromt1.[count]
FROM
    Table1 t1
    CROSS APPLY (
        SELECT
             COUNT(x) as [count]
        FROM
             Table2 t2
        WHERE NOT EXISTS (SELECT 1 FROM Table1 tbl1 WHERE tbl1.y = t2.y)
    ) t2missingFromt1
WHERE
    t1.y IS NULL


问:
Sending simple commands from Android through USB
I am a completely new at programming, and must get this task completed for a demonstration. I have a Samsung Captivate that I need to send simple messages to a device over USB. I'm not worried about having the droid act as host, not the issue here. I just need to find the proper code to access the USB functions in Android 2.1. I need to send simple on/off commands and audio level changes.

It would seem to me that this shouldn't be that hard, as the droid will communicate with my laptop and act as a storage device, so I know the two can talk. Can anybody help me find these  resources? I have been looking extensively, to no avail.

Thanks!

Bill

答:
The simplest solution would be to use the Android Debug Bridge (ADB) which comes with the Android SDK.
It allows to connect to your Android device via USB (AFAIR USB debugging must be enabled on the device).

If you want to send your commands from a custom [Java] app on the host you could try to use the ADB feature to forward ports from the host onto the device. Your app on the device could listen to the port and therefore you would have a simple TCP connection between device and the host over USB.

ContentLicense: CC BY-SA 2.5


问:
Running ng e2e removes dist folder and doesn't look for the compiled .js files
I am trying to run ng e2e to run my protractor tests. My compiled .js files are saved in 'dist' folder. However, whenever I run 'ng e2e', I observed that my dist folder is removed and the result of ng e2e is no specs found since the compiled files that are in 'dist' folder are removed when i run ng e2e.

Also, my protractor.conf.js file contains plugins related to 'jasmine2-protractor-utils' and 'protractor-html-reporter. So, when I run 'ng e2e', it says no modules found for 'jasmine2-protractor-utils'.

All my above tests work fine when I run them directly using 'protractor conf.js' command. Can you please advise on how to achieve the same result with 'ng e2e' so that it can be used while doing the environment builds.

Thanks in advance!

答:
To stop ng e2e from removing your /dist directory run

ng e2e --delete-output-path=false

To learn more Angular CLI command line arguments run

ng help


问:
Bankers Algorithm processes
Using Bankers algorithm,

If a process (p1) is unable to complete by any other process p2,p3,p4 etc giving up it's resources singly, can they ALL relinquish their resources together so p1 could complete?

Or is that not a thing that could be done?

答:
Are you asking about capabilities of abstract processes, or of the Banker's algorithm in particular?

If it's abstract processes, then yes, it's easily possible.  Create a signal yield_all, and code each process to relinquish the resources when it receives that signal.  Some master process will have to send the signal to each of P2, P3, and P4, and then allow P1 to proceed with its allocation.  Implementation details are up to the designer.

If you're asking about the Banker's algorithm, I'm not entirely clear what you need.  No allocation is allowed to proceed unless the system is still in a safe state: each process is capable of terminating (thus returning all resources) in some order, with the remaining system availability.

Thus, in the situation you describe, forcing any other process to yield resources is not a valid operation.  Rather, P1 has to wait until the others have terminated normally, before it is allowed to allocate the requested resources.  If this is not possible, then the system is in an unsafe state -- one or more prior requests should not have been granted.

Does that answer your question?

Title: Bankers Algorithm processes


问:
Use multiple WITH tablename AS (...) statements SQL Server
I'm trying to create two temporary tables and join them with a permanent table.  For example: </p>

```<code>WITH temp1 AS (COUNT(*) AS count_sales, ID FROM table1 GROUP BY ID)
WITH temp2 AS (COUNT(*) AS count_somethingelse, ID FROM table2 GROUP BY ID)
SELECT *
FROM table3 JOIN table2 JOIN table1
     ON table1.ID = table2.ID = table3.ID
</code>```

<p>but there seems to be an issue having multiple WITH tablename AS (...) statments.  I tried a semicolon.  </p>

答:
Your query should look more like this:

```<code>WITH temp1 AS (
      SELECT COUNT(*) AS count_sales, ID
      FROM table1
      GROUP BY ID
     ),
     temp2 AS (
      SELECT COUNT(*) AS count_somethingelse, ID
      FROM table2
      GROUP BY ID
     )
SELECT *
FROM temp2 JOIN
     temp1
     ON temp1.ID = temp2.ID;
</code>```

Your query has multiple errors.  I would suggest you start by understanding why this version works -- or at least does something other than report on syntax errors.  Then, go back and study SQL some more.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to create two temporary tables and join them with a permanent table.  For example:

WITH temp1 AS (COUNT(*) AS count_sales, ID FROM table1 GROUP BY ID)
WITH temp2 AS (COUNT(*) AS count_somethingelse, ID FROM table2 GROUP BY ID)
SELECT *
FROM table3 JOIN table2 JOIN table1
     ON table1.ID = table2.ID = table3.ID

but there seems to be an issue having multiple WITH tablename AS (...) statments.  I tried a semicolon.

Body:
Your query should look more like this:

WITH temp1 AS (
      SELECT COUNT(*) AS count_sales, ID
      FROM table1
      GROUP BY ID
     ),
     temp2 AS (
      SELECT COUNT(*) AS count_somethingelse, ID
      FROM table2
      GROUP BY ID
     )
SELECT *
FROM temp2 JOIN
     temp1
     ON temp1.ID = temp2.ID;

Your query has multiple errors.  I would suggest you start by understanding why this version works -- or at least does something other than report on syntax errors.  Then, go back and study SQL some more.


问:
How to emit an event from HttpInterceptor in the angular 5
I'm trying to send an event from HttpInterceptor.

Code of my events service:

```<code>import { EventEmitter } from '@angular/core';

export class Message {
    constructor( public name:string, public data:any){
  }
}

export class NotifyService {
dispatcher: EventEmitter<any> = new EventEmitter();

constructor() {}

emitMessageEvent(name:string, data:any){
  let message = new Message(name,data);
  this.dispatcher.emit(message);
}

getEmitter() {
  return this.dispatcher;
}
</code>```

A component that receives events

```<code>import { Component } from '@angular/core';
import { Router } from '@angular/router';

import { NotifyService } from './services/notify.service';

@Component({
  ...
  providers: [ NotifyService ]
})
export class AppComponent {
  subscription: any;

  constructor(private router: Router, private notifyService: NotifyService) {
  }

  ngOnInit() {
    this.subscription = this.notifyService.getEmitter()
      .subscribe(item => this.showAppLevelAlarm(item));
  }

  private showAppLevelAlarm(_notify: any): void {
    // this.message = _notify.msg;
    console.log(_notify);
  }
}
</code>```

And my HttpInterceptor:

```<code>import { NotifyService } from '../services/notify.service';

@Injectable()
export class ApiInterceptor implements HttpInterceptor {

constructor(public notifyService: NotifyService) {}

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  return next.handle(req).do(event => {
  return event;
},
error => {
  this.notifyService.emitMessageEvent('showAppLevelAlert', error.error);
})
</code>```

Help me understand why the events that were sent from the HttpInterceptor are not received by the AppComponent. But if I send an event from another component, the AppComponent receives an event.

答:
You are going about this wrong, first of all Event Emitter shouldnt be a go to method for watching changes as explained here in

http://blog.bogdancarpean.com/how-to-watch-for-changes-an-arrayobject-on-angular-2/

You should rather use localstorage or sessionstorage to store your data in interceptor (as they are global in nature) and then recieve changes to them using doCheck lifecycle hook in Angular

I use my interceptor for appending Authorization Tokens and detecting whether I should display the loading bar,

Here is my code

interceptor.ts

```<code>import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';

@Injectable()
export class IndInterceptor implements HttpInterceptor{
    intercept(
    req: HttpRequest<any>,
    next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).do(evt => {
      localStorage.setItem('loading','Y');
      if (evt instanceof HttpResponse) {
        localStorage.setItem('loading','N');
        console.log('---> status:', evt.status);
        console.log('---> filter:', req.params.get('filter'));
      }
    });

  }
}
</code>```

component.ts

```<code>import { Component, DoCheck } from '@angular/core';
export class AppComponent implements DoCheck{
   public loading;
   ngDoCheck(){
       this.loading = localStorage.getItem('loading');
       console.log(this.loading);
   }
}
</code>```

Body:
I'm trying to send an event from HttpInterceptor.

Code of my events service:

import { EventEmitter } from '@angular/core';

export class Message {
    constructor( public name:string, public data:any){
  }
}

export class NotifyService {
dispatcher: EventEmitter<any> = new EventEmitter();

constructor() {}

emitMessageEvent(name:string, data:any){
  let message = new Message(name,data);
  this.dispatcher.emit(message);
}

getEmitter() {
  return this.dispatcher;
}

A component that receives events

import { Component } from '@angular/core';
import { Router } from '@angular/router';

import { NotifyService } from './services/notify.service';

@Component({
  ...
  providers: [ NotifyService ]
})
export class AppComponent {
  subscription: any;

  constructor(private router: Router, private notifyService: NotifyService) {
  }

  ngOnInit() {
    this.subscription = this.notifyService.getEmitter()
      .subscribe(item => this.showAppLevelAlarm(item));
  }

  private showAppLevelAlarm(_notify: any): void {
    // this.message = _notify.msg;
    console.log(_notify);
  }
}

And my HttpInterceptor:

import { NotifyService } from '../services/notify.service';

@Injectable()
export class ApiInterceptor implements HttpInterceptor {

constructor(public notifyService: NotifyService) {}

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  return next.handle(req).do(event => {
  return event;
},
error => {
  this.notifyService.emitMessageEvent('showAppLevelAlert', error.error);
})

Help me understand why the events that were sent from the HttpInterceptor are not received by the AppComponent. But if I send an event from another component, the AppComponent receives an event.

Body:
You are going about this wrong, first of all Event Emitter shouldnt be a go to method for watching changes as explained here in

http://blog.bogdancarpean.com/how-to-watch-for-changes-an-arrayobject-on-angular-2/

You should rather use localstorage or sessionstorage to store your data in interceptor (as they are global in nature) and then recieve changes to them using doCheck lifecycle hook in Angular

I use my interceptor for appending Authorization Tokens and detecting whether I should display the loading bar,

Here is my code

interceptor.ts

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';

@Injectable()
export class IndInterceptor implements HttpInterceptor{
    intercept(
    req: HttpRequest<any>,
    next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).do(evt => {
      localStorage.setItem('loading','Y');
      if (evt instanceof HttpResponse) {
        localStorage.setItem('loading','N');
        console.log('---> status:', evt.status);
        console.log('---> filter:', req.params.get('filter'));
      }
    });

  }
}

component.ts

import { Component, DoCheck } from '@angular/core';
export class AppComponent implements DoCheck{
   public loading;
   ngDoCheck(){
       this.loading = localStorage.getItem('loading');
       console.log(this.loading);
   }
}


问:
Run jar file with arguments without having to use command line
I am using Alpn-boot to add support for HTTP.2 requests using OkHttp. In order for that to work i always have to launch my compiled jar file through the command line and specify the path of alpn-boot.jar file with a <-Xbootclasspath> argument :

java -jar -Xbootclasspath/p:<path_to_alpn-boot.jar> <path_to_myjar.jar>

Is there anyway to avoid this, and make the jar run with the -Xbootclasspath argument specified by default?

Edit: I thought about using a batch file to do this, but is there no other native way?

答: Batch file is convenient and standard enough. Unless you have specific reason not to use batch file, batch file would do it</p>


问:
Add two textviews side by side in a TableLayout dynamically
I'm trying to add rows dynamically in a table. I need to add two TextViews side by side in each row. This has to be done dynamically. I have written the code that creates rows dynamically. I'm unable to add a second TextView on the side.

activity.xml

```<code><TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:stretchColumns="0,1"
    android:id="@+id/tableView"
    android:layout_weight="1"
    android:layout_height="wrap_content"
    android:layout_width="match_parent">
</TableLayout>`
</code>```

MainActivity.java

```<code>    TableLayout ll = (TableLayout) findViewById(R.id.tableView);
    for (int i = 0; i <2; i++) {

        TableRow row= new TableRow(this);
        TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
        row.setLayoutParams(lp);
        TextView qty = new TextView(this);
        qty.setText("10");
        row.addView(qty);
        ll.addView(row,i);
    }
</code>```

答:
Try this:

```<code>TableLayout ll = (TableLayout) findViewById(R.id.tableView);
TableRow row= new TableRow(this);
for (int i = 0; i <2; i++) {
    TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
    row.setLayoutParams(lp);
    TextView qty = new TextView(this);
    qty.setText("10");
    row.addView(qty);
}
ll.addView(row);
</code>```

You were adding two different rows with a single TextView each and not a row with two TextViews.

You need two levels of for.

Body:
I'm trying to add rows dynamically in a table. I need to add two TextViews side by side in each row. This has to be done dynamically. I have written the code that creates rows dynamically. I'm unable to add a second TextView on the side.

activity.xml

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:stretchColumns="0,1"
    android:id="@+id/tableView"
    android:layout_weight="1"
    android:layout_height="wrap_content"
    android:layout_width="match_parent">
</TableLayout>`

MainActivity.java

    TableLayout ll = (TableLayout) findViewById(R.id.tableView);
    for (int i = 0; i <2; i++) {

        TableRow row= new TableRow(this);
        TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
        row.setLayoutParams(lp);
        TextView qty = new TextView(this);
        qty.setText("10");
        row.addView(qty);
        ll.addView(row,i);
    }

Body:
Try this:

TableLayout ll = (TableLayout) findViewById(R.id.tableView);
TableRow row= new TableRow(this);
for (int i = 0; i <2; i++) {
    TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
    row.setLayoutParams(lp);
    TextView qty = new TextView(this);
    qty.setText("10");
    row.addView(qty);
}
ll.addView(row);

You were adding two different rows with a single TextView each and not a row with two TextViews.

You need two levels of for.


问:
Respect validation for Select
I'm using Respect validation for my PHP form. It works fine for all elements but not sure which validation rule to use for the country select element. The default value (when the select box displays 'Please select one') is -1. In all other cases, the value is a string. So I want to check if the value of country is different from -1. Obviously v::notEmpty() does not work. Is there a validation rule in Respect for something like this? or should I write my own rule?
Thanks.</p>

答:
v::stringType()->notEmpty()->validate($country); should work....

see documentation:
StringType, NotEmpty

Title: Respect validation for Select


问:
IOT_LAUNCHER activity not starting on boot
I have a Xamarin app built to run on Android. I am attempting to run it on a Raspberry Pi 3 on Android Things. I have flashed the default image and I can successfully run the app via Visual Studio when connected to the pi.

However, I cannot get the app to start on boot either by installing via adb or by creating a bundle and building via the Android Things console. I have setup the manifest correctly I believe.

My MainActivity has the correct properties:

```<code>Activity(Label = "PropertyVision", MainLauncher = true, Theme = "@style/PVLightTheme")]
[IntentFilter(new[] { Intent.ActionMain }, Categories = new[] { Intent.CategoryLauncher })]
[IntentFilter(new[] { Intent.ActionMain }, Categories = new[] { Intent.CategoryDefault })]
[IntentFilter(new[] { Intent.ActionMain }, Categories = new[] { "android.intent.category.IOT_LAUNCHER" })]
</code>```

I can install and run the APK via ADB and when pulled back I can analyze the APK and see that the manifest does indeed have the correct intent-filters but when I restart the device I get the standard Android Things dashboard.

```<code><activity
    android:theme="@ref/0x7f0d0199"
    android:label="PropertyVision"
    android:name="md5cbdbb5fa2925f03038c91923122a6627.MainActivity">
    <intent-filter>
        <action
            android:name="android.intent.action.MAIN" />
        <category
            android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    <intent-filter>
        <action
            android:name="android.intent.action.MAIN" />
        <category
            android:name="android.intent.category.DEFAULT" />
    </intent-filter>
    <intent-filter>
        <action
            android:name="android.intent.action.MAIN" />
        <category
            android:name="android.intent.category.IOT_LAUNCHER" />
     </intent-filter>
</activity>
</code>```

Using 0.6.0-preview. When I create a bundle.zip and create a new build via Android Things console it also boots into the standard dashboard but I can start my app via adb.

Where am I going wrong?

答:
You want your manifest to contain two intent filters within the application tag, one for debugging and one for IoT boot.

Android Things expects one application to expose a "home activity" in its manifest as the main entry point for the system to automatically launch on boot. This activity must contain an intent filter that includes both CATEGORY_DEFAULT and IOT_LAUNCHER.

To do this via Activity attributes:

```<code>[Activity(Label = "KeyPadEntry", Icon = "@mipmap/icon")]
[IntentFilter(new[] { Intent.ActionMain }, Categories = new[] { Intent.CategoryLauncher })]
[IntentFilter(new[] { Intent.ActionMain }, Categories = new[] { "android.intent.category.IOT_LAUNCHER", Intent.CategoryDefault })]
public class MainActivity : Activity
{
  ~~~
}
</code>```

The generated manifest should look something like this within the application tag:

```<code><activity android:name="md5228f519fe41cfb3cf46c839bf977fe9b.MainActivity"">
    <intent-filter>
        <action android:name="android.intent.action.MAIN"/>
        <category android:name="android.intent.category.LAUNCHER"/>
    </intent-filter>
   <intent-filter>
        <action android:name="android.intent.action.MAIN"/>
        <category android:name="android.intent.category.IOT_LAUNCHER"/>
        <category android:name="android.intent.category.DEFAULT"/>
    </intent-filter>

    ~~~~

</activity>
</code>```

Body:
I have a Xamarin app built to run on Android. I am attempting to run it on a Raspberry Pi 3 on Android Things. I have flashed the default image and I can successfully run the app via Visual Studio when connected to the pi.

However, I cannot get the app to start on boot either by installing via adb or by creating a bundle and building via the Android Things console. I have setup the manifest correctly I believe.

My MainActivity has the correct properties:

Activity(Label = "PropertyVision", MainLauncher = true, Theme = "@style/PVLightTheme")]
[IntentFilter(new[] { Intent.ActionMain }, Categories = new[] { Intent.CategoryLauncher })]
[IntentFilter(new[] { Intent.ActionMain }, Categories = new[] { Intent.CategoryDefault })]
[IntentFilter(new[] { Intent.ActionMain }, Categories = new[] { "android.intent.category.IOT_LAUNCHER" })]

I can install and run the APK via ADB and when pulled back I can analyze the APK and see that the manifest does indeed have the correct intent-filters but when I restart the device I get the standard Android Things dashboard.

<activity
    android:theme="@ref/0x7f0d0199"
    android:label="PropertyVision"
    android:name="md5cbdbb5fa2925f03038c91923122a6627.MainActivity">
    <intent-filter>
        <action
            android:name="android.intent.action.MAIN" />
        <category
            android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    <intent-filter>
        <action
            android:name="android.intent.action.MAIN" />
        <category
            android:name="android.intent.category.DEFAULT" />
    </intent-filter>
    <intent-filter>
        <action
            android:name="android.intent.action.MAIN" />
        <category
            android:name="android.intent.category.IOT_LAUNCHER" />
     </intent-filter>
</activity>

Using 0.6.0-preview. When I create a bundle.zip and create a new build via Android Things console it also boots into the standard dashboard but I can start my app via adb.

Where am I going wrong?

Body:
You want your manifest to contain two intent filters within the application tag, one for debugging and one for IoT boot.

Android Things expects one application to expose a "home activity" in its manifest as the main entry point for the system to automatically launch on boot. This activity must contain an intent filter that includes both CATEGORY_DEFAULT and IOT_LAUNCHER.

To do this via Activity attributes:

[Activity(Label = "KeyPadEntry", Icon = "@mipmap/icon")]
[IntentFilter(new[] { Intent.ActionMain }, Categories = new[] { Intent.CategoryLauncher })]
[IntentFilter(new[] { Intent.ActionMain }, Categories = new[] { "android.intent.category.IOT_LAUNCHER", Intent.CategoryDefault })]
public class MainActivity : Activity
{
  ~~~
}

The generated manifest should look something like this within the application tag:

<activity android:name="md5228f519fe41cfb3cf46c839bf977fe9b.MainActivity"">
    <intent-filter>
        <action android:name="android.intent.action.MAIN"/>
        <category android:name="android.intent.category.LAUNCHER"/>
    </intent-filter>
   <intent-filter>
        <action android:name="android.intent.action.MAIN"/>
        <category android:name="android.intent.category.IOT_LAUNCHER"/>
        <category android:name="android.intent.category.DEFAULT"/>
    </intent-filter>

    ~~~~

</activity>


问:
Do.. While.. with Exists predicates. Access to modified closure?
```<code>string reference;
do {
  reference = GenerateNewReference();
} while (currentItems.Exists(i=>i.Reference.Equals(reference));
</code>```

ReSharper is warning me about this, something called Access to Modified Closure. I've tried my best to read and understand it, but my code still seems fine to me.

Is there a problem with my code?

答:
No, there's no problem because the List<T>.Exists method executes eagerly. Consequently, changes in the value of the captured variable are "responded to" immediately. You do have a modified-closure, but that isn't necessarily (as in this case) wrong.

On the other hand, if you'd added the "lambda" (really the delegate) to a list inside the loop and then run these queries afterwards, you'd run in to the actual modified-closure problems that Resharper is warning you about.

If want to get rid of the warning, you could do:

```<code>string reference;
do {
  reference = GenerateNewReference();
  var refCopy = reference;
} while (currentItems.Exists(i => i.Reference.Equals(refCopy));
</code>```

Slightly off-topic: If you want a fancy of way of writing your search (without any modified-closure warnings), you could write a utility method such as:

```<code>public static IEnumerable<T> Generate(Func<T> func)
{
     if(func == null)
        throw new ArgumentNullException("func");

     while(true)
        yield return func();
}
</code>```

And then use it as:

```<code>var result = MyExtensions.Generate(GenerateNewReference)
                         .First(reference => !currentItems.Exists(i => i.Reference.Equals(reference)));
</code>```

Body:
string reference;
do {
  reference = GenerateNewReference();
} while (currentItems.Exists(i=>i.Reference.Equals(reference));

ReSharper is warning me about this, something called Access to Modified Closure. I've tried my best to read and understand it, but my code still seems fine to me.

Is there a problem with my code?

Body:
No, there's no problem because the List<T>.Exists method executes eagerly. Consequently, changes in the value of the captured variable are "responded to" immediately. You do have a modified-closure, but that isn't necessarily (as in this case) wrong.

On the other hand, if you'd added the "lambda" (really the delegate) to a list inside the loop and then run these queries afterwards, you'd run in to the actual modified-closure problems that Resharper is warning you about.

If want to get rid of the warning, you could do:

string reference;
do {
  reference = GenerateNewReference();
  var refCopy = reference;
} while (currentItems.Exists(i => i.Reference.Equals(refCopy));

Slightly off-topic: If you want a fancy of way of writing your search (without any modified-closure warnings), you could write a utility method such as:

public static IEnumerable<T> Generate(Func<T> func)
{
     if(func == null)
        throw new ArgumentNullException("func");

     while(true)
        yield return func();
}

And then use it as:

var result = MyExtensions.Generate(GenerateNewReference)
                         .First(reference => !currentItems.Exists(i => i.Reference.Equals(reference)));


问:
Best way to avoid deadlock for several objects transaction?
I was looking for deadlock example and stumbled across this code:

```<code>package com.example.thread.deadlock._synchronized;

public class BankAccount {
    double balance;
    int id;

    BankAccount(int id, double balance) {
        this.id = id;
        this.balance = balance;
    }

    void withdraw(double amount) {
        // Wait to simulate io like database access ...
        try {Thread.sleep(10l);} catch (InterruptedException e) {}
        balance -= amount;
    }

    void deposit(double amount) {
        // Wait to simulate io like database access ...
        try {Thread.sleep(10l);} catch (InterruptedException e) {}
        balance += amount;
    }

    static void transfer(BankAccount from, BankAccount to, double amount) {
        synchronized(from) {
            from.withdraw(amount);
            synchronized(to) {
                to.deposit(amount);
            }
        }
    }

    public static void main(String[] args) {
        final BankAccount fooAccount = new BankAccount(1, 100d);
        final BankAccount barAccount = new BankAccount(2, 100d);

        new Thread() {
            public void run() {
                BankAccount.transfer(fooAccount, barAccount, 10d);
            }
        }.start();

        new Thread() {
            public void run() {
                BankAccount.transfer(barAccount, fooAccount, 10d);
            }
        }.start();

    }
}
</code>```

How would you change transfer method so that it doesn't cause deadlock? First thought is to create a shared lock for all accounts, but that of course would just kill all concurrency. So is there a good way to lock just two accounts involved into a transaction and not affect other accounts?

答:
One way to avoid deadlocks in multi-lock situations is to always lock the objects in the same order.

In this case it would mean that you'd create a total ordering for all BankAccount objects. Luckily we've got an id that we can use, so you could always lock the lower id first and then (inside the other synchronized block) the higher id one.

This assumes that there's no BankAccount objects with identical ids, but that seems like a reasonable assumption.

Body:
I was looking for deadlock example and stumbled across this code:

package com.example.thread.deadlock._synchronized;

public class BankAccount {
    double balance;
    int id;

    BankAccount(int id, double balance) {
        this.id = id;
        this.balance = balance;
    }

    void withdraw(double amount) {
        // Wait to simulate io like database access ...
        try {Thread.sleep(10l);} catch (InterruptedException e) {}
        balance -= amount;
    }

    void deposit(double amount) {
        // Wait to simulate io like database access ...
        try {Thread.sleep(10l);} catch (InterruptedException e) {}
        balance += amount;
    }

    static void transfer(BankAccount from, BankAccount to, double amount) {
        synchronized(from) {
            from.withdraw(amount);
            synchronized(to) {
                to.deposit(amount);
            }
        }
    }

    public static void main(String[] args) {
        final BankAccount fooAccount = new BankAccount(1, 100d);
        final BankAccount barAccount = new BankAccount(2, 100d);

        new Thread() {
            public void run() {
                BankAccount.transfer(fooAccount, barAccount, 10d);
            }
        }.start();

        new Thread() {
            public void run() {
                BankAccount.transfer(barAccount, fooAccount, 10d);
            }
        }.start();

    }
}

How would you change transfer method so that it doesn't cause deadlock? First thought is to create a shared lock for all accounts, but that of course would just kill all concurrency. So is there a good way to lock just two accounts involved into a transaction and not affect other accounts?


问:
Where do I put front-end code in my backend project and how/when to run it?
The question is, say I have written a backend REST service using Python, and then some other guy wrote some frontend code in Angular JS. Is the typical workflow putting them into two separate folders and run them separately? So the process will look like below

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

in Python colder and then probably

```<code># in the angular2 folder
npm start
</code>```

Or should I place all the JS code into some assets folder and when I start my server, all the JS code will run automatically with them? If so, how should I do it?

Another question related is, when is all the JS code sent to users’ browsers? If the app is a client-side rendering app, is the code sent to browser at the first time of server requesting? How does the server know it should package your JS code and ship it?

答:
There are many approaches to this problem.

If infrastructure management is difficult for you, than maybe it's easier to place them in the same server. You can create another directory and place your html that is served to browser with your JavaScript code.

In case you have a good pipeline (which I think it pays for it self) than having another server that serves your application is better. You can do more things without affecting your service, like caching etc. And your server that runs your service wont be busy serving assets as well.

I have a case where we run a node server, which serves the html and javascript to our users, because that way we can do server side rendering.enter link description here

The flow of code execution will be this : Once the browser of your user hits the server that is serving html and assets, it will download it locally and it will start with JavaScript execution (Parsing, Compiling and Executing). Your JavaScript app might do some API calls upon initialization or it might not, but your service will be executed only if frontend makes a request.

As for CORS it is irrelevant how you serve them, because you can keep them always in the same domain.

Body:
The question is, say I have written a backend REST service using Python, and then some other guy wrote some frontend code in Angular JS. Is the typical workflow putting them into two separate folders and run them separately? So the process will look like below

python manage.py runserver

in Python colder and then probably

# in the angular2 folder
npm start

Or should I place all the JS code into some assets folder and when I start my server, all the JS code will run automatically with them? If so, how should I do it?

Another question related is, when is all the JS code sent to users’ browsers? If the app is a client-side rendering app, is the code sent to browser at the first time of server requesting? How does the server know it should package your JS code and ship it?


问:
Is there any way to round a string?
So i have a string for exampe "-389761456.6570000000" and i need to round this number to 4 characters behind the dor. I wrote a whole function for this but its too long(100 lines).
i cant convert it like this:

```<code>void Calculator::Display(string a)
{
    long double q = stod(a);
    cout << setprecision(4) << q << endl;
}
</code>```

because it will look like this (3.89e^-10 etc)(just an example not the real result)
and i want smth like this "-389761456.6570"
is there any way to do it?

答:
This should do what you want. It's much easier to just use the system libraries to do this, though.</p>

```<code>#include <iostream>
#include <string>

void increment( std::string& num )
{
    for ( auto ch = num.rbegin(); ch != num.rend(); ch++ )
    {
        switch ( *ch )
        {
        case '9':
                *ch = '0';
        case '.':
                continue;
        case '-':
                num.insert( 1, 1, '1' );
                return;
        default:
            (*ch)++;
            return;
        }
    }
    num.insert( 0, 1, '1' );
}

std::string round( const std::string& num, size_t precision )
{
    size_t dot = num.find( '.' );
    if ( dot == std::string::npos || dot + precision >= num.size() )
    {
        return num;
    }
    size_t length = std::min( dot + precision + 1, num.size() );
    char lastCh = num[ length ];
    std::string result = num.substr( 0, length );
    if ( lastCh >= '5' && lastCh <= '9' )
    {
        increment( result );
    }
    return result;
}

int main()
{
    std::cout << round( "123.45", 4 ) << "\n";
    std::cout << round( "123.456", 4 ) << "\n";
    std::cout << round( "123.4567", 4 ) << "\n";
    std::cout << round( "123.45678", 4 ) << "\n";
    std::cout << round( "123.456789", 4 ) << "\n";
    std::cout << round( "123.456723", 4 ) << "\n";
    std::cout << round( "999.9999995", 4 ) << "\n";
    std::cout << round( "-123.456723", 4 ) << "\n";
    std::cout << round( "-999.9999995", 4 ) << "\n";
}
</code>```

Title: Is there any way to round a string?

Body:
So i have a string for exampe "-389761456.6570000000" and i need to round this number to 4 characters behind the dor. I wrote a whole function for this but its too long(100 lines).
i cant convert it like this:

void Calculator::Display(string a)
{
    long double q = stod(a);
    cout << setprecision(4) << q << endl;
}

because it will look like this (3.89e^-10 etc)(just an example not the real result)
and i want smth like this "-389761456.6570"
is there any way to do it?

Body:
This should do what you want. It's much easier to just use the system libraries to do this, though.

#include <iostream>
#include <string>

void increment( std::string& num )
{
    for ( auto ch = num.rbegin(); ch != num.rend(); ch++ )
    {
        switch ( *ch )
        {
        case '9':
                *ch = '0';
        case '.':
                continue;
        case '-':
                num.insert( 1, 1, '1' );
                return;
        default:
            (*ch)++;
            return;
        }
    }
    num.insert( 0, 1, '1' );
}

std::string round( const std::string& num, size_t precision )
{
    size_t dot = num.find( '.' );
    if ( dot == std::string::npos || dot + precision >= num.size() )
    {
        return num;
    }
    size_t length = std::min( dot + precision + 1, num.size() );
    char lastCh = num[ length ];
    std::string result = num.substr( 0, length );
    if ( lastCh >= '5' && lastCh <= '9' )
    {
        increment( result );
    }
    return result;
}

int main()
{
    std::cout << round( "123.45", 4 ) << "\n";
    std::cout << round( "123.456", 4 ) << "\n";
    std::cout << round( "123.4567", 4 ) << "\n";
    std::cout << round( "123.45678", 4 ) << "\n";
    std::cout << round( "123.456789", 4 ) << "\n";
    std::cout << round( "123.456723", 4 ) << "\n";
    std::cout << round( "999.9999995", 4 ) << "\n";
    std::cout << round( "-123.456723", 4 ) << "\n";
    std::cout << round( "-999.9999995", 4 ) << "\n";
}


问:
ObjectDisposedException in .NET Core middleware with Entity Framework
I have an API written in .NET Core. I have a token middleware that I'm having some issues with.

If I send a request to the middleware from one client at a time it's fine. If I try to use the middleware by more than one client at a time I get errors.

From what I can tell I think the _userManager doesn't have a new instance created every time a request is made and I think this causes my problem. I seem to either get

System.InvalidOperationException: An attempt was made to use the context while it is being configured

or

System.ObjectDisposedException: Cannot access a disposed object

I'm thinking maybe the UserManager<ApplicationUser> that I'm injecting is a singleton? Maybe both requests are trying to use the same instance of _userManager and the first one disposes it and the second request errors?

I'm sorta new to this so maybe I'm way off base. Maybe _userManager wasn't meant to be used this way or maybe I'm injecting it incorrectly.

Here is some code from the starup.cs and token middleware. Below that are some of the error logs.

Parts of startup.cs

```<code>public void ConfigureServices(IServiceCollection services)
{
     ...
     services.AddDbContext<ApplicationDbContext>(options =>
     {

options.UseNpgsql(Environment.GetEnvironmentVariable("DbConnString"));
     });

        services.AddIdentity<ApplicationUser, IdentityRole>(o=>
        {
            o.Password.RequireDigit = false;
            o.Password.RequiredLength = 0;
            o.Password.RequireLowercase = false;
            o.Password.RequireNonAlphanumeric = false;
            o.Password.RequireUppercase = false;
            o.SignIn.RequireConfirmedEmail = true;
            o.User.RequireUniqueEmail = true;

        })

                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();
        services.AddAuthentication(o =>
        {
            o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

        }).AddJwtBearer(options =>
        {
            options.TokenValidationParameters = tokenValidationParameters;
        });
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
     ...
      app.UseJWTTokenProviderMiddleware(Options.Create(jwtOptions));

        app.UseAuthentication();
        app.UseMvc();
     ...
 }
</code>```

TokenProviderMiddleware

```<code>public class TokenProviderMiddleware
{
    private readonly RequestDelegate _next;
    private TokenProviderOptions _options;
    private UserManager<ApplicationUser> _userManager;
    private readonly ILogger<TokenProviderMiddleware> _logger;
    public TokenProviderMiddleware(RequestDelegate next, IOptions<TokenProviderOptions> options, ILogger<TokenProviderMiddleware> logger)
    {
        _next = next;
        _options = options.Value;
        _logger = logger;
    }

    public async Task Invoke(HttpContext context, UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;

        if (!context.Request.Path.Equals(_options.Path, StringComparison.Ordinal))
        {
            await _next(context);
            return;
        }
        if (!context.Request.Method.Equals("POST") || !context.Request.HasFormContentType)
        {
            context.Response.StatusCode = 400;
            await context.Response.WriteAsync("Bad Request");
            return;
        }

        ApplicationUser user = null;
        string refreshToken;
        string accessToken;

        if (context.Request.Form["grant_type"].Equals("refresh_token"))
        {
            refreshToken = context.Request.Form["refresh_token"];
            if(String.IsNullOrEmpty(refreshToken))
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsync("refresh_token not sent");
                return;
            }

            // Check that the refresh_token is valid
            // I don't like using exceptions for flow control but it's how ValidateToken works
            try
            {
                ValidateRefreshToken(refreshToken);
            }
            catch(SecurityTokenInvalidSignatureException ex)
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsync("refresh_token failed validation");
                return;
            }
            catch(Exception ex)
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsync("refresh_token failed validation");
                return;
            }
            user = await GetUserAsync(context, "from_refresh_token");
            accessToken = await GenerateAccessToken(user);

            var response = new
            {
                access_token = accessToken
            };
            context.Response.ContentType = "application/json";
            await context.Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings { Formatting = Formatting.Indented }));
            return;
        }

private async Task<ApplicationUser> GetUserAsync(HttpContext context, string getUserFrom)
    {
        ApplicationUser user = null;
        if(getUserFrom.Equals("from_username_password"))
        {
            string username = context.Request.Form["username"];
            string password = context.Request.Form["password"];

            if(String.IsNullOrEmpty(username) || String.IsNullOrEmpty(password))
            {
                throw new ArgumentException("Username/password not sent");
            }

            user = await _userManager.FindByNameAsync(username);
            var result = _userManager.CheckPasswordAsync(user, password);
            if (result.Result == false)
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsync("Invalid username or password");
            }
            if(!await _userManager.IsEmailConfirmedAsync(user))
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsync("Email address not confirmed");
            }

        }

        else if (getUserFrom.Equals("from_refresh_token"))
        {
            JwtSecurityToken decodedRefreshToken = new JwtSecurityTokenHandler().ReadJwtToken(context.Request.Form["refresh_token"]);
            string uid = decodedRefreshToken.Payload.Claims.FirstOrDefault(x => x.Type == "uid").Value;
            user = await _userManager.FindByIdAsync(uid);
        }

        return user;
    }
</code>```

Error logs

```<code>2017-12-02 19:45:27.171 -05:00 [Information] Request starting HTTP/1.1 POST http://0.0.0.0:5000/api/token application/x-www-form-urlencoded 204
2017-12-02 19:45:27.171 -05:00 [Information] Request starting HTTP/1.1 POST http://0.0.0.0:5000/api/token application/x-www-form-urlencoded 204
2017-12-02 19:45:27.171 -05:00 [Debug] "POST" requests are not supported
2017-12-02 19:45:27.171 -05:00 [Debug] "POST" requests are not supported
2017-12-02 19:45:27.171 -05:00 [Debug] The request has an origin header: '"http://0.0.0.0:8080"'.
2017-12-02 19:45:27.171 -05:00 [Debug] The request has an origin header: '"http://0.0.0.0:8080"'.
2017-12-02 19:45:27.171 -05:00 [Information] Policy execution successful.
2017-12-02 19:45:27.172 -05:00 [Information] Policy execution successful.
2017-12-02 19:45:27.172 -05:00 [Debug] Connection id ""0HL9PS1UOQ2DS"", Request id ""0HL9PS1UOQ2DS:000000C7"": started reading request body.
2017-12-02 19:45:27.172 -05:00 [Debug] Connection id ""0HL9PS1UOQ2E0"", Request id ""0HL9PS1UOQ2E0:0000000B"": started reading request body.
2017-12-02 19:45:27.175 -05:00 [Debug] Connection id ""0HL9PS1UOQ2DS"", Request id ""0HL9PS1UOQ2DS:000000C7"": done reading request body.
2017-12-02 19:45:27.175 -05:00 [Debug] Connection id ""0HL9PS1UOQ2E0"", Request id ""0HL9PS1UOQ2E0:0000000B"": done reading request body.
2017-12-02 19:45:27.450 -05:00 [Information] Entity Framework Core "2.0.0-rtm-26452" initialized '"ApplicationDbContext"' using provider '"Npgsql.EntityFrameworkCore.PostgreSQL"' with options: "None"
2017-12-02 19:45:27.762 -05:00 [Debug] System.InvalidOperationException occurred, checking if Entity Framework recorded this exception as resulting from a failed database operation.
2017-12-02 19:45:27.762 -05:00 [Debug] Entity Framework did not record any exceptions due to failed database operations. This means the current exception is not a failed Entity Framework database operation, or the current exception occurred from a DbContext that was not obtained from request services.
2017-12-02 19:45:27.763 -05:00 [Error] An unhandled exception has occurred while executing the request
System.InvalidOperationException: An attempt was made to use the context while it is being configured. A DbContext instance cannot be used inside OnConfiguring since it is still being configured at this point. This can happen if a second operation is started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.
   at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
   at Microsoft.EntityFrameworkCore.DbContext.Set[TEntity]()
   at Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9.get_UsersSet()
   at Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9.FindByIdAsync(String userId, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Identity.UserManager`1.FindByIdAsync(String userId)
   at MyProject.TokenProviderMiddleware.<GetUserAsync>d__9.MoveNext() in /home/jrow/Projects/MyProject/MyProject/Middleware/TokenProviderMiddleware.cs:line 220
</code>```

```<code>System.ObjectDisposedException: Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Object name: 'AsyncDisposer'.
   at Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.AsyncDisposer.Dispose()
   at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.<MoveNext>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at System.Linq.AsyncEnumerable.<Aggregate_>d__6`3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9.<GetClaimsAsync>d__38.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.AspNetCore.Identity.UserManager`1.<GetClaimsAsync>d__103.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at MyProject.TokenProviderMiddleware.<CreateClaims>d__10.MoveNext() in /home/jrow/Projects/MyProject/MyProject/Middleware/TokenProviderMiddleware.cs:line 239
</code>```

答:
Fixed it by passing the variable around instead of globally newing it every time. (got an answer from reddit).</p>

```<code>public async Task Invoke(HttpContext context, UserManager<ApplicationUser> userManager)
{

    ...
    try
    {
        user = await GetUserAsync(_userManager, context, "from_refresh_token");
    }
    ...
}

private async Task<ApplicationUser> GetUserAsync(UserManager<ApplicationUser> _userManager, HttpContext context, string getUserFrom)
{
    //Do stuff with _userManager
}
</code>```

Body:
I have an API written in .NET Core. I have a token middleware that I'm having some issues with.

If I send a request to the middleware from one client at a time it's fine. If I try to use the middleware by more than one client at a time I get errors.

From what I can tell I think the _userManager doesn't have a new instance created every time a request is made and I think this causes my problem. I seem to either get

System.InvalidOperationException: An attempt was made to use the context while it is being configured

or

System.ObjectDisposedException: Cannot access a disposed object

I'm thinking maybe the UserManager<ApplicationUser> that I'm injecting is a singleton? Maybe both requests are trying to use the same instance of _userManager and the first one disposes it and the second request errors?

I'm sorta new to this so maybe I'm way off base. Maybe _userManager wasn't meant to be used this way or maybe I'm injecting it incorrectly.

Here is some code from the starup.cs and token middleware. Below that are some of the error logs.

Parts of startup.cs

public void ConfigureServices(IServiceCollection services)
{
     ...
     services.AddDbContext<ApplicationDbContext>(options =>
     {

options.UseNpgsql(Environment.GetEnvironmentVariable("DbConnString"));
     });

        services.AddIdentity<ApplicationUser, IdentityRole>(o=>
        {
            o.Password.RequireDigit = false;
            o.Password.RequiredLength = 0;
            o.Password.RequireLowercase = false;
            o.Password.RequireNonAlphanumeric = false;
            o.Password.RequireUppercase = false;
            o.SignIn.RequireConfirmedEmail = true;
            o.User.RequireUniqueEmail = true;

        })

                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();
        services.AddAuthentication(o =>
        {
            o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

        }).AddJwtBearer(options =>
        {
            options.TokenValidationParameters = tokenValidationParameters;
        });
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
     ...
      app.UseJWTTokenProviderMiddleware(Options.Create(jwtOptions));

        app.UseAuthentication();
        app.UseMvc();
     ...
 }

TokenProviderMiddleware

public class TokenProviderMiddleware
{
    private readonly RequestDelegate _next;
    private TokenProviderOptions _options;
    private UserManager<ApplicationUser> _userManager;
    private readonly ILogger<TokenProviderMiddleware> _logger;
    public TokenProviderMiddleware(RequestDelegate next, IOptions<TokenProviderOptions> options, ILogger<TokenProviderMiddleware> logger)
    {
        _next = next;
        _options = options.Value;
        _logger = logger;
    }

    public async Task Invoke(HttpContext context, UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;

        if (!context.Request.Path.Equals(_options.Path, StringComparison.Ordinal))
        {
            await _next(context);
            return;
        }
        if (!context.Request.Method.Equals("POST") || !context.Request.HasFormContentType)
        {
            context.Response.StatusCode = 400;
            await context.Response.WriteAsync("Bad Request");
            return;
        }

        ApplicationUser user = null;
        string refreshToken;
        string accessToken;

        if (context.Request.Form["grant_type"].Equals("refresh_token"))
        {
            refreshToken = context.Request.Form["refresh_token"];
            if(String.IsNullOrEmpty(refreshToken))
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsync("refresh_token not sent");
                return;
            }

            // Check that the refresh_token is valid
            // I don't like using exceptions for flow control but it's how ValidateToken works
            try
            {
                ValidateRefreshToken(refreshToken);
            }
            catch(SecurityTokenInvalidSignatureException ex)
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsync("refresh_token failed validation");
                return;
            }
            catch(Exception ex)
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsync("refresh_token failed validation");
                return;
            }
            user = await GetUserAsync(context, "from_refresh_token");
            accessToken = await GenerateAccessToken(user);

            var response = new
            {
                access_token = accessToken
            };
            context.Response.ContentType = "application/json";
            await context.Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings { Formatting = Formatting.Indented }));
            return;
        }

private async Task<ApplicationUser> GetUserAsync(HttpContext context, string getUserFrom)
    {
        ApplicationUser user = null;
        if(getUserFrom.Equals("from_username_password"))
        {
            string username = context.Request.Form["username"];
            string password = context.Request.Form["password"];

            if(String.IsNullOrEmpty(username) || String.IsNullOrEmpty(password))
            {
                throw new ArgumentException("Username/password not sent");
            }

            user = await _userManager.FindByNameAsync(username);
            var result = _userManager.CheckPasswordAsync(user, password);
            if (result.Result == false)
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsync("Invalid username or password");
            }
            if(!await _userManager.IsEmailConfirmedAsync(user))
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsync("Email address not confirmed");
            }

        }

        else if (getUserFrom.Equals("from_refresh_token"))
        {
            JwtSecurityToken decodedRefreshToken = new JwtSecurityTokenHandler().ReadJwtToken(context.Request.Form["refresh_token"]);
            string uid = decodedRefreshToken.Payload.Claims.FirstOrDefault(x => x.Type == "uid").Value;
            user = await _userManager.FindByIdAsync(uid);
        }

        return user;
    }

Error logs

2017-12-02 19:45:27.171 -05:00 [Information] Request starting HTTP/1.1 POST http://0.0.0.0:5000/api/token application/x-www-form-urlencoded 204
2017-12-02 19:45:27.171 -05:00 [Information] Request starting HTTP/1.1 POST http://0.0.0.0:5000/api/token application/x-www-form-urlencoded 204
2017-12-02 19:45:27.171 -05:00 [Debug] "POST" requests are not supported
2017-12-02 19:45:27.171 -05:00 [Debug] "POST" requests are not supported
2017-12-02 19:45:27.171 -05:00 [Debug] The request has an origin header: '"http://0.0.0.0:8080"'.
2017-12-02 19:45:27.171 -05:00 [Debug] The request has an origin header: '"http://0.0.0.0:8080"'.
2017-12-02 19:45:27.171 -05:00 [Information] Policy execution successful.
2017-12-02 19:45:27.172 -05:00 [Information] Policy execution successful.
2017-12-02 19:45:27.172 -05:00 [Debug] Connection id ""0HL9PS1UOQ2DS"", Request id ""0HL9PS1UOQ2DS:000000C7"": started reading request body.
2017-12-02 19:45:27.172 -05:00 [Debug] Connection id ""0HL9PS1UOQ2E0"", Request id ""0HL9PS1UOQ2E0:0000000B"": started reading request body.
2017-12-02 19:45:27.175 -05:00 [Debug] Connection id ""0HL9PS1UOQ2DS"", Request id ""0HL9PS1UOQ2DS:000000C7"": done reading request body.
2017-12-02 19:45:27.175 -05:00 [Debug] Connection id ""0HL9PS1UOQ2E0"", Request id ""0HL9PS1UOQ2E0:0000000B"": done reading request body.
2017-12-02 19:45:27.450 -05:00 [Information] Entity Framework Core "2.0.0-rtm-26452" initialized '"ApplicationDbContext"' using provider '"Npgsql.EntityFrameworkCore.PostgreSQL"' with options: "None"
2017-12-02 19:45:27.762 -05:00 [Debug] System.InvalidOperationException occurred, checking if Entity Framework recorded this exception as resulting from a failed database operation.
2017-12-02 19:45:27.762 -05:00 [Debug] Entity Framework did not record any exceptions due to failed database operations. This means the current exception is not a failed Entity Framework database operation, or the current exception occurred from a DbContext that was not obtained from request services.
2017-12-02 19:45:27.763 -05:00 [Error] An unhandled exception has occurred while executing the request
System.InvalidOperationException: An attempt was made to use the context while it is being configured. A DbContext instance cannot be used inside OnConfiguring since it is still being configured at this point. This can happen if a second operation is started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.
   at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
   at Microsoft.EntityFrameworkCore.DbContext.Set[TEntity]()
   at Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9.get_UsersSet()
   at Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9.FindByIdAsync(String userId, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Identity.UserManager`1.FindByIdAsync(String userId)
   at MyProject.TokenProviderMiddleware.<GetUserAsync>d__9.MoveNext() in /home/jrow/Projects/MyProject/MyProject/Middleware/TokenProviderMiddleware.cs:line 220

System.ObjectDisposedException: Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Object name: 'AsyncDisposer'.
   at Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.AsyncDisposer.Dispose()
   at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.<MoveNext>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at System.Linq.AsyncEnumerable.<Aggregate_>d__6`3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9.<GetClaimsAsync>d__38.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.AspNetCore.Identity.UserManager`1.<GetClaimsAsync>d__103.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at MyProject.TokenProviderMiddleware.<CreateClaims>d__10.MoveNext() in /home/jrow/Projects/MyProject/MyProject/Middleware/TokenProviderMiddleware.cs:line 239

Body:
Fixed it by passing the variable around instead of globally newing it every time. (got an answer from reddit).

public async Task Invoke(HttpContext context, UserManager<ApplicationUser> userManager)
{

    ...
    try
    {
        user = await GetUserAsync(_userManager, context, "from_refresh_token");
    }
    ...
}

private async Task<ApplicationUser> GetUserAsync(UserManager<ApplicationUser> _userManager, HttpContext context, string getUserFrom)
{
    //Do stuff with _userManager
}


问:
Angular test failing to instantiate module with Jasmine and Karma
I have setted up a test environment with Angular 1.6.6, ng-mock 1.6.6, Jasmine and Karma. But even with the easiest test I'm getting a [$injector:modulerr] when trying to inject the deloreanApp module

Failed to instantiate module deloreanApp due to: Error:
  [$injector:nomod]

Theoretically there aren't tipo errors and Angular and ng-mock versions matches.

My files are:

app.js

```<code>(function () {
    "use strict";

    // initialize Angular
    angular.module('deloreanApp', ['deloreanApp.controllers', 'deloreanApp.services']);

    angular.module('deloreanApp.controllers', []);
    angular.module('deloreanApp.services', []);
})();
</code>```

controllers.js

```<code>(function () {
    "use strict";

function deloreanController($scope){
    $scope.sum = function(a,b){
        return a + b;
    }
}

  angular.module('deloreanApp.controllers', []).controller('DeloreanController', ['$scope', deloreanController] );
})();
</code>```

DeloreanController.test.js

```<code>describe('calculator', function () {

    beforeEach(module('deloreanApp'));

    var $controller;

    beforeEach(inject(function (_$controller_) {
        $controller = _$controller_;
    }));

    describe('sum', function () {
        it('1 + 2 should equal 3', function () {
            var result = 3;
            expect(result).toBe(3);
        });
    });

});
</code>```

And part of my karma.conf.js file:

```<code>// list of files / patterns to load in the browser
files: [
  'lib/angular.min.js',
  'lib/angular-mocks.js',
  'js/app.js',
  'js/controllers.js',
  'tests/DeloreanController.test.js'
],
</code>```

答:
Try this,</p>

```<code>(function () {
    "use strict";
    angular.module('deloreanApp.controllers', []);
    angular.module('deloreanApp.services', []);
    // initialize Angular
    angular.module('deloreanApp', ['deloreanApp.controllers', 'deloreanApp.services']);
})();
</code>```

Body:
I have setted up a test environment with Angular 1.6.6, ng-mock 1.6.6, Jasmine and Karma. But even with the easiest test I'm getting a [$injector:modulerr] when trying to inject the deloreanApp module

Failed to instantiate module deloreanApp due to: Error:
  [$injector:nomod]

Theoretically there aren't tipo errors and Angular and ng-mock versions matches.

My files are:

app.js

(function () {
    "use strict";

    // initialize Angular
    angular.module('deloreanApp', ['deloreanApp.controllers', 'deloreanApp.services']);

    angular.module('deloreanApp.controllers', []);
    angular.module('deloreanApp.services', []);
})();

controllers.js

(function () {
    "use strict";

function deloreanController($scope){
    $scope.sum = function(a,b){
        return a + b;
    }
}

  angular.module('deloreanApp.controllers', []).controller('DeloreanController', ['$scope', deloreanController] );
})();

DeloreanController.test.js

describe('calculator', function () {

    beforeEach(module('deloreanApp'));

    var $controller;

    beforeEach(inject(function (_$controller_) {
        $controller = _$controller_;
    }));

    describe('sum', function () {
        it('1 + 2 should equal 3', function () {
            var result = 3;
            expect(result).toBe(3);
        });
    });

});

And part of my karma.conf.js file:

// list of files / patterns to load in the browser
files: [
  'lib/angular.min.js',
  'lib/angular-mocks.js',
  'js/app.js',
  'js/controllers.js',
  'tests/DeloreanController.test.js'
],

Body:
Try this,

(function () {
    "use strict";
    angular.module('deloreanApp.controllers', []);
    angular.module('deloreanApp.services', []);
    // initialize Angular
    angular.module('deloreanApp', ['deloreanApp.controllers', 'deloreanApp.services']);
})();


问:
Overload assignment(=) operator in Pair Template
Hello everyone I am trying to implement a pair like Template. I have tried this:

```<code>#include<iostream>
using namespace std;
template<class T1, class T2>
class Pair
{
    //defining two points
    public:
    T1 first;
    T2 second;

    //default constructor
    Pair():first(T1()), second(T2())
    {}

    //parametrized constructor
    Pair(T1 f, T2 s) : first(f),second(s)
    {}

    //copy constructor
    Pair(const Pair<T1,T2>& otherPair) : first(otherPair.first), second(otherPair.second)
    {}

    //overloading == operator
    bool operator == (const Pair<T1, T2>& otherPair) const
    {
        return (first == otherPair.first) && (second == otherPair.second);
    }

    //overloading = operator
    Pair<T1, T2> operator = (const Pair<T1, T2>& otherPair)
    {
        first=otherPair.first;
        second=otherPair.second;
        return this;
    }

    int main()
    {
        Pair<int, int> p1(10,20);
        Pair<int, int> p2;
        p2 = p1;
    }
</code>```

But I am getting the error in the last line of  the overloaded method =. It is not allowing to return the this object.

Can anyone help where i am doing wrong?

答:
The operator should look like

```<code>//overloading = operator
Pair<T1, T2> & operator = (const Pair<T1, T2>& otherPair)
{
    if ( this != &otherPair )
    {
        first=otherPair.first;
        second=otherPair.second;
    }

    return *this;
}
</code>```

As for the error then you are trying to convert the pointer this to an object of the type Pair in the operator.

Body:
Hello everyone I am trying to implement a pair like Template. I have tried this:

#include<iostream>
using namespace std;
template<class T1, class T2>
class Pair
{
    //defining two points
    public:
    T1 first;
    T2 second;

    //default constructor
    Pair():first(T1()), second(T2())
    {}

    //parametrized constructor
    Pair(T1 f, T2 s) : first(f),second(s)
    {}

    //copy constructor
    Pair(const Pair<T1,T2>& otherPair) : first(otherPair.first), second(otherPair.second)
    {}

    //overloading == operator
    bool operator == (const Pair<T1, T2>& otherPair) const
    {
        return (first == otherPair.first) && (second == otherPair.second);
    }

    //overloading = operator
    Pair<T1, T2> operator = (const Pair<T1, T2>& otherPair)
    {
        first=otherPair.first;
        second=otherPair.second;
        return this;
    }

    int main()
    {
        Pair<int, int> p1(10,20);
        Pair<int, int> p2;
        p2 = p1;
    }

But I am getting the error in the last line of  the overloaded method =. It is not allowing to return the this object.

Can anyone help where i am doing wrong?

Body:
The operator should look like

//overloading = operator
Pair<T1, T2> & operator = (const Pair<T1, T2>& otherPair)
{
    if ( this != &otherPair )
    {
        first=otherPair.first;
        second=otherPair.second;
    }

    return *this;
}

As for the error then you are trying to convert the pointer this to an object of the type Pair in the operator.


问:
Markdown typographical features or Unicode glyphs?
Which are the pros and cons of depending on Markdown support for typographical features after ASCII characters (like --, --- and ... for en- and em-dashes and ellipsis) vs. using the Unicode glyphs themselves (–, — and …) in the text?

[I am considering writing dynamic reports in rmarkdown that can be converted (knitr+pandoc) to html, pdf and docx/odt formats.

答: Some editors that aren't compatible with Unicode will mangle Unicode glyphs.  It's more common in older or poorly written text editors. I've seen characters removed directly, or replaced with garbage depending on the editor.  If all editors used to manage your markdown, as well as the parsers you use to process your markdown, are compatible with Unicode, then there may be no downside to using those glyphs directly.</p>


问:
ngFor cannot find a differ supporting object ... using BehaviorSubject
Getting back to learning Angular and extending the Tour of Heroes tutorial. I have a shared data service that loads data into a BehaviorSubject. The issue is that when I try to iterate the data with *ngFor, I get the "cannot find a differ supporting object" error. From all the other questions, I get that it is trying to bind to an object and not an Array, but for the life of me I cannot figure out why. Or what object needs to get converted into an Array.

I am using Angular 5.0.5. Interestingly enough, this was working with Angular 4 but apparently I have broken something in the upgrade.

Any thoughts on what I did wrong? Besides everything. :D lol

This is my service

```<code>import { Injectable, EventEmitter } from '@angular/core';
import { HttpHeaders, HttpClient } from '@angular/common/http';

import { Subject } from 'rxjs/Subject';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';

import { Hero } from '../models/hero';

@Injectable()
export class HeroService {

    private heroesUrl = 'api/heroes';
    private headers = new HttpHeaders({'Content-Type': 'application/json'});

    private loadingSubject = new BehaviorSubject<boolean>(false);
    private dataSubject = new BehaviorSubject<Hero[]>([]);

    private http: HttpClient;

    constructor(http: HttpClient) {
        this.http = http;
    }

    public getLoadingStream(): Observable<boolean> {
        return this.loadingSubject.asObservable();
    }
    public getDataStream(): Observable<Hero[]> {
        return this.dataSubject.asObservable();
    }

    public load(): void {
        this.loadingSubject.next(true);
        this.http.get<Hero[]>(this.heroesUrl).subscribe(data => {
            this.dataSubject.next(data);
            this.loadingSubject.next(false);
        });
    }

    public search(term: string): void {
        this.loadingSubject.next(true);
        this.http
            .get<Hero[]>(`${this.heroesUrl}/?name=${term}`)
            .subscribe(data => {
                this.dataSubject.next(data);
                this.loadingSubject.next(false);
        });
    }
}
</code>```

List Component

```<code>import { Component, OnInit, OnDestroy, Input, Output, EventEmitter } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';

import { HeroService } from '../../services/hero.service';
import { Hero } from '../../models/hero';

@Component({
  selector: 'hero-list',
  templateUrl: './hero-list.component.html',
  styleUrls: ['./hero-list.component.css']
})
export class HeroListComponent implements OnInit {

  private dataSubscription: Subscription;
  private loadingSubscription: Subscription;

  private heroService: HeroService;

  heroes: Hero[] = [];
  isLoading: boolean;

  @Output()
  public onHeroSelected = new EventEmitter<Hero>();

  constructor(heroService: HeroService) {
    this.heroService = heroService;
  }

  ngOnInit() {
    this.loadingSubscription = this.heroService.getLoadingStream()
        .subscribe(loading => {
            this.isLoading = loading;
        });

    this.dataSubscription = this.heroService.getDataStream()
        .subscribe(data => {
            this.heroes = data;
        });
  }

  ngOnDestory() {
    this.dataSubscription.unsubscribe();
    this.loadingSubscription.unsubscribe();
  }

  onSelect(hero: Hero) {
    this.onHeroSelected.emit(hero);
  }
}
</code>```

List template

```<code><div *ngIf="isLoading">Loading ...</div>

<div *ngIf="!isLoading" class="ui relaxed divided list">
  <div *ngFor="let hero of heroes"  class="item" (click)="onSelect(hero)">
    <span class="ui blue circular label">{{ hero.id }}</span>
    <div class="content">
      <a class="header">{{ hero.name }}</a>
      <div class="description">...</div>
    </div>
  </div>
</div>
</code>```

答:
Rather than defining a function that returns an observable, shouldn't you be defining a property that is in fact an observable? For example:

Service

public heroDataStream: Observable<Hero[]> = this.dataSubject.asObservable();

Then you would subscribe directly to heroDataStream. Thats typically how I go about converting BehaviorSubjects into observables rather than wrapping them in a new function.

You might be running into a cold vs hot issue with the Observable not being created until the subscription is called since its definition is within the function. In other words its cold. You want its declaration to take place right away, meaning it needs to be hot and ready to go. So defining it as a property within your service declares it with the service. I could be wrong, this is definitely scratching the boundary of my depth of knowledge when it comes to RxJs and how everything gets spooled up.

Body:
Getting back to learning Angular and extending the Tour of Heroes tutorial. I have a shared data service that loads data into a BehaviorSubject. The issue is that when I try to iterate the data with *ngFor, I get the "cannot find a differ supporting object" error. From all the other questions, I get that it is trying to bind to an object and not an Array, but for the life of me I cannot figure out why. Or what object needs to get converted into an Array.

I am using Angular 5.0.5. Interestingly enough, this was working with Angular 4 but apparently I have broken something in the upgrade.

Any thoughts on what I did wrong? Besides everything. :D lol

This is my service

import { Injectable, EventEmitter } from '@angular/core';
import { HttpHeaders, HttpClient } from '@angular/common/http';

import { Subject } from 'rxjs/Subject';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';

import { Hero } from '../models/hero';

@Injectable()
export class HeroService {

    private heroesUrl = 'api/heroes';
    private headers = new HttpHeaders({'Content-Type': 'application/json'});

    private loadingSubject = new BehaviorSubject<boolean>(false);
    private dataSubject = new BehaviorSubject<Hero[]>([]);

    private http: HttpClient;

    constructor(http: HttpClient) {
        this.http = http;
    }

    public getLoadingStream(): Observable<boolean> {
        return this.loadingSubject.asObservable();
    }
    public getDataStream(): Observable<Hero[]> {
        return this.dataSubject.asObservable();
    }

    public load(): void {
        this.loadingSubject.next(true);
        this.http.get<Hero[]>(this.heroesUrl).subscribe(data => {
            this.dataSubject.next(data);
            this.loadingSubject.next(false);
        });
    }

    public search(term: string): void {
        this.loadingSubject.next(true);
        this.http
            .get<Hero[]>(`${this.heroesUrl}/?name=${term}`)
            .subscribe(data => {
                this.dataSubject.next(data);
                this.loadingSubject.next(false);
        });
    }
}

List Component

import { Component, OnInit, OnDestroy, Input, Output, EventEmitter } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';

import { HeroService } from '../../services/hero.service';
import { Hero } from '../../models/hero';

@Component({
  selector: 'hero-list',
  templateUrl: './hero-list.component.html',
  styleUrls: ['./hero-list.component.css']
})
export class HeroListComponent implements OnInit {

  private dataSubscription: Subscription;
  private loadingSubscription: Subscription;

  private heroService: HeroService;

  heroes: Hero[] = [];
  isLoading: boolean;

  @Output()
  public onHeroSelected = new EventEmitter<Hero>();

  constructor(heroService: HeroService) {
    this.heroService = heroService;
  }

  ngOnInit() {
    this.loadingSubscription = this.heroService.getLoadingStream()
        .subscribe(loading => {
            this.isLoading = loading;
        });

    this.dataSubscription = this.heroService.getDataStream()
        .subscribe(data => {
            this.heroes = data;
        });
  }

  ngOnDestory() {
    this.dataSubscription.unsubscribe();
    this.loadingSubscription.unsubscribe();
  }

  onSelect(hero: Hero) {
    this.onHeroSelected.emit(hero);
  }
}

List template

Loading ...

    {{ hero.id }}

      {{ hero.name }}

...


问:
Linked List in my Array not working
I am trying to create a program to store words in a Array. I have a hashFunction which computes a Integer value. This value is used to put the Word in a Node if that position in the array is null. If there is already a Cell there, it should create a new Cell with the word as its data type, and it should then point to the old Cell with all the other data. However this dosen't seem to be working - I have added a few words and although it adds the first word to the Cell the other words aren't being added. I'm not sure why this is happening - can someone show my why?</p>

```<code>public class test2{

    public static class Node<T>{
        public T data;
        public Node<T> next;

    public Node(T data, Node<T> next)
    {
       this.data = data;
       this.next = next;
    }
 }

    static Node[] array = new Node[10];

    public static void add(String word){
        int position = hashFunction(word);
        if(array[position] == null){
            array[position] = new Node(word, null);
        }else{
            new Node(word, array[position]);
        }
    }

    public static int hashFunction(String a){
        int sum = 1;
        for(int i = 0; i<a.length(); i++){
            char b = a.charAt(i);
            int value = (int) b;
            sum *= value;
        }
     return sum % array.length;
 }

 public static void main(String[] args) {
     add("abc");
     add("acb");
     add("bca");
     add("bac");
     add("cba");
     System.out.println(array[4].next);
 }
}
</code>```

答:
Instead of

```<code>new Node(word, array[position])
</code>```

You should do the following:

```<code>array[position] = new Node(word, array[position]);
</code>```

With the original line of code you are correctly creating an new instance of Node to which you assigned the current array[position] as its next value.

But array[position] is still the same, you need to change it to the newly created instance of Node.

Title: Linked List in my Array not working

Body:
I am trying to create a program to store words in a Array. I have a hashFunction which computes a Integer value. This value is used to put the Word in a Node if that position in the array is null. If there is already a Cell there, it should create a new Cell with the word as its data type, and it should then point to the old Cell with all the other data. However this dosen't seem to be working - I have added a few words and although it adds the first word to the Cell the other words aren't being added. I'm not sure why this is happening - can someone show my why?

public class test2{

    public static class Node<T>{
        public T data;
        public Node<T> next;

    public Node(T data, Node<T> next)
    {
       this.data = data;
       this.next = next;
    }
 }

    static Node[] array = new Node[10];

    public static void add(String word){
        int position = hashFunction(word);
        if(array[position] == null){
            array[position] = new Node(word, null);
        }else{
            new Node(word, array[position]);
        }
    }

    public static int hashFunction(String a){
        int sum = 1;
        for(int i = 0; i<a.length(); i++){
            char b = a.charAt(i);
            int value = (int) b;
            sum *= value;
        }
     return sum % array.length;
 }

 public static void main(String[] args) {
     add("abc");
     add("acb");
     add("bca");
     add("bac");
     add("cba");
     System.out.println(array[4].next);
 }
}

Body:
Instead of

new Node(word, array[position])

You should do the following:

array[position] = new Node(word, array[position]);

With the original line of code you are correctly creating an new instance of Node to which you assigned the current array[position] as its next value.

But array[position] is still the same, you need to change it to the newly created instance of Node.


问:
Easiest way to copy a single file from host to Vagrant guest?
I have a use case where I occasionally want to copy a single file from my host machine to the Vagrant guest.

I don't want to do so via traditional provisioners (Puppet / Chef) because this is often a one-off -- I just want something quick to add to my Vagrantfile.

I don't want to share an entire directory, possibly because I want to overwrite an existing file without nuking an entire directory on the guest.

It also seems a bit overkill to write a shell provisioning script, and deal with potential escaping, when all I want to do is copy a file.

So, what's the easiest way to copy a single file from host to guest?

答:
Try this.. vagrant ubuntu 14.04
This worked for me.</p>

```<code>scp -r -P 2222 vagrant@localhost:/home .
</code>```

Body:
Try this.. vagrant ubuntu 14.04
This worked for me.

scp -r -P 2222 vagrant@localhost:/home .