问:
`cin` incorrectly parses `double` input on Mac
A little bit of background - I'm new to learning C++. I'm working through Accelerated C++ and following things along. In chapter 4, the code I've got doesn't quite work as the book suggests, and I've double-checked all my of code to make sure I'm not mis-typing something from their example (I can't see any errors, anyway).

I have the following struct and two functions:

```<code>struct Student {
  std::string        name;
  double             midtermGrade, finalGrade;
  std::vector<double>homework;
};

std::istream& read(std::istream& is, Student& s) {
  is >> s.name >> s.midtermGrade >> s.finalGrade;

  std::cout << std::endl << "Name: " << s.name << std::endl
            << " - Md: " << s.midtermGrade << std::endl
            << " - Fn: " << s.finalGrade << std::endl;

  read_hw(is, s.homework);

  return is;
}

std::istream& read_hw(std::istream& in, std::vector<double>& hw) {
  if (in) {
    hw.clear();

    double h;

    while (in >> h) {
      std::cout << " - Hw: " << h << std::endl;
      hw.push_back(h);
    }

    in.clear();
  }

  return in;
}
</code>```

In int main() I'm calling that code like this:

```<code>Student record;
while (read(std::cin, record)) {
</code>```

If I compile and run, then paste (or type) in the following input, I get the following output:

```<code>// Input
Johnny 70 80 50 Fred 95 90 100 Joe 40 40 50

// Output
Name: Johnny
 - Md: 70
 - Fn: 80
 - Hw: 50

Name: red
 - Md: 95
 - Fn: 90
 - Hw: 100

Name: Joe
 - Md: 40
 - Fn: 40
 - Hw: 50
</code>```

As you can see, "Fred" has become "red". I've tried this with a whole bunch of names; anything starting with A-F is affected by the same issue, which caused me to suspect it may be a hexadecimal issue. However, "Nick" becomes "k" and "Xander" simply becomes "r".

I'm utterly baffled. Do you have any idea what's going on?

As requested, here's a MCVE:

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

struct Student {
  std::string        name;
  double             midtermGrade, finalGrade;
  std::vector<double>homework;
};

std::istream& read_hw(std::istream& in, std::vector<double>& hw) {
  if (in) {
    hw.clear();

    double h;

    while (in >> h) {
      std::cout << " - Hw: " << h << std::endl;
      hw.push_back(h);
    }

    in.clear();
  }

  return in;
}

std::istream& read(std::istream& is, Student& s) {
  is >> s.name >> s.midtermGrade >> s.finalGrade;

  std::cout << std::endl << "Name: " << s.name << std::endl
            << " - Md: " << s.midtermGrade << std::endl
            << " - Fn: " << s.finalGrade << std::endl;

  read_hw(is, s.homework);

  return is;
}

int main()
{
  Student record;

  std::vector<Student> students;

  while (read(std::cin, record)) {}

  return 0;
}
</code>```

答:
Having looked into this further, it would appear that libc++ doesn't read doubles from cin in the way you'd except. I'm not sure if it's only specifically doubles, but I think it might be. It only appears to affect the Clang compiler on OSX, and it's really annoying :P

For the TL;DR version please see David's answer which I've accepted.

I'm not currently aware of any good fix for it, but if you add the compiler flag -stdlib=libstdc++ you can force it to use an older, deprecated stdlib which will work as expected. Obviously it has less features (in my example, std::sort and std::domain_error were missing). Other options include not using double and doing further parsing on the input (although as I'm new to C++, I don't have a scooby on that one I'm afraid).

Related reading:

Trying to read lines from an ASCII file using C++ , Ubuntu vs Mac...?

C++ - Reading a double, followed by a character, from cin

std::istringstream >> to double weird behaviour

http://clang-developers.42468.n3.nabble.com/g-4-2-8-vs-libc-bug-td4051616.html

https://hg.mozilla.org/mozilla-central/raw-rev/edd76ca3717f

The official bug report was opened 3.5 years ago and still hasn't been resolved.

Body:
A little bit of background - I'm new to learning C++. I'm working through Accelerated C++ and following things along. In chapter 4, the code I've got doesn't quite work as the book suggests, and I've double-checked all my of code to make sure I'm not mis-typing something from their example (I can't see any errors, anyway).

I have the following struct and two functions:

struct Student {
  std::string        name;
  double             midtermGrade, finalGrade;
  std::vector<double>homework;
};

std::istream& read(std::istream& is, Student& s) {
  is >> s.name >> s.midtermGrade >> s.finalGrade;

  std::cout << std::endl << "Name: " << s.name << std::endl
            << " - Md: " << s.midtermGrade << std::endl
            << " - Fn: " << s.finalGrade << std::endl;

  read_hw(is, s.homework);

  return is;
}

std::istream& read_hw(std::istream& in, std::vector<double>& hw) {
  if (in) {
    hw.clear();

    double h;

    while (in >> h) {
      std::cout << " - Hw: " << h << std::endl;
      hw.push_back(h);
    }

    in.clear();
  }

  return in;
}

In int main() I'm calling that code like this:

Student record;
while (read(std::cin, record)) {

If I compile and run, then paste (or type) in the following input, I get the following output:

// Input
Johnny 70 80 50 Fred 95 90 100 Joe 40 40 50

// Output
Name: Johnny
 - Md: 70
 - Fn: 80
 - Hw: 50

Name: red
 - Md: 95
 - Fn: 90
 - Hw: 100

Name: Joe
 - Md: 40
 - Fn: 40
 - Hw: 50

As you can see, "Fred" has become "red". I've tried this with a whole bunch of names; anything starting with A-F is affected by the same issue, which caused me to suspect it may be a hexadecimal issue. However, "Nick" becomes "k" and "Xander" simply becomes "r".

I'm utterly baffled. Do you have any idea what's going on?

As requested, here's a MCVE:

#include <iomanip>
#include <iostream>
#include <string>
#include <vector>

struct Student {
  std::string        name;
  double             midtermGrade, finalGrade;
  std::vector<double>homework;
};

std::istream& read_hw(std::istream& in, std::vector<double>& hw) {
  if (in) {
    hw.clear();

    double h;

    while (in >> h) {
      std::cout << " - Hw: " << h << std::endl;
      hw.push_back(h);
    }

    in.clear();
  }

  return in;
}

std::istream& read(std::istream& is, Student& s) {
  is >> s.name >> s.midtermGrade >> s.finalGrade;

  std::cout << std::endl << "Name: " << s.name << std::endl
            << " - Md: " << s.midtermGrade << std::endl
            << " - Fn: " << s.finalGrade << std::endl;

  read_hw(is, s.homework);

  return is;
}

int main()
{
  Student record;

  std::vector<Student> students;

  while (read(std::cin, record)) {}

  return 0;
}


来源: stackexchange

问:
Python 2 on MAC OSX in Visual Studio Code
I am a Python 2 developer and I have everything working fine in Windows 7 visual studio 2015. I was wondering if anyone got the IDE and Visual Studio Code working on a Mac in OS X. If so, maybe you could give a few hints on setting it up and downloading. Thanks.</p>

答:
I would recommend you to use brew to install all this on your mac. It is a package manager such as apt in Debian Linux or composer for php.

You can find all informations here: https://brew.sh

I know it is probably to late after 9 month and you already managed everything.

ContentLicense: CC BY-SA 3.0


问:
Display RTSP live stream in the web browser using java and Web Socket
I want to write a java program that decodes an RTSP live stream, coming from an Ip camera and sends it to an HTML5 web client over web Sockets.
I can do that when it comes to a simple mp4 file on my pc. My code looks like this:

JAVA

```<code>@ServerEndpoint("/echo")
public class EchoEndPoint {

@OnMessage
public byte[] echo(String message) {
    File file = new File("/home/maher/devTools/video/testVideo.mp4");
    byte[] data = new byte[(int) file.length()];
    DataInputStream stream = null;
    try {
        stream = new DataInputStream(new FileInputStream(file));
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    if (stream != null) {
        try {
            stream.readFully(data);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            stream.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return data;
    }
  }
</code>```

HTML

```<code><!DOCTYPE html>
<html>
<head>
<title>Test streaming over WebSockets</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<script language="javascript" type="text/javascript">
    var wsUri = "ws://localhost:7070/serverWs/echo";
    function init() {
        websocket = new WebSocket(wsUri);
        websocket.onmessage = function (evt) {
            readFile(evt.data);
        };
    }
    function readFile(fileData) {
        var video = document.getElementById('area');
        video.src = window.URL.createObjectURL(fileData);
    }
    function createObjectURL(file) {
        if (window.webkitURL) {
            return window.webkitURL.createObjectURL(file);
        } else if (window.URL && window.URL.createObjectURL) {
            return window.URL.createObjectURL(file);
        } else {
            return null;
        }
    }
    function startVideo() {
        var message = "startVideo";
        websocket.send(message);
    }
    window.addEventListener("load", init, false);
</script>
</head>

<body>
<h2 style="text-align: center;">Client WebSocket Echo</h2>
<div style="text-align: center;">
<input onclick="startVideo()" value="Start video" type="button">
</div>
<div>
<video id='area' controls="controls" autoplay></video>
</div>

</body>
</html>
</code>```

But when it comes to a live RTSP streaming URL, I cannot find a way to decode the stream and send it over WS then display that stream in my web page.

答:
Unless you really want to do it yourself for educational purposes or to meet some other requirement, you will likely find it easier to build your service around an existing streaming server.

This is because video streaming is quite a specialist area, and there are many codecs, containers, streaming protocol etc which you may need to convert between to support different end devices, browsers etc.

Additionally, if you want to provide a good user experience you may want to offer the live stream in multiple bit rates so that client can switch between them depending on its current network conditions, screen size etc.

Most Streaming servers will support transcoding videos into different formats and streaming multiple bit rates for Adaptive Bit Rate streaming.

GStreamer (https://gstreamer.freedesktop.org) is an open source streamer which you may find will meet your needs - even if it does not it will be a good reference implementation to look at.

You can see info on its RTSP support here: https://gstreamer.freedesktop.org/documentation/rtp.html

Body:
I want to write a java program that decodes an RTSP live stream, coming from an Ip camera and sends it to an HTML5 web client over web Sockets.
I can do that when it comes to a simple mp4 file on my pc. My code looks like this:

JAVA

@ServerEndpoint("/echo")
public class EchoEndPoint {

@OnMessage
public byte[] echo(String message) {
    File file = new File("/home/maher/devTools/video/testVideo.mp4");
    byte[] data = new byte[(int) file.length()];
    DataInputStream stream = null;
    try {
        stream = new DataInputStream(new FileInputStream(file));
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    if (stream != null) {
        try {
            stream.readFully(data);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            stream.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return data;
    }
  }

HTML

<!DOCTYPE html>

<title>Test streaming over WebSockets</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">

Client WebSocket Echo

<input onclick="startVideo()" value="Start video" type="button">

<video id='area' controls="controls" autoplay></video>

But when it comes to a live RTSP streaming URL, I cannot find a way to decode the stream and send it over WS then display that stream in my web page.


问:
How can I update swift from 3.1 to 3.2, but not to 4.0
I have checked the question related to how to find the current Swift version by the command swift --version, but how can I upgrade my Swift version from 3.1 to 3.2? (because the Xcode 9 only supports Swift 4.0 & Swift 3.2)

To build successfully both in Xcode 8 & Xcode 9, it's better to upgrade Swift from 3.1 to 3.2. But how?

My target was to make sure build successfully both in Xcode 8 & Xcode 9, So that publish with Xcode 8 would be OK, and try out the feature of Xcode 9 is OK too. So I will not upgrade code to swift 4.0 yet until Xcode 9.0 official edition is published.

After my test, I can't convert my code from swift 3.1 to 3.2 by Xcode 8.3.3's 'edit->convert' function.

The reason why I try to convert the code to Swift 3.2 is that I will get error of "Module compiled with Swift 3.1 cannot be imported in Swift 4.0" if I build the code with Xcode 9.

答:
Swift 3.2 is a stopgap solution to continue using Swift 3 code under Xcode 9 without fully converting projects to Swift 4.

The Swift version included in Xcode 8.3.3 is 3.1. Converting your code to Swift 3.2 under Xcode 9 does not guarantee that it will still compile under Xcode 8.

I'm not sure compiling Swift 3.1 code as Swift 3.2 under Xcode 9 requires any conversion at all, since they both share the same syntax. You may have to fix some API calls to compensate for changes in the new SDKs.

Apple has a little more information here:

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Compatibility.html

(updated)

Regarding your last image, if you have the source code for the Runes module, you'll have to recompile it under Xcode 9. That will make use of Swift 3.2 and allow it to be imported in Swift 4.


问:
Response time of solr instance with shards and no shards
When I test my solr instance, it turns out instance with no shard has a shorter response time than instance with shards. So, why?</p>

答:
This is basically because, in solrcloud mode, your query will first need to be sent out to all the nodes involved. All the nodes will then return the results to the original node that was queried, which will then collate the results and return them to you. The overhead of distributing the requests and collating the results is what increases the response time.

This is in contrast with standalone mode, where only one server will be queried and will return the response.

See the documentation here for details.


问:
How can I use Webview to load a web page in UWP
// I want my Application to point to a particular page of a site and display it on webview, I tried this but not working

```<code>string site = "https://google.com";
myweb.Navigate(new Uri(site));
</code>```

答:
try the following: </p>

```<code>string site = @"https://google.com";
myweb.Navigate(new Uri(site));
</code>```

<p>or </p>

```<code>myweb.Navigate(new Uri(@"https://www.google.com"));
</code>```

Body:
// I want my Application to point to a particular page of a site and display it on webview, I tried this but not working

string site = "https://google.com";
myweb.Navigate(new Uri(site));

Body:
try the following:

string site = @"https://google.com";
myweb.Navigate(new Uri(site));

or

myweb.Navigate(new Uri(@"https://www.google.com"));


问:
Visual Studio NuGet Cannot Restore Packages
I have a large project that has about a dozen dependencies. I have tried to install them all but ran into an error from VS. I am using Visual Studio 2015

"An error occurred while trying to restore packages: Unable to find version '3.0.3.1' of package'Lucene.Net.Core'."

Now I have a solution which I can use that is by the same name as this package, but VS refuses to let me updates, remove, or change ANYTHING related to these packages and asks that I restore the packages. I am entirely lost here friends, what should I do?

P.S. the two sources I am using for my package sources are:

https://www.nuget.org/api/v2/

https://www.nuget.org/api/v2/curated-feeds/microsoftdotnet/

The same error occurs for Lucene.Net.Contrib, pstsdk.net, and various packages.

答:
"An error occurred while trying to restore packages: Unable to find version '3.0.3.1' of package'Lucene.Net.Core'."

When I use the packages sources which you provided, I found that only two versions (4.8.0 & 4.9.0) of package"Lucene.Net.Core" not have the version '3.0.3.1'.

Pay Attention:

I noticed that the author of this package have updated this package at March 11, 2017(3/11/2017), and only release the version 4.8.0 & 4.9.0. So this must be the reason for NuGet restore failed.

Besides, you said:

I have a solution which I can use that is by the same name as this
  package, but VS refuses to let me updates, remove, or change ANYTHING
  related to these packages

If you want to remove those error packages, you can try to use below command to force uninstall those packages:

```<code>Uninstall-Package Lucene.Net.Core -Force
</code>```

Or you can delete this package from the package folder and delete the package list from the package.config.

Then install the correct version of the packages.

Body:
"An error occurred while trying to restore packages: Unable to find version '3.0.3.1' of package'Lucene.Net.Core'."

When I use the packages sources which you provided, I found that only two versions (4.8.0 & 4.9.0) of package"Lucene.Net.Core" not have the version '3.0.3.1'.

Pay Attention:

I noticed that the author of this package have updated this package at March 11, 2017(3/11/2017), and only release the version 4.8.0 & 4.9.0. So this must be the reason for NuGet restore failed.

Besides, you said:

I have a solution which I can use that is by the same name as this
  package, but VS refuses to let me updates, remove, or change ANYTHING
  related to these packages

If you want to remove those error packages, you can try to use below command to force uninstall those packages:

Uninstall-Package Lucene.Net.Core -Force

Or you can delete this package from the package folder and delete the package list from the package.config.

Then install the correct version of the packages.


问:
Remote database management from local development server
I am looking for a way to access and query my remote databases from my local server.
Something like PhpMyAdmin, but little more versatile.

So that I can feed it with databases I would like to see, store my queries (or better, if it has ways to access simple queries built in itself)

Can someone help me with such a PHP Script (or Class)?

Regards
Nikhil Gupta

答:
If it's ok to run as windows-programs, here are two suggestions:

Dbvisualizer http://www.dbvis.com/

Visual studio (even express versions) has what they call "database explorer", just install some mysql-connector that VS can handle, like odbc.

ContentLicense: CC BY-SA 2.5


问:
How can I change the lazyload module in routes to normal module?
Version:

```<code>ng version:
@angular/cli: 1.0.0-rc.1
node: 6.10.2
os: win32 x64
@angular/common: 4.1.1
@angular/compiler: 4.1.1
@angular/compiler-cli: 4.1.1
@angular/core: 4.1.1
@angular/forms: 4.1.1
@angular/http: 4.1.1
@angular/platform-browser: 4.1.1
@angular/platform-browser-dynamic: 4.1.1
@angular/router: 4.1.1
@angular/cli: 1.0.0-rc.1
</code>```

My project used to use lazyload modules in routes, such as:

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

export const routes: Routes = [
  { path: 'global-config', loadChildren: 'app/modules/act-widget/main.module#GlobalConfigModule' }
];
</code>```

But we have too many lazyload modules. It makes our building process slowly(92% chunk asset optimization).
So we make a decision to discard lazyload modules.

But when I change to this:

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {GlobalConfigModule} from '../modules/global-config/global-config.module';

export const routes: Routes = [
  { path: 'global-config', loadChildren: () => GlobalConfigModule }
];
</code>```

Error appears:

```<code>ERROR in Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function (position 12:42 in the original .ts file), resolving symbol routes in E:/pgg_oa/src/app/container/container-routing.module.ts, resolving symbol AppRoutingModule in E:/pgg_oa/src/app/container/container-routing.module.ts, resolving symbol AppRoutingModule in E:/pgg_oa/src/app/container/container-routing.module.ts, resolving symbol AppRoutingModule in E:/pgg_oa/src/app/container/container-routing.module.ts
</code>```

My question is:

How can I change our lazyload modules into normal modules with the least cost?

答:
You should create an exported function, and use that as the loadChildren value. The problem is, that you have to create a function for every module:

```<code>export function getGlobalConfigModule(): typeof GlobalConfigModule {
   return GlobalConfigModule;
}

export const routes: Routes = [
  { path: 'global-config', loadChildren: getGlobalConfigModule}
];
</code>```

The initial startup time of the application will be a lot slower though, I'm not sure you would want to make that decision. A build process takes a long time, because of the AoT compilation being done. Perhaps investing in new disks with high I/O will improve build time

Body:
Version:

ng version:
@angular/cli: 1.0.0-rc.1
node: 6.10.2
os: win32 x64
@angular/common: 4.1.1
@angular/compiler: 4.1.1
@angular/compiler-cli: 4.1.1
@angular/core: 4.1.1
@angular/forms: 4.1.1
@angular/http: 4.1.1
@angular/platform-browser: 4.1.1
@angular/platform-browser-dynamic: 4.1.1
@angular/router: 4.1.1
@angular/cli: 1.0.0-rc.1

My project used to use lazyload modules in routes, such as:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

export const routes: Routes = [
  { path: 'global-config', loadChildren: 'app/modules/act-widget/main.module#GlobalConfigModule' }
];

But we have too many lazyload modules. It makes our building process slowly(92% chunk asset optimization).
So we make a decision to discard lazyload modules.

But when I change to this:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {GlobalConfigModule} from '../modules/global-config/global-config.module';

export const routes: Routes = [
  { path: 'global-config', loadChildren: () => GlobalConfigModule }
];

Error appears:

ERROR in Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function (position 12:42 in the original .ts file), resolving symbol routes in E:/pgg_oa/src/app/container/container-routing.module.ts, resolving symbol AppRoutingModule in E:/pgg_oa/src/app/container/container-routing.module.ts, resolving symbol AppRoutingModule in E:/pgg_oa/src/app/container/container-routing.module.ts, resolving symbol AppRoutingModule in E:/pgg_oa/src/app/container/container-routing.module.ts

My question is:

How can I change our lazyload modules into normal modules with the least cost?

Body:
You should create an exported function, and use that as the loadChildren value. The problem is, that you have to create a function for every module:

export function getGlobalConfigModule(): typeof GlobalConfigModule {
   return GlobalConfigModule;
}

export const routes: Routes = [
  { path: 'global-config', loadChildren: getGlobalConfigModule}
];

The initial startup time of the application will be a lot slower though, I'm not sure you would want to make that decision. A build process takes a long time, because of the AoT compilation being done. Perhaps investing in new disks with high I/O will improve build time


问:
Azure Data factory Dataset From a StoredProcedure
My goal is to pass data from one SQl azure database (User DB) to another SQl azure database (Datawarehouse) through a stored procedure.

I have created two linked Services, one for each DB. And two DataSets of which I have doubts.

The stored procedure in question collects data from a table and several joins with other tables and returns a result that should be stored in a table in the Datawarehouse

The SP is like this:

```<code>ALTER PROCEDURE [DataWarehouse].[Item_init]
AS
BEGIN
    SET NOCOUNT ON
    SELECT Id, a.Name, Code, f.Name, s.Name, g.Name
    FROM Item.Item a
        join Item.Groupg on g.idGroup= a.idGroup
        join Item.Subfam s on s.idSubfam = g.idSubfam
        join Item.Fam f on f.idFam= s.idFam

END
</code>```

The dataset that collects data from the UserDB (I think it is not correct) is like this:

```<code>{
    "name": "ds_SProcItem_init",
    "properties": {
        "published": false,
        "type": "AzureSqlTable",
        "linkedServiceName": "UserTable",
        "typeProperties": {
            "tableName": "Item.Item"
        },
        "availability": {
            "frequency": "Hour",
            "interval": 1
        }
    }
}
</code>```

The other dataset:

```<code>{
    "name": "ds_DWItemOutput",
    "properties": {
        "published": false,
        "type": "AzureSqlTable",
        "linkedServiceName": "DataWareHouse",
        "typeProperties": {
            "tableName": "Item"
        },
        "availability": {
            "frequency": "Hour",
            "interval": 1
        }
    }
}
</code>```

The pipeline that communicates the datasets is as follows:

```<code>{
    "name": "SprocItem_InitPipeline",
    "properties": {
        "activities": [
            {
                "type": "SqlServerStoredProcedure",
                "typeProperties": {
                    "storedProcedureName": "DataWarehouse.Item_init"
                },
                "inputs": [
                    {
                        "name": "ds_SProcItem_init"
                    }
                ],
                "outputs": [
                    {
                        "name": "ds_DWItemOutput"
                    }
                ],
                "scheduler": {
                    "frequency": "Hour",
                    "interval": 1
                },
                "name": "SprocItem_Init"
            }
        ],
        "start": "2016-08-02T00:00:00Z",
        "end": "2016-08-02T05:00:00Z",
        "isPaused": false,
        "hubName": "pruebasaas_hub",
        "pipelineMode": "Scheduled"
    }
}
</code>```

Please, someone who knows the subject, could you help me?
Thanks!

答:
Given the limits of Azure SQL DB I suggest you need to use a copy activity here as well as the stored procedure. You need to handle this within the confines of how ADF wants to work. Remember this isn't SSIS :-)

If I was building the data factory these are the steps I'd take...

For completeness define datasets of each of the tables used by the stored procedure.

First pipeline. Have an activity that calls the stored procedure that does the joins of the input datasets and outputs to a new staging table (do a SQL INSERT INTO ... SELECT... here) on the first Azure SQL DB instance.

Have the output dataset in ADF for the staging table defined (the proc result).

Second pipeline. Have a copy activity from the output staging table in point 3 as the input. Then output to the table on the second Azure SQL DB instance.

Again for completeness an ADF dataset for the final destination table.

The copy activity bridges the gap where cross database queries aren't possible and SQL Server Linked Servers don't exist.

Picture to help...

(Please forgive the poor paint skills)

Make sense? :-)
Good, crack on.

Body:
My goal is to pass data from one SQl azure database (User DB) to another SQl azure database (Datawarehouse) through a stored procedure.

I have created two linked Services, one for each DB. And two DataSets of which I have doubts.

The stored procedure in question collects data from a table and several joins with other tables and returns a result that should be stored in a table in the Datawarehouse

The SP is like this:

ALTER PROCEDURE [DataWarehouse].[Item_init]
AS
BEGIN
    SET NOCOUNT ON
    SELECT Id, a.Name, Code, f.Name, s.Name, g.Name
    FROM Item.Item a
        join Item.Groupg on g.idGroup= a.idGroup
        join Item.Subfam s on s.idSubfam = g.idSubfam
        join Item.Fam f on f.idFam= s.idFam

END

The dataset that collects data from the UserDB (I think it is not correct) is like this:

{
    "name": "ds_SProcItem_init",
    "properties": {
        "published": false,
        "type": "AzureSqlTable",
        "linkedServiceName": "UserTable",
        "typeProperties": {
            "tableName": "Item.Item"
        },
        "availability": {
            "frequency": "Hour",
            "interval": 1
        }
    }
}

The other dataset:

{
    "name": "ds_DWItemOutput",
    "properties": {
        "published": false,
        "type": "AzureSqlTable",
        "linkedServiceName": "DataWareHouse",
        "typeProperties": {
            "tableName": "Item"
        },
        "availability": {
            "frequency": "Hour",
            "interval": 1
        }
    }
}

The pipeline that communicates the datasets is as follows:

{
    "name": "SprocItem_InitPipeline",
    "properties": {
        "activities": [
            {
                "type": "SqlServerStoredProcedure",
                "typeProperties": {
                    "storedProcedureName": "DataWarehouse.Item_init"
                },
                "inputs": [
                    {
                        "name": "ds_SProcItem_init"
                    }
                ],
                "outputs": [
                    {
                        "name": "ds_DWItemOutput"
                    }
                ],
                "scheduler": {
                    "frequency": "Hour",
                    "interval": 1
                },
                "name": "SprocItem_Init"
            }
        ],
        "start": "2016-08-02T00:00:00Z",
        "end": "2016-08-02T05:00:00Z",
        "isPaused": false,
        "hubName": "pruebasaas_hub",
        "pipelineMode": "Scheduled"
    }
}

Please, someone who knows the subject, could you help me?
Thanks!


问:
Pandas multi column mean
I have a pandas DataFrame, and would like to get column wise mean()
as below.

```<code>    A    B    C      D
1   10  100 1000    10000
2   20  200 2000    20000
3   30  300 3000    30000
4   40  400 4000    40000
5   50  500 5000    50000
</code>```

Answer:

```<code>  A    B      C      D
  30  300   3000    30000
</code>```

Please suggest a way to do it.
I have tried df.mean() and other variations of it.

答:
Add to_frame with T:

```<code>print (df.mean().to_frame().T)
      A      B       C        D
0  30.0  300.0  3000.0  30000.0
</code>```

Or:

```<code>print (pd.DataFrame(df.mean().values.reshape(1,-1), columns=df.columns))
      A      B       C        D
0  30.0  300.0  3000.0  30000.0
</code>```

Or:

```<code>print (pd.DataFrame(np.mean(df.values, axis=0).reshape(1,-1), columns=df.columns))
      A      B       C        D
0  30.0  300.0  3000.0  30000.0
</code>```

Title: Pandas multi column mean

Body:
I have a pandas DataFrame, and would like to get column wise mean()
as below.

    A    B    C      D
1   10  100 1000    10000
2   20  200 2000    20000
3   30  300 3000    30000
4   40  400 4000    40000
5   50  500 5000    50000

Answer:

  A    B      C      D
  30  300   3000    30000

Please suggest a way to do it.
I have tried df.mean() and other variations of it.

Body:
Add to_frame with T:

print (df.mean().to_frame().T)
      A      B       C        D
0  30.0  300.0  3000.0  30000.0

Or:

print (pd.DataFrame(df.mean().values.reshape(1,-1), columns=df.columns))
      A      B       C        D
0  30.0  300.0  3000.0  30000.0

Or:

print (pd.DataFrame(np.mean(df.values, axis=0).reshape(1,-1), columns=df.columns))
      A      B       C        D
0  30.0  300.0  3000.0  30000.0


问:
Cannot find control with name: formControlName in angular reactive form
I found this problem in many questions in stackoverflow but no luck. Please help me for figuring out what I am doing wrong.

In component :

ngOnInit() {
    this.companyCreatForm = this._formBuilder.group({
      name: [null, [Validators.required, Validators.minLength(5)]],
      about: [null, [Validators.required]],
      businessType: [null, [Validators.required]],
      address: this._formBuilder.group({
        street: [],
        website: [null, [Validators.required]],
        mobile: [null, [Validators.required]],
        email: [null, [Validators.required]],
        pageId: [null, [Validators.required]],
      }),
    });
```
<p><strong>Form :</strong></p>
<pre class="lang-xml prettyprint-override"><code><form [formGroup]="companyCreatForm" (ngSubmit)="creat_company()" novalidate class="form-horizontal">
    <div class="panel panel-default" *ngIf="generalPanel">
        <div class="panel-heading">General Info</div>
        <div class="panel-body">
            <div class="form-group">
                <label for="comapny name" class="col-sm-3 control-label">Company's Name</label>
                <div class="col-sm-8">
                    <input type="text" class="form-control" placeholder="Company's Name" formControlName="name" #refName>
                    <div *ngIf="companyCreatForm.controls['name'].hasError('required') && refName.touched" class="alert alert-danger">
                        please enter name
                    </div>
                    <div *ngIf="companyCreatForm.controls['name'].hasError('minlength')" class="alert alert-danger">
                        please enter at least 5 characters
                    </div>
                </div>
            </div>

            <div class="form-group">
                <label for="business type" class="col-sm-3 control-label">Business type</label>
                <div class="col-sm-8">
                    <select name="businessType" formControlName="businessType" class="form-control" [(ngModel)]="defaultType">

                        <option  *ngFor="let type of businessTypes" [value]="type.id">{{type.name}}</option>
                    </select>
                </div>
            </div>

            <div class="form-group">
                <label for="about" class="col-sm-3 control-label">Add Company Description</label>
                <div class="col-sm-8">
                    <textarea formControlName="about" class="form-control" id="txtArea" rows="6" cols="70"></textarea>
                </div>
            </div>
        </div>
    </div>

    <div class="panel panel-default">
        <div class="panel-heading">Contact Info</div>
        <div class="panel-body">
            <div class="form-group">
                <label for="address" class="col-sm-3 control-label">Business Address</label>
                <div class="col-sm-8">
                    <input type="text" class="form-control" formControlName="street" placeholder="Business Address">
                </div>
            </div>

            <div class="form-group">
                <label for="website" class="col-sm-3 control-label">Website</label>
                <div class="col-sm-8">
                    <input type="text" class="form-control" formControlName="website" placeholder="website">
                </div>
            </div>

            <div class="form-group">
                <label for="telephone" class="col-sm-3 control-label">Telephone</label>
                <div class="col-sm-8">
                    <input type="text" class="form-control" formControlName="mobile" placeholder="telephone">
                </div>
            </div>

            <div class="form-group">
                <label for="email" class="col-sm-3 control-label">Email</label>
                <div class="col-sm-8">
                    <input type="text" class="form-control" formControlName="email" placeholder="email">
                </div>
            </div>

            <div class="form-group">
                <label for="page id" class="col-sm-3 control-label">Facebook Page ID</label>
                <div class="col-sm-8">
                    <input type="text" class="form-control" formControlName="pageId" placeholder="facebook page id">
                </div>
            </div>

            <div class="form-group">
                <label for="about" class="col-sm-3  control-label"></label>
                <div class="col-sm-3">

                    <!--span class="btn btn-success form-control" (click)="openGeneralPanel()">Back</span-->
                </div>
                <label for="about" class="col-sm-2  control-label"></label>
                <div class="col-sm-3">
                    <button class="btn btn-success form-control" [disabled]="companyCreatForm.invalid" (click)="openContactInfo()">Continue</button>
                </div>
            </div>
        </div>
    </div>
</form>
</code>```

Everything should be right but when I load page find error

Cannot find control with name: 'website' ,'street', 'mobile', 'email','pageId'

Full error page from browser console is like below:

```<code>CompanyCreateComponent.html:69 ERROR CONTEXT DebugContext_ {view: Object, nodeIndex: 69, nodeDef: Object, elDef: Object, elView: Object}
View_CompanyCreateComponent_0 @ CompanyCreateComponent.html:69
proxyClass @ compiler.es5.js:14091
DebugContext_.logError @ core.es5.js:13124
ErrorHandler.handleError @ core.es5.js:1149
ApplicationRef_.tick @ core.es5.js:5060
(anonymous) @ core.es5.js:4933
ZoneDelegate.invoke @ zone.js:381
onInvoke @ core.es5.js:4128
ZoneDelegate.invoke @ zone.js:380
Zone.run @ zone.js:141
NgZone.run @ core.es5.js:3996
next @ core.es5.js:4933
schedulerFn @ core.es5.js:3830
SafeSubscriber.__tryOrUnsub @ Subscriber.js:238
SafeSubscriber.next @ Subscriber.js:185
Subscriber._next @ Subscriber.js:125
Subscriber.next @ Subscriber.js:89
Subject.next @ Subject.js:55
EventEmitter.emit @ core.es5.js:3816
NgZone.checkStable @ core.es5.js:4093
NgZone.setHasMicrotask @ core.es5.js:4177
onHasTask @ core.es5.js:4140
ZoneDelegate.hasTask @ zone.js:434
ZoneDelegate._updateTaskCount @ zone.js:454
Zone._updateTaskCount @ zone.js:278
Zone.runTask @ zone.js:198
drainMicroTaskQueue @ zone.js:574
ZoneTask.invoke @ zone.js:480
CompanyCreateComponent.html:76 ERROR Error: Cannot find control with name: 'mobile'
    at _throwError (forms.es5.js:1830)
    at setUpControl (forms.es5.js:1738)
    at FormGroupDirective.addControl (forms.es5.js:4711)
    at FormControlName._setUpControl (forms.es5.js:5299)
    at FormControlName.ngOnChanges (forms.es5.js:5217)
    at checkAndUpdateDirectiveInline (core.es5.js:10790)
    at checkAndUpdateNodeInline (core.es5.js:12216)
    at checkAndUpdateNode (core.es5.js:12155)
    at debugCheckAndUpdateNode (core.es5.js:12858)
    at debugCheckDirectivesFn (core.es5.js:12799)
View_CompanyCreateComponent_0 @ CompanyCreateComponent.html:76
proxyClass @ compiler.es5.js:14091
DebugContext_.logError @ core.es5.js:13124
ErrorHandler.handleError @ core.es5.js:1144
ApplicationRef_.tick @ core.es5.js:5060
(anonymous) @ core.es5.js:4933
ZoneDelegate.invoke @ zone.js:381
onInvoke @ core.es5.js:4128
ZoneDelegate.invoke @ zone.js:380
Zone.run @ zone.js:141
NgZone.run @ core.es5.js:3996
next @ core.es5.js:4933
schedulerFn @ core.es5.js:3830
SafeSubscriber.__tryOrUnsub @ Subscriber.js:238
SafeSubscriber.next @ Subscriber.js:185
Subscriber._next @ Subscriber.js:125
Subscriber.next @ Subscriber.js:89
Subject.next @ Subject.js:55
EventEmitter.emit @ core.es5.js:3816
NgZone.checkStable @ core.es5.js:4093
NgZone.onLeave @ core.es5.js:4169
onInvoke @ core.es5.js:4131
ZoneDelegate.invoke @ zone.js:380
Zone.runGuarded @ zone.js:154
_loop_1 @ zone.js:640
api.microtaskDrainDone @ zone.js:649
drainMicroTaskQueue @ zone.js:582
ZoneTask.invoke @ zone.js:480
CompanyCreateComponent.html:76 ERROR CONTEXT DebugContext_ {view: Object, nodeIndex: 85, nodeDef: Object, elDef: Object, elView: Object}
View_CompanyCreateComponent_0 @ CompanyCreateComponent.html:76
proxyClass @ compiler.es5.js:14091
DebugContext_.logError @ core.es5.js:13124
ErrorHandler.handleError @ core.es5.js:1149
ApplicationRef_.tick @ core.es5.js:5060
(anonymous) @ core.es5.js:4933
ZoneDelegate.invoke @ zone.js:381
onInvoke @ core.es5.js:4128
ZoneDelegate.invoke @ zone.js:380
Zone.run @ zone.js:141
NgZone.run @ core.es5.js:3996
next @ core.es5.js:4933
schedulerFn @ core.es5.js:3830
SafeSubscriber.__tryOrUnsub @ Subscriber.js:238
SafeSubscriber.next @ Subscriber.js:185
Subscriber._next @ Subscriber.js:125
Subscriber.next @ Subscriber.js:89
Subject.next @ Subject.js:55
EventEmitter.emit @ core.es5.js:3816
NgZone.checkStable @ core.es5.js:4093
NgZone.onLeave @ core.es5.js:4169
onInvoke @ core.es5.js:4131
ZoneDelegate.invoke @ zone.js:380
Zone.runGuarded @ zone.js:154
_loop_1 @ zone.js:640
api.microtaskDrainDone @ zone.js:649
drainMicroTaskQueue @ zone.js:582
ZoneTask.invoke @ zone.js:480
core.es5.js:1084 ERROR Error: Uncaught (in promise): Error: Cannot find control with name: 'street'
Error: Cannot find control with name: 'street'
    at _throwError (forms.es5.js:1830)
    at setUpControl (forms.es5.js:1738)
    at FormGroupDirective.addControl (forms.es5.js:4711)
    at FormControlName._setUpControl (forms.es5.js:5299)
    at FormControlName.ngOnChanges (forms.es5.js:5217)
    at checkAndUpdateDirectiveInline (core.es5.js:10790)
    at checkAndUpdateNodeInline (core.es5.js:12216)
    at checkAndUpdateNode (core.es5.js:12155)
    at debugCheckAndUpdateNode (core.es5.js:12858)
    at debugCheckDirectivesFn (core.es5.js:12799)
    at _throwError (forms.es5.js:1830)
    at setUpControl (forms.es5.js:1738)
    at FormGroupDirective.addControl (forms.es5.js:4711)
    at FormControlName._setUpControl (forms.es5.js:5299)
    at FormControlName.ngOnChanges (forms.es5.js:5217)
    at checkAndUpdateDirectiveInline (core.es5.js:10790)
    at checkAndUpdateNodeInline (core.es5.js:12216)
    at checkAndUpdateNode (core.es5.js:12155)
    at debugCheckAndUpdateNode (core.es5.js:12858)
    at debugCheckDirectivesFn (core.es5.js:12799)
    at resolvePromise (zone.js:757)
    at resolvePromise (zone.js:728)
    at zone.js:805
    at ZoneDelegate.invokeTask (zone.js:414)
    at Object.onInvokeTask (core.es5.js:4119)
    at ZoneDelegate.invokeTask (zone.js:413)
    at Zone.runTask (zone.js:181)
    at drainMicroTaskQueue (zone.js:574)
    at HTMLButtonElement.ZoneTask.invoke (zone.js:480)
defaultErrorLogger @ core.es5.js:1084
ErrorHandler.handleError @ core.es5.js:1144
next @ core.es5.js:4757
schedulerFn @ core.es5.js:3830
SafeSubscriber.__tryOrUnsub @ Subscriber.js:238
SafeSubscriber.next @ Subscriber.js:185
Subscriber._next @ Subscriber.js:125
Subscriber.next @ Subscriber.js:89
Subject.next @ Subject.js:55
EventEmitter.emit @ core.es5.js:3816
NgZone.triggerError @ core.es5.js:4188
onHandleError @ core.es5.js:4149
ZoneDelegate.handleError @ zone.js:385
Zone.runGuarded @ zone.js:157
_loop_1 @ zone.js:640
api.microtaskDrainDone @ zone.js:649
drainMicroTaskQueue @ zone.js:582
ZoneTask.invoke @ zone.js:480
CompanyCreateComponent.html:83 ERROR Error: Cannot find control with name: 'email'
    at _throwError (forms.es5.js:1830)
    at setUpControl (forms.es5.js:1738)
    at FormGroupDirective.addControl (forms.es5.js:4711)
    at FormControlName._setUpControl (forms.es5.js:5299)
    at FormControlName.ngOnChanges (forms.es5.js:5217)
    at checkAndUpdateDirectiveInline (core.es5.js:10790)
    at checkAndUpdateNodeInline (core.es5.js:12216)
    at checkAndUpdateNode (core.es5.js:12155)
    at debugCheckAndUpdateNode (core.es5.js:12858)
    at debugCheckDirectivesFn (core.es5.js:12799)
View_CompanyCreateComponent_0 @ CompanyCreateComponent.html:83
proxyClass @ compiler.es5.js:14091
DebugContext_.logError @ core.es5.js:13124
ErrorHandler.handleError @ core.es5.js:1144
ApplicationRef_.tick @ core.es5.js:5060
(anonymous) @ core.es5.js:4933
ZoneDelegate.invoke @ zone.js:381
onInvoke @ core.es5.js:4128
ZoneDelegate.invoke @ zone.js:380
Zone.run @ zone.js:141
NgZone.run @ core.es5.js:3996
next @ core.es5.js:4933
schedulerFn @ core.es5.js:3830
SafeSubscriber.__tryOrUnsub @ Subscriber.js:238
SafeSubscriber.next @ Subscriber.js:185
Subscriber._next @ Subscriber.js:125
Subscriber.next @ Subscriber.js:89
Subject.next @ Subject.js:55
EventEmitter.emit @ core.es5.js:3816
NgZone.checkStable @ core.es5.js:4093
NgZone.onLeave @ core.es5.js:4169
onInvokeTask @ core.es5.js:4122
ZoneDelegate.invokeTask @ zone.js:413
Zone.runTask @ zone.js:181
ZoneTask.invoke @ zone.js:476
CompanyCreateComponent.html:83 ERROR CONTEXT DebugContext_ {view: Object, nodeIndex: 101, nodeDef: Object, elDef: Object, elView: Object}
View_CompanyCreateComponent_0 @ CompanyCreateComponent.html:83
proxyClass @ compiler.es5.js:14091
DebugContext_.logError @ core.es5.js:13124
ErrorHandler.handleError @ core.es5.js:1149
ApplicationRef_.tick @ core.es5.js:5060
(anonymous) @ core.es5.js:4933
ZoneDelegate.invoke @ zone.js:381
onInvoke @ core.es5.js:4128
ZoneDelegate.invoke @ zone.js:380
Zone.run @ zone.js:141
NgZone.run @ core.es5.js:3996
next @ core.es5.js:4933
schedulerFn @ core.es5.js:3830
SafeSubscriber.__tryOrUnsub @ Subscriber.js:238
SafeSubscriber.next @ Subscriber.js:185
Subscriber._next @ Subscriber.js:125
Subscriber.next @ Subscriber.js:89
Subject.next @ Subject.js:55
EventEmitter.emit @ core.es5.js:3816
NgZone.checkStable @ core.es5.js:4093
NgZone.onLeave @ core.es5.js:4169
onInvokeTask @ core.es5.js:4122
ZoneDelegate.invokeTask @ zone.js:413
Zone.runTask @ zone.js:181
ZoneTask.invoke @ zone.js:476
CompanyCreateComponent.html:90 ERROR Error: Cannot find control with name: 'pageId'
    at _throwError (forms.es5.js:1830)
    at setUpControl (forms.es5.js:1738)
    at FormGroupDirective.addControl (forms.es5.js:4711)
    at FormControlName._setUpControl (forms.es5.js:5299)
    at FormControlName.ngOnChanges (forms.es5.js:5217)
    at checkAndUpdateDirectiveInline (core.es5.js:10790)
    at checkAndUpdateNodeInline (core.es5.js:12216)
    at checkAndUpdateNode (core.es5.js:12155)
    at debugCheckAndUpdateNode (core.es5.js:12858)
    at debugCheckDirectivesFn (core.es5.js:12799)
</code>```

答:
You should specify formGroupName for nested controls

```<code><div class="panel panel-default" formGroupName="address"> <== add this
    <div class="panel-heading">Contact Info</div>
</code>```

Plunker Example

ContentLicense: CC BY-SA 4.0

Body:
I found this problem in many questions in stackoverflow but no luck. Please help me for figuring out what I am doing wrong.

In component :

ngOnInit() {
    this.companyCreatForm = this._formBuilder.group({
      name: [null, [Validators.required, Validators.minLength(5)]],
      about: [null, [Validators.required]],
      businessType: [null, [Validators.required]],
      address: this._formBuilder.group({
        street: [],
        website: [null, [Validators.required]],
        mobile: [null, [Validators.required]],
        email: [null, [Validators.required]],
        pageId: [null, [Validators.required]],
      }),
    });

Form :

<form [formGroup]="companyCreatForm" (ngSubmit)="creat_company()" novalidate class="form-horizontal">

General Info

                Company's Name

                    <input type="text" class="form-control" placeholder="Company's Name" formControlName="name" #refName>

                        please enter name

                        please enter at least 5 characters

                Business type

                    <select name="businessType" formControlName="businessType" class="form-control" [(ngModel)]="defaultType">

                        <option  *ngFor="let type of businessTypes" [value]="type.id">{{type.name}}</option>
                    </select>

                Add Company Description

                    <textarea formControlName="about" class="form-control" id="txtArea" rows="6" cols="70"></textarea>

Contact Info

                Business Address

                    <input type="text" class="form-control" formControlName="street" placeholder="Business Address">

                Website

                    <input type="text" class="form-control" formControlName="website" placeholder="website">

                Telephone

                    <input type="text" class="form-control" formControlName="mobile" placeholder="telephone">

                Email

                    <input type="text" class="form-control" formControlName="email" placeholder="email">

                Facebook Page ID

                    <input type="text" class="form-control" formControlName="pageId" placeholder="facebook page id">

                    <button class="btn btn-success form-control" [disabled]="companyCreatForm.invalid" (click)="openContactInfo()">Continue</button>

</form>

Everything should be right but when I load page find error

Cannot find control with name: 'website' ,'street', 'mobile', 'email','pageId'

Full error page from browser console is like below:

CompanyCreateComponent.html:69 ERROR CONTEXT DebugContext_ {view: Object, nodeIndex: 69, nodeDef: Object, elDef: Object, elView: Object}
View_CompanyCreateComponent_0 @ CompanyCreateComponent.html:69
proxyClass @ compiler.es5.js:14091
DebugContext_.logError @ core.es5.js:13124
ErrorHandler.handleError @ core.es5.js:1149
ApplicationRef_.tick @ core.es5.js:5060
(anonymous) @ core.es5.js:4933
ZoneDelegate.invoke @ zone.js:381
onInvoke @ core.es5.js:4128
ZoneDelegate.invoke @ zone.js:380
Zone.run @ zone.js:141
NgZone.run @ core.es5.js:3996
next @ core.es5.js:4933
schedulerFn @ core.es5.js:3830
SafeSubscriber.__tryOrUnsub @ Subscriber.js:238
SafeSubscriber.next @ Subscriber.js:185
Subscriber._next @ Subscriber.js:125
Subscriber.next @ Subscriber.js:89
Subject.next @ Subject.js:55
EventEmitter.emit @ core.es5.js:3816
NgZone.checkStable @ core.es5.js:4093
NgZone.setHasMicrotask @ core.es5.js:4177
onHasTask @ core.es5.js:4140
ZoneDelegate.hasTask @ zone.js:434
ZoneDelegate._updateTaskCount @ zone.js:454
Zone._updateTaskCount @ zone.js:278
Zone.runTask @ zone.js:198
drainMicroTaskQueue @ zone.js:574
ZoneTask.invoke @ zone.js:480
CompanyCreateComponent.html:76 ERROR Error: Cannot find control with name: 'mobile'
    at _throwError (forms.es5.js:1830)
    at setUpControl (forms.es5.js:1738)
    at FormGroupDirective.addControl (forms.es5.js:4711)
    at FormControlName._setUpControl (forms.es5.js:5299)
    at FormControlName.ngOnChanges (forms.es5.js:5217)
    at checkAndUpdateDirectiveInline (core.es5.js:10790)
    at checkAndUpdateNodeInline (core.es5.js:12216)
    at checkAndUpdateNode (core.es5.js:12155)
    at debugCheckAndUpdateNode (core.es5.js:12858)
    at debugCheckDirectivesFn (core.es5.js:12799)
View_CompanyCreateComponent_0 @ CompanyCreateComponent.html:76
proxyClass @ compiler.es5.js:14091
DebugContext_.logError @ core.es5.js:13124
ErrorHandler.handleError @ core.es5.js:1144
ApplicationRef_.tick @ core.es5.js:5060
(anonymous) @ core.es5.js:4933
ZoneDelegate.invoke @ zone.js:381
onInvoke @ core.es5.js:4128
ZoneDelegate.invoke @ zone.js:380
Zone.run @ zone.js:141
NgZone.run @ core.es5.js:3996
next @ core.es5.js:4933
schedulerFn @ core.es5.js:3830
SafeSubscriber.__tryOrUnsub @ Subscriber.js:238
SafeSubscriber.next @ Subscriber.js:185
Subscriber._next @ Subscriber.js:125
Subscriber.next @ Subscriber.js:89
Subject.next @ Subject.js:55
EventEmitter.emit @ core.es5.js:3816
NgZone.checkStable @ core.es5.js:4093
NgZone.onLeave @ core.es5.js:4169
onInvoke @ core.es5.js:4131
ZoneDelegate.invoke @ zone.js:380
Zone.runGuarded @ zone.js:154
_loop_1 @ zone.js:640
api.microtaskDrainDone @ zone.js:649
drainMicroTaskQueue @ zone.js:582
ZoneTask.invoke @ zone.js:480
CompanyCreateComponent.html:76 ERROR CONTEXT DebugContext_ {view: Object, nodeIndex: 85, nodeDef: Object, elDef: Object, elView: Object}
View_CompanyCreateComponent_0 @ CompanyCreateComponent.html:76
proxyClass @ compiler.es5.js:14091
DebugContext_.logError @ core.es5.js:13124
ErrorHandler.handleError @ core.es5.js:1149
ApplicationRef_.tick @ core.es5.js:5060
(anonymous) @ core.es5.js:4933
ZoneDelegate.invoke @ zone.js:381
onInvoke @ core.es5.js:4128
ZoneDelegate.invoke @ zone.js:380
Zone.run @ zone.js:141
NgZone.run @ core.es5.js:3996
next @ core.es5.js:4933
schedulerFn @ core.es5.js:3830
SafeSubscriber.__tryOrUnsub @ Subscriber.js:238
SafeSubscriber.next @ Subscriber.js:185
Subscriber._next @ Subscriber.js:125
Subscriber.next @ Subscriber.js:89
Subject.next @ Subject.js:55
EventEmitter.emit @ core.es5.js:3816
NgZone.checkStable @ core.es5.js:4093
NgZone.onLeave @ core.es5.js:4169
onInvoke @ core.es5.js:4131
ZoneDelegate.invoke @ zone.js:380
Zone.runGuarded @ zone.js:154
_loop_1 @ zone.js:640
api.microtaskDrainDone @ zone.js:649
drainMicroTaskQueue @ zone.js:582
ZoneTask.invoke @ zone.js:480
core.es5.js:1084 ERROR Error: Uncaught (in promise): Error: Cannot find control with name: 'street'
Error: Cannot find control with name: 'street'
    at _throwError (forms.es5.js:1830)
    at setUpControl (forms.es5.js:1738)
    at FormGroupDirective.addControl (forms.es5.js:4711)
    at FormControlName._setUpControl (forms.es5.js:5299)
    at FormControlName.ngOnChanges (forms.es5.js:5217)
    at checkAndUpdateDirectiveInline (core.es5.js:10790)
    at checkAndUpdateNodeInline (core.es5.js:12216)
    at checkAndUpdateNode (core.es5.js:12155)
    at debugCheckAndUpdateNode (core.es5.js:12858)
    at debugCheckDirectivesFn (core.es5.js:12799)
    at _throwError (forms.es5.js:1830)
    at setUpControl (forms.es5.js:1738)
    at FormGroupDirective.addControl (forms.es5.js:4711)
    at FormControlName._setUpControl (forms.es5.js:5299)
    at FormControlName.ngOnChanges (forms.es5.js:5217)
    at checkAndUpdateDirectiveInline (core.es5.js:10790)
    at checkAndUpdateNodeInline (core.es5.js:12216)
    at checkAndUpdateNode (core.es5.js:12155)
    at debugCheckAndUpdateNode (core.es5.js:12858)
    at debugCheckDirectivesFn (core.es5.js:12799)
    at resolvePromise (zone.js:757)
    at resolvePromise (zone.js:728)
    at zone.js:805
    at ZoneDelegate.invokeTask (zone.js:414)
    at Object.onInvokeTask (core.es5.js:4119)
    at ZoneDelegate.invokeTask (zone.js:413)
    at Zone.runTask (zone.js:181)
    at drainMicroTaskQueue (zone.js:574)
    at HTMLButtonElement.ZoneTask.invoke (zone.js:480)
defaultErrorLogger @ core.es5.js:1084
ErrorHandler.handleError @ core.es5.js:1144
next @ core.es5.js:4757
schedulerFn @ core.es5.js:3830
SafeSubscriber.__tryOrUnsub @ Subscriber.js:238
SafeSubscriber.next @ Subscriber.js:185
Subscriber._next @ Subscriber.js:125
Subscriber.next @ Subscriber.js:89
Subject.next @ Subject.js:55
EventEmitter.emit @ core.es5.js:3816
NgZone.triggerError @ core.es5.js:4188
onHandleError @ core.es5.js:4149
ZoneDelegate.handleError @ zone.js:385
Zone.runGuarded @ zone.js:157
_loop_1 @ zone.js:640
api.microtaskDrainDone @ zone.js:649
drainMicroTaskQueue @ zone.js:582
ZoneTask.invoke @ zone.js:480
CompanyCreateComponent.html:83 ERROR Error: Cannot find control with name: 'email'
    at _throwError (forms.es5.js:1830)
    at setUpControl (forms.es5.js:1738)
    at FormGroupDirective.addControl (forms.es5.js:4711)
    at FormControlName._setUpControl (forms.es5.js:5299)
    at FormControlName.ngOnChanges (forms.es5.js:5217)
    at checkAndUpdateDirectiveInline (core.es5.js:10790)
    at checkAndUpdateNodeInline (core.es5.js:12216)
    at checkAndUpdateNode (core.es5.js:12155)
    at debugCheckAndUpdateNode (core.es5.js:12858)
    at debugCheckDirectivesFn (core.es5.js:12799)
View_CompanyCreateComponent_0 @ CompanyCreateComponent.html:83
proxyClass @ compiler.es5.js:14091
DebugContext_.logError @ core.es5.js:13124
ErrorHandler.handleError @ core.es5.js:1144
ApplicationRef_.tick @ core.es5.js:5060
(anonymous) @ core.es5.js:4933
ZoneDelegate.invoke @ zone.js:381
onInvoke @ core.es5.js:4128
ZoneDelegate.invoke @ zone.js:380
Zone.run @ zone.js:141
NgZone.run @ core.es5.js:3996
next @ core.es5.js:4933
schedulerFn @ core.es5.js:3830
SafeSubscriber.__tryOrUnsub @ Subscriber.js:238
SafeSubscriber.next @ Subscriber.js:185
Subscriber._next @ Subscriber.js:125
Subscriber.next @ Subscriber.js:89
Subject.next @ Subject.js:55
EventEmitter.emit @ core.es5.js:3816
NgZone.checkStable @ core.es5.js:4093
NgZone.onLeave @ core.es5.js:4169
onInvokeTask @ core.es5.js:4122
ZoneDelegate.invokeTask @ zone.js:413
Zone.runTask @ zone.js:181
ZoneTask.invoke @ zone.js:476
CompanyCreateComponent.html:83 ERROR CONTEXT DebugContext_ {view: Object, nodeIndex: 101, nodeDef: Object, elDef: Object, elView: Object}
View_CompanyCreateComponent_0 @ CompanyCreateComponent.html:83
proxyClass @ compiler.es5.js:14091
DebugContext_.logError @ core.es5.js:13124
ErrorHandler.handleError @ core.es5.js:1149
ApplicationRef_.tick @ core.es5.js:5060
(anonymous) @ core.es5.js:4933
ZoneDelegate.invoke @ zone.js:381
onInvoke @ core.es5.js:4128
ZoneDelegate.invoke @ zone.js:380
Zone.run @ zone.js:141
NgZone.run @ core.es5.js:3996
next @ core.es5.js:4933
schedulerFn @ core.es5.js:3830
SafeSubscriber.__tryOrUnsub @ Subscriber.js:238
SafeSubscriber.next @ Subscriber.js:185
Subscriber._next @ Subscriber.js:125
Subscriber.next @ Subscriber.js:89
Subject.next @ Subject.js:55
EventEmitter.emit @ core.es5.js:3816
NgZone.checkStable @ core.es5.js:4093
NgZone.onLeave @ core.es5.js:4169
onInvokeTask @ core.es5.js:4122
ZoneDelegate.invokeTask @ zone.js:413
Zone.runTask @ zone.js:181
ZoneTask.invoke @ zone.js:476
CompanyCreateComponent.html:90 ERROR Error: Cannot find control with name: 'pageId'
    at _throwError (forms.es5.js:1830)
    at setUpControl (forms.es5.js:1738)
    at FormGroupDirective.addControl (forms.es5.js:4711)
    at FormControlName._setUpControl (forms.es5.js:5299)
    at FormControlName.ngOnChanges (forms.es5.js:5217)
    at checkAndUpdateDirectiveInline (core.es5.js:10790)
    at checkAndUpdateNodeInline (core.es5.js:12216)
    at checkAndUpdateNode (core.es5.js:12155)
    at debugCheckAndUpdateNode (core.es5.js:12858)
    at debugCheckDirectivesFn (core.es5.js:12799)

Body:
You should specify formGroupName for nested controls

<div class="panel panel-default" formGroupName="address"> <== add this
    <div class="panel-heading">Contact Info</div>

Plunker Example


问:
How can I make this PowerShell script into one line
This PowerShell script works great, but I need it to be a one line script, how can I create the parameter objects inline?

```<code>$action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument 'invoke-command -scriptblock {iisreset}'
$trigger =  New-ScheduledTaskTrigger -Daily -At 9am
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "Reset IIS" -Description "Daily Reset IIS"
</code>```

e.g.

```<code>Register-ScheduledTask -Action `New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument 'invoke-command -scriptblock {iisreset}'` -Trigger `New-ScheduledTaskTrigger -Daily -At 9am -TaskName "Reset IIS" -Description "Daily Reset IIS"`
</code>```

I've tried wrapping it in double quotes and with backticks and with curly braces but no luck so far.

答:
Subexpressions should do it. Brackets outside subexpressions not required AFAIK.

$( ) Subexpression operator

Returns the result of one or more statements. For a single result,
  returns a scalar. For multiple results, returns an array.
  sauce: about_Operators

```<code>Register-ScheduledTask -Action $(New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument 'invoke-command -scriptblock {iisreset}') -Trigger $(New-ScheduledTaskTrigger -Daily -At 9am)-TaskName "Reset IIS" -Description "Daily Reset IIS"
</code>```

Body:
This PowerShell script works great, but I need it to be a one line script, how can I create the parameter objects inline?

$action = New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument 'invoke-command -scriptblock {iisreset}'
$trigger =  New-ScheduledTaskTrigger -Daily -At 9am
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "Reset IIS" -Description "Daily Reset IIS"

e.g.

Register-ScheduledTask -Action `New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument 'invoke-command -scriptblock {iisreset}'` -Trigger `New-ScheduledTaskTrigger -Daily -At 9am -TaskName "Reset IIS" -Description "Daily Reset IIS"`

I've tried wrapping it in double quotes and with backticks and with curly braces but no luck so far.

Body:
Subexpressions should do it. Brackets outside subexpressions not required AFAIK.

$( ) Subexpression operator

Returns the result of one or more statements. For a single result,
  returns a scalar. For multiple results, returns an array.
  sauce: about_Operators

Register-ScheduledTask -Action $(New-ScheduledTaskAction -Execute 'Powershell.exe' -Argument 'invoke-command -scriptblock {iisreset}') -Trigger $(New-ScheduledTaskTrigger -Daily -At 9am)-TaskName "Reset IIS" -Description "Daily Reset IIS"


问:
How to convert a string into double and vice versa?
I want to convert a string into a double and after doing some math on it, convert it back to a string.

How do I do this in Objective-C?

Is there a way to round a double to the nearest integer too?

答:
from this example here, you can see the the conversions both ways:</p>

```<code>NSString *str=@"5678901234567890";

long long verylong;
NSRange range;
range.length = 15;
range.location = 0;

[[NSScanner scannerWithString:[str substringWithRange:range]] scanLongLong:&verylong];

NSLog(@"long long value %lld",verylong);
</code>```

OwnerDisplayName: rksprst

LastEditorDisplayName: Paul

Body:
from this example here, you can see the the conversions both ways:

NSString *str=@"5678901234567890";

long long verylong;
NSRange range;
range.length = 15;
range.location = 0;

[[NSScanner scannerWithString:[str substringWithRange:range]] scanLongLong:&verylong];

NSLog(@"long long value %lld",verylong);


问:
nightwatch custom command prototype
I followed the instruction from here (pause command in nightwatch), in order to create a custom command which gets the current used selector (css or xpath).

```<code>var util = require('util');
var events = require('events');

function GetSelector() {
    events.EventEmitter.call(this);
}

util.inherits(GetSelector, events.EventEmitter);

GetSelector.prototype.command = function (callback) {
    callback(this.client.locateStrategy);
};

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

The implementation gets the current selector, although the program stuck when the custom command is called.

```<code>  browser
    .getSelector(function (currentSelector) {
      console.log('getSelector: ' + currentSelector);
    })

</code>```

I have also tried to wrap around with "self.perform" as suggested here, unfortunatelly without any luck.

```<code>GetSelector.prototype.command = function (browser, callback) {
    browser.perform(function () {
        callback(this.client.locateStrategy);
    })
};
</code>```

What am I missing?

答:
"Signaling the complete event needs to be done inside an asynchronous action" action"self.emit('complete');, according to the Nightwatch homepage.

```<code>GetSelector.prototype.command = function (cb) {
    var self = this;

    process.nextTick(function () {
        cb(self.client.locateStrategy);

        //Signaling the complete event needs to be done inside an asynchronous action.
        self.emit('complete');
    });

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

process.nextTick makes sure that the self.emit('complete'); will be called by the next tick of the event loop which are processed by Node.

Title: nightwatch custom command prototype

Body:
I followed the instruction from here (pause command in nightwatch), in order to create a custom command which gets the current used selector (css or xpath).

var util = require('util');
var events = require('events');

function GetSelector() {
    events.EventEmitter.call(this);
}

util.inherits(GetSelector, events.EventEmitter);

GetSelector.prototype.command = function (callback) {
    callback(this.client.locateStrategy);
};

module.exports = GetSelector;

The implementation gets the current selector, although the program stuck when the custom command is called.

  browser
    .getSelector(function (currentSelector) {
      console.log('getSelector: ' + currentSelector);
    })

I have also tried to wrap around with "self.perform" as suggested here, unfortunatelly without any luck.

GetSelector.prototype.command = function (browser, callback) {
    browser.perform(function () {
        callback(this.client.locateStrategy);
    })
};

What am I missing?

Body:
"Signaling the complete event needs to be done inside an asynchronous action" action"self.emit('complete');, according to the Nightwatch homepage.

GetSelector.prototype.command = function (cb) {
    var self = this;

    process.nextTick(function () {
        cb(self.client.locateStrategy);

        //Signaling the complete event needs to be done inside an asynchronous action.
        self.emit('complete');
    });

    return this;
};

process.nextTick makes sure that the self.emit('complete'); will be called by the next tick of the event loop which are processed by Node.


问:
python new line in txt file
I have written some code to save usernames, passwords and email addresses in a text file.
by reading an email from an input text file and writing it with the other information to an output text file.

However, in the output file, new-lines are appearing after the email.

For example:

```<code>abcd@gmail.com
,name,user,pass
</code>```

After changing the order of "email" and "name" it is happening again:

```<code>name,abcd@gmail.com
,user,pass.
</code>```

My email file looks like:

```<code>abcd@gmail.com
abcde@gmail.com
...
</code>```

How do I fix this issue?
Thanks in advance

My code:

```<code>line=""
driver = webdriver.Firefox()
f=open(r'C:\Users\11\Desktop\emailes.txt','r')

while True:
    password=id_generator()
    username=checkname()
    email=f.readline()
    if username !="":
            f2=open(r'C:\Users\11\Desktop\info.txt','a')
            f2.write(  email + "," + username + "," + username + "," +
            password)
            f2.write("\n")
            driver.get("xxxx")
            assert "xxxx" in driver.title
            driver.implicitly_wait(5)
            elem=driver.find_element_by_name("email")
            elem.clear
            elem.send_keys(email)
            elem=driver.find_element_by_name("fullName")
            elem.clear
            elem.send_keys(username)
            elem=driver.find_element_by_name("username")
            elem.clear
            elem.send_keys(username)
            elem=driver.find_element_by_name("password")
            elem.clear
            elem.send_keys(password)
            elem.send_keys(Keys.RETURN)
            f2.close()
f.close()
</code>```

答:
When you read the email, it gets an EOF ('\n') character because you are reading a line. You need to do this

```<code>email=f.readline().replace('\n','')
</code>```

so you take off the EOF

Title: python new line in txt file

Body:
I have written some code to save usernames, passwords and email addresses in a text file.
by reading an email from an input text file and writing it with the other information to an output text file.

However, in the output file, new-lines are appearing after the email.

For example:

abcd@gmail.com
,name,user,pass

After changing the order of "email" and "name" it is happening again:

name,abcd@gmail.com
,user,pass.

My email file looks like:

abcd@gmail.com
abcde@gmail.com
...

How do I fix this issue?
Thanks in advance

My code:

line=""
driver = webdriver.Firefox()
f=open(r'C:\Users\11\Desktop\emailes.txt','r')

while True:
    password=id_generator()
    username=checkname()
    email=f.readline()
    if username !="":
            f2=open(r'C:\Users\11\Desktop\info.txt','a')
            f2.write(  email + "," + username + "," + username + "," +
            password)
            f2.write("\n")
            driver.get("xxxx")
            assert "xxxx" in driver.title
            driver.implicitly_wait(5)
            elem=driver.find_element_by_name("email")
            elem.clear
            elem.send_keys(email)
            elem=driver.find_element_by_name("fullName")
            elem.clear
            elem.send_keys(username)
            elem=driver.find_element_by_name("username")
            elem.clear
            elem.send_keys(username)
            elem=driver.find_element_by_name("password")
            elem.clear
            elem.send_keys(password)
            elem.send_keys(Keys.RETURN)
            f2.close()
f.close()

Body:
When you read the email, it gets an EOF ('\n') character because you are reading a line. You need to do this

email=f.readline().replace('\n','')

so you take off the EOF


问:
Configuring socket.io for node.js application
I have a few questions about configuring socket.io for my node.js application.

When requiring var socket = require('socket.io')( /* HERE */ ), do I need to input the port my server listens where the /* HERE */ is at?

Right below the above line, I have another require function, for a .js file that contains a few constants and a function (see below). When I try to refer to 'socket' in that file it says it's undefined. But since this line is below the require line for the socket.io middleware seen above, why does it say 'undefined'?

```<code>const numbers = '1234'
function asd(req,res,next) {
  socket.emit('a')
}

module.exports = {
  asd
}
</code>```

For configuring client-side socket.io, I added this line:

```<code>var socket = io.connect('https://mydomain')
</code>```

Do I need to say 'mydomain:port' or is 'mydomain' enough?

答:
This is how you use socket.io

```<code>var http = require('http');
var express = require('express');
var path = require('path');

var app = http.createServer();
var io = require('socket.io')(app);

var port = 8081;

io.on('connection', function(socket){

    socket.on('event1', function (data) {
        console.log(data);
        socket.emit('event2', { msg: 'delivered' });
    });

});

app.listen(port);
</code>```

Answer to your second question

Yes, you will need to specify the port you are using

```<code> <script src="socket.io.js"></script>

 <script>
     var socket = new io.Socket();
     socket.connect('https://mydomain:8081')

     socket.on('your_event',function() {
         console.log('your_event receivid from the server');
     });
 </script>
</code>```

Here socket will connect to port 8081

This is a simple server side code

```<code>var http = require('http');
var io = require('socket.io');
var port = 8081;

// Start the server at port 8081
var server = http.createServer();

server.listen(port);

var socket = io.listen(server);

// example listener
socket.on('event_2', function(client){
    console.log('event_2 received');
});

// example emitter
socket.emit('event_1', { hello: 'world' });
</code>```

Body:
I have a few questions about configuring socket.io for my node.js application.

When requiring var socket = require('socket.io')( /* HERE */ ), do I need to input the port my server listens where the /* HERE */ is at?

Right below the above line, I have another require function, for a .js file that contains a few constants and a function (see below). When I try to refer to 'socket' in that file it says it's undefined. But since this line is below the require line for the socket.io middleware seen above, why does it say 'undefined'?

const numbers = '1234'
function asd(req,res,next) {
  socket.emit('a')
}

module.exports = {
  asd
}

For configuring client-side socket.io, I added this line:

var socket = io.connect('https://mydomain')

Do I need to say 'mydomain:port' or is 'mydomain' enough?

Body:
This is how you use socket.io

var http = require('http');
var express = require('express');
var path = require('path');

var app = http.createServer();
var io = require('socket.io')(app);

var port = 8081;

io.on('connection', function(socket){

    socket.on('event1', function (data) {
        console.log(data);
        socket.emit('event2', { msg: 'delivered' });
    });

});

app.listen(port);

Answer to your second question

Yes, you will need to specify the port you are using

 <script src="socket.io.js"></script>

 <script>
     var socket = new io.Socket();
     socket.connect('https://mydomain:8081')

     socket.on('your_event',function() {
         console.log('your_event receivid from the server');
     });
 </script>

Here socket will connect to port 8081

This is a simple server side code

var http = require('http');
var io = require('socket.io');
var port = 8081;

// Start the server at port 8081
var server = http.createServer();

server.listen(port);

var socket = io.listen(server);

// example listener
socket.on('event_2', function(client){
    console.log('event_2 received');
});

// example emitter
socket.emit('event_1', { hello: 'world' });


问:
Azure Event Hub multiple recipients
I have a server which will need to send messages to several clients to let the clients know that something needs to be done.

I am trying to achieve this by using Azure Event Hub.

I use the following code to send the message:

await eventHubClient.SendAsync(
    new EventData(Encoding.UTF8.GetBytes(String.Format("Message {0}, {1}", i, sMessage))),
    "1")
    .ConfigureAwait(continueOnCapturedContext: false);
await eventHubClient.CloseAsync();
```

I use two WPF application as listeners which will create the listener at startup and will save the EventProcessorHost in a private variable.

When I send a message it's random  which of the listeners will process the message.

Is is possible to send messages to multiple recipients with Azure Event Hub?

答:
You need to put each listener to a separate Consumer Group.

Listeners of the same consumer group are "Competing Consumers", i.e. the first one who takes a lock on an event hub partition wins.

Title: Azure Event Hub multiple recipients

Body:
I have a server which will need to send messages to several clients to let the clients know that something needs to be done.

I am trying to achieve this by using Azure Event Hub.

I use the following code to send the message:

await eventHubClient.SendAsync(
    new EventData(Encoding.UTF8.GetBytes(String.Format("Message {0}, {1}", i, sMessage))),
    "1")
    .ConfigureAwait(continueOnCapturedContext: false);
await eventHubClient.CloseAsync();

I use two WPF application as listeners which will create the listener at startup and will save the EventProcessorHost in a private variable.

When I send a message it's random  which of the listeners will process the message.

Is is possible to send messages to multiple recipients with Azure Event Hub?


问:
FromHeader Asp.NET Core binding to default value
I'm testing Asp.Net core WebApi with the following basic controller:

```<code>[Route("test")]
public class TestController
{
    [Route("mult")]
    [HttpGet]
    public int Multiply(int x, int y)
    {
        return x * y;
    }
}
</code>```

Then, in Fiddler, I send the following request:

And, for some reason, the response is 0. Both x and y are binded to the default integer value when entering the method.

I also tried:

```<code>[Route("test")]
public class TestController
{
    [Route("mult")]
    [HttpGet]
    public int Multiply([FromHeader]int x, [FromHeader]int y)
    {
        return x * y;
    }
}
</code>```

But the result is the same. What am I doing wrong?

答: Apparently it was initially thought this wouldn't be needed and they were waiting for feedback.  However, it looks like it will likely be in the 2.1.0 milestone according to issue 5859.</p>

Body:
I'm testing Asp.Net core WebApi with the following basic controller:

[Route("test")]
public class TestController
{
    [Route("mult")]
    [HttpGet]
    public int Multiply(int x, int y)
    {
        return x * y;
    }
}

Then, in Fiddler, I send the following request:

And, for some reason, the response is 0. Both x and y are binded to the default integer value when entering the method.

I also tried:

[Route("test")]
public class TestController
{
    [Route("mult")]
    [HttpGet]
    public int Multiply([FromHeader]int x, [FromHeader]int y)
    {
        return x * y;
    }
}

But the result is the same. What am I doing wrong?


问:
Is there a driver for SQLite in Java?
I did some research on their site, and after some Google-ing, it looks like there are only drivers for C & C++. Is there an open driver that I can use with SQLLite, or is there a way I can use it with JDBC?

UPDATE

I'm doing development on Linux, but I would like to keep my options open. Native libraries would work, but wouldn't give the cross-platform freedom that I'm used to with Java.

答: There is also SQLJet, which is a pure java impl which is compatible with sqlite.</p>

Title: Is there a driver for SQLite in Java?


问:
findbugs is objecting to anonymous inner class
This code:

```<code>Set<Map.Entry<String, SSGSession>> theSet =  new TreeSet<Map.Entry<String, SSGSession>>(new Comparator<Map.Entry<String, SSGSession>>() {

        @Override
        public int compare(final Map.Entry<String, SSGSession> e1, final Map.Entry<String, SSGSession> e2) {
            return e2.getValue().getStartTime().compareTo(e1.getValue().getStartTime());
        }
    }));
</code>```

triggers a violation in Sonar, tripping the findbugs rule "SIC_INNER_SHOULD_BE_STATIC_ANON" which has the description:

This class is an inner class, but does not use its embedded reference
  to the object which created it.  This reference makes the instances of
  the class larger, and may keep the reference to the creator object
  alive longer than necessary.  If possible, the class should be made
  into a static inner class. Since anonymous inner classes cannot be
  marked as static, doing this will require refactoring the inner class
  so that it is a named inner class.

Really? Isn't this very nit-picky? Should I really refactor a one line method in an anonymous inner class to save the cost of an extra reference ? In this case, there's no possibility of it holding the reference longer than necessary.

I don't mind doing it as our strongly enforced coding standards are "zero sonar violations" but I'm strongly tempted to argue the case for a //NOSONAR here, as imho extracting a one line method to a static inner makes the code slightly harder to grok.

What do the java purists think?

答:
Just a note: anonymous inner classes are great way to leak memory, especially when used in JEE beans. Something as simple:
new HashMap<>() {{
    put"("a","b");
}};

in bean annotated with @javax.ejb.Singleton might lead to multiple instanced being kept alive as that Map keeps reference to bean.

Body:
This code:

Set<Map.Entry<String, SSGSession>> theSet =  new TreeSet<Map.Entry<String, SSGSession>>(new Comparator<Map.Entry<String, SSGSession>>() {

        @Override
        public int compare(final Map.Entry<String, SSGSession> e1, final Map.Entry<String, SSGSession> e2) {
            return e2.getValue().getStartTime().compareTo(e1.getValue().getStartTime());
        }
    }));

triggers a violation in Sonar, tripping the findbugs rule "SIC_INNER_SHOULD_BE_STATIC_ANON" which has the description:

This class is an inner class, but does not use its embedded reference
  to the object which created it.  This reference makes the instances of
  the class larger, and may keep the reference to the creator object
  alive longer than necessary.  If possible, the class should be made
  into a static inner class. Since anonymous inner classes cannot be
  marked as static, doing this will require refactoring the inner class
  so that it is a named inner class.

Really? Isn't this very nit-picky? Should I really refactor a one line method in an anonymous inner class to save the cost of an extra reference ? In this case, there's no possibility of it holding the reference longer than necessary.

I don't mind doing it as our strongly enforced coding standards are "zero sonar violations" but I'm strongly tempted to argue the case for a //NOSONAR here, as imho extracting a one line method to a static inner makes the code slightly harder to grok.

What do the java purists think?


答:
you're missing group nested controls with formGroupName directive

        Business Address

          <input type="text" class="form-control" formControlName="street" placeholder="Business Address">

        Website

          <input type="text" class="form-control" formControlName="website" placeholder="website">

        Telephone

          <input type="text" class="form-control" formControlName="mobile" placeholder="telephone">

        Email

          <input type="text" class="form-control" formControlName="email" placeholder="email">

        Facebook Page ID

          <input type="text" class="form-control" formControlName="pageId" placeholder="facebook page id">

          <button class="btn btn-success form-control" [disabled]="companyCreatForm.invalid" (click)="openContactInfo()">Continue</button>

```

Title: Cannot find control with name: formControlName in angular reactive form

Body:
you're missing group nested controls with formGroupName directive

    <div class="panel-body" formGroupName="address">
      <div class="form-group">
        <label for="address" class="col-sm-3 control-label">Business Address</label>
        <div class="col-sm-8">
          <input type="text" class="form-control" formControlName="street" placeholder="Business Address">
        </div>
      </div>
      <div class="form-group">
        <label for="website" class="col-sm-3 control-label">Website</label>
        <div class="col-sm-8">
          <input type="text" class="form-control" formControlName="website" placeholder="website">
        </div>
      </div>
      <div class="form-group">
        <label for="telephone" class="col-sm-3 control-label">Telephone</label>
        <div class="col-sm-8">
          <input type="text" class="form-control" formControlName="mobile" placeholder="telephone">
        </div>
      </div>
      <div class="form-group">
        <label for="email" class="col-sm-3 control-label">Email</label>
        <div class="col-sm-8">
          <input type="text" class="form-control" formControlName="email" placeholder="email">
        </div>
      </div>
      <div class="form-group">
        <label for="page id" class="col-sm-3 control-label">Facebook Page ID</label>
        <div class="col-sm-8">
          <input type="text" class="form-control" formControlName="pageId" placeholder="facebook page id">
        </div>
      </div>
      <div class="form-group">
        <label for="about" class="col-sm-3  control-label"></label>
        <div class="col-sm-3">
          <!--span class="btn btn-success form-control" (click)="openGeneralPanel()">Back</span-->
        </div>
        <label for="about" class="col-sm-2  control-label"></label>
        <div class="col-sm-3">
          <button class="btn btn-success form-control" [disabled]="companyCreatForm.invalid" (click)="openContactInfo()">Continue</button>
        </div>
      </div>
    </div>


问:
hasNext() method equivalent for Mongoid::Criteria in Rails for pagination
How can I tell if there are more results from a query in MongoDB?

I need to know if there are more documents after the limit query just like the question linked above, but in Ruby Mongoid.

Is there any method equivalent to hasNext for Mongoid?

UPDATE : Updating my question to give some context.

I'm trying to implement pagination but my

Here's a part of my API logic :

```<code>limit = params[:limit] + 1
query_conditions << { :_id.lt => params[:flag] }
@query = Notification.where({ '$and' => query_conditions }).limit(limit)

@last_page = @notifications_query.count < limit
</code>```

I would be sending out the first (n-1) elements of the query result and last_page boolean to let the client know if this is the last page. But I would like to know if there is any built-in function or a smarter way of determining the last page boolean.

答:
In that case, I would totally recommend kaminari-mongoid gem. It provides various helper methods to implement pagination (docs), in your case (just a rough sketch, as I don't have access to mongodb)

```<code>@query = Notification.where({ '$and' => query_conditions }).page(params[:page] || 1).per(params[:limit].to_i + 1)
@last_page = !@query.next_page
</code>```

Body:
How can I tell if there are more results from a query in MongoDB?

I need to know if there are more documents after the limit query just like the question linked above, but in Ruby Mongoid.

Is there any method equivalent to hasNext for Mongoid?

UPDATE : Updating my question to give some context.

I'm trying to implement pagination but my

Here's a part of my API logic :

limit = params[:limit] + 1
query_conditions << { :_id.lt => params[:flag] }
@query = Notification.where({ '$and' => query_conditions }).limit(limit)

@last_page = @notifications_query.count < limit

I would be sending out the first (n-1) elements of the query result and last_page boolean to let the client know if this is the last page. But I would like to know if there is any built-in function or a smarter way of determining the last page boolean.

Body:
In that case, I would totally recommend kaminari-mongoid gem. It provides various helper methods to implement pagination (docs), in your case (just a rough sketch, as I don't have access to mongodb)

@query = Notification.where({ '$and' => query_conditions }).page(params[:page] || 1).per(params[:limit].to_i + 1)
@last_page = !@query.next_page


问:
How to run an etcd cluster among pod replicas?
I have a pod/service running an application that consumes etcd as a synchronization system and datastore. I want to run etcd within the pod, such that all of the replicas form a coherent cluster. In other words, so the application in replica #1 can write "foo" to localhost:4001/v2/keys/my_key and then replica #2 can then read localhost:4001/v2/keys/my_key and get "foo" as a result.

It's not clear how this can be done, since pod replicas are not individually addressable. I could in theory create an "etcd" service exposing the cluster ports, but any requests would round-robin to all the replicas so the individual etcd nodes would not be able to find each other.

Am I approaching this problem the correct way?

答:
You can deploy etcd on kubernetes using an Operator (from the extensions/v1beta1) and the quay.io/coreos/etcd-operator image.

An example deployment with a cluster size of 3 looks like this:

```<code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: etcd-operator
spec:
  replicas: 1
  template:
    metadata:
      name: etcd-operator
      labels:
        app: etcd
        component: operator
    spec:
      containers:
      - name: etcd-operator
        image: quay.io/coreos/etcd-operator:v0.3.0
        env:
        - name: MY_POD_NAMESPACE
          valueFrom: { fieldRef: { fieldPath: metadata.namespace } }
        - name: MY_POD_NAME
          valueFrom: { fieldRef: { fieldPath: metadata.name } }

---

apiVersion: etcd.coreos.com/v1beta1
kind: Cluster
metadata:
  name: etcd-cluster
  labels:
    app: etcd
    component: cluster
spec:
  size: 3
  version: "3.1.8"
</code>```

Please be aware of the beta status of this project. However according to the maintainers the operator is now stable. I have deployed the configuration above successfully but I didn't run any of this in production.

The operator code is available on github. You can find additional documentation there.

Body:
You can deploy etcd on kubernetes using an Operator (from the extensions/v1beta1) and the quay.io/coreos/etcd-operator image.

An example deployment with a cluster size of 3 looks like this:

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: etcd-operator
spec:
  replicas: 1
  template:
    metadata:
      name: etcd-operator
      labels:
        app: etcd
        component: operator
    spec:
      containers:
      - name: etcd-operator
        image: quay.io/coreos/etcd-operator:v0.3.0
        env:
        - name: MY_POD_NAMESPACE
          valueFrom: { fieldRef: { fieldPath: metadata.namespace } }
        - name: MY_POD_NAME
          valueFrom: { fieldRef: { fieldPath: metadata.name } }

---

apiVersion: etcd.coreos.com/v1beta1
kind: Cluster
metadata:
  name: etcd-cluster
  labels:
    app: etcd
    component: cluster
spec:
  size: 3
  version: "3.1.8"

Please be aware of the beta status of this project. However according to the maintainers the operator is now stable. I have deployed the configuration above successfully but I didn't run any of this in production.

The operator code is available on github. You can find additional documentation there.


问:
How do I test "Parameters Passed In Final Call" using RhinoMocks?
What's the best way in Rhino Mocks to test that a particular parameter is passed on the FINAL call to a method? Eg mockview.SetSomething(myObj) might be called any number of times by mockview.Init, but I want to test that the last time it's called  as mockview.SetSomething(inParticular).

Now I know I can use GetArgumentsForCallsMadeOn with this, but my problem is that it doesn't work if I've subsequently changed the parameter holding variable. e.g

```<code>public interface IView
{
    void SetSomething(ViewData data);
}

public class ViewData
{
    public int Age { get; set; }
    public string Name { get; set; }

    public ViewData Person(int age, string name)
    {
        Age = age;
        Name = name;
        return (this);
    }
}

public class WorkingPresenter
{
    public void Init(IView view)
    {
        var data = new ViewData {Age = 1, Name = "One"};
        view.SetSomething(data);
        data = new ViewData {Age = 2, Name = "Two"};
        view.SetSomething(data);
        data = new ViewData {Age = 3, Name = "Three"};
    }
}

public class NotWorkingPresenter
{
    private ViewData _data;

    public void Init(IView view)
    {
        _data = new ViewData();
        view.SetSomething(_data.Person(1, "One"));
        view.SetSomething(_data.Person(2, "Two"));
        _data.Person(3, "Three");

    }
}
</code>```

then my tests are ...

```<code>    [Test]
    public void GetDataOfLastCall()
    {
        ViewData dummydata=null;
        var view = MockRepository.GenerateStub<IView>();

        //Approach 1 : This works
        var workingPresenter = new WorkingPresenter();
        workingPresenter.Init(view);
        var lastCall = view.GetArgumentsForCallsMadeOn(v => v.SetSomething(dummydata)).Count - 1;
        var lastParams = view.GetArgumentsForCallsMadeOn(v => v.SetSomething(dummydata))[lastCall];
        var lastData = (ViewData)lastParams[0];

        //Approach 2: This doesn't
        var notWorkingPresenter = new NotWorkingPresenter();
        notWorkingPresenter.Init(view);
        lastCall = view.GetArgumentsForCallsMadeOn(v => v.SetSomething(dummydata)).Count - 1;
        lastParams = view.GetArgumentsForCallsMadeOn(v => v.SetSomething(dummydata))[lastCall];
        lastData = (ViewData)lastParams[0];
</code>```

What I want is to verify that the last call to SetSomething was with {name="Two", age=2}. Now workingPresenter does this but wouldn't you expect notWorkingPresenter to do so too?

答:
There must be something else going on in your code (outside of the mocking).  I just threw together a few items:

```<code>public interface IView
{
    void SetSomething(ViewData data);
}

public class ViewData
{
    public int Age { get; set; }
    public string Name { get; set; }
}
</code>```

And I tested it with:

```<code>[TestMethod]
public void GetDataOfLastCall()
{
    var view = MockRepository.GenerateStub<IView>();

    var data = new ViewData {Age = 1, Name = "One"};
    view.SetSomething(data);
    data = new ViewData { Age = 2, Name = "Two" };
    view.SetSomething(data);
    data = new ViewData { Age = 3, Name = "Three" };

    var lastCall = view.GetArgumentsForCallsMadeOn(v => v.SetSomething(data)).Count - 1;
    var lastParams = view.GetArgumentsForCallsMadeOn(v => v.SetSomething(data))[lastCall];
    var lastData = (ViewData) lastParams[0];
}
</code>```

And I got the values of 2 and "Two" inside the ViewData.  It appears Rhino.Mocks supports what you want to do.  Could you create a failing test case that shows the issue identified in your original question (where you got a reference to the most recent information)?

Body:
What's the best way in Rhino Mocks to test that a particular parameter is passed on the FINAL call to a method? Eg mockview.SetSomething(myObj) might be called any number of times by mockview.Init, but I want to test that the last time it's called  as mockview.SetSomething(inParticular).

Now I know I can use GetArgumentsForCallsMadeOn with this, but my problem is that it doesn't work if I've subsequently changed the parameter holding variable. e.g

public interface IView
{
    void SetSomething(ViewData data);
}

public class ViewData
{
    public int Age { get; set; }
    public string Name { get; set; }

    public ViewData Person(int age, string name)
    {
        Age = age;
        Name = name;
        return (this);
    }
}

public class WorkingPresenter
{
    public void Init(IView view)
    {
        var data = new ViewData {Age = 1, Name = "One"};
        view.SetSomething(data);
        data = new ViewData {Age = 2, Name = "Two"};
        view.SetSomething(data);
        data = new ViewData {Age = 3, Name = "Three"};
    }
}

public class NotWorkingPresenter
{
    private ViewData _data;

    public void Init(IView view)
    {
        _data = new ViewData();
        view.SetSomething(_data.Person(1, "One"));
        view.SetSomething(_data.Person(2, "Two"));
        _data.Person(3, "Three");

    }
}

then my tests are ...

    [Test]
    public void GetDataOfLastCall()
    {
        ViewData dummydata=null;
        var view = MockRepository.GenerateStub<IView>();

        //Approach 1 : This works
        var workingPresenter = new WorkingPresenter();
        workingPresenter.Init(view);
        var lastCall = view.GetArgumentsForCallsMadeOn(v => v.SetSomething(dummydata)).Count - 1;
        var lastParams = view.GetArgumentsForCallsMadeOn(v => v.SetSomething(dummydata))[lastCall];
        var lastData = (ViewData)lastParams[0];

        //Approach 2: This doesn't
        var notWorkingPresenter = new NotWorkingPresenter();
        notWorkingPresenter.Init(view);
        lastCall = view.GetArgumentsForCallsMadeOn(v => v.SetSomething(dummydata)).Count - 1;
        lastParams = view.GetArgumentsForCallsMadeOn(v => v.SetSomething(dummydata))[lastCall];
        lastData = (ViewData)lastParams[0];

What I want is to verify that the last call to SetSomething was with {name="Two", age=2}. Now workingPresenter does this but wouldn't you expect notWorkingPresenter to do so too?

Body:
There must be something else going on in your code (outside of the mocking).  I just threw together a few items:

public interface IView
{
    void SetSomething(ViewData data);
}

public class ViewData
{
    public int Age { get; set; }
    public string Name { get; set; }
}

And I tested it with:

[TestMethod]
public void GetDataOfLastCall()
{
    var view = MockRepository.GenerateStub<IView>();

    var data = new ViewData {Age = 1, Name = "One"};
    view.SetSomething(data);
    data = new ViewData { Age = 2, Name = "Two" };
    view.SetSomething(data);
    data = new ViewData { Age = 3, Name = "Three" };

    var lastCall = view.GetArgumentsForCallsMadeOn(v => v.SetSomething(data)).Count - 1;
    var lastParams = view.GetArgumentsForCallsMadeOn(v => v.SetSomething(data))[lastCall];
    var lastData = (ViewData) lastParams[0];
}

And I got the values of 2 and "Two" inside the ViewData.  It appears Rhino.Mocks supports what you want to do.  Could you create a failing test case that shows the issue identified in your original question (where you got a reference to the most recent information)?