问:
How to stop navigate back while in mainpage?
I'm using Windows Template Studio, and now meet a navigate problem.

Suppose I have a MainPage, SettingsPage.

First, open app, it navigate to MainPage, and then I click to navigate to SettingsPage. And then click MainPage to navigate to MainPage.

At this time, the goback button works. But the go back order is SettingsPage ----> MainPage.

I want the goback button is disabled while in MainPage.

Here is the NavigationService code in WTS. How to stop navigate back while in MainPage? Thanks.

```<code>using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Animation;

namespace WeRecognition.Services
{
    public static class NavigationService
    {
        private static Frame _frame;
        public static Frame Frame
        {
            get
            {
                if (_frame == null)
                {
                    _frame = Window.Current.Content as Frame;
                }

                return _frame;
            }
            set
            {
                _frame = value;
            }
        }

        public static bool CanGoBack => Frame.CanGoBack;
        public static bool CanGoForward => Frame.CanGoForward;

        public static void GoBack() => Frame.GoBack();
        public static void GoForward() => Frame.GoForward();

        public static bool Navigate(Type pageType, object parameter = null, NavigationTransitionInfo infoOverride = null)
        {
            // Don't open the same page multiple times
            if (Frame.Content?.GetType() != pageType)
            {
                return Frame.Navigate(pageType, parameter, infoOverride);
            }
            else
            {
                return false;
            }
        }

        public static bool Navigate<T>(object parameter = null, NavigationTransitionInfo infoOverride = null) where T : Page => Navigate(typeof(T), parameter, infoOverride);
    }
}
</code>```

答:
You have two solutions:

After navigating to MainPage, clear the back stack of the frame.

```<code>Frame.BackStack.Clear();
</code>```

Change this CanGoBack line to return false if current page is MainPage.

```<code>Frame.CanGoBack && activeFrame.CurrentSourcePageType!=typeof(MainPage)
</code>```

Note: for the second option, you didn't clear the back stack but hide/disabled the back button.

Try them and see which works better for you.

Body:
I'm using Windows Template Studio, and now meet a navigate problem.

Suppose I have a MainPage, SettingsPage.

First, open app, it navigate to MainPage, and then I click to navigate to SettingsPage. And then click MainPage to navigate to MainPage.

At this time, the goback button works. But the go back order is SettingsPage ----> MainPage.

I want the goback button is disabled while in MainPage.

Here is the NavigationService code in WTS. How to stop navigate back while in MainPage? Thanks.

using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Animation;

namespace WeRecognition.Services
{
    public static class NavigationService
    {
        private static Frame _frame;
        public static Frame Frame
        {
            get
            {
                if (_frame == null)
                {
                    _frame = Window.Current.Content as Frame;
                }

                return _frame;
            }
            set
            {
                _frame = value;
            }
        }

        public static bool CanGoBack => Frame.CanGoBack;
        public static bool CanGoForward => Frame.CanGoForward;

        public static void GoBack() => Frame.GoBack();
        public static void GoForward() => Frame.GoForward();

        public static bool Navigate(Type pageType, object parameter = null, NavigationTransitionInfo infoOverride = null)
        {
            // Don't open the same page multiple times
            if (Frame.Content?.GetType() != pageType)
            {
                return Frame.Navigate(pageType, parameter, infoOverride);
            }
            else
            {
                return false;
            }
        }

        public static bool Navigate<T>(object parameter = null, NavigationTransitionInfo infoOverride = null) where T : Page => Navigate(typeof(T), parameter, infoOverride);
    }
}

Body:
You have two solutions:

After navigating to MainPage, clear the back stack of the frame.

Frame.BackStack.Clear();

Change this CanGoBack line to return false if current page is MainPage.

Frame.CanGoBack && activeFrame.CurrentSourcePageType!=typeof(MainPage)

Note: for the second option, you didn't clear the back stack but hide/disabled the back button.

Try them and see which works better for you.


来源: stackexchange

问:
kue - Unexpected token import
Hi I am trying to import my class in worker and getting following error

```<code>(function (exports, require, module, __filename, __dirname) { import { Myclass } from '../utility/myclass';
                                                              ^^^^^^
SyntaxError: Unexpected token import
    at createScript (vm.js:53:10)
    at Object.runInThisContext (vm.js:95:10)
    at Module._compile (module.js:543:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.runMain (module.js:605:10)
    at run (bootstrap_node.js:427:7)
</code>```

I also get error in following

```<code>async function getOrder() : Promise<any> {
                         ^
SyntaxError: Unexpected token :
</code>```

I am using typescript and have included type files for kue. I run the worker from command line and it looks like it is able to understand the env... not sure whats wrong ..

答:
It seems you running the code without ES6 support.

You need to use babel-cli to run this code, it will compile the code to ES6 before running it.

```<code>babel-node yourscript.js
</code>```

ContentLicense: CC BY-SA 3.0

Title: kue - Unexpected token import

Body:
Hi I am trying to import my class in worker and getting following error

(function (exports, require, module, __filename, __dirname) { import { Myclass } from '../utility/myclass';
                                                              ^^^^^^
SyntaxError: Unexpected token import
    at createScript (vm.js:53:10)
    at Object.runInThisContext (vm.js:95:10)
    at Module._compile (module.js:543:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.runMain (module.js:605:10)
    at run (bootstrap_node.js:427:7)

I also get error in following

async function getOrder() : Promise<any> {
                         ^
SyntaxError: Unexpected token :

I am using typescript and have included type files for kue. I run the worker from command line and it looks like it is able to understand the env... not sure whats wrong ..

Body:
It seems you running the code without ES6 support.

You need to use babel-cli to run this code, it will compile the code to ES6 before running it.

babel-node yourscript.js


问:
Why is compiling with CGO_ENABLED=0 slower?
When writing programs which utilize network, you can see quite noticeable slowdown of compilation with CGO_ENABLED=0.

For example, the simplest HTTP server:

```<code>package main

import (
    "flag"
    "fmt"
    "log"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hi! glad you requested %s.\n", r.URL.Path[1:])
}

func main() {
    port := flag.Int("port", 9000, "")
    flag.Parse()

    http.HandleFunc("/", handler)
    err := http.ListenAndServe(fmt.Sprintf(":%d", *port), nil)
    if err != nil {
        log.Fatal(err)
    }
}
</code>```

the timings are:

```<code>% time go build
go build  0.46s user 0.06s system 131% cpu 0.396 total
% time CGO_ENABLED=0 go build
CGO_ENABLED=0 go build  3.93s user 0.15s system 143% cpu 2.849 total
</code>```

So far I'm not using bindings to C so CGo handling or not seems irrelevant, what I'd like to do is to compile 100% static binary, but not if there's such slowdown.

What is the cause of such behavior?

答:
This is the time spent re-building dependencies.
Go build by default does not save rebuilt dependencies. See the -i flag:

The -i flag installs the packages that are dependencies of the target.

Let's try your program with -i instead:

```<code>$ time go build -i .
real    0m0.337s
user    0m0.343s
sys 0m0.121s

$ time CGO_ENABLED=0 go build -i .
real    0m2.135s
user    0m3.098s
sys 0m0.196s

$ time CGO_ENABLED=0 go build .
real    0m0.329s
user    0m0.367s
sys 0m0.085s

$ time go build .
real    0m2.588s
user    0m3.393s
sys 0m0.300s
</code>```

The first time you switch cgo mode, it needs to rebuild dependencies. If you specify -i, it will save them and the second build call will be much faster.

Body:
When writing programs which utilize network, you can see quite noticeable slowdown of compilation with CGO_ENABLED=0.

For example, the simplest HTTP server:

package main

import (
    "flag"
    "fmt"
    "log"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hi! glad you requested %s.\n", r.URL.Path[1:])
}

func main() {
    port := flag.Int("port", 9000, "")
    flag.Parse()

    http.HandleFunc("/", handler)
    err := http.ListenAndServe(fmt.Sprintf(":%d", *port), nil)
    if err != nil {
        log.Fatal(err)
    }
}

the timings are:

% time go build
go build  0.46s user 0.06s system 131% cpu 0.396 total
% time CGO_ENABLED=0 go build
CGO_ENABLED=0 go build  3.93s user 0.15s system 143% cpu 2.849 total

So far I'm not using bindings to C so CGo handling or not seems irrelevant, what I'd like to do is to compile 100% static binary, but not if there's such slowdown.

What is the cause of such behavior?

Body:
This is the time spent re-building dependencies.
Go build by default does not save rebuilt dependencies. See the -i flag:

The -i flag installs the packages that are dependencies of the target.

Let's try your program with -i instead:

$ time go build -i .
real    0m0.337s
user    0m0.343s
sys 0m0.121s

$ time CGO_ENABLED=0 go build -i .
real    0m2.135s
user    0m3.098s
sys 0m0.196s

$ time CGO_ENABLED=0 go build .
real    0m0.329s
user    0m0.367s
sys 0m0.085s

$ time go build .
real    0m2.588s
user    0m3.393s
sys 0m0.300s

The first time you switch cgo mode, it needs to rebuild dependencies. If you specify -i, it will save them and the second build call will be much faster.


问:
I can access jquery from developer console but not from inside a component in angular 2
I have a script bundle that already includes jquery amont other things. I just want to use it. When trying to us it from a component it fails saying ERROR ReferenceError: $ is not defined. But when I go to console type $('body') for example it works correctly. What am I doing wrong?

Edit

I forgot to mention of course that the top of the page includes this:
declare var $ : any;

This is an angular-cli project and the bundle is already included in .angular-cli.json

答:
Install typings for jquery:

```<code>npm install --save-dev @types/jquery
</code>```

In your component at the top include this:

```<code>declare const $: JQueryStatic;
</code>```

And make sure your src/tsconfig.app.json file has such keys:

```<code>"typeRoots": [
   "../node_modules/@types"
 ],
 "types": [
   "jquery"
 ]
</code>```

Body:
Install typings for jquery:

npm install --save-dev @types/jquery

In your component at the top include this:

declare const $: JQueryStatic;

And make sure your src/tsconfig.app.json file has such keys:

"typeRoots": [
   "../node_modules/@types"
 ],
 "types": [
   "jquery"
 ]


问:
Does SQL Server 2008 R2 play nice with VS2010?
I know from firsthand experience that if you wanted to install both SQL Server 2008 and Visual Studio 2008 on the same machine, you had to jump through all sorts of service packs and installation orders to ensure that both programs ran properly.

In my case, I have VS 2010 installed on my PC currently, and find I'm in need of the SQL Enterprise Manager, which is not included from the Visual Studio installation. What, if anything, do I need to do before installing SQL Server 2008 R2?

Related question: Does it matter which sub-version of SQL Server I install? (Thanks to my University connection, I have my pick between Developer, Enterprise, Standard, and Web; is one preferred in my case?)

答:
The "connect to DB" works well in VS2010 and 2008R8 works well enough with LINQ (as well as LINQ works, anyway). I would recommend using SQL Server Management Studio to actually deal with SQL Server though.

However, BIDS does not work in VS2010. VS2008 is needed for it (or perhaps VS2005? I know not). I have VS2010 and VS2008 both installed for this reason.

The order of installation does not matter as long as none of the installations are "mysteriously corrupt" (of course VS2008 is a requirement for BIDS, but that's not a core part of SQL Server). Yes, you need to install the latest service packs for VS2008, but that should be done anyway. No "hoops". Just possibly an annoying SQL Server installation restart.

As far as sub-version: depends on what you need. MSDN should cover the differences in features fairly well. One thing to consider is avoiding a lock-in of more expensive version for features used (that aren't needed). It may or may not make a difference, depending upon target audience.

ContentLicense: CC BY-SA 2.5


问:
uitableviewcell not showing swift 3
I'm working on a swift assignment about table view controller and my table view doesn't have anything on it. I have correctly connected the labels and classes and assigned tableview cell identifier as "cell" in the attribute on storyboard but I still have the error "need to register nib" and even if I wrote self.tableView.register(TableViewCell.self, forCellReuseIdentifier: "Cell") the error is gone but there's still nothing on it.

My cell class is as below.

```<code>class cartTableViewCell: UITableViewCell {

@IBOutlet weak var itemImage: UIImageView!
@IBOutlet weak var itemName: UILabel!
@IBOutlet weak var itemQuan: UILabel!
@IBOutlet weak var itemFrame: UILabel!
@IBOutlet weak var itemSize: UILabel!
@IBOutlet weak var itemPrice: UILabel!
@IBOutlet weak var itemSub: UILabel!

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
}`
</code>```

my function is

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = self.tableView.dequeueReusableCell(withIdentifier:"Cell", for: indexPath) as! cartTableViewCell

    let item = itemArray[indexPath.row]

    cell.itemName?.text = item.itemName!
    cell.itemFrame?.text = "haha"//itemArray[indexPath.row].itemFrame!
    cell.itemSize?.text = item.itemSize!
    cell.itemPrice?.text = item.sellingPrice!
    //cell.itemQuan?.text =
    cell.itemSub?.text = "\(Int(item.sellingNumber!)! * Int(item.sellingPrice!)!)"
    return cell
}`
</code>```

If I print(item.itemName), I can get some value. cell.itemName?.text is nil

I checked some answers online but so far no luck. Any help is highly appreciated.

答:
Do this, I just got this error today and I got it fixed by :</p>

```<code>let yourNib = UINib(nibName: "yourNibName", bundle: Bundle.main)
yourTableView.register(yourNib, forCellReuseIdentifier: "cell")
</code>```

Title: uitableviewcell not showing swift 3

Body:
I'm working on a swift assignment about table view controller and my table view doesn't have anything on it. I have correctly connected the labels and classes and assigned tableview cell identifier as "cell" in the attribute on storyboard but I still have the error "need to register nib" and even if I wrote self.tableView.register(TableViewCell.self, forCellReuseIdentifier: "Cell") the error is gone but there's still nothing on it.

My cell class is as below.

class cartTableViewCell: UITableViewCell {

@IBOutlet weak var itemImage: UIImageView!
@IBOutlet weak var itemName: UILabel!
@IBOutlet weak var itemQuan: UILabel!
@IBOutlet weak var itemFrame: UILabel!
@IBOutlet weak var itemSize: UILabel!
@IBOutlet weak var itemPrice: UILabel!
@IBOutlet weak var itemSub: UILabel!

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)
}`

my function is

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = self.tableView.dequeueReusableCell(withIdentifier:"Cell", for: indexPath) as! cartTableViewCell

    let item = itemArray[indexPath.row]

    cell.itemName?.text = item.itemName!
    cell.itemFrame?.text = "haha"//itemArray[indexPath.row].itemFrame!
    cell.itemSize?.text = item.itemSize!
    cell.itemPrice?.text = item.sellingPrice!
    //cell.itemQuan?.text =
    cell.itemSub?.text = "\(Int(item.sellingNumber!)! * Int(item.sellingPrice!)!)"
    return cell
}`

If I print(item.itemName), I can get some value. cell.itemName?.text is nil

I checked some answers online but so far no luck. Any help is highly appreciated.

Body:
Do this, I just got this error today and I got it fixed by :

let yourNib = UINib(nibName: "yourNibName", bundle: Bundle.main)
yourTableView.register(yourNib, forCellReuseIdentifier: "cell")


问:
Django cache how to remove key prefix of ":1:"
I set a cache in Django as below:

```<code>from django.core.cache import cache
...
cache.set("cae9ad31b9206a1b5594813b509e1003", "test", timeout=10)
</code>```

It generates a key like this:

```<code>:1:cae9ad31b9206a1b5594813b509e1003
</code>```

How to remove :1: prefix from the key?

答:
You don't have to worry about it, really, as this doesn't affect how you get the value of a key.

```<code>cache.get("cae9ad31b9206a1b5594813b509e1003")
# outputs
"test"
</code>```

Why's this happening?

Django generates the cache keys by combining the key you give it with the version of the cache.

Example:

```<code>cache.set("my_key", "value", version=2)
# becomes
":2:my-key"
</code>```

Since, by default version=1, that is why in your case it becomes :1:cae9a....

This is called Cache Versioning. It is useful because this way you can have multiple cached versions of a particular object.

How to override this?

If you still want to override this behaviour for whatever reason, you can do it as the docs suggest.

First create a function somewhere like this:

```<code>def my_key_maker(key, key_prefix, version):
    return key # just return the key without doing anything
</code>```

Then, in your CACHES settings do this:

```<code>CACHES = {
    "default": {
        "BACKEND": ...,
        # other settings ...
        "KEY_FUNCTION": "path.to.my_key_maker"
    }
}
</code>```

Body:
I set a cache in Django as below:

from django.core.cache import cache
...
cache.set("cae9ad31b9206a1b5594813b509e1003", "test", timeout=10)

It generates a key like this:

:1:cae9ad31b9206a1b5594813b509e1003

How to remove :1: prefix from the key?

Body:
You don't have to worry about it, really, as this doesn't affect how you get the value of a key.

cache.get("cae9ad31b9206a1b5594813b509e1003")
# outputs
"test"

Why's this happening?

Django generates the cache keys by combining the key you give it with the version of the cache.

Example:

cache.set("my_key", "value", version=2)
# becomes
":2:my-key"

Since, by default version=1, that is why in your case it becomes :1:cae9a....

This is called Cache Versioning. It is useful because this way you can have multiple cached versions of a particular object.

How to override this?

If you still want to override this behaviour for whatever reason, you can do it as the docs suggest.

First create a function somewhere like this:

def my_key_maker(key, key_prefix, version):
    return key # just return the key without doing anything

Then, in your CACHES settings do this:

CACHES = {
    "default": {
        "BACKEND": ...,
        # other settings ...
        "KEY_FUNCTION": "path.to.my_key_maker"
    }
}


问:
Why i can't take address of variable?
guys!
Why i can't take address of "t" - variable ?

```<code>flygs->type == 'X' ? t = a_ib_u(u->us, 16) : (a_lowcasealph(&(t = a_ib_u(u->us, 16))));
\\a_ib_u returns *char, a_lowcasealph take **char argument
</code>```

error: cannot take the address of an rvalue of type 'char *'

答:
The answer by @dbush have already explained the cause of the error.

I like to add that you can rewrite the code and get something much easier to understand and maintain. Like:

```<code>t = a_ib_u(u->us, 16);
if (flygs->type != 'X') a_lowcasealph(&t);
</code>```

Title: Why i can't take address of variable?

Body:
guys!
Why i can't take address of "t" - variable ?

flygs->type == 'X' ? t = a_ib_u(u->us, 16) : (a_lowcasealph(&(t = a_ib_u(u->us, 16))));
\\a_ib_u returns *char, a_lowcasealph take **char argument

error: cannot take the address of an rvalue of type 'char *'

Body:
The answer by @dbush have already explained the cause of the error.

I like to add that you can rewrite the code and get something much easier to understand and maintain. Like:

t = a_ib_u(u->us, 16);
if (flygs->type != 'X') a_lowcasealph(&t);


问:
expected initializer before '&' token in enumarator operator overloading C++
I want to write overloading operator, that increments enum type:

```<code>#include <iostream>
#include <vector>
#include <string>
#include <stdexcept>
using namespace std;

enum Type {grun,grun_blinkend,gelb,rot ,rot_gelb,gelb_blinkend}

Type& operator++(Type& color){
    return color = static_cast<Type>(++static_cast<int>(Type));
};
</code>```

But it throws me an error:

error: expected initializer before '&' token

Why and how can I fix it?

I need this operator in order to iterate over the Type for "traffic light" simulation:

```<code>Ampel Ampel::weiter(){
    if(zustand ==  Type(rot_gelb)){
        zustand = Type(grun);
        return Ampel(zustand);
    }
    ++zustand;
    return Ampel(zustand);
}
</code>```

答:
This is a solution, but you must be cautious about an integer higher to gelb_blinkend, for a good explanation about that I recommend see this question and also you should think about change enum for enum class, for this I suggest this  another question.

```<code>enum Type {grun,grun_blinkend,gelb,rot ,rot_gelb,gelb_blinkend};

Type& operator++(Type& color){
    int current = static_cast<int>(color);
    return color = static_cast<Type>(++current);
};
</code>```

Body:
I want to write overloading operator, that increments enum type:

#include <iostream>
#include <vector>
#include <string>
#include <stdexcept>
using namespace std;

enum Type {grun,grun_blinkend,gelb,rot ,rot_gelb,gelb_blinkend}

Type& operator++(Type& color){
    return color = static_cast<Type>(++static_cast<int>(Type));
};

But it throws me an error:

error: expected initializer before '&' token

Why and how can I fix it?

I need this operator in order to iterate over the Type for "traffic light" simulation:

Ampel Ampel::weiter(){
    if(zustand ==  Type(rot_gelb)){
        zustand = Type(grun);
        return Ampel(zustand);
    }
    ++zustand;
    return Ampel(zustand);
}

Body:
This is a solution, but you must be cautious about an integer higher to gelb_blinkend, for a good explanation about that I recommend see this question and also you should think about change enum for enum class, for this I suggest this  another question.

enum Type {grun,grun_blinkend,gelb,rot ,rot_gelb,gelb_blinkend};

Type& operator++(Type& color){
    int current = static_cast<int>(color);
    return color = static_cast<Type>(++current);
};


问:
How can I use mongoose $lookup operator for lookup chaining and then grouping the result?
Lets consider I have three pseudo collections like following

users:

```<code>{ "_id" : ObjectId("5a2a2c3dcf7961800e44dfc9"), "uid" : 1234,
     "name" : "ashish", "email" : "info@gmail.com" },
{ "_id" : ObjectId("5a2a2c51cf7961800e44dfca"), "uid" : 1235,
     "name" : "swapnil", "email" : "info@femail.com" }
</code>```

bank_details:

```<code>{ "_id" : ObjectId("5a2a2c9bcf7961800e44dfcb"), "uid" : 1234, "acc_no" : 1111 },
{ "_id" : ObjectId("5a2a2cc9cf7961800e44dfcc"), "uid" : 1234, "acc_no" : 2222 },
{ "_id" : ObjectId("5a2a2cd7cf7961800e44dfcd"), "uid" : 1235, "acc_no" : 3333 },
{ "_id" : ObjectId("5a2a2cdccf7961800e44dfce"), "uid" : 1235, "acc_no" : 4444 }
</code>```

bank

```<code>{ "_id" : ObjectId("5a2a2d05cf7961800e44dfcf"), "acc_no" : 1111, "balance" : 100 },
{ "_id" : ObjectId("5a2a2d10cf7961800e44dfd0"), "acc_no" : 2222, "balance" : 200 },
{ "_id" : ObjectId("5a2a2d19cf7961800e44dfd1"), "acc_no" : 3333, "balance" : 300 },
{ "_id" : ObjectId("5a2a2d21cf7961800e44dfd2"), "acc_no" : 4444, "balance" : 400 }
</code>```

I wanna have output as following

```<code>{ "_id" : ObjectId("5a2a2c3dcf7961800e44dfc9"), "uid" : "1234",
  "name" : "ashish", "email" : "info@gmail.com" ,
bank_details: [{
  acc_no:'1111',
  balance:'100'
},{
  acc_no:'2222',
  balance:'200'
}]}
</code>```

for each profile of user, I'm sure this can be done using $lookup and $group operator but I could never achieve it, I have tried to do this using several ways. Can anybody please write a sample query for the required result.

I'm trying to write the query using mongoose in NodeJs

答:
If you don't want to lose the users that have no bank_details you have to add a $project before you unwind. By "$unwind" you flatten the bank_details array and the documents that have an empty array, disappear after since there is nothing to unwind. So you can check your bank_details array if it's empty and add zero values to the fields:

```<code>db.getCollection('users').aggregate([{
        $lookup: {
            from: "bank_details",
            localField: "uid",
            foreignField: "uid",
            as: "bank_details"
        }
    },
    {
        $project: {
            "_id": "$_id",
            uid: "$uid",
            name: "$name",
            email: "$email",
            bank_details: {
                $cond: [{
                        $eq: ["$bank_details", []]
                    },
                    [{
                        _id: 0,
                        uid: {
                            $literal: NumberInt(0)
                        },
                        acc_no: {
                            $literal: NumberInt(0)
                        }
                    }], '$bank_details'
                ]
            }
        }
    },
    {
        $unwind: "$bank_details"
    },
    {
        $lookup: {
            from: "bank",
            localField: "bank_details.acc_no",
            foreignField: "acc_no",
            as: "banks"
        }
    },
    {
        $project: {
            "_id": "$_id",
            uid: "$uid",
            name: "$name",
            email: "$email",
            bank_details: "$bank_details",
            banks: {
                $cond: [{
                        $eq: ["$banks", []]
                    },
                    [{
                        _id: 0,
                        acc_no: {
                            $literal: NumberInt(0)
                        },
                        balance: {
                            $literal: NumberInt(0)
                        }
                    }], '$banks'
                ]
            }
        }
    },

    {
        $unwind: "$banks"
    },
    {
        $group: {
            "_id": "$_id",
            uid: {
                $first: "$uid"
            },
            name: {
                $first: "$name"
            },
            email: {
                $first: "$email"
            },
            bank_details: {
                $push: {
                    acc_no: "$banks.acc_no",
                    balance: "$banks.balance"
                }
            }
        }
    }
])
</code>```

Here the results of the query:

```<code>/* 1 */
{
    "_id" : ObjectId("5a2a83a53b3899dec93be178"),
    "uid" : 1239,
    "name" : "emil",
    "email" : "emil@femail.com",
    "bank_details" : [
        {
            "acc_no" : 0.0,
            "balance" : 0.0
        }
    ]
}

/* 2 */
{
    "_id" : ObjectId("5a2a2c51cf7961800e44dfca"),
    "uid" : 1235,
    "name" : "swapnil",
    "email" : "info@femail.com",
    "bank_details" : [
        {
            "acc_no" : 3333,
            "balance" : 300
        },
        {
            "acc_no" : 4444,
            "balance" : 400
        }
    ]
}

/* 3 */
{
    "_id" : ObjectId("5a2a2c3dcf7961800e44dfc9"),
    "uid" : 1234,
    "name" : "ashish",
    "email" : "info@gmail.com",
    "bank_details" : [
        {
            "acc_no" : 1111,
            "balance" : 100
        },
        {
            "acc_no" : 2222,
            "balance" : 200
        }
    ]
}
</code>```

Body:
Lets consider I have three pseudo collections like following

users:

{ "_id" : ObjectId("5a2a2c3dcf7961800e44dfc9"), "uid" : 1234,
     "name" : "ashish", "email" : "info@gmail.com" },
{ "_id" : ObjectId("5a2a2c51cf7961800e44dfca"), "uid" : 1235,
     "name" : "swapnil", "email" : "info@femail.com" }

bank_details:

{ "_id" : ObjectId("5a2a2c9bcf7961800e44dfcb"), "uid" : 1234, "acc_no" : 1111 },
{ "_id" : ObjectId("5a2a2cc9cf7961800e44dfcc"), "uid" : 1234, "acc_no" : 2222 },
{ "_id" : ObjectId("5a2a2cd7cf7961800e44dfcd"), "uid" : 1235, "acc_no" : 3333 },
{ "_id" : ObjectId("5a2a2cdccf7961800e44dfce"), "uid" : 1235, "acc_no" : 4444 }

bank

{ "_id" : ObjectId("5a2a2d05cf7961800e44dfcf"), "acc_no" : 1111, "balance" : 100 },
{ "_id" : ObjectId("5a2a2d10cf7961800e44dfd0"), "acc_no" : 2222, "balance" : 200 },
{ "_id" : ObjectId("5a2a2d19cf7961800e44dfd1"), "acc_no" : 3333, "balance" : 300 },
{ "_id" : ObjectId("5a2a2d21cf7961800e44dfd2"), "acc_no" : 4444, "balance" : 400 }

I wanna have output as following

{ "_id" : ObjectId("5a2a2c3dcf7961800e44dfc9"), "uid" : "1234",
  "name" : "ashish", "email" : "info@gmail.com" ,
bank_details: [{
  acc_no:'1111',
  balance:'100'
},{
  acc_no:'2222',
  balance:'200'
}]}

for each profile of user, I'm sure this can be done using $lookup and $group operator but I could never achieve it, I have tried to do this using several ways. Can anybody please write a sample query for the required result.

I'm trying to write the query using mongoose in NodeJs

Body:
If you don't want to lose the users that have no bank_details you have to add a $project before you unwind. By "$unwind" you flatten the bank_details array and the documents that have an empty array, disappear after since there is nothing to unwind. So you can check your bank_details array if it's empty and add zero values to the fields:

db.getCollection('users').aggregate([{
        $lookup: {
            from: "bank_details",
            localField: "uid",
            foreignField: "uid",
            as: "bank_details"
        }
    },
    {
        $project: {
            "_id": "$_id",
            uid: "$uid",
            name: "$name",
            email: "$email",
            bank_details: {
                $cond: [{
                        $eq: ["$bank_details", []]
                    },
                    [{
                        _id: 0,
                        uid: {
                            $literal: NumberInt(0)
                        },
                        acc_no: {
                            $literal: NumberInt(0)
                        }
                    }], '$bank_details'
                ]
            }
        }
    },
    {
        $unwind: "$bank_details"
    },
    {
        $lookup: {
            from: "bank",
            localField: "bank_details.acc_no",
            foreignField: "acc_no",
            as: "banks"
        }
    },
    {
        $project: {
            "_id": "$_id",
            uid: "$uid",
            name: "$name",
            email: "$email",
            bank_details: "$bank_details",
            banks: {
                $cond: [{
                        $eq: ["$banks", []]
                    },
                    [{
                        _id: 0,
                        acc_no: {
                            $literal: NumberInt(0)
                        },
                        balance: {
                            $literal: NumberInt(0)
                        }
                    }], '$banks'
                ]
            }
        }
    },

    {
        $unwind: "$banks"
    },
    {
        $group: {
            "_id": "$_id",
            uid: {
                $first: "$uid"
            },
            name: {
                $first: "$name"
            },
            email: {
                $first: "$email"
            },
            bank_details: {
                $push: {
                    acc_no: "$banks.acc_no",
                    balance: "$banks.balance"
                }
            }
        }
    }
])

Here the results of the query:

/* 1 */
{
    "_id" : ObjectId("5a2a83a53b3899dec93be178"),
    "uid" : 1239,
    "name" : "emil",
    "email" : "emil@femail.com",
    "bank_details" : [
        {
            "acc_no" : 0.0,
            "balance" : 0.0
        }
    ]
}

/* 2 */
{
    "_id" : ObjectId("5a2a2c51cf7961800e44dfca"),
    "uid" : 1235,
    "name" : "swapnil",
    "email" : "info@femail.com",
    "bank_details" : [
        {
            "acc_no" : 3333,
            "balance" : 300
        },
        {
            "acc_no" : 4444,
            "balance" : 400
        }
    ]
}

/* 3 */
{
    "_id" : ObjectId("5a2a2c3dcf7961800e44dfc9"),
    "uid" : 1234,
    "name" : "ashish",
    "email" : "info@gmail.com",
    "bank_details" : [
        {
            "acc_no" : 1111,
            "balance" : 100
        },
        {
            "acc_no" : 2222,
            "balance" : 200
        }
    ]
}


问:
Apache storm: why and how to choose number of tasks per executor?
According to the official documentation:

How many instances to create for a spout/bolt. A task runs on a thread with zero or more other tasks for the same spout/bolt. The number of tasks for a spout/bolt is always the same throughout the lifetime of a topology, but the number of executors (threads) for a spout/bolt can change over time. This allows a topology to scale to more or less resources without redeploying the topology or violating the constraints of Storm (such as a fields grouping guaranteeing that the same value goes to the same task)

My questions are:

Under what circumstances would I choose to run multiple tasks in one executor?

If I do use multiple tasks in one executor, what might be reasons that I would choose different number of tasks per executor between my spout and my bolt (such as 2 tasks per bolt executor but only 1 task per spout executor)?

答:
```<code>Config#TOPOLOGY_TASKS -> How many tasks to create per component.
</code>```

A task performs the actual data processing and is run within its parent executor’s thread of execution. Each spout or bolt that you implement in your code executes as many tasks across the cluster.

The number of tasks for a component is always the same throughout the lifetime of a topology, but the number of executors (threads) for a component can change over time. This means that the following condition holds true: #threads <= #tasks.

By default, the number of tasks is set to be the same as the number of executors, i.e. Storm will run one task per thread (which is usually what you want anyways).

Also be aware that:

The number of executor threads can be changed after the topology has been started.

The number of tasks of a topology is static.

Body:
Config#TOPOLOGY_TASKS -> How many tasks to create per component.

A task performs the actual data processing and is run within its parent executor’s thread of execution. Each spout or bolt that you implement in your code executes as many tasks across the cluster.

The number of tasks for a component is always the same throughout the lifetime of a topology, but the number of executors (threads) for a component can change over time. This means that the following condition holds true: #threads <= #tasks.

By default, the number of tasks is set to be the same as the number of executors, i.e. Storm will run one task per thread (which is usually what you want anyways).

Also be aware that:

The number of executor threads can be changed after the topology has been started.

The number of tasks of a topology is static.


问:
The executable was signed with invalid entitlements. error
Please help me understand what I'm missing when setting up iCloud testing for the sample iCloudUIApp.
https://github.com/xamarin/ios-samples/tree/master/IntroductionToiCloud/iCloudUIDoc

The sample app uploads to a physical device just fine without iCloud being enabled (crashes, but that's OK) which means that Provisioning Profile, Devices, Team ID, App ID are set correctly.

Now, as soon as I enable iCloud in Entitlements.plist it gives me this error:
'error MT1006: Could not install the application'
and
'The executable was signed with invalid entitlements.'

Here is what I did:

I set up an iCloud Container in Developer portal with the ID: iCloud.com.sketch.iCloudUIDoc

I added iCloud Application Service to the App ID in Developer portal (Also non-optionally enabled are In-App Purchase and Game Center)

I set iCloud Container Assignment to iCloud.com.sketch.iCloudUIDoc and enabled it

in Visual Studio:

in the Entitlements.plist I enable iCloud

Services: I enable iCloud Documents and CloudKit

I set Containers to: iCloud.com.sketch.iCloudUIDoc (also tried with Team ID as prefix - to no avail)

In Info.plist I have Team, Signing Certificate, Provisioning Profile set up with Automatic signing management enabled.
No other services are enabled here (Background Modes, GameCenter, Maps).

Device:

signed in to iCloud

iCloud Drive enabled

iCloud access for iCloudUIDoc app is enabled

Run the app -> uploading error.
Tried with different hardware - same result.

What do I get wrong?
Thanks

答:
Turns out that it's not enough to download and dbl click .mobileprovisioning files on the Apple Developer site - I also needed to goto to Visual Studio - Preferences - Apple Developer Accounts - View Details - Download All Profiles.
After that it worked.

I hope it helps someone out there stuck in this loop.


问:
Node js authentication in cross domain
I am working on a MEAN application, I am using Angular 4 for my project. For authentication, I have implemented the Passport js Local-strategy. And I am maintaining persistent session using Express-session. Things are working fine till here.

The Problem

In the same domain session works fine and I am able to authenticate the user. But in cross-domain, I am not able to maintain the session. It generates a new session id for each new request in cross-domain.

I then tried Passport-jwt but the problem with it is I don't have the control over user session. I mean I can't logout the user from the server if he is inactive or even on server re-start also the token don't get invalid.

So in simple words, I am looking for an authentication solution in Node js (Express js) in which I can manage authentication in cross-domain.

I have already seen some blog post and SO questions like this, but it doesn't help.

Thank you.

EDIT

Should I write my own code to achieve this? If so I have a plan.

My basic plan is:

The user will send credentials with the login request.

I will check for the credentials in the database. If credentials are valid, I will generate a random token and save it to the database, in the user table and the same token I will provide to the user with success response.

Now, with each request user will send the token and I will check the token for each request in the database. If the token is valid then I will allow the user to access the API otherwise I will generate an error with 401 status code.

I am using Mongoose (MongoDB) so I will be ok to check the token in each request (performance point of view).

I think this is also a good idea. I just want some suggestions, whether I am thinking in right direction or not.

What I will get with this:

The number of logged in user in the application (active sessions).

I can logout a user if he is idle for a certain interval of time.

I can manage multiple login session of the same user (by doing an entry in the database).

I can allow the end user to clear all other login sessions (like Facebook and Gmail offers).

Any customization related to authorization.

EDIT 2

Here I am shareing my app.js code

```<code>var express = require('express');
var helmet = require('helmet');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var dotenv = require('dotenv');
var env = dotenv.load();
var mongoose = require('mongoose');
var passport = require('passport');
var flash    = require('connect-flash');
var session      = require('express-session');
var cors = require('cors');

var databaseUrl = require('./config/database.js')[process.env.NODE_ENV || 'development'];
// configuration
mongoose.connect(databaseUrl); // connect to our database

var app = express();

// app.use(helmet());

// required for passport

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Origin', req.headers.origin);
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
  if ('OPTIONS' == req.method) {
       res.send(200);
   } else {
       next();
   }
});

app.use(cookieParser());

app.use(session({
    secret: 'ilovescotchscotchyscotchscotch', // session secret
    resave: true,
    saveUninitialized: true,
    name: 'Session-Id',
    cookie: {
      secure: false,
      httpOnly: false
    }
}));

require('./config/passport')(passport); // pass passport for configuration

var index = require('./routes/index');
var users = require('./routes/user.route');
var seeders = require('./routes/seeder.route');
var branches = require('./routes/branch.route');
var companies = require('./routes/company.route');
var dashboard = require('./routes/dashboard.route');
var navigation = require('./routes/navigation.route');
var roles = require('./routes/role.route');
var services = require('./routes/services.route');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session

require('./routes/auth.route')(app, passport);
app.use('/', index);
app.use('/users', users);
app.use('/seed', seeders);
app.use('/branches', branches);
app.use('/companies', companies);
app.use('/dashboard', dashboard);
app.use('/navigation', navigation);
app.use('/roles', roles);
app.use('/services', services);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  res.status(404).send({ status: 'NOT_FOUND', message: 'This resource is not available.'});
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  let errorObj = {
    status: 'INTERNAL_SERVER_ERROR',
    message: 'Something went wrong.',
    error: err.message
  };
  res.status(err.status || 500).send(errorObj);
});

module.exports = app;
</code>```

EDIT 3

For those who don't understand my problem. Explaining the problem in
  simple words:

My Express server is running on port 3000.

In order to consume any API from the server, a user must be logged in.

When a user gets logged in from localhost:3000, the server checks the credentials(using Passport-local) and returns a token in the response header.

Now after login, when a user hits any API from localhost:3000, a predefined Header comes with passport-session and then passport verifies the user session using req.isAuthenticated() and all the things works as expected.

When a user gets logged in from localhost:4000 and the server send a token in response header (same as localhost:3000).

When after successful login, the user hits any API from localhost:4000 the passport js function req.isAuthenticated() returns false.

This was happening because in cross-domain the cookie doesn't go to the server we need to set withCredentials header to true at the client side.

I have set withCredentials header to true but still at the server the req.isAuthenticated() is returning false.

答:
did you already take a look here:

In this case, responses can be sent back based on some considerations.

If the resource in question is meant to be widely accessed (just like any HTTP resource accessed by GET), then sending back the Access-Control-Allow-Origin: * header will be sufficient,[...]

You may try this (allow any public IP) :

```<code>app.use(function(req, res, next) {
 res.header('Access-Control-Allow-Credentials', true);
 res.header('Access-Control-Allow-Origin', '*');  // add this line
 // res.header('Access-Control-Allow-Origin', req.headers.origin);
 res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');

</code>```

It is normal that the second server re-create a new session, because assuming that you use Express-session, and according to the documentation:

Session data is not saved in the cookie itself, just the session ID. Session data is stored server-side.

Which mean that you need to find a way to synchronize servers session data ...
Assuming that you find a method to do that, when you will try to connect, both server will retrieve the same user session data and the second will not have to create a new session...

Title: Node js authentication in cross domain

Body:
I am working on a MEAN application, I am using Angular 4 for my project. For authentication, I have implemented the Passport js Local-strategy. And I am maintaining persistent session using Express-session. Things are working fine till here.

The Problem

In the same domain session works fine and I am able to authenticate the user. But in cross-domain, I am not able to maintain the session. It generates a new session id for each new request in cross-domain.

I then tried Passport-jwt but the problem with it is I don't have the control over user session. I mean I can't logout the user from the server if he is inactive or even on server re-start also the token don't get invalid.

So in simple words, I am looking for an authentication solution in Node js (Express js) in which I can manage authentication in cross-domain.

I have already seen some blog post and SO questions like this, but it doesn't help.

Thank you.

EDIT

Should I write my own code to achieve this? If so I have a plan.

My basic plan is:

The user will send credentials with the login request.

I will check for the credentials in the database. If credentials are valid, I will generate a random token and save it to the database, in the user table and the same token I will provide to the user with success response.

Now, with each request user will send the token and I will check the token for each request in the database. If the token is valid then I will allow the user to access the API otherwise I will generate an error with 401 status code.

I am using Mongoose (MongoDB) so I will be ok to check the token in each request (performance point of view).

I think this is also a good idea. I just want some suggestions, whether I am thinking in right direction or not.

What I will get with this:

The number of logged in user in the application (active sessions).

I can logout a user if he is idle for a certain interval of time.

I can manage multiple login session of the same user (by doing an entry in the database).

I can allow the end user to clear all other login sessions (like Facebook and Gmail offers).

Any customization related to authorization.

EDIT 2

Here I am shareing my app.js code

var express = require('express');
var helmet = require('helmet');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var dotenv = require('dotenv');
var env = dotenv.load();
var mongoose = require('mongoose');
var passport = require('passport');
var flash    = require('connect-flash');
var session      = require('express-session');
var cors = require('cors');

var databaseUrl = require('./config/database.js')[process.env.NODE_ENV || 'development'];
// configuration
mongoose.connect(databaseUrl); // connect to our database

var app = express();

// app.use(helmet());

// required for passport

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Origin', req.headers.origin);
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
  if ('OPTIONS' == req.method) {
       res.send(200);
   } else {
       next();
   }
});

app.use(cookieParser());

app.use(session({
    secret: 'ilovescotchscotchyscotchscotch', // session secret
    resave: true,
    saveUninitialized: true,
    name: 'Session-Id',
    cookie: {
      secure: false,
      httpOnly: false
    }
}));

require('./config/passport')(passport); // pass passport for configuration

var index = require('./routes/index');
var users = require('./routes/user.route');
var seeders = require('./routes/seeder.route');
var branches = require('./routes/branch.route');
var companies = require('./routes/company.route');
var dashboard = require('./routes/dashboard.route');
var navigation = require('./routes/navigation.route');
var roles = require('./routes/role.route');
var services = require('./routes/services.route');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session

require('./routes/auth.route')(app, passport);
app.use('/', index);
app.use('/users', users);
app.use('/seed', seeders);
app.use('/branches', branches);
app.use('/companies', companies);
app.use('/dashboard', dashboard);
app.use('/navigation', navigation);
app.use('/roles', roles);
app.use('/services', services);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  res.status(404).send({ status: 'NOT_FOUND', message: 'This resource is not available.'});
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  let errorObj = {
    status: 'INTERNAL_SERVER_ERROR',
    message: 'Something went wrong.',
    error: err.message
  };
  res.status(err.status || 500).send(errorObj);
});

module.exports = app;

EDIT 3

For those who don't understand my problem. Explaining the problem in
  simple words:

My Express server is running on port 3000.

In order to consume any API from the server, a user must be logged in.

When a user gets logged in from localhost:3000, the server checks the credentials(using Passport-local) and returns a token in the response header.

Now after login, when a user hits any API from localhost:3000, a predefined Header comes with passport-session and then passport verifies the user session using req.isAuthenticated() and all the things works as expected.

When a user gets logged in from localhost:4000 and the server send a token in response header (same as localhost:3000).

When after successful login, the user hits any API from localhost:4000 the passport js function req.isAuthenticated() returns false.

This was happening because in cross-domain the cookie doesn't go to the server we need to set withCredentials header to true at the client side.

I have set withCredentials header to true but still at the server the req.isAuthenticated() is returning false.

Body:
did you already take a look here:

In this case, responses can be sent back based on some considerations.

If the resource in question is meant to be widely accessed (just like any HTTP resource accessed by GET), then sending back the Access-Control-Allow-Origin: * header will be sufficient,[...]

You may try this (allow any public IP) :

app.use(function(req, res, next) {
 res.header('Access-Control-Allow-Credentials', true);
 res.header('Access-Control-Allow-Origin', '*');  // add this line
 // res.header('Access-Control-Allow-Origin', req.headers.origin);
 res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');

It is normal that the second server re-create a new session, because assuming that you use Express-session, and according to the documentation:

Session data is not saved in the cookie itself, just the session ID. Session data is stored server-side.

Which mean that you need to find a way to synchronize servers session data ...
Assuming that you find a method to do that, when you will try to connect, both server will retrieve the same user session data and the second will not have to create a new session...


问:
Dropout: why is my neural network not working?
I'm using normalized MNIST dataset (input features = 784). My network architecture is 784-256-256-10: two hidden layers of 256 neurons each using sigmoid activation functions, and softmax activation at 10-neuron output layer. Also I'm using the Cross-Entropy cost function.

Weight matrix initialization:

```<code>input_size=784
hidden1_size=256
hidden2_size=256
output_size=10
Theta1 = np.random.randn(hidden1_size, input_size)
b1 = np.random.randn(hidden1_size)

Theta2 = np.random.randn(hidden2_size, hidden1_size)
b2 = np.random.randn(hidden2_size)

Theta3 = np.random.randn(output_size, hidden2_size)
b3 = np.random.randn(output_size)
</code>```

My network works as expected here:

```<code>epochs = 2000
learning_rate = 0.01
for j in range(epochs):
    # total_train is an array of length 50000
    # Each element of total_train is a tuple of: (a) input vector of length 784
    # and (b) the corresponding one-hot encoded label of length 10
    # Similarly, total_test is an array of length 10000
    shuffle(total_train)
    train = total_train[:1000]
    shuffle(total_test)
    test = total_test[:1000]
    predictions = []
    test_predictions = []
    for i in range(len(train)):
        # Feed forward
        x, t = train[i][0], train[i][1]
        z1 = np.dot(Theta1, x) + b1
        a1 = sigmoid(z1)
        z2 = np.dot(Theta2, a1) + b2
        a2 = sigmoid(z2)
        z3 = np.dot(Theta3, a2) + b3
        y = softmax(z3)
        # Is prediction == target?
        predictions.append(np.argmax(y) == np.argmax(t))

        # Negative log probability cost function
        cost = -t * np.log(y)

        # Backpropagation
        delta3 = (y - t) * softmax_prime(z3)
        dTheta3 = np.outer(delta3, a2)
        db3 = delta3

        delta2 = np.dot(Theta3.T, delta3) * sigmoid_prime(z2)
        dTheta2 = np.outer(delta2, a1)
        db2 = delta2

        delta1 = np.dot(Theta2.T, delta2) * sigmoid_prime(z1)
        dTheta1 = np.outer(delta1, x)
        db1 = delta1

        # Update weights
        Theta1 -= learning_rate * dTheta1
        b1 -= learning_rate * db1
        Theta2 -= learning_rate * dTheta2
        b2 -= learning_rate * db2
        Theta3 -= learning_rate * dTheta3
        b3 -= learning_rate * db3

    if j % 10 == 0:
        m = len(predictions)
        performance = sum(predictions)/m
        print('Epoch:', j, 'Train performance:', performance)

    # Test accuracy on test data
    for i in range(len(test)):
        # Feed forward
        x, t = test[i][0], test[i][1]
        z1 = np.dot(Theta1, x) + b1
        a1 = sigmoid(z1)
        z2 = np.dot(Theta2, a1) + b2
        a2 = sigmoid(z2)
        z3 = np.dot(Theta3, a2) + b3
        y = softmax(z3)
        # Is prediction == target?
        test_predictions.append(np.argmax(y) == np.argmax(t))

    m = len(test_predictions)
    performance = sum(test_predictions)/m
    print('Epoch:', j, 'Test performance:', performance)
</code>```

Output (Every 10 epochs):

```<code>Epoch: 0 Train performance: 0.121
Epoch: 0 Test performance: 0.146
Epoch: 10 Train performance: 0.37
Epoch: 10 Test performance: 0.359
Epoch: 20 Train performance: 0.41
Epoch: 20 Test performance: 0.433
Epoch: 30 Train performance: 0.534
Epoch: 30 Test performance: 0.52
Epoch: 40 Train performance: 0.607
Epoch: 40 Test performance: 0.601
Epoch: 50 Train performance: 0.651
Epoch: 50 Test performance: 0.669
Epoch: 60 Train performance: 0.71
Epoch: 60 Test performance: 0.711
Epoch: 70 Train performance: 0.719
Epoch: 70 Test performance: 0.694
Epoch: 80 Train performance: 0.75
Epoch: 80 Test performance: 0.752
Epoch: 90 Train performance: 0.76
Epoch: 90 Test performance: 0.758
Epoch: 100 Train performance: 0.766
Epoch: 100 Test performance: 0.769
</code>```

But when I introduce Dropout regularization scheme, my network breaks. My code updates for dropout are:

```<code>dropout_prob = 0.5

# Feed forward
x, t = train[i][0], train[i][1]
z1 = np.dot(Theta1, x) + b1
a1 = sigmoid(z1)
mask1 = np.random.random(len(z1))
mask1 = mask1 < dropout_prob
a1 *= mask1
z2 = np.dot(Theta2, a1) + b2
a2 = sigmoid(z2)
mask2 = np.random.random(len(z2))
mask2 = mask2 < dropout_prob
a2 *= mask2
z3 = np.dot(Theta3, a2) + b3
y = softmax(z3)

# Backpropagation
delta3 = (y - t) * softmax_prime(z3)
dTheta3 = np.outer(delta3, a2)
db3 = delta3 * 1

delta2 = np.dot(Theta3.T, delta3) * sigmoid_prime(z2)
dTheta2 = np.outer(delta2, a1)
db2 = delta2 * 1

delta1 = np.dot(Theta2.T, delta2) * sigmoid_prime(z1)
dTheta1 = np.outer(delta1, x)
db1 = delta1 * 1
</code>```

The performance stays at around 0.1 (10%).

Any pointers on where I'm going wrong is much appreciated.

答:
There is a major issue in your implementation of dropout, because you're not scaling the activations on test time. Here's the quote from the great CS231n tutorial:

Crucially, note that in the predict function we are not dropping anymore, but we are performing a scaling of both hidden layer outputs by p.

This is important because at test time all neurons see all their
  inputs, so we want the outputs of neurons at test time to be identical
  to their expected outputs at training time. For example, in case of
  p=0.5, the neurons must halve their outputs at test time to have
  the same output as they had during training time (in expectation).

To see this, consider an output of a neuron x (before dropout). With
  dropout, the expected output from this neuron will become
  px+(1−p)0, because the neuron’s output will be set to zero
  with probability 1−p. At test time, when we keep the neuron always
  active, we must adjust x→px to keep the same expected output.

It can also be shown that performing this attenuation at test time can be
  related to the process of iterating over all the possible binary masks
  (and therefore all the exponentially many sub-networks) and computing
  their ensemble prediction.

The most common solution is to use an inverted dropout, which performs the scaling at train time, leaving the forward pass at test time untouched. This is how it looks like in code:

mask1 = (mask1 < dropout_prob) / dropout_prob
...
mask2 = (mask2 < dropout_prob) / dropout_prob
...
```

Body:
I'm using normalized MNIST dataset (input features = 784). My network architecture is 784-256-256-10: two hidden layers of 256 neurons each using sigmoid activation functions, and softmax activation at 10-neuron output layer. Also I'm using the Cross-Entropy cost function.

Weight matrix initialization:

input_size=784
hidden1_size=256
hidden2_size=256
output_size=10
Theta1 = np.random.randn(hidden1_size, input_size)
b1 = np.random.randn(hidden1_size)

Theta2 = np.random.randn(hidden2_size, hidden1_size)
b2 = np.random.randn(hidden2_size)

Theta3 = np.random.randn(output_size, hidden2_size)
b3 = np.random.randn(output_size)

My network works as expected here:

epochs = 2000
learning_rate = 0.01
for j in range(epochs):
    # total_train is an array of length 50000
    # Each element of total_train is a tuple of: (a) input vector of length 784
    # and (b) the corresponding one-hot encoded label of length 10
    # Similarly, total_test is an array of length 10000
    shuffle(total_train)
    train = total_train[:1000]
    shuffle(total_test)
    test = total_test[:1000]
    predictions = []
    test_predictions = []
    for i in range(len(train)):
        # Feed forward
        x, t = train[i][0], train[i][1]
        z1 = np.dot(Theta1, x) + b1
        a1 = sigmoid(z1)
        z2 = np.dot(Theta2, a1) + b2
        a2 = sigmoid(z2)
        z3 = np.dot(Theta3, a2) + b3
        y = softmax(z3)
        # Is prediction == target?
        predictions.append(np.argmax(y) == np.argmax(t))

        # Negative log probability cost function
        cost = -t * np.log(y)

        # Backpropagation
        delta3 = (y - t) * softmax_prime(z3)
        dTheta3 = np.outer(delta3, a2)
        db3 = delta3

        delta2 = np.dot(Theta3.T, delta3) * sigmoid_prime(z2)
        dTheta2 = np.outer(delta2, a1)
        db2 = delta2

        delta1 = np.dot(Theta2.T, delta2) * sigmoid_prime(z1)
        dTheta1 = np.outer(delta1, x)
        db1 = delta1

        # Update weights
        Theta1 -= learning_rate * dTheta1
        b1 -= learning_rate * db1
        Theta2 -= learning_rate * dTheta2
        b2 -= learning_rate * db2
        Theta3 -= learning_rate * dTheta3
        b3 -= learning_rate * db3

    if j % 10 == 0:
        m = len(predictions)
        performance = sum(predictions)/m
        print('Epoch:', j, 'Train performance:', performance)

    # Test accuracy on test data
    for i in range(len(test)):
        # Feed forward
        x, t = test[i][0], test[i][1]
        z1 = np.dot(Theta1, x) + b1
        a1 = sigmoid(z1)
        z2 = np.dot(Theta2, a1) + b2
        a2 = sigmoid(z2)
        z3 = np.dot(Theta3, a2) + b3
        y = softmax(z3)
        # Is prediction == target?
        test_predictions.append(np.argmax(y) == np.argmax(t))

    m = len(test_predictions)
    performance = sum(test_predictions)/m
    print('Epoch:', j, 'Test performance:', performance)

Output (Every 10 epochs):

Epoch: 0 Train performance: 0.121
Epoch: 0 Test performance: 0.146
Epoch: 10 Train performance: 0.37
Epoch: 10 Test performance: 0.359
Epoch: 20 Train performance: 0.41
Epoch: 20 Test performance: 0.433
Epoch: 30 Train performance: 0.534
Epoch: 30 Test performance: 0.52
Epoch: 40 Train performance: 0.607
Epoch: 40 Test performance: 0.601
Epoch: 50 Train performance: 0.651
Epoch: 50 Test performance: 0.669
Epoch: 60 Train performance: 0.71
Epoch: 60 Test performance: 0.711
Epoch: 70 Train performance: 0.719
Epoch: 70 Test performance: 0.694
Epoch: 80 Train performance: 0.75
Epoch: 80 Test performance: 0.752
Epoch: 90 Train performance: 0.76
Epoch: 90 Test performance: 0.758
Epoch: 100 Train performance: 0.766
Epoch: 100 Test performance: 0.769

But when I introduce Dropout regularization scheme, my network breaks. My code updates for dropout are:

dropout_prob = 0.5

# Feed forward
x, t = train[i][0], train[i][1]
z1 = np.dot(Theta1, x) + b1
a1 = sigmoid(z1)
mask1 = np.random.random(len(z1))
mask1 = mask1 < dropout_prob
a1 *= mask1
z2 = np.dot(Theta2, a1) + b2
a2 = sigmoid(z2)
mask2 = np.random.random(len(z2))
mask2 = mask2 < dropout_prob
a2 *= mask2
z3 = np.dot(Theta3, a2) + b3
y = softmax(z3)

# Backpropagation
delta3 = (y - t) * softmax_prime(z3)
dTheta3 = np.outer(delta3, a2)
db3 = delta3 * 1

delta2 = np.dot(Theta3.T, delta3) * sigmoid_prime(z2)
dTheta2 = np.outer(delta2, a1)
db2 = delta2 * 1

delta1 = np.dot(Theta2.T, delta2) * sigmoid_prime(z1)
dTheta1 = np.outer(delta1, x)
db1 = delta1 * 1

The performance stays at around 0.1 (10%).

Any pointers on where I'm going wrong is much appreciated.


问:
How to Select from an array of arrays
I'm trying to compare json data being streamed in from websockets.

An array like this would work flawlessly:

```<code>["stream","apple","orange"]
</code>```

But an array of arrays not so well:

```<code>[["stream","apple","orange"],["stream","pear","kiwi"],["stream","apple","juice"]]
</code>```

Any help would be greatly appreciated. Thanks in advance!

```<code>function handler(jsonString) {

    var json = jQuery.parseJSON(jsonString);

    if (json[0] == "blah") {
       //Do something
    }

    else if (json[0] == "blah2") {
        //Do something else
    }

}
</code>```

答:
First reference which inner Array you want [0] from the outer, then using the same square bracket notation, reference the item in that inner Array  [0][1].

```<code>if (json[0][0] == "blah") {
   //Do something
}
else if (json[0][1] == "blah2") {
    //Do something else
}
</code>```

So the following examples would produce this:

```<code>json[0][0];  // "stream"
json[0][1];  // "apple"

json[1][0];  // "stream"
json[1][1];  // "pear"

// etc...
</code>```

To iterate over all the items in the Arrays, you'd need a loop inside a loop. The outer one to iterate through the Arrays stored in the outer Array, and the inner loop to iterate through the values of those inner Arrays.

Like this:

```<code>for( var i = 0, len_i = json.length; i < len_i; i++ ) {
    for( var j = 0, len_j = json[ i ].length; j < len_j; j++ ) {
        // do something with json[ i ][ j ]; (the value in the inner Array)
    }
}
</code>```

or if you wanted jQuery.each()(docs):

```<code>jQuery.each( json, function(i,val) {
    jQuery.each( val, function(j,val_j) {
        // do something with val_j (the value in the inner Array)
    });
});
</code>```

I'd prefer the for loops though.

Title: How to Select from an array of arrays

Body:
I'm trying to compare json data being streamed in from websockets.

An array like this would work flawlessly:

["stream","apple","orange"]

But an array of arrays not so well:

[["stream","apple","orange"],["stream","pear","kiwi"],["stream","apple","juice"]]

Any help would be greatly appreciated. Thanks in advance!

function handler(jsonString) {

    var json = jQuery.parseJSON(jsonString);

    if (json[0] == "blah") {
       //Do something
    }

    else if (json[0] == "blah2") {
        //Do something else
    }

}

Body:
First reference which inner Array you want [0] from the outer, then using the same square bracket notation, reference the item in that inner Array  [0][1].

if (json[0][0] == "blah") {
   //Do something
}
else if (json[0][1] == "blah2") {
    //Do something else
}

So the following examples would produce this:

json[0][0];  // "stream"
json[0][1];  // "apple"

json[1][0];  // "stream"
json[1][1];  // "pear"

// etc...

To iterate over all the items in the Arrays, you'd need a loop inside a loop. The outer one to iterate through the Arrays stored in the outer Array, and the inner loop to iterate through the values of those inner Arrays.

Like this:

for( var i = 0, len_i = json.length; i < len_i; i++ ) {
    for( var j = 0, len_j = json[ i ].length; j < len_j; j++ ) {
        // do something with json[ i ][ j ]; (the value in the inner Array)
    }
}

or if you wanted jQuery.each()(docs):

jQuery.each( json, function(i,val) {
    jQuery.each( val, function(j,val_j) {
        // do something with val_j (the value in the inner Array)
    });
});

I'd prefer the for loops though.


问:
AmCharts with multiple dataset and different baloon appearance
I'm using AmCharts to display temperature indications. This data has multiple lines, so I load multiple dataSets in chart. Also I need to display pill giving times. This dataSet must show different text in baloon text. Also I have another problem: only first dataSet is shown in category scroll bar.

How can I do it?

My code sample

```<code>AmCharts.addInitHandler(function(chart) {

  // check if plugin is enabled
  if (chart.syncDataTimestamps !== true)
    return;

  // go thorugh all data sets and collect all the different timestamps
  var dates = {};
   for (var i = 0; i < chart.dataSets.length; i++) {
    var ds = chart.dataSets[i];
    for (var x = 0; x < ds.dataProvider.length; x++) {
      var date = ds.dataProvider[x][ds.categoryField];
      if (dates[date.getTime()] === undefined)
        dates[date.getTime()] = {};
      dates[date.getTime()][i] = ds.dataProvider[x];
    }
  }

  for (var i = 0; i < chart.dataSets.length; i++) {
    var ds = chart.dataSets[i];
    var dp = [];
    for (var ts in dates) {
      if (!dates.hasOwnProperty(ts))
        continue;
      var row = dates[ts];
      if (row[i] === undefined) {
        row[i] = {};
        var d = new Date();
        d.setTime(ts);
        row[i][ds.categoryField] = d;
      }
      dp.push(row[i]);
    }
    dp.sort(function(a,b){
      return new Date(a[ds.categoryField]) - new Date(b[ds.categoryField]);
    });
    ds.dataProvider = dp;
  }

}, ["stock"]);
var chartData1 = [{
  date: new Date(2011, 5, 1, 0, 0, 0, 0),
  value: 10
}, {
  date: new Date(2011, 5, 2, 0, 0, 0, 0),
  value: 11
}, {
  date: new Date(2011, 5, 3, 0, 0, 0, 0),
  value: 12
}, {
  date: new Date(2011, 5, 4, 0, 0, 0, 0),
  value: 11
}, {
  date: new Date(2011, 5, 6, 0, 0, 0, 0),
  value: 11
}, ];

var chartData2 = [{
  date: new Date(2011, 5, 8, 0, 0, 0, 0),
  value: 1
}, {
  date: new Date(2011, 5, 9, 0, 0, 0, 0),
  value: 2
}, {
  date: new Date(2011, 5, 10, 0, 0, 0, 0),
  value: 3
}, {
  date: new Date(2011, 5, 11, 0, 0, 0, 0),
  value: 10
}, {
  date: new Date(2011, 5, 12, 0, 0, 0, 0),
  value: 4
}, ];

var chart = AmCharts.makeChart("chartdiv", {
        //*
        "type": "stock",
        "theme": "light",
        "syncDataTimestamps": true,
        "language": "ru",

        dataSets: [
          {
            title: "temperature1",
            fieldMappings: [
              {
                fromField: "value",
                toField: "value"
              }
            ],
            compared: true,
            dataProvider: chartData1,
            categoryField: "date"
          },
          {
            title: "temperature1",
            fieldMappings: [
              {
                fromField: "value",
                toField: "value"
              }
            ],
            compared: true,
            dataProvider: chartData2,
            categoryField: "date"
          }
        ],

        "categoryAxesSettings": {
            "position": "bottom",
            "parseDates": false,
            "dashLength": 1,
            "minorGridEnabled": false,
            "equalSpacing": false,
            "minPeriod": "ss",
            "gridColor": "fff",
            "position": "top",
            "axisColor": "#f591b3"
        },
        "chartScrollbarSettings": {
            "graph": "g1",
            "position": "bottom",
            "oppositeAxis": false,
            "backgroundAlpha": 0,
            "selectedBackgroundAlpha": 0.4,
            "selectedBackgroundColor": "#F592B3",
            "graphFillAlpha": 0,
            "graphLineAlpha": 0.5,
            "selectedGraphFillAlpha": 0,
            "selectedGraphLineAlpha": 1,
            "color": "#AAAAAA"
        },
        panels: [{
            recalculateToPercents: 'never',

            stockGraphs: [{
                id: "g1",
                valueField: "value",
                comparable: true,
                compareField: "value",
                compareGraphBullet: 'round',
                compareGraphBulletSize: 3,
                "lineColor": "#F591B3",
                compareGraph: {
                    "color": "#F592B3",
                    "baloonColor": "#F591B3",
                    baloon: {
                        "adjustBorderColor": true,
                        "color": "#fff",
                        "cornerRadius": 5,
                        "fillColor": "#F591B3",
                        "fillAlpha": 1,
                        "borderAlpha": 0,
                        "shadowAlpha": 0,
                        "fontSize": 10,
                    },
                    baloonText: "[[value]]"
                },
            }]
        }]
    });
</code>```

答:
AmCharts only supports one graph object inside the scrollbar, which means only the first dataSet is drawn. There is no workaround for this outside of removing the graph from the scrollbar if you don't want it to look different from the chart.

As for the balloons, the relevant properties are called balloon and balloonText - you misspelled balloon as baloon in both cases. Set the desired properties in compareGraph and you're set. You also don't need to set compared: true in the first dataSet object as it will duplicate the balloon in the compared graph.

Updated fiddle

Body:
I'm using AmCharts to display temperature indications. This data has multiple lines, so I load multiple dataSets in chart. Also I need to display pill giving times. This dataSet must show different text in baloon text. Also I have another problem: only first dataSet is shown in category scroll bar.

How can I do it?

My code sample

AmCharts.addInitHandler(function(chart) {

  // check if plugin is enabled
  if (chart.syncDataTimestamps !== true)
    return;

  // go thorugh all data sets and collect all the different timestamps
  var dates = {};
   for (var i = 0; i < chart.dataSets.length; i++) {
    var ds = chart.dataSets[i];
    for (var x = 0; x < ds.dataProvider.length; x++) {
      var date = ds.dataProvider[x][ds.categoryField];
      if (dates[date.getTime()] === undefined)
        dates[date.getTime()] = {};
      dates[date.getTime()][i] = ds.dataProvider[x];
    }
  }

  for (var i = 0; i < chart.dataSets.length; i++) {
    var ds = chart.dataSets[i];
    var dp = [];
    for (var ts in dates) {
      if (!dates.hasOwnProperty(ts))
        continue;
      var row = dates[ts];
      if (row[i] === undefined) {
        row[i] = {};
        var d = new Date();
        d.setTime(ts);
        row[i][ds.categoryField] = d;
      }
      dp.push(row[i]);
    }
    dp.sort(function(a,b){
      return new Date(a[ds.categoryField]) - new Date(b[ds.categoryField]);
    });
    ds.dataProvider = dp;
  }

}, ["stock"]);
var chartData1 = [{
  date: new Date(2011, 5, 1, 0, 0, 0, 0),
  value: 10
}, {
  date: new Date(2011, 5, 2, 0, 0, 0, 0),
  value: 11
}, {
  date: new Date(2011, 5, 3, 0, 0, 0, 0),
  value: 12
}, {
  date: new Date(2011, 5, 4, 0, 0, 0, 0),
  value: 11
}, {
  date: new Date(2011, 5, 6, 0, 0, 0, 0),
  value: 11
}, ];

var chartData2 = [{
  date: new Date(2011, 5, 8, 0, 0, 0, 0),
  value: 1
}, {
  date: new Date(2011, 5, 9, 0, 0, 0, 0),
  value: 2
}, {
  date: new Date(2011, 5, 10, 0, 0, 0, 0),
  value: 3
}, {
  date: new Date(2011, 5, 11, 0, 0, 0, 0),
  value: 10
}, {
  date: new Date(2011, 5, 12, 0, 0, 0, 0),
  value: 4
}, ];

var chart = AmCharts.makeChart("chartdiv", {
        //*
        "type": "stock",
        "theme": "light",
        "syncDataTimestamps": true,
        "language": "ru",

        dataSets: [
          {
            title: "temperature1",
            fieldMappings: [
              {
                fromField: "value",
                toField: "value"
              }
            ],
            compared: true,
            dataProvider: chartData1,
            categoryField: "date"
          },
          {
            title: "temperature1",
            fieldMappings: [
              {
                fromField: "value",
                toField: "value"
              }
            ],
            compared: true,
            dataProvider: chartData2,
            categoryField: "date"
          }
        ],

        "categoryAxesSettings": {
            "position": "bottom",
            "parseDates": false,
            "dashLength": 1,
            "minorGridEnabled": false,
            "equalSpacing": false,
            "minPeriod": "ss",
            "gridColor": "fff",
            "position": "top",
            "axisColor": "#f591b3"
        },
        "chartScrollbarSettings": {
            "graph": "g1",
            "position": "bottom",
            "oppositeAxis": false,
            "backgroundAlpha": 0,
            "selectedBackgroundAlpha": 0.4,
            "selectedBackgroundColor": "#F592B3",
            "graphFillAlpha": 0,
            "graphLineAlpha": 0.5,
            "selectedGraphFillAlpha": 0,
            "selectedGraphLineAlpha": 1,
            "color": "#AAAAAA"
        },
        panels: [{
            recalculateToPercents: 'never',

            stockGraphs: [{
                id: "g1",
                valueField: "value",
                comparable: true,
                compareField: "value",
                compareGraphBullet: 'round',
                compareGraphBulletSize: 3,
                "lineColor": "#F591B3",
                compareGraph: {
                    "color": "#F592B3",
                    "baloonColor": "#F591B3",
                    baloon: {
                        "adjustBorderColor": true,
                        "color": "#fff",
                        "cornerRadius": 5,
                        "fillColor": "#F591B3",
                        "fillAlpha": 1,
                        "borderAlpha": 0,
                        "shadowAlpha": 0,
                        "fontSize": 10,
                    },
                    baloonText: "[[value]]"
                },
            }]
        }]
    });


问:
Validation in Business Layer: How to call service methods?
I have created a struct on validating models on Business Layer which is based on Steven's answer.

It is working well but something confuses my mind. I inject UserService in CreateUserValidator to able to use GetUser method. This means I call validator in UserService and create a new UserService instance to check whether user exist.

UserService ->  [ValidateUser -> new UserService().GetUser()]

It works but seems to be a very bad design. But I have to use that method.

Could you please let me know how I can solve this problem, or Shouldn't I worry about it?

```<code>public class CreateUser
{
    public string Name { get; set; }
    public string Email { get; set; }
}

public sealed class CreateUserValidator : Validator<CreateUser>
{
    private IUserService _userService;
    public CreateUserValidator(IUserService userService)
    {
        _userService = userService;
    }
    protected override IEnumerable<ValidationResult> Validate(
        CreateUser entity)
    {

        var user = _userService.GetUserByEmail(entity.Email);
        if (user != null)
        {
            yield return new ValidationResult("Email", "Email address is already exist!");
        }
    }
}
</code>```

UserService.cs

```<code>public partial class UserService : IUserService
{
    IGenericUnitofWork _uow = null;
    private readonly IValidationProvider _validationProvider;
    public UserService(IGenericUnitofWork uow, IValidationProvider validationProvider)
    {
        _uow = uow;
        _validationProvider = validationProvider;
    }

    public User CreateUser(CreateUser createUser)
    {
        this._validationProvider.Validate(createUser);

        var user = new User()
        {
            Email = createUser.Email,
            Name = createUser.Name,
        };
        _uow.Repository<User>().Insert(User);
        _uow.SaveChanges();
        return user;
    }

    public User GetUser(string email)
    {
        var user = _uow.Repository<User>().Where(m => m.Email == email).FirstOrDefault();
        return user;
    }
}
</code>```

答:
You dependency graph is cyclic. As described in section 6.3 of Dependency Injection in .NET second edition, dependency cycles are often caused by Single Responsibility Principle violations, as is the case in your design.

The problem is that UserService has too many responsibilities: Creating a user is a different responsibility than getting a user. Creating a user can become a very complex use case, as the validation logic hints at, while getting a user is something typically quite simple. It would therefore be beneficial to split UserService into multiple smaller classes. This would allow the validator to depend on the service that allows retrieving the user by its mail address, while the 'create user' service can depend on the validator.

To take it even one step further, you might want to remove validation from the 'create user' service completely. Validation is a cross-cutting concern, and mixing it with the class that contains the business logic, makes such class harder to maintain.

A design that might benefit you is one where you place all state changing business actions behind a common abstraction, as described here.

Body:
I have created a struct on validating models on Business Layer which is based on Steven's answer.

It is working well but something confuses my mind. I inject UserService in CreateUserValidator to able to use GetUser method. This means I call validator in UserService and create a new UserService instance to check whether user exist.

UserService ->  [ValidateUser -> new UserService().GetUser()]

It works but seems to be a very bad design. But I have to use that method.

Could you please let me know how I can solve this problem, or Shouldn't I worry about it?

public class CreateUser
{
    public string Name { get; set; }
    public string Email { get; set; }
}

public sealed class CreateUserValidator : Validator<CreateUser>
{
    private IUserService _userService;
    public CreateUserValidator(IUserService userService)
    {
        _userService = userService;
    }
    protected override IEnumerable<ValidationResult> Validate(
        CreateUser entity)
    {

        var user = _userService.GetUserByEmail(entity.Email);
        if (user != null)
        {
            yield return new ValidationResult("Email", "Email address is already exist!");
        }
    }
}

UserService.cs

public partial class UserService : IUserService
{
    IGenericUnitofWork _uow = null;
    private readonly IValidationProvider _validationProvider;
    public UserService(IGenericUnitofWork uow, IValidationProvider validationProvider)
    {
        _uow = uow;
        _validationProvider = validationProvider;
    }

    public User CreateUser(CreateUser createUser)
    {
        this._validationProvider.Validate(createUser);

        var user = new User()
        {
            Email = createUser.Email,
            Name = createUser.Name,
        };
        _uow.Repository<User>().Insert(User);
        _uow.SaveChanges();
        return user;
    }

    public User GetUser(string email)
    {
        var user = _uow.Repository<User>().Where(m => m.Email == email).FirstOrDefault();
        return user;
    }
}


问:
Error handling checking database with else if for existing email
Im stuck with some code. Im pretty new to this.

If the else statement ($uidcheck) returns false it should execute the elseif statement ($emailcheck). See code below.

```<code>$username = $_POST['username'];
$email = $_POST['email'];
$pwd = $_POST['pwd'];

if (empty($username)) {
    header("Location: ../signup.php?error=empty");
    exit();
}
if (empty($email)) {
    header("Location: ../signup.php?error=empty");
    exit();
}
if (empty($pwd)) {
    header("Location: ../signup.php?error=empty");
    exit();

} else {
        $sql = "SELECT username FROM user WHERE username='$username'";
        $result = mysqli_query($conn, $sql);
        $uidcheck = mysqli_num_rows($result);
        if ($uidcheck > 0) {
            header("Location: ../signup.php?error=username");
            exit();

    } elseif ($uidcheck < 0) {

        $sql = "SELECT email FROM user WHERE email='$email'";
        $result = mysqli_query($conn, $sql);
        $emailcheck = mysqli_num_rows($result);
        if ($emailcheck > 0) {
            header("Location: ../signup.php?error=email");
            exit();

        } else {

            $sql = "INSERT INTO user (username, email, pwd)
            VALUES ('$username', '$email', '$pwd')";
            $result = mysqli_query($conn, $sql);

            header("Location: ../index.php");
        }

    }
}
</code>```

When the emailadress already exists in the database it should exit and add a parameter to the header.

Thanks in advance!

Sven

答:
Your code may does the purpose. But that is not good enough to read/debug.

```<code>if( !isset($_POST["username"]) || !isset($_POST["email"]) || !isset($_POST["pwd"]) || empty($_POST["username"]) || empty($_POST["email"]) || empty($_POST["pwd"]) )
{
    header("Location: ../signup.php?error=empty");
    exit();
}
$sql = "SELECT username FROM user WHERE username='".mysqli_real_escape_string($username)."'";
$result = mysqli_query($conn, $sql);
$uidcheck = mysqli_num_rows($result);
if ($uidcheck > 0)
{
    header("Location: ../signup.php?error=username");
    exit();
}
else
{
    $sql = "SELECT email FROM user WHERE email='".mysqli_real_escape_string($email)."'";
    $result = mysqli_query($conn, $sql);
    $emailcheck = mysqli_num_rows($result);
    if ($emailcheck > 0) {
        header("Location: ../signup.php?error=email");
        exit();
    }
    else {
        $sql = "INSERT INTO user (username, email, pwd)
            VALUES ('$username', '$email', '$pwd')";
        $result = mysqli_query($conn, $sql);
        header("Location: ../index.php");
    }
}
</code>```

Here are my Recommendations:

Always check if an variable is declared in the scope using isset() function. If the value of "username" or "email or "pwd" is not submitted in the POST request, your code will throw a Fatal Exception and rendering stops there.....

Don't put the value submitted by the User directly into the SQL query....This will make your web application Vulnerable to SQL Injection Attack.

Body:
Im stuck with some code. Im pretty new to this.

If the else statement ($uidcheck) returns false it should execute the elseif statement ($emailcheck). See code below.

$username = $_POST['username'];
$email = $_POST['email'];
$pwd = $_POST['pwd'];

if (empty($username)) {
    header("Location: ../signup.php?error=empty");
    exit();
}
if (empty($email)) {
    header("Location: ../signup.php?error=empty");
    exit();
}
if (empty($pwd)) {
    header("Location: ../signup.php?error=empty");
    exit();

} else {
        $sql = "SELECT username FROM user WHERE username='$username'";
        $result = mysqli_query($conn, $sql);
        $uidcheck = mysqli_num_rows($result);
        if ($uidcheck > 0) {
            header("Location: ../signup.php?error=username");
            exit();

    } elseif ($uidcheck < 0) {

        $sql = "SELECT email FROM user WHERE email='$email'";
        $result = mysqli_query($conn, $sql);
        $emailcheck = mysqli_num_rows($result);
        if ($emailcheck > 0) {
            header("Location: ../signup.php?error=email");
            exit();

        } else {

            $sql = "INSERT INTO user (username, email, pwd)
            VALUES ('$username', '$email', '$pwd')";
            $result = mysqli_query($conn, $sql);

            header("Location: ../index.php");
        }

    }
}

When the emailadress already exists in the database it should exit and add a parameter to the header.

Thanks in advance!

Sven

Body:
Your code may does the purpose. But that is not good enough to read/debug.

if( !isset($_POST["username"]) || !isset($_POST["email"]) || !isset($_POST["pwd"]) || empty($_POST["username"]) || empty($_POST["email"]) || empty($_POST["pwd"]) )
{
    header("Location: ../signup.php?error=empty");
    exit();
}
$sql = "SELECT username FROM user WHERE username='".mysqli_real_escape_string($username)."'";
$result = mysqli_query($conn, $sql);
$uidcheck = mysqli_num_rows($result);
if ($uidcheck > 0)
{
    header("Location: ../signup.php?error=username");
    exit();
}
else
{
    $sql = "SELECT email FROM user WHERE email='".mysqli_real_escape_string($email)."'";
    $result = mysqli_query($conn, $sql);
    $emailcheck = mysqli_num_rows($result);
    if ($emailcheck > 0) {
        header("Location: ../signup.php?error=email");
        exit();
    }
    else {
        $sql = "INSERT INTO user (username, email, pwd)
            VALUES ('$username', '$email', '$pwd')";
        $result = mysqli_query($conn, $sql);
        header("Location: ../index.php");
    }
}

Here are my Recommendations:

Always check if an variable is declared in the scope using isset() function. If the value of "username" or "email or "pwd" is not submitted in the POST request, your code will throw a Fatal Exception and rendering stops there.....

Don't put the value submitted by the User directly into the SQL query....This will make your web application Vulnerable to SQL Injection Attack.


问:
Fibonacci sequence in Haskell
I am trying to build a fibonacci wrapper function that takes in multiple command line arguments and computes the associated Fibonacci number for each argument</p>

答:
Wrapper solution could be:

```<code>wrapperStringToInt :: [String] -> [Int]
wrapperStringToInt [] = []
wrapperStringToInt (x:xs) = (read x :: Int) : wrapperStringToInt xs
</code>```

You could use tuples to return fibonacci 4 is 3. The function printFibonacci prints that for each tuple.

```<code>printFibonacci :: [(Int, Int)] -> IO ()
printFibonacci [] = return ()
printFibonacci ((x, z):xs) =
    do  putStrLn $ "fibonacci " ++ show x ++ " is " ++ show z
        printFibonacci xs
</code>```

The command

```<code>map f (wrapperStringToInt arguments)
    where
        f = (\ x -> (x, fibonacci x))
</code>```

returns an array with tuples ( Input, Output ) (e.g. With [3,4,5] this command returns [(3,2),(4,3),(5,5)]).

```<code>main = do
    arguments <- getArgs
    printFibonacci $ map f (wrapperStringToInt arguments)
        where f = (\ x -> (x, fibonacci x))
</code>```

After that, run in the terminal:

```<code>runhaskell Fibonacci.hs <INPUT>
</code>```

(e.g. runhaskell Fibonacci.hs 3 4 5)

Finally, to execute this program like ./program 4 5 6, you could write an executable bash program, for example:

```<code>#!/bin/bash
runhaskell Fibonacci.hs "$@"
</code>```

If error control is important you should use Maybe as other users have commented. I hope you find this information useful.

Title: Fibonacci sequence in Haskell

Body:
Wrapper solution could be:

wrapperStringToInt :: [String] -> [Int]
wrapperStringToInt [] = []
wrapperStringToInt (x:xs) = (read x :: Int) : wrapperStringToInt xs

You could use tuples to return fibonacci 4 is 3. The function printFibonacci prints that for each tuple.

printFibonacci :: [(Int, Int)] -> IO ()
printFibonacci [] = return ()
printFibonacci ((x, z):xs) =
    do  putStrLn $ "fibonacci " ++ show x ++ " is " ++ show z
        printFibonacci xs

The command

map f (wrapperStringToInt arguments)
    where
        f = (\ x -> (x, fibonacci x))

returns an array with tuples ( Input, Output ) (e.g. With [3,4,5] this command returns [(3,2),(4,3),(5,5)]).

main = do
    arguments <- getArgs
    printFibonacci $ map f (wrapperStringToInt arguments)
        where f = (\ x -> (x, fibonacci x))

After that, run in the terminal:

runhaskell Fibonacci.hs <INPUT>

(e.g. runhaskell Fibonacci.hs 3 4 5)

Finally, to execute this program like ./program 4 5 6, you could write an executable bash program, for example:

#!/bin/bash
runhaskell Fibonacci.hs "$@"

If error control is important you should use Maybe as other users have commented. I hope you find this information useful.


问:
window.print() not working in Chrome
In the below code, the window.print() function not working in Chrome.what to do?

 <input type="text" placeholder="Enter Item Name" size="20">

 <input type="num" placeholder="quantity" size="20" id="qty">

 <input type="text" placeholder="prize" size="20" id="rs"> <button onclick="mul()" id="add">add </button>

 <input type="text"  size="20" id="amt">  <input type="text" size="7" id="total"> <button onclick="print()" id="print"> print

```

答:
It is because of it went on infinite loop. The code onclick="print()" will automatically call the window.print().

Either you change the function name or remove the print function. It will work.

Title: window.print() not working in Chrome


问:
Parsing JSON result from Nodejs mssql result
I have a NodeJS app calling a MSSqlserver stored procs and returns a JSON result.

How do I parse the JSON result to get only this value

```<code>[{"DataMartCode":"NPL","DataMartDescription":null},{"DataMartCode":"FP","DataMartDescription":"Only for Banks that report Funding Plans"}]
</code>```

JSON result

```<code>{
    recordsets:[
        [
            {
                JSON_F52E2B61-18A1-11d1 - B105-00805F49916B:"[{"DataMartCode":"NPL","DataMartDescription":null},{"DataMartCode":"FP","DataMartDescription":"Only for Banks that report Funding Plans"}]"
            }
        ]
    ],
    recordset:[
        {
            JSON_F52E2B61-18A1-11d1 - B105-00805F49916B:"[{"DataMartCode":"NPL","DataMartDescription":null},{"DataMartCode":"FP","DataMartDescription":"Only for Banks that report Funding Plans"}]"
        }
    ],
    output: {},
    rowsAffected:[11],
    returnValue:0
}
</code>```

Javascript

```<code>var express = require('express');
var router = express.Router();
var sql = require('mssql');

/* GET home page. */
router.get('/', function(req, res, next) {
    res.render('index',  {title:'Express'});
});

// SQL Server config
var config =  {
    user:'user',
    password:'pass',
    server:'localhost',
    database:'mydb'
};

router.get('/datamart', function (req, res) {

    // connect to your database
    sql.connect(config, function (err) {
        if (err)console.log(err);

        // create Request object
        var request = new sql.Request();

        // query to the database and get the data
        request.execute('dbo.get_datamart', function (err, result) {
            if (err)console.log(err)

            // send data as a response
            console.log(result.recordset);
            res.send(result);

            sql.close();
        });

    });

});

module.exports = router;
</code>```

答:
note that your json is not a valid json and i had to fix it manually. also you can upgrade my answer with recursion that check if array has array in it and so on. but this will work to

results = {
    recordsets:[
        [
            {
                "JSON_F52E2B61-18A1-11d1 - B105-00805F49916B":[{"DataMartCode":"NPL","DataMartDescription":null},{"DataMartCode":"FP","DataMartDescription":"Only for Banks that report Funding Plans"}]
            }
        ]
    ],
    recordset:[
        {
            "JSON_F52E2B61-18A1-11d1 - B105-00805F49916B":[{"DataMartCode":"NPL","DataMartDescription":null},{"DataMartCode":"FP","DataMartDescription":"Only for Banks that report Funding Plans"}]
        }
    ],
    output: {},
    rowsAffected:[11],
    returnValue:0
}
let newResults = [];
for(let key in results){
   if(key === "recordsets"){
      results[key].forEach(arr =>{
        arr.forEach(obj =>{
            Object.keys(obj).forEach((key) =>{
              newResults.push(obj[key])
            })
          });
      })
   }
}
console.log(newResults)```

Body:
I have a NodeJS app calling a MSSqlserver stored procs and returns a JSON result.

How do I parse the JSON result to get only this value

[{"DataMartCode":"NPL","DataMartDescription":null},{"DataMartCode":"FP","DataMartDescription":"Only for Banks that report Funding Plans"}]

JSON result

{
    recordsets:[
        [
            {
                JSON_F52E2B61-18A1-11d1 - B105-00805F49916B:"[{"DataMartCode":"NPL","DataMartDescription":null},{"DataMartCode":"FP","DataMartDescription":"Only for Banks that report Funding Plans"}]"
            }
        ]
    ],
    recordset:[
        {
            JSON_F52E2B61-18A1-11d1 - B105-00805F49916B:"[{"DataMartCode":"NPL","DataMartDescription":null},{"DataMartCode":"FP","DataMartDescription":"Only for Banks that report Funding Plans"}]"
        }
    ],
    output: {},
    rowsAffected:[11],
    returnValue:0
}

Javascript

var express = require('express');
var router = express.Router();
var sql = require('mssql');

/* GET home page. */
router.get('/', function(req, res, next) {
    res.render('index',  {title:'Express'});
});

// SQL Server config
var config =  {
    user:'user',
    password:'pass',
    server:'localhost',
    database:'mydb'
};

router.get('/datamart', function (req, res) {

    // connect to your database
    sql.connect(config, function (err) {
        if (err)console.log(err);

        // create Request object
        var request = new sql.Request();

        // query to the database and get the data
        request.execute('dbo.get_datamart', function (err, result) {
            if (err)console.log(err)

            // send data as a response
            console.log(result.recordset);
            res.send(result);

            sql.close();
        });

    });

});

module.exports = router;