问:
how to display only userform in vba excel?
I have a userform which is created in vba and I want to display only the userform when I open my excel... is there a way to do this.. I have already tried the codes such as

```<code>application.visible = false , activewindow.visible= false
</code>```

if I use this codes in the module before open the files which are already open will b hidden along with the file which I am opening
can someone tel me how can i particularly hide the file which I want to open and display the userform

答:
Try something like this

1- Create a user form with 2 button (see below pic)

2- ThisWorkbook code

```<code>Private Sub Workbook_Open()
    UserForm1.Show vbModeless
End Sub
</code>```

3- Form code

```<code>Private Sub CommandButton1_Click()
    If Workbooks.Count > 1 Then
        Windows("Test.xlsm").Visible = True
    Else
        Application.Visible = True
    End If
End Sub

Private Sub CommandButton2_Click()
    If Workbooks.Count > 1 Then
        Windows("Test.xlsm").Visible = False
    Else
        Application.Visible = False
    End If
End Sub

Private Sub UserForm_Initialize()
    If Workbooks.Count > 1 Then
        Windows("Test.xlsm").Visible = False
    Else
        Application.Visible = False
    End If
End Sub

Private Sub UserForm_Terminate()
    If Workbooks.Count > 1 Then
        Windows("Test.xlsm").Visible = True
    Else
        Application.Visible = True
    End If
End Sub
</code>```

This will only show or hide the form's workbook. Any other workbooks opened will remain unaffected.

Body:
I have a userform which is created in vba and I want to display only the userform when I open my excel... is there a way to do this.. I have already tried the codes such as

application.visible = false , activewindow.visible= false

if I use this codes in the module before open the files which are already open will b hidden along with the file which I am opening
can someone tel me how can i particularly hide the file which I want to open and display the userform

Body:
Try something like this

1- Create a user form with 2 button (see below pic)

2- ThisWorkbook code

Private Sub Workbook_Open()
    UserForm1.Show vbModeless
End Sub

3- Form code

Private Sub CommandButton1_Click()
    If Workbooks.Count > 1 Then
        Windows("Test.xlsm").Visible = True
    Else
        Application.Visible = True
    End If
End Sub

Private Sub CommandButton2_Click()
    If Workbooks.Count > 1 Then
        Windows("Test.xlsm").Visible = False
    Else
        Application.Visible = False
    End If
End Sub

Private Sub UserForm_Initialize()
    If Workbooks.Count > 1 Then
        Windows("Test.xlsm").Visible = False
    Else
        Application.Visible = False
    End If
End Sub

Private Sub UserForm_Terminate()
    If Workbooks.Count > 1 Then
        Windows("Test.xlsm").Visible = True
    Else
        Application.Visible = True
    End If
End Sub

This will only show or hide the form's workbook. Any other workbooks opened will remain unaffected.


来源: stackexchange

问:
GitLab CI/Docker on Windows/node container - unknown network http
I'm trying to run basic pipeline that should build my web-project using GitLab CI

My setup:

GitLab CE 10.1.4 on Ubuntu 16.04

GitLab Runner 10.1.0 on Windows 10 1703 with docker executor

Docker 17.09.0-ce-win33 (13620) on same Windows machine

.gitlab-ci.yml:

```<code>image: node:latest

cache:
  paths:
    - node_modules/

build:
  script:
    - npm install
    - npm run build
</code>```

And I get failed build with this output:

```<code>Running with gitlab-runner 10.1.0 (c1ecf97f)
    on ****** (9366a476)
Using Docker executor with image node:latest ...
Using docker image sha256:4d72396806765f67139745bb91135098acaf23ce7d627e41eb4da9c62e5d6729 for predefined container...
Pulling docker image node:latest ...
Using docker image node:latest ID=sha256:cf20b9ab2cbc1b6f76e820839ad5f296b4c9a9fd04f3e74651c16ed49943dbc4 for build container...
ERROR: Job failed (system failure): dial http: unknown network http
</code>```

I've thought that problem might happen because container can't access internet, but https://hub.docker.com/r/byrnedo/alpine-curl/ curl container got the data, so I think it's not the case.

UPD:
Problem occurs when GitLab runner try to attach to container.

答:
Problem was in GitLab CI config (config.toml), docker host.

host = "http://127.0.0.1:2375" - wrong one

should be host = "tcp://127.0.0.1:2375"

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to run basic pipeline that should build my web-project using GitLab CI

My setup:

GitLab CE 10.1.4 on Ubuntu 16.04

GitLab Runner 10.1.0 on Windows 10 1703 with docker executor

Docker 17.09.0-ce-win33 (13620) on same Windows machine

.gitlab-ci.yml:

image: node:latest

cache:
  paths:
    - node_modules/

build:
  script:
    - npm install
    - npm run build

And I get failed build with this output:

Running with gitlab-runner 10.1.0 (c1ecf97f)
    on ****** (9366a476)
Using Docker executor with image node:latest ...
Using docker image sha256:4d72396806765f67139745bb91135098acaf23ce7d627e41eb4da9c62e5d6729 for predefined container...
Pulling docker image node:latest ...
Using docker image node:latest ID=sha256:cf20b9ab2cbc1b6f76e820839ad5f296b4c9a9fd04f3e74651c16ed49943dbc4 for build container...
ERROR: Job failed (system failure): dial http: unknown network http

I've thought that problem might happen because container can't access internet, but https://hub.docker.com/r/byrnedo/alpine-curl/ curl container got the data, so I think it's not the case.

UPD:
Problem occurs when GitLab runner try to attach to container.


问:
Is it better to use the column name or column index on .Net DataSets?
When retrieving values from a DataRow is it better to use the column name or column index?

The column name is more readable and easier to maintain:

```<code>int price = (int)dr["Price"];
</code>```

While column index is just faster (I think):

```<code>int price = (int)dr[3];
</code>```

Would using column names break if you decide to obfuscate the database?

答:
Accessing columns/row values via column names is better for human-reading and for forward-compatibility (if in future someone change order or count of columns).

Accissing columns/row values via column indeces is better for performance.

So, if you want change some value in one/two/..... rows, the column names are ok.
But if you want change some value in thousands of rows, you should use column index computed from column name:

```<code>int ndxMyColumn = table.Columns.IndexOf( "MyColumn" );
foreach(DataRow record in table.Rows ) {
    record[ndxMyColumn] = 15;
}
</code>```

OwnerDisplayName: tpower

ContentLicense: CC BY-SA 2.5

Body:
When retrieving values from a DataRow is it better to use the column name or column index?

The column name is more readable and easier to maintain:

int price = (int)dr["Price"];

While column index is just faster (I think):

int price = (int)dr[3];

Would using column names break if you decide to obfuscate the database?

LastEditorDisplayName: tpower

Body:
Accessing columns/row values via column names is better for human-reading and for forward-compatibility (if in future someone change order or count of columns).

Accissing columns/row values via column indeces is better for performance.

So, if you want change some value in one/two/..... rows, the column names are ok.
But if you want change some value in thousands of rows, you should use column index computed from column name:

int ndxMyColumn = table.Columns.IndexOf( "MyColumn" );
foreach(DataRow record in table.Rows ) {
    record[ndxMyColumn] = 15;
}

OwnerDisplayName: TcKs


问:
java program using sax parser
```<code><z:row ows_team="india" ows_code="1121" ows_Response="president" ows_SubFunction="finance" ows_Plant="teamindia" ows_tenure="2years" ></z:row >
</code>```

can i read xml of the above format using sax parser? and how?

答: I just google and find -> How to read XML file in Java – (SAX Parser)</p>

Title: java program using sax parser

Body:
<z:row ows_team="india" ows_code="1121" ows_Response="president" ows_SubFunction="finance" ows_Plant="teamindia" ows_tenure="2years" ></z:row >

can i read xml of the above format using sax parser? and how?


问:
Posix thread in Qt
I'm getting an error:

Invalid use of non-static member function

Basically, I need to update the UI in my thread whenever I receive a message:

```<code>if (pthread_create(&thread, NULL, MainWindow::thread_message, &sock))
{
    perror("error in creating the thread");
    // return EXIT_FAILURE;
}

void *MainWindow::thread_message(void *arg)
{
    // UI update, whenever I receive a message from the server.
}
</code>```

答:
you either need to declare thread_message of class MainWindow static or have a non-class/struct-bound function, as pthread_create requires classic c-style function pointers and there is a difference between those pointers and pointers to class/struct methods in C++.

To overcome that issue C++11 introduced std::thread which accepts both types of function pointers and frees you from having to use platform dependent thread functions in your code.

Title: Posix thread in Qt

Body:
I'm getting an error:

Invalid use of non-static member function

Basically, I need to update the UI in my thread whenever I receive a message:

if (pthread_create(&thread, NULL, MainWindow::thread_message, &sock))
{
    perror("error in creating the thread");
    // return EXIT_FAILURE;
}

void *MainWindow::thread_message(void *arg)
{
    // UI update, whenever I receive a message from the server.
}


问:
cant find the right node value for my XML
im making a project that has to display xml data to my website but im stuck. I need to figure out how to display 'ows_Person' from the 'z:row'. i dont know how to define it in the [0].ChildNodes[0].nodeValue, i would appreciate some help.

Javascript code:

```<code><script>
var xmlhttp, xmlDoc;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "test.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
document.getElementById("name").innerHTML=
xmlDoc.getElementsByTagName("z:row")[0].childNodes[0].nodeValue;
document.getElementById("ID").innerHTML=
xmlDoc.getElementsByTagName("z:row")[0].childNodes[0].nodeValue;
document.getElementById("Title").innerHTML=
xmlDoc.getElementsByTagName("z:row")[0].childNodes[0].nodeValue;
</script>
</code>```

XML Code:

```<code><xml xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882"
xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882" xmlns:rs="urn:schemas-
microsoft-com:rowset" xmlns:z="#RowsetSchema">
<s:Schema id="RowsetSchema">
<s:ElementType name="row" content="eltOnly" rs:CommandTimeout="30">
<s:AttributeType name="ows_Attachments" rs:name="Attachments" rs:number="1">
<s:datatype dt:type="boolean" dt:maxLength="1" />
</s:AttributeType>
<s:AttributeType name="ows_LinkTitle" rs:name="Title" rs:number="2">
<s:datatype dt:type="string" dt:maxLength="512" />
</s:AttributeType>
<s:AttributeType name="ows_Person" rs:name="Person" rs:number="3">
<s:datatype dt:type="string" dt:lookup="true" dt:maxLength="512" />
</s:AttributeType>
<s:AttributeType name="ows_ID" rs:name="ID" rs:number="4">
<s:datatype dt:type="i4" dt:maxLength="4" />
</s:AttributeType>
<s:AttributeType name="ows_Modified" rs:name="Modified" rs:number="5">
<s:datatype dt:type="datetime" dt:maxLength="8" />
</s:AttributeType>
<s:AttributeType name="ows_DocIcon" rs:name="Type" rs:number="6">
<s:datatype dt:type="string" dt:maxLength="512" />
</s:AttributeType>
</s:ElementType>
</s:Schema>
<rs:data>
<z:row ows_Attachments="0" ows_LinkTitle="Test" ows_Person="1257;#Stefan de
Boer" ows_ID="1" ows_Modified="2017-11-15 15:00:22" />
<z:row ows_Attachments="0" ows_LinkTitle="testtesttesttest"
ows_Person="1256;#Kevin" ows_ID="2" ows_Modified="2017-11-16 10:46:07"
/>
<z:row ows_Attachments="0" ows_LinkTitle="nog een test"
ows_Person="1258;#Naomi" ows_ID="3" ows_Modified="2017-11-16
10:53:11" />
<z:row ows_Attachments="0" ows_LinkTitle="alweer een test"
ows_Person="1257;#Stefan" ows_ID="4" ows_Modified="2017-11-16
10:53:44" />
</rs:data>
</xml>
</code>```

答:
Just try with getAttribute:

```<code>xmlDoc.getElementsByTagName("z:row")[0].getAttribute('ows_person')
</code>```

Body:
im making a project that has to display xml data to my website but im stuck. I need to figure out how to display 'ows_Person' from the 'z:row'. i dont know how to define it in the [0].ChildNodes[0].nodeValue, i would appreciate some help.

Javascript code:

XML Code:

<xml xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882"
xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882" xmlns:rs="urn:schemas-
microsoft-com:rowset" xmlns:z="#RowsetSchema">
<s:Schema id="RowsetSchema">
<s:ElementType name="row" content="eltOnly" rs:CommandTimeout="30">
<s:AttributeType name="ows_Attachments" rs:name="Attachments" rs:number="1">
<s:datatype dt:type="boolean" dt:maxLength="1" />
</s:AttributeType>
<s:AttributeType name="ows_LinkTitle" rs:name="Title" rs:number="2">
<s:datatype dt:type="string" dt:maxLength="512" />
</s:AttributeType>
<s:AttributeType name="ows_Person" rs:name="Person" rs:number="3">
<s:datatype dt:type="string" dt:lookup="true" dt:maxLength="512" />
</s:AttributeType>
<s:AttributeType name="ows_ID" rs:name="ID" rs:number="4">
<s:datatype dt:type="i4" dt:maxLength="4" />
</s:AttributeType>
<s:AttributeType name="ows_Modified" rs:name="Modified" rs:number="5">
<s:datatype dt:type="datetime" dt:maxLength="8" />
</s:AttributeType>
<s:AttributeType name="ows_DocIcon" rs:name="Type" rs:number="6">
<s:datatype dt:type="string" dt:maxLength="512" />
</s:AttributeType>
</s:ElementType>
</s:Schema>
<rs:data>
<z:row ows_Attachments="0" ows_LinkTitle="Test" ows_Person="1257;#Stefan de
Boer" ows_ID="1" ows_Modified="2017-11-15 15:00:22" />
<z:row ows_Attachments="0" ows_LinkTitle="testtesttesttest"
ows_Person="1256;#Kevin" ows_ID="2" ows_Modified="2017-11-16 10:46:07"
/>
<z:row ows_Attachments="0" ows_LinkTitle="nog een test"
ows_Person="1258;#Naomi" ows_ID="3" ows_Modified="2017-11-16
10:53:11" />
<z:row ows_Attachments="0" ows_LinkTitle="alweer een test"
ows_Person="1257;#Stefan" ows_ID="4" ows_Modified="2017-11-16
10:53:44" />
</rs:data>
</xml>

Body:
Just try with getAttribute:

xmlDoc.getElementsByTagName("z:row")[0].getAttribute('ows_person')


问:
Docker on Windows does not support COPY --from?
I am trying to make use of this Docker construct:

Optionally a name can be given to a new build stage by adding AS name
  to the FROM instruction. The name can be used in subsequent FROM and
  COPY --from= instructions to refer to the image built in
  this stage.

But I get this message:

```<code>COPY failed: stat /var/lib/docker/tmp/docker-builder869050639/-–from=build-env:
no such file or directory
</code>```

Is copying files from a previous stage supported on Docker for Windows 17.09.0-ce-win33 (13620)? This is the Dockerfile:

```<code>FROM microsoft/dotnet:2.0-sdk AS build-env

WORKDIR /app
COPY ./ ./
RUN dotnet build ProviderApi.csproj
RUN dotnet publish ProviderApi.csproj -c Release -r linux-x64 -o out

FROM microsoft/dotnet:2.0-runtime-deps
WORKDIR /app
COPY -–from=build-env /app/out/ ./
EXPOSE 80
ENTRYPOINT ["./ProviderApi"]
</code>```

答:
The problem was that the destination directory was not present in the docker image of the final build stage. Here is the working Dockerfile for future reference.</p>

```<code>FROM microsoft/aspnetcore-build:2.0.3-stretch AS build-env

WORKDIR /app
COPY . ./
RUN dotnet build ProviderApi.csproj
RUN dotnet publish ProviderApi.csproj -c Release -r linux-x64 -o out

FROM microsoft/aspnetcore:2.0.3-stretch
RUN mkdir /app
COPY --from=build-env /app/out /app

ENV ASPNETCORE_URLS=http://+:5001
EXPOSE 5001

ENTRYPOINT ["/app/ProviderApi"]
</code>```

Body:
I am trying to make use of this Docker construct:

Optionally a name can be given to a new build stage by adding AS name
  to the FROM instruction. The name can be used in subsequent FROM and
  COPY --from= instructions to refer to the image built in
  this stage.

But I get this message:

COPY failed: stat /var/lib/docker/tmp/docker-builder869050639/-–from=build-env:
no such file or directory

Is copying files from a previous stage supported on Docker for Windows 17.09.0-ce-win33 (13620)? This is the Dockerfile:

FROM microsoft/dotnet:2.0-sdk AS build-env

WORKDIR /app
COPY ./ ./
RUN dotnet build ProviderApi.csproj
RUN dotnet publish ProviderApi.csproj -c Release -r linux-x64 -o out

FROM microsoft/dotnet:2.0-runtime-deps
WORKDIR /app
COPY -–from=build-env /app/out/ ./
EXPOSE 80
ENTRYPOINT ["./ProviderApi"]

Body:
The problem was that the destination directory was not present in the docker image of the final build stage. Here is the working Dockerfile for future reference.

FROM microsoft/aspnetcore-build:2.0.3-stretch AS build-env

WORKDIR /app
COPY . ./
RUN dotnet build ProviderApi.csproj
RUN dotnet publish ProviderApi.csproj -c Release -r linux-x64 -o out

FROM microsoft/aspnetcore:2.0.3-stretch
RUN mkdir /app
COPY --from=build-env /app/out /app

ENV ASPNETCORE_URLS=http://+:5001
EXPOSE 5001

ENTRYPOINT ["/app/ProviderApi"]


问:
Lambda function
Why these two have different result?

input:

```<code>print((lambda x: x**2 + 5*x + 4) (-4))
</code>```

output:

```<code>0
</code>```

input:

```<code>print(lambda x: x**2 + 5*x + 4, -4)
</code>```

output:

```<code><function <lambda> at 0x00ECD588> -4
</code>```

答:
The first one:

```<code>print((lambda x: x**2 + 5*x + 4) (-4))
</code>```

This is:

Make a function (lambda x: x**2 + 5*x + 4)

Call the function with (-4) as an argument

Print the result: 0

The second one:

```<code>print(lambda x: x**2 + 5*x + 4, -4)
</code>```

This is:

Make a function lambda x: x**2 + 5*x + 4

Print the function: <function <lambda> at 0x1071230d0> ...

... followed by the number -4

ContentLicense: CC BY-SA 4.0

Title: Lambda function

Body:
Why these two have different result?

input:

print((lambda x: x**2 + 5*x + 4) (-4))

output:

0

input:

print(lambda x: x**2 + 5*x + 4, -4)

output:

<function <lambda> at 0x00ECD588> -4

Body:
The first one:

print((lambda x: x**2 + 5*x + 4) (-4))

This is:

Make a function (lambda x: x**2 + 5*x + 4)

Call the function with (-4) as an argument

Print the result: 0

The second one:

print(lambda x: x**2 + 5*x + 4, -4)

This is:

Make a function lambda x: x**2 + 5*x + 4

Print the function: <function <lambda> at 0x1071230d0> ...

... followed by the number -4


问:
'Uncaught Error: Can't resolve all parameters for' runtime error when upgrading from Angular 4 to 5.0.1
This is fine in Angular 4.x, just not Angular 5.0.1.  This project was generated with Angular CLI.

```<code>compiler.js:466 Uncaught Error: Can't resolve all parameters for RegistrationService: (?).
    at syntaxError (compiler.js:466)
    at CompileMetadataResolver._getDependenciesMetadata (compiler.js:15546)
    at CompileMetadataResolver._getTypeMetadata (compiler.js:15381)
    at CompileMetadataResolver._getInjectableMetadata (compiler.js:15361)
    at CompileMetadataResolver.getProviderMetadata (compiler.js:15721)
    at eval (compiler.js:15632)
    at Array.forEach (<anonymous>)
    at CompileMetadataResolver._getProvidersMetadata (compiler.js:15592)
    at CompileMetadataResolver.getNgModuleMetadata (compiler.js:15160)
    at CompileMetadataResolver.getNgModuleSummary (compiler.js:14998)
syntaxError @ compiler.js:466
CompileMetadataResolver._getDependenciesMetadata @ compiler.js:15546
CompileMetadataResolver._getTypeMetadata @ compiler.js:15381
CompileMetadataResolver._getInjectableMetadata @ compiler.js:15361
CompileMetadataResolver.getProviderMetadata @ compiler.js:15721
(anonymous) @ compiler.js:15632
CompileMetadataResolver._getProvidersMetadata @ compiler.js:15592
CompileMetadataResolver.getNgModuleMetadata @ compiler.js:15160
CompileMetadataResolver.getNgModuleSummary @ compiler.js:14998
(anonymous) @ compiler.js:15086
CompileMetadataResolver.getNgModuleMetadata @ compiler.js:15071
JitCompiler._loadModules @ compiler.js:33486
JitCompiler._compileModuleAndComponents @ compiler.js:33447
JitCompiler.compileModuleAsync @ compiler.js:33363
CompilerImpl.compileModuleAsync @ platform-browser-dynamic.js:230
PlatformRef.bootstrapModule @ core.js:5446
(anonymous) @ main.ts:12
../../../../../src/main.ts @ main.bundle.js:640
__webpack_require__ @ inline.bundle.js:55
1 @ main.bundle.js:670
__webpack_require__ @ inline.bundle.js:55
webpackJsonpCallback @ inline.bundle.js:26
(anonymous) @ main.bundle.js:1
</code>```

This is what the constructor looks like:

```<code>     constructor(
    private apiHelperService: ApiHelperService
  ) {
  }
</code>```

The class has @Injectable()

```<code>    @Injectable()
export class ApiHelperService {
</code>```

It has also properly imported into the module providers.

```<code>providers: [
    AuthGuard,
    ApiHelperService,
</code>```

If I change it to this, then the error goes away and it works, but then it wants you to change every constructor in the entire solution to this syntax, which I don't believe to be correct.

```<code>@Inject(ApiHelperService) private apiHelperService: ApiHelperService
</code>```

Here is my tsconfig.json, which does have emitDecoratorMetadata properly set to true

```<code>{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": "src",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  }
}
</code>```

答:
In Angular 5 Update blog post the author mentions that they are using a static injector instead of a reflection based one and mentions that the reflection polyfills are no longer needed but in my case it was.

If you removed the polyfills for reflections try adding them again:

```<code>import 'core-js/es6/reflect';
import 'core-js/es7/reflect';
</code>```

I hope it woks for you as well.

Body:
This is fine in Angular 4.x, just not Angular 5.0.1.  This project was generated with Angular CLI.

compiler.js:466 Uncaught Error: Can't resolve all parameters for RegistrationService: (?).
    at syntaxError (compiler.js:466)
    at CompileMetadataResolver._getDependenciesMetadata (compiler.js:15546)
    at CompileMetadataResolver._getTypeMetadata (compiler.js:15381)
    at CompileMetadataResolver._getInjectableMetadata (compiler.js:15361)
    at CompileMetadataResolver.getProviderMetadata (compiler.js:15721)
    at eval (compiler.js:15632)
    at Array.forEach (<anonymous>)
    at CompileMetadataResolver._getProvidersMetadata (compiler.js:15592)
    at CompileMetadataResolver.getNgModuleMetadata (compiler.js:15160)
    at CompileMetadataResolver.getNgModuleSummary (compiler.js:14998)
syntaxError @ compiler.js:466
CompileMetadataResolver._getDependenciesMetadata @ compiler.js:15546
CompileMetadataResolver._getTypeMetadata @ compiler.js:15381
CompileMetadataResolver._getInjectableMetadata @ compiler.js:15361
CompileMetadataResolver.getProviderMetadata @ compiler.js:15721
(anonymous) @ compiler.js:15632
CompileMetadataResolver._getProvidersMetadata @ compiler.js:15592
CompileMetadataResolver.getNgModuleMetadata @ compiler.js:15160
CompileMetadataResolver.getNgModuleSummary @ compiler.js:14998
(anonymous) @ compiler.js:15086
CompileMetadataResolver.getNgModuleMetadata @ compiler.js:15071
JitCompiler._loadModules @ compiler.js:33486
JitCompiler._compileModuleAndComponents @ compiler.js:33447
JitCompiler.compileModuleAsync @ compiler.js:33363
CompilerImpl.compileModuleAsync @ platform-browser-dynamic.js:230
PlatformRef.bootstrapModule @ core.js:5446
(anonymous) @ main.ts:12
../../../../../src/main.ts @ main.bundle.js:640
__webpack_require__ @ inline.bundle.js:55
1 @ main.bundle.js:670
__webpack_require__ @ inline.bundle.js:55
webpackJsonpCallback @ inline.bundle.js:26
(anonymous) @ main.bundle.js:1

This is what the constructor looks like:

     constructor(
    private apiHelperService: ApiHelperService
  ) {
  }

The class has @Injectable()

    @Injectable()
export class ApiHelperService {

It has also properly imported into the module providers.

providers: [
    AuthGuard,
    ApiHelperService,

If I change it to this, then the error goes away and it works, but then it wants you to change every constructor in the entire solution to this syntax, which I don't believe to be correct.

@Inject(ApiHelperService) private apiHelperService: ApiHelperService

Here is my tsconfig.json, which does have emitDecoratorMetadata properly set to true

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": "src",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  }
}

Body:
In Angular 5 Update blog post the author mentions that they are using a static injector instead of a reflection based one and mentions that the reflection polyfills are no longer needed but in my case it was.

If you removed the polyfills for reflections try adding them again:

import 'core-js/es6/reflect';
import 'core-js/es7/reflect';

I hope it woks for you as well.


问:
how to set column name in DataTable
I am taking Excel data into DataTable but it is taking Excel Column name as first row of data in DataTable. So help me to set Excel's first row as columns in DataTable.
PS: I am using Microsoft.Offfice.Interop.Excel and System.Data.DataTable namespace
This is my code:

```<code>connExcel.Open();
cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
oda.SelectCommand = cmdExcel;
new System.Data.OleDb.OleDbDataAdapter(cmdExcel).Fill(dt);
connExcel.Close();
</code>```

I am getting all the data of specified excel sheet into DataTable dt but it is taking Excel column names as first row of data in Datatable

答:
```<code>DataTable tab = new DataTable();
for (int i = 0; i < tab.Columns.Count; i++)
{
    tab.Columns[i].Caption = "example"
}
</code>```

Title: how to set column name in DataTable

Body:
I am taking Excel data into DataTable but it is taking Excel Column name as first row of data in DataTable. So help me to set Excel's first row as columns in DataTable.
PS: I am using Microsoft.Offfice.Interop.Excel and System.Data.DataTable namespace
This is my code:

connExcel.Open();
cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
oda.SelectCommand = cmdExcel;
new System.Data.OleDb.OleDbDataAdapter(cmdExcel).Fill(dt);
connExcel.Close();

I am getting all the data of specified excel sheet into DataTable dt but it is taking Excel column names as first row of data in Datatable


问:
Creating new folders in java with dynamic naming
```<code>File file = new File("C:\\Users\\user\\Desktop\\new\\"+count);
if (!file.exists()) {
    if (file.mkdir()) {
        System.out.println("Directory is created!");
    } else {
        System.out.println("Failed to create directory!");
    }
</code>```

This is my current code for making a folder. As you can see, I am using count (an integer) as my folder name. I have initialized count to zero. Now, I need to increment the counter for new folder, for the dynamic naming of folders, as required for my project. What modification should I do?

答:
Use recursive method , if Folder already exists this will create new folder using counter</p>

```<code>int count;

public void createFolder() {
    File file = new File("C:\\Users\\user\\Desktop\\new\\"" + count);
    if (!file.exists()) {
        if (file.mkdir()) {
            System.out.println("Directory is created!");
            count++;
        }
    } else {
        System.out.println("Failed to create directory!");
        count++;
        createFolder();
    }
}
</code>```

Body:
File file = new File("C:\\Users\\user\\Desktop\\new\\"+count);
if (!file.exists()) {
    if (file.mkdir()) {
        System.out.println("Directory is created!");
    } else {
        System.out.println("Failed to create directory!");
    }

This is my current code for making a folder. As you can see, I am using count (an integer) as my folder name. I have initialized count to zero. Now, I need to increment the counter for new folder, for the dynamic naming of folders, as required for my project. What modification should I do?

Body:
Use recursive method , if Folder already exists this will create new folder using counter

int count;

public void createFolder() {
    File file = new File("C:\\Users\\user\\Desktop\\new\\"" + count);
    if (!file.exists()) {
        if (file.mkdir()) {
            System.out.println("Directory is created!");
            count++;
        }
    } else {
        System.out.println("Failed to create directory!");
        count++;
        createFolder();
    }
}


问:
Work-around for enclosing instance ineligible for garbage collection
The enclosing instance here isn't eligible for garbage collection as long as the enclosed instance is alive, right?

```<code>interface Foo<T> {
    T compute();

    default Foo<T> memoize() {
        return new Foo<>() {
            T result = null;

            boolean cached = false;

            @Override
            public T compute() {
                if (!cached) {
                    result = Foo.this.compute();
                    cached = true;
                }
                return result;
            }
        };
    }
}
</code>```

Does this solve that problem?

```<code>interface Foo<T> {
    T compute();

    default Foo<T> memoize() {
        return Foo.memoize(this);
    }

    private static <T> Foo<T> memoize(Foo<T> original) {
        class Bar implements Foo<T> {
            T result = null;

            Foo<T> foo;

            Bar(Foo<T> original) {
                foo = original;
            }

            @Override
            public T compute() {
                if (foo != null) {
                    result = foo.compute();
                    foo = null;
                }
                return result;
            }
        }
        return new Bar(original);
    }
}
</code>```

答:
In the first case, the anonymous inner class 'captures' a reference to the enclosing Foo by using Foo.this. As the anonymous class keeps this reference indefinitely, the enclosing Foo is not eligible for garbage collection until the anonymous class is also eligible.

In the second example, this reference is discarded after compute has been called once, so the enclosing class is eligible for garbage collection after that.

See Accessing Members of an Enclosing Class

Body:
The enclosing instance here isn't eligible for garbage collection as long as the enclosed instance is alive, right?

interface Foo<T> {
    T compute();

    default Foo<T> memoize() {
        return new Foo<>() {
            T result = null;

            boolean cached = false;

            @Override
            public T compute() {
                if (!cached) {
                    result = Foo.this.compute();
                    cached = true;
                }
                return result;
            }
        };
    }
}

Does this solve that problem?

interface Foo<T> {
    T compute();

    default Foo<T> memoize() {
        return Foo.memoize(this);
    }

    private static <T> Foo<T> memoize(Foo<T> original) {
        class Bar implements Foo<T> {
            T result = null;

            Foo<T> foo;

            Bar(Foo<T> original) {
                foo = original;
            }

            @Override
            public T compute() {
                if (foo != null) {
                    result = foo.compute();
                    foo = null;
                }
                return result;
            }
        }
        return new Bar(original);
    }
}


问:
iOS Alamofire stop all requests
Is there any way I can for example say:

Alamofire.Manager.cancelAllRequests() or Alamofire.Manager.sharedInstance.cancelAllRequests()?

Of course it would be great if these requests especially in case of image download would only be paused for later when I'll cal the same URL but... I need at least to be able to cancel all requests at a global level. Some suggestions ?

In my app I have a wrapper above the Alamofire.request(.Post....) way of doing things so I would really appreciate not making me create or interact with Manager class in another way besides that specified above.

答:
Below Code stops the Requests in [Swift 3]:

Plus the code works for Alamofire v3 & v4 plus for iOS 8+.

```<code>func stopTheDamnRequests(){
    if #available(iOS 9.0, *) {
        Alamofire.SessionManager.default.session.getAllTasks { (tasks) in
            tasks.forEach{ $0.cancel() }
        }
    } else {
        Alamofire.SessionManager.default.session.getTasksWithCompletionHandler { (sessionDataTask, uploadData, downloadData) in
            sessionDataTask.forEach { $0.cancel() }
            uploadData.forEach { $0.cancel() }
            downloadData.forEach { $0.cancel() }
        }
    }
}
</code>```

Simply Copy and paste the function.

Title: iOS Alamofire stop all requests

Body:
Below Code stops the Requests in [Swift 3]:

Plus the code works for Alamofire v3 & v4 plus for iOS 8+.

func stopTheDamnRequests(){
    if #available(iOS 9.0, *) {
        Alamofire.SessionManager.default.session.getAllTasks { (tasks) in
            tasks.forEach{ $0.cancel() }
        }
    } else {
        Alamofire.SessionManager.default.session.getTasksWithCompletionHandler { (sessionDataTask, uploadData, downloadData) in
            sessionDataTask.forEach { $0.cancel() }
            uploadData.forEach { $0.cancel() }
            downloadData.forEach { $0.cancel() }
        }
    }
}

Simply Copy and paste the function.


问:
Custom "confirm" dialog in JavaScript?
I've been working on an ASP.net project that uses custom 'modal dialogs'.  I use scare quotes here because I understand that the 'modal dialog' is simply a div in my html document that is set to appear "on top" of the rest of the document and is not a modal dialog in the true sense of the word.

In many parts of the web site, I have code that looks like this:

```<code>var warning = 'Are you sure you want to do this?';
if (confirm(warning)) {
    // Do something
}
else {
    // Do something else
}
</code>```

This is okay, but it would be nice to make the confirm dialog match the style of the rest of the page.

However, since it is not a true modal dialog, I think that I need to write something like this: (I use jQuery-UI in this example)

```<code><div id='modal_dialog'>
    <div class='title'>
    </div>
    <input type='button' value='yes' id='btnYes' />
    <input type='button' value='no' id='btnNo' />
</div>

<script>
function DoSomethingDangerous() {
    var warning = 'Are you sure you want to do this?';
    $('.title').html(warning);
    var dialog = $('#modal_dialog').dialog();
    function Yes() {
        dialog.dialog('close');
        // Do something
    }
    function No() {
        dialog.dialog('close');
        // Do something else
    }
    $('#btnYes').click(Yes);
    $('#btnNo').click(No);
}
</code>```

Is this a good way to accomplish what I want, or is there a better way?

答:
var confirmBox = '
' +
    '
' +
    '
' +
    '<button type="button" class="close m-4 c-pointer" data-dismiss="modal" aria-label="Close">' +
    '×' +
    '</button>' +
    '

' +
    '
' +
    'OK' +
    '<button type="button" class="btn btn-secondary abortBtn btn-sm" data-dismiss="modal">Abbrechen</button>' +
    '
' +
    '
' +
    '
' +
    '
';

var dialog = function(el, text, trueCallback, abortCallback) {

    el.click(function(e) {

        var thisConfirm = $(confirmBox).clone();

        thisConfirm.find('.modal-body').text(text);

        e.preventDefault();
        $('body').append(thisConfirm);
        $(thisConfirm).modal('show');

        if (abortCallback) {
            $(thisConfirm).find('.abortBtn').click(function(e) {
                e.preventDefault();
                abortCallback();
                $(thisConfirm).modal('hide');
            });
        }

        if (trueCallback) {
            $(thisConfirm).find('.yesBtn').click(function(e) {
                e.preventDefault();
                trueCallback();
                $(thisConfirm).modal('hide');
            });
        } else {

            if (el.prop('nodeName') == 'A') {
                $(thisConfirm).find('.yesBtn').attr('href', el.attr('href'));
            }

            if (el.attr('type') == 'submit') {
                $(thisConfirm).find('.yesBtn').click(function(e) {
                    e.preventDefault();
                    el.off().click();
                });
            }
        }

        $(thisConfirm).on('hidden.bs.modal', function(e) {
            $(this).remove();
        });

    });
}

// custom confirm
$(function() {
    $('[data-confirm]').each(function() {
        dialog($(this), $(this).attr('data-confirm'));
    });

    dialog($('#customCallback'), "dialog with custom callback", function() {

        alert("hi there");

    });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.test {
  display:block;
  padding: 5p 10px;
  background:orange;
  color:white;
  border-radius:4px;
  margin:0;
  border:0;
  width:150px;
  text-align:center;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

example 1
leave website

example 2
<form action="">
<button class="test" type="submit" data-confirm="send form to delete some files?">delete some files</button>
</form>

example 3
with callback```

Title: Custom "confirm" dialog in JavaScript?

Body:
I've been working on an ASP.net project that uses custom 'modal dialogs'.  I use scare quotes here because I understand that the 'modal dialog' is simply a div in my html document that is set to appear "on top" of the rest of the document and is not a modal dialog in the true sense of the word.

In many parts of the web site, I have code that looks like this:

var warning = 'Are you sure you want to do this?';
if (confirm(warning)) {
    // Do something
}
else {
    // Do something else
}

This is okay, but it would be nice to make the confirm dialog match the style of the rest of the page.

However, since it is not a true modal dialog, I think that I need to write something like this: (I use jQuery-UI in this example)

    <input type='button' value='yes' id='btnYes' />
    <input type='button' value='no' id='btnNo' />

Body:
var confirmBox = '<div class="modal fade confirm-modal">' +
    '<div class="modal-dialog modal-sm" role="document">' +
    '<div class="modal-content">' +
    '<button type="button" class="close m-4 c-pointer" data-dismiss="modal" aria-label="Close">' +
    '<span aria-hidden="true">&times;</span>' +
    '</button>' +
    '<div class="modal-body pb-5"></div>' +
    '<div class="modal-footer pt-3 pb-3">' +
    '<a href="#" class="btn btn-primary yesBtn btn-sm">OK</a>' +
    '<button type="button" class="btn btn-secondary abortBtn btn-sm" data-dismiss="modal">Abbrechen</button>' +
    '</div>' +
    '</div>' +
    '</div>' +
    '</div>';

var dialog = function(el, text, trueCallback, abortCallback) {

    el.click(function(e) {

        var thisConfirm = $(confirmBox).clone();

        thisConfirm.find('.modal-body').text(text);

        e.preventDefault();
        $('body').append(thisConfirm);
        $(thisConfirm).modal('show');

        if (abortCallback) {
            $(thisConfirm).find('.abortBtn').click(function(e) {
                e.preventDefault();
                abortCallback();
                $(thisConfirm).modal('hide');
            });
        }

        if (trueCallback) {
            $(thisConfirm).find('.yesBtn').click(function(e) {
                e.preventDefault();
                trueCallback();
                $(thisConfirm).modal('hide');
            });
        } else {

            if (el.prop('nodeName') == 'A') {
                $(thisConfirm).find('.yesBtn').attr('href', el.attr('href'));
            }

            if (el.attr('type') == 'submit') {
                $(thisConfirm).find('.yesBtn').click(function(e) {
                    e.preventDefault();
                    el.off().click();
                });
            }
        }

        $(thisConfirm).on('hidden.bs.modal', function(e) {
            $(this).remove();
        });

    });
}

// custom confirm
$(function() {
    $('[data-confirm]').each(function() {
        dialog($(this), $(this).attr('data-confirm'));
    });

    dialog($('#customCallback'), "dialog with custom callback", function() {

        alert("hi there");

    });

});

.test {
  display:block;
  padding: 5p 10px;
  background:orange;
  color:white;
  border-radius:4px;
  margin:0;
  border:0;
  width:150px;
  text-align:center;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

example 1
<a class="test" href="http://example" data-confirm="do you want really leave the website?">leave website</a><br><br>

example 2
<form action="">
<button class="test" type="submit" data-confirm="send form to delete some files?">delete some files</button>
</form><br><br>

example 3
<span class="test"  id="customCallback">with callback</span>


问:
Postgres - simplify repeat of select subqueries based on dates
Newbie with Postgres (9.6).

I have 2 tables

sales_account (list of customers)

journal (transactions line invoices payments)

I want to create another table called balances which has a summary of outstanding transactions based on periods (like 7 days, 14 days, 30 days, 60 days or older).

I have written the query in long hand as sub-queries (it takes far too long to generate - there are over 15m journal records) but am looking for any hints as to how I can simplify the query.

Thank you.

```<code>INSERT INTO balances (sales_account,
    balance,
    period_1,
    period_2,
    period_3,
    period_4,
    period_5)

SELECT  sales_account.id,

(SELECT coalesce(sum(journal.outstanding),0)
FROM journal
WHERE journal.sales_account = sales_account.id AND
journal.status='Active'), -- overall balance

(SELECT coalesce(sum(journal.outstanding),0)
FROM journal
WHERE journal.sales_account = sales_account.id AND
journal.status='Active' AND
journal.reversed_by is null AND
journal.original_id is null AND
journal.transaction_date <= CURRENT_DATE - interval '7 days'), -- current

(SELECT coalesce(sum(journal.outstanding),0)
FROM journal
WHERE journal.sales_account = sales_account.id AND
journal.status='Active' AND
journal.reversed_by is null AND
journal.original_id is null AND
journal.transaction_date <= CURRENT_DATE  - interval '14 days' AND
journal.transaction_date >= CURRENT_DATE - interval '8 days'), -- 8-14 days

(SELECT coalesce(sum(journal.outstanding),0)
FROM journal
WHERE journal.sales_account = sales_account.id AND
journal.status='Active' AND
journal.transaction_date <=CURRENT_DATE  - interval '30 days' AND
journal.transaction_date >= CURRENT_DATE - interval '15 days'), -- 22-30 days

(SELECT coalesce(sum(journal.outstanding),0)
FROM journal
WHERE journal.sales_account = sales_account.id AND
journal.status='Active' AND
journal.transaction_date >= CURRENT_DATE - interval '31 days' AND
journal.transaction_date <=CURRENT_DATE  - interval '60 days'), -- 31-60 days

(SELECT coalesce(sum(journal.outstanding),0)
FROM journal
WHERE journal.sales_account = sales_account.id AND
journal.status='Active' AND
journal.transaction_date >= CURRENT_DATE - interval '61 days') -- 61+ days

FROM sales_account;
</code>```

答:
You can use FILTER expression to simplify SUM:

```<code>INSERT INTO balances (sales_account,
    balance,
    period_1,
    period_2,
    period_3,
    period_4,
    period_5)
SELECT
    COALESCE(sum(journal.outstanding), 0) AS overall,
    COALESCE(sum(journal.outstanding)
        FILTER (WHERE journal.transaction_date >= CURRENT_DATE - interval '7 days'
            AND journal.reversed_by IS NULL
            AND journal.original_id IS NULL), 0) AS period_1,
    COALESCE(sum(journal.outstanding)
        FILTER (WHERE journal.transaction_date >= CURRENT_DATE - interval '14 days'
            AND journal.transaction_date <= CURRENT_DATE  - interval ' 8 days'
            AND journal.reversed_by IS NULL
            AND journal.original_id IS NULL), 0) AS period_2,
    COALESCE(sum(journal.outstanding)
        FILTER (WHERE journal.transaction_date >= CURRENT_DATE - interval '30 days'
            AND journal.transaction_date <= CURRENT_DATE  - interval '22 days'), 0) AS period_3,
    COALESCE(sum(journal.outstanding)
        FILTER (WHERE journal.transaction_date >= CURRENT_DATE - interval '60 days'
            AND journal.transaction_date <= CURRENT_DATE  - interval ' 31 days'), 0) AS period_4,
    COALESCE(sum(journal.outstanding)
        FILTER (WHERE journal.transaction_date >= CURRENT_DATE - interval '61 days'), 0) AS period_5
FROM
    journal
    JOIN sales_account ON (journal.sales_account = sales_account.id)
WHERE
    journal.status='Active';
</code>```

Body:
Newbie with Postgres (9.6).

I have 2 tables

sales_account (list of customers)

journal (transactions line invoices payments)

I want to create another table called balances which has a summary of outstanding transactions based on periods (like 7 days, 14 days, 30 days, 60 days or older).

I have written the query in long hand as sub-queries (it takes far too long to generate - there are over 15m journal records) but am looking for any hints as to how I can simplify the query.

Thank you.

INSERT INTO balances (sales_account,
    balance,
    period_1,
    period_2,
    period_3,
    period_4,
    period_5)

SELECT  sales_account.id,

(SELECT coalesce(sum(journal.outstanding),0)
FROM journal
WHERE journal.sales_account = sales_account.id AND
journal.status='Active'), -- overall balance

(SELECT coalesce(sum(journal.outstanding),0)
FROM journal
WHERE journal.sales_account = sales_account.id AND
journal.status='Active' AND
journal.reversed_by is null AND
journal.original_id is null AND
journal.transaction_date <= CURRENT_DATE - interval '7 days'), -- current

(SELECT coalesce(sum(journal.outstanding),0)
FROM journal
WHERE journal.sales_account = sales_account.id AND
journal.status='Active' AND
journal.reversed_by is null AND
journal.original_id is null AND
journal.transaction_date <= CURRENT_DATE  - interval '14 days' AND
journal.transaction_date >= CURRENT_DATE - interval '8 days'), -- 8-14 days

(SELECT coalesce(sum(journal.outstanding),0)
FROM journal
WHERE journal.sales_account = sales_account.id AND
journal.status='Active' AND
journal.transaction_date <=CURRENT_DATE  - interval '30 days' AND
journal.transaction_date >= CURRENT_DATE - interval '15 days'), -- 22-30 days

(SELECT coalesce(sum(journal.outstanding),0)
FROM journal
WHERE journal.sales_account = sales_account.id AND
journal.status='Active' AND
journal.transaction_date >= CURRENT_DATE - interval '31 days' AND
journal.transaction_date <=CURRENT_DATE  - interval '60 days'), -- 31-60 days

(SELECT coalesce(sum(journal.outstanding),0)
FROM journal
WHERE journal.sales_account = sales_account.id AND
journal.status='Active' AND
journal.transaction_date >= CURRENT_DATE - interval '61 days') -- 61+ days

FROM sales_account;

Body:
You can use FILTER expression to simplify SUM:

INSERT INTO balances (sales_account,
    balance,
    period_1,
    period_2,
    period_3,
    period_4,
    period_5)
SELECT
    COALESCE(sum(journal.outstanding), 0) AS overall,
    COALESCE(sum(journal.outstanding)
        FILTER (WHERE journal.transaction_date >= CURRENT_DATE - interval '7 days'
            AND journal.reversed_by IS NULL
            AND journal.original_id IS NULL), 0) AS period_1,
    COALESCE(sum(journal.outstanding)
        FILTER (WHERE journal.transaction_date >= CURRENT_DATE - interval '14 days'
            AND journal.transaction_date <= CURRENT_DATE  - interval ' 8 days'
            AND journal.reversed_by IS NULL
            AND journal.original_id IS NULL), 0) AS period_2,
    COALESCE(sum(journal.outstanding)
        FILTER (WHERE journal.transaction_date >= CURRENT_DATE - interval '30 days'
            AND journal.transaction_date <= CURRENT_DATE  - interval '22 days'), 0) AS period_3,
    COALESCE(sum(journal.outstanding)
        FILTER (WHERE journal.transaction_date >= CURRENT_DATE - interval '60 days'
            AND journal.transaction_date <= CURRENT_DATE  - interval ' 31 days'), 0) AS period_4,
    COALESCE(sum(journal.outstanding)
        FILTER (WHERE journal.transaction_date >= CURRENT_DATE - interval '61 days'), 0) AS period_5
FROM
    journal
    JOIN sales_account ON (journal.sales_account = sales_account.id)
WHERE
    journal.status='Active';


问:
Check if all children of div have class
I want to check if all children of different divs (with same id/class) have the class active. A typical if/else sentence but I can't quite wrap my head around it.

See the example here, this would be true as all children have the same class:

```<code><div class="parent">
   <div class="child active"></div>
   <div class="child active"></div>
   <div class="child active"></div>
   <div class="child active"></div>
</div>
</code>```

And this would be false as not all children have the same class:

```<code><div class="parent">
   <div class="child active"></div>
   <div class="child"></div>
   <div class="child active"></div>
   <div class="child"></div>
</div>
</code>```

There are many divs alike but the amount of children vary. It's important that it's 100% of the children that have the class before it is true.

How would you make the code?

Thanks.

答:
Here you go with a solution

var flag = true;
$('.parent').find('div.child').each(function(){
  if(!$(this).hasClass('active'))
    flag = false;
});

if(flag)
  console.log("All Child divs have active class");
else
  console.log("All child divs doesn't have active class");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
   <div class="child active"></div>
   <div class="child active"></div>
   <div class="child active"></div>
   <div class="child active"></div>
</div></code>```

One more example

var flag = true;
$('.parent').find('div.child').each(function(){
  if(!$(this).hasClass('active'))
    flag = false;
});

if(flag)
  console.log("All Child divs have active class");
else
  console.log("All child divs doesn't have active class");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
   <div class="child active"></div>
   <div class="child"></div>
   <div class="child active"></div>
   <div class="child"></div>
</div></code>```

Hope this will help you.

Title: Check if all children of div have class

Body:
I want to check if all children of different divs (with same id/class) have the class active. A typical if/else sentence but I can't quite wrap my head around it.

See the example here, this would be true as all children have the same class:

And this would be false as not all children have the same class:

There are many divs alike but the amount of children vary. It's important that it's 100% of the children that have the class before it is true.

How would you make the code?

Thanks.

Body:
Here you go with a solution

var flag = true;
$('.parent').find('div.child').each(function(){
  if(!$(this).hasClass('active'))
    flag = false;
});

if(flag)
  console.log("All Child divs have active class");
else
  console.log("All child divs doesn't have active class");

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
   <div class="child active"></div>
   <div class="child active"></div>
   <div class="child active"></div>
   <div class="child active"></div>
</div>

One more example

var flag = true;
$('.parent').find('div.child').each(function(){
  if(!$(this).hasClass('active'))
    flag = false;
});

if(flag)
  console.log("All Child divs have active class");
else
  console.log("All child divs doesn't have active class");

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
   <div class="child active"></div>
   <div class="child"></div>
   <div class="child active"></div>
   <div class="child"></div>
</div>

Hope this will help you.


问:
listview in dialougbox shows nothing
i have this code to show listview in dialogbox frame of listview is shown but without any text in it(i have background colored listview)

```<code> public void shw(View view)
    {

        Dialog dialog=new Dialog(MainActivity.this);
        dialog.setTitle("Dialog Title");
        dialog.setContentView(R.layout.custadd);
        LayoutInflater inflater = getLayoutInflater();
        View convertView = (View) inflater.inflate(R.layout.custadd,null);
        ListView lv=(ListView) convertView.findViewById(R.id.listv);
        String s1[]={"sunday","monday","tuesday"};
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                this,
                R.layout.simple_list_item, s1 );
        lv.setAdapter(arrayAdapter);
        dialog.show();

    }
</code>```

答:
Yes, because the view you display ListView is not the view you set for your Dialog. You should fix as below:

```<code>Dialog dialog=new Dialog(MainActivity.this);
dialog.setTitle("Dialog Title");
LayoutInflater inflater = getLayoutInflater();
View convertView = (View) inflater.inflate(R.layout.custadd,null    );
dialog.setContentView(convertView); // set convertView as content view.
// you can find listview and then fill data here
</code>```

Title: listview in dialougbox shows nothing

Body:
i have this code to show listview in dialogbox frame of listview is shown but without any text in it(i have background colored listview)

 public void shw(View view)
    {

        Dialog dialog=new Dialog(MainActivity.this);
        dialog.setTitle("Dialog Title");
        dialog.setContentView(R.layout.custadd);
        LayoutInflater inflater = getLayoutInflater();
        View convertView = (View) inflater.inflate(R.layout.custadd,null);
        ListView lv=(ListView) convertView.findViewById(R.id.listv);
        String s1[]={"sunday","monday","tuesday"};
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                this,
                R.layout.simple_list_item, s1 );
        lv.setAdapter(arrayAdapter);
        dialog.show();

    }

Body:
Yes, because the view you display ListView is not the view you set for your Dialog. You should fix as below:

Dialog dialog=new Dialog(MainActivity.this);
dialog.setTitle("Dialog Title");
LayoutInflater inflater = getLayoutInflater();
View convertView = (View) inflater.inflate(R.layout.custadd,null    );
dialog.setContentView(convertView); // set convertView as content view.
// you can find listview and then fill data here


问:
Oracle forms 11: Changing label of tab page very slow
I have a tab page in oracle forms. On the first tab, I have a master table. The master table has a few detail tables, which I show on other tab pages.

I would like to show the amount of records of the detail table, in the label of the tab page.

I change the labels in the when new record instance trigger of the master table. The problem is that

```<code>set_tab_page_property('CANVAS.DETAIL', label, 'Detail (' || amount || ')');
</code>```

is extremely slow.

In Oracle Forms 6i, the change happens in a blink of an eye, in Oracle Forms 11, it takes about 8 seconds to load the new lables of the tab pages.

Does anyone have an idea how I can improve the performance of set_tab_page_property in Oracle Forms 11?

答:
This is extremly slow when changing label of active tab.
Change the active tab (if possible) before to change label.</p>

Body:
I have a tab page in oracle forms. On the first tab, I have a master table. The master table has a few detail tables, which I show on other tab pages.

I would like to show the amount of records of the detail table, in the label of the tab page.

I change the labels in the when new record instance trigger of the master table. The problem is that

set_tab_page_property('CANVAS.DETAIL', label, 'Detail (' || amount || ')');

is extremely slow.

In Oracle Forms 6i, the change happens in a blink of an eye, in Oracle Forms 11, it takes about 8 seconds to load the new lables of the tab pages.

Does anyone have an idea how I can improve the performance of set_tab_page_property in Oracle Forms 11?


问:
How to start MySQL server on windows xp
Whenever I try to start MySQL by typing

```<code>> mysql -u root
</code>```

I get the error

ERROR 2003(HY000): Can't connect to MySQL server on 'localhost' (10061)

How can I solve the problem above? I just downloaded MySQL and unzipped it in the E: drive. I have not done anything else. Do I have to make a connection first? If so, how can I do that?

答:
I was using MySQL Server 5.5 as a result I was missing the folder which majority of the answers made mention of in the bin folder. What I did instead was the following:

Open Explorer and make your way to C:\Program Files\MySQL\MySQL Server 5.5\bin or your MySQL installation directory.

Run the executable application MySQLInstanceConfig and follow the images below.

This solved my issue and I was able to access the database without any errors.

Title: How to start MySQL server on windows xp

Body:
Whenever I try to start MySQL by typing

> mysql -u root

I get the error

ERROR 2003(HY000): Can't connect to MySQL server on 'localhost' (10061)

How can I solve the problem above? I just downloaded MySQL and unzipped it in the E: drive. I have not done anything else. Do I have to make a connection first? If so, how can I do that?


答:
Use length comparison or Array.prototype.every.

let parent1 = document.querySelector(".parent1"),
  parent2 = document.querySelector(".parent2");

if (parent1.children.length == parent1.querySelectorAll(".active").length) {
  console.log("All children have the class “active”.");
}

// or

if (Array.from(parent1.children).every(child => child.classList.contains("active"))) {
  console.log("All children have the class “active”.");
}

// similarly, for .parent2:

console.log(parent2.children.length == parent2.querySelectorAll(".active").length);
console.log(Array.from(parent2.children).every(child => child.classList.contains("active")));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent1">
  <div class="child active"></div>
  <div class="child active"></div>
  <div class="child active"></div>
  <div class="child active"></div>
</div>

<div class="parent2">
  <div class="child active"></div>
  <div class="child"></div>
  <div class="child active"></div>
  <div class="child"></div>
</div></code>```

Title: Check if all children of div have class

Body:
Use length comparison or Array.prototype.every.

let parent1 = document.querySelector(".parent1"),
  parent2 = document.querySelector(".parent2");

if (parent1.children.length == parent1.querySelectorAll(".active").length) {
  console.log("All children have the class “active”.");
}

// or

if (Array.from(parent1.children).every(child => child.classList.contains("active"))) {
  console.log("All children have the class “active”.");
}

// similarly, for .parent2:

console.log(parent2.children.length == parent2.querySelectorAll(".active").length);
console.log(Array.from(parent2.children).every(child => child.classList.contains("active")));

<div class="parent1">
  <div class="child active"></div>
  <div class="child active"></div>
  <div class="child active"></div>
  <div class="child active"></div>
</div>

<div class="parent2">
  <div class="child active"></div>
  <div class="child"></div>
  <div class="child active"></div>
  <div class="child"></div>
</div>


问:
Why when using EhCache, CPU reaches to 100%?
I use EhCache Hibernate Second Level Cache for and Query Caching.
Everything is fine, but the CPU I have 100 per cent up to 10 users via the JMeter.
If you disable the EhCache, then CPU becomes appropriate.
Anyone have any opinions on this?
So instead of improving performance, EhCache loaded my CPU.

It's my dependency:

```<code><dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-ehcache</artifactId>
        <version>4.3.8.Final</version>
    </dependency>
</code>```

ehcache.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance "
         xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
         name="cacheManager"
         monitoring="autodetect" dynamicConfig="true">

    <diskStore path="user.home/ehcacheEntriesStore" />

    <defaultCache maxEntriesLocalHeap="100" eternal="false"
                  timeToIdleSeconds="10" timeToLiveSeconds="10" diskSpoolBufferSizeMB="30"
                  maxEntriesLocalDisk="1000" diskExpiryThreadIntervalSeconds="1200"
                  memoryStoreEvictionPolicy="LRU" statistics="false">
        <persistence strategy="localTempSwap"/>
    </defaultCache>

    <cache name="serviceCache"
        maxBytesLocalHeap="500M"
        eternal="false"
        timeToIdleSeconds="300"
        overflowToDisk="true"
        maxElementsOnDisk="1000"
        memoryStoreEvictionPolicy="LRU"/>

    <cache  name="org.hibernate.cache.StandardQueryCache"
            maxEntriesLocalHeap="50000"
            eternal="false"
            timeToLiveSeconds="300">
        <persistence strategy="localTempSwap"/>
    </cache>
    <cache name="org.hibernate.cache.spi.UpdateTimestampsCache"
           maxEntriesLocalHeap="50000" eternal="true">
        <persistence strategy="localTempSwap"/>
    </cache>
</ehcache>
</code>```

persistence.xml

```<code><properties>
    <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL9Dialect"/>
    <property name="hibernate.transaction.jta.platform"
              value="org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform"/>
    <property name="hibernate.hbm2ddl.auto" value="update"/>
    <property name="hibernate.show_sql" value="true"/>

    <property name="hibernate.cache.region.factory_class"
              value="org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory"/>
    <property name="hibernate.cache.use_second_level_cache" value="true"/>
    <property name="hibernate.cache.use_query_cache" value="true"/>
    <property name="net.sf.ehcache.configurationResourceName" value="ehcache.xml"/>
    <property name="hibernate.cache.default_cache_concurrency_strategy" value="transactional"/>
    <property name="hibernate.max_fetch_depth" value="4"/>
    <property name="hibernate.auto_close_session" value="true"/>
    <!--<property name="hibernate.transaction.flush_before_completion" value="true"/>-->
    <property name="hibernate.transaction.auto_close_session" value="true" />
    <property name="hibernate.c3p0.timeout" value="30" />

    <!--<property name="hibernate.generate_statistics" value="true"/>-->
    <!--<property name="hibernate.cache.use_structured_entries" value="true"/>-->

</properties
</code>```

>

答:
For Ehcache 3.x, it is a bug.
The cache statistics threadpool is creating a new thread for every statistics. So the thread itself is doing very less work, but OS is consuming most CPU to create that thread.

It is to be fixed in later releases, but temporary workaround is to set the system property org.ehcache.statisticsExecutor.poolSize to 1

Ref: https://github.com/ehcache/ehcache3/issues/387

Body:
I use EhCache Hibernate Second Level Cache for and Query Caching.
Everything is fine, but the CPU I have 100 per cent up to 10 users via the JMeter.
If you disable the EhCache, then CPU becomes appropriate.
Anyone have any opinions on this?
So instead of improving performance, EhCache loaded my CPU.

It's my dependency:

<dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-ehcache</artifactId>
        <version>4.3.8.Final</version>
    </dependency>

ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance "
         xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
         name="cacheManager"
         monitoring="autodetect" dynamicConfig="true">

    <diskStore path="user.home/ehcacheEntriesStore" />

    <defaultCache maxEntriesLocalHeap="100" eternal="false"
                  timeToIdleSeconds="10" timeToLiveSeconds="10" diskSpoolBufferSizeMB="30"
                  maxEntriesLocalDisk="1000" diskExpiryThreadIntervalSeconds="1200"
                  memoryStoreEvictionPolicy="LRU" statistics="false">
        <persistence strategy="localTempSwap"/>
    </defaultCache>

    <cache name="serviceCache"
        maxBytesLocalHeap="500M"
        eternal="false"
        timeToIdleSeconds="300"
        overflowToDisk="true"
        maxElementsOnDisk="1000"
        memoryStoreEvictionPolicy="LRU"/>

    <cache  name="org.hibernate.cache.StandardQueryCache"
            maxEntriesLocalHeap="50000"
            eternal="false"
            timeToLiveSeconds="300">
        <persistence strategy="localTempSwap"/>
    </cache>
    <cache name="org.hibernate.cache.spi.UpdateTimestampsCache"
           maxEntriesLocalHeap="50000" eternal="true">
        <persistence strategy="localTempSwap"/>
    </cache>
</ehcache>

persistence.xml

<properties>
    <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL9Dialect"/>
    <property name="hibernate.transaction.jta.platform"
              value="org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform"/>
    <property name="hibernate.hbm2ddl.auto" value="update"/>
    <property name="hibernate.show_sql" value="true"/>

    <property name="hibernate.cache.region.factory_class"
              value="org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory"/>
    <property name="hibernate.cache.use_second_level_cache" value="true"/>
    <property name="hibernate.cache.use_query_cache" value="true"/>
    <property name="net.sf.ehcache.configurationResourceName" value="ehcache.xml"/>
    <property name="hibernate.cache.default_cache_concurrency_strategy" value="transactional"/>
    <property name="hibernate.max_fetch_depth" value="4"/>
    <property name="hibernate.auto_close_session" value="true"/>

    <property name="hibernate.transaction.auto_close_session" value="true" />
    <property name="hibernate.c3p0.timeout" value="30" />

</properties

>


答:
You can  select the items you want and also filter that set for your extra class. Those sets should be the same length</p>

```<code>let $children = $('.parent').children('.child');
console.log( $children.length == $children.filter('.active').length);
</code>```

Title: Check if all children of div have class

Body:
You can  select the items you want and also filter that set for your extra class. Those sets should be the same length

let $children = $('.parent').children('.child');
console.log( $children.length == $children.filter('.active').length);


答:
You can count all the elements with the child class and compare it to the number of objects having the active class. If they match, you're good to go.

```<code>if ($('.parent .child').length === $('.parent .child.active')) {
    // everything good
}
</code>```

Title: Check if all children of div have class

Body:
You can count all the elements with the child class and compare it to the number of objects having the active class. If they match, you're good to go.

if ($('.parent .child').length === $('.parent .child.active')) {
    // everything good
}


答:
You can count elements with :not selector:

```<code>var result = $('.parent').find('.child:not(.active)').length === 0;
</code>```

Title: Check if all children of div have class

Body:
You can count elements with :not selector:

var result = $('.parent').find('.child:not(.active)').length === 0;


问:
Cython's calculations are incorrect
I implemented the Madhava–Leibniz series to calculate pi in Python, and then in Cython to improve the speed. The Python version:

```<code>from __future__ import division
pi = 0
l = 1
x = True
while True:
    if x:
        pi += 4/l
    else:
        pi -= 4/l
    x = not x
    l += 2
    print str(pi)
</code>```

The Cython version:

```<code>cdef float pi = 0.0
cdef float l = 1.0
cdef unsigned short x = True
while True:
    if x:
        pi += 4.0/l
    else:
        pi -= 4.0/l
    x = not x
    l += 2
    print str(pi)
</code>```

When I stopped the Python version it had correctly calculated pi to 3.141592. The Cython version eventually ended up at 3.141597 with some more digits that I don't remember (my terminal crashed) but were incorrect. Why are the Cython version's calculations incorrect?

答:
If you want to increase speed, note that you can simplify the logic by unrolling your loop once, like so:

```<code>cdef double pi = 0.0
cdef double L = 1.0

while True:
    pi += 4.0/L - 4.0/(L+2.0)
    L += 4.0
    print str(pi)
</code>```

Also note that you don't have to call print inside the loop - it is probably taking ten times longer than the rest of the calculation.

Title: Cython's calculations are incorrect

Body:
I implemented the Madhava–Leibniz series to calculate pi in Python, and then in Cython to improve the speed. The Python version:

from __future__ import division
pi = 0
l = 1
x = True
while True:
    if x:
        pi += 4/l
    else:
        pi -= 4/l
    x = not x
    l += 2
    print str(pi)

The Cython version:

cdef float pi = 0.0
cdef float l = 1.0
cdef unsigned short x = True
while True:
    if x:
        pi += 4.0/l
    else:
        pi -= 4.0/l
    x = not x
    l += 2
    print str(pi)

When I stopped the Python version it had correctly calculated pi to 3.141592. The Cython version eventually ended up at 3.141597 with some more digits that I don't remember (my terminal crashed) but were incorrect. Why are the Cython version's calculations incorrect?

Body:
If you want to increase speed, note that you can simplify the logic by unrolling your loop once, like so:

cdef double pi = 0.0
cdef double L = 1.0

while True:
    pi += 4.0/L - 4.0/(L+2.0)
    L += 4.0
    print str(pi)

Also note that you don't have to call print inside the loop - it is probably taking ten times longer than the rest of the calculation.


问:
How to display image on full div in html css
I try to display the image on full div but it display only center of the div
 i am using the following code
my html code is

.all-stores .store-logo {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    border: 1px solid red
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="white-block all-stores">
 <div class="embed-responsive embed-responsive-4by3">
  <div class="store-logo">

    <img src="http://via.placeholder.com/350x350" class="img-responsive wp-post-image">

  </div>
 </div>
</div></code>```

thanks

答:
You want something like this:-

.img{
width:100%;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="white-block all-stores">
<div class="embed-responsive embed-responsive-4by3">
    <div class="store-logo">

            <img src="http://images.clipartpanda.com/nest-clip-art-nest.jpg" class="img">

    </div>
</div></code>```

Body:
I try to display the image on full div but it display only center of the div
 i am using the following code
my html code is

.all-stores .store-logo {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    border: 1px solid red
    }

thanks

Body:
You want something like this:-

.img{
width:100%;

}

<div class="white-block all-stores">
<div class="embed-responsive embed-responsive-4by3">
    <div class="store-logo">
        <a href="test">
            <img src="http://images.clipartpanda.com/nest-clip-art-nest.jpg" class="img">
        </a>
    </div>
</div>


问:
Facebook Cordova plugin - sharing a photo (with no link) results in empty Share Dialog
I'm using the cordova Facebook plugin (https://github.com/jeduan/cordova-plugin-facebook4) in a Meteor mobile app on Android.

I can successfully use the Share Dialog to share a photo with a link (as in the plugin example here: https://github.com/jeduan/cordova-plugin-facebook4#show-a-dialog). I.e...

```<code>{
  method: "share",
  href: "http://example.com",
  caption: "Such caption, very feed.",
  description: "Much description",
  picture: 'http://example.com/image.png'
}
</code>```

However, if I attempt to share a photo-only (i.e. with no website link)...

```<code>facebookConnectPlugin.showDialog({
  method: "share",
  picture:'https://www.google.co.jp/logos/doodles/2014/doodle-4-google-2014-japan-winner-5109465267306496.2-hp.png',
  name:'Test Post',
  message:'First photo post',
  caption: 'Testing using phonegap plugin',
  description: 'Posting photo using phonegap facebook plugin'
}, function (response) {
  console.log(response)
}, function (response) {
  console.log(response)
});
</code>```

....the Share Dialog opens, but is empty.

This is exactly as per the final example given on the plugin's github (https://github.com/jeduan/cordova-plugin-facebook4#publish-a-photo) so I assume it's a valid use-case.

Any ideas?

答:
I had the same issues and finally got it resolved! How? I just did this:

```<code>method: "share",
href: 'url_of_image_or_photo_to_share'
</code>```

Even after doing it this way, the share dialog was showing like a link or small icon! So I went ahead and hit the Post but and saw it like I would expect on Facebook.

Give it a trial!

Body:
I'm using the cordova Facebook plugin (https://github.com/jeduan/cordova-plugin-facebook4) in a Meteor mobile app on Android.

I can successfully use the Share Dialog to share a photo with a link (as in the plugin example here: https://github.com/jeduan/cordova-plugin-facebook4#show-a-dialog). I.e...

{
  method: "share",
  href: "http://example.com",
  caption: "Such caption, very feed.",
  description: "Much description",
  picture: 'http://example.com/image.png'
}

However, if I attempt to share a photo-only (i.e. with no website link)...

facebookConnectPlugin.showDialog({
  method: "share",
  picture:'https://www.google.co.jp/logos/doodles/2014/doodle-4-google-2014-japan-winner-5109465267306496.2-hp.png',
  name:'Test Post',
  message:'First photo post',
  caption: 'Testing using phonegap plugin',
  description: 'Posting photo using phonegap facebook plugin'
}, function (response) {
  console.log(response)
}, function (response) {
  console.log(response)
});

....the Share Dialog opens, but is empty.

This is exactly as per the final example given on the plugin's github (https://github.com/jeduan/cordova-plugin-facebook4#publish-a-photo) so I assume it's a valid use-case.

Any ideas?

Body:
I had the same issues and finally got it resolved! How? I just did this:

method: "share",
href: 'url_of_image_or_photo_to_share'

Even after doing it this way, the share dialog was showing like a link or small icon! So I went ahead and hit the Post but and saw it like I would expect on Facebook.

Give it a trial!


问:
MongoDB Spark Connector : mongo-spark cannot connect to DB
I'm trying MongoDB's  Spark connector to read data from MongoDB. I supplied the DB and collection details to Spark conf object while starting the application. And then use the following piece of code to read.

```<code>// create configuration
SparkSession spark = SparkSession.builder()
  .master("local")
  .appName("MongoSparkConnectorIntro")
  .config("spark.mongodb.input.uri", "mongodb://localhost:27017/Employee.zipcodes")
  .config("spark.mongodb.output.uri", "mongodb://localhost:27017/Employee.test")
  .getOrCreate();
// Create a JavaSparkContext using the SparkSession's SparkContext object
JavaSparkContext jsc = new JavaSparkContext(spark.sparkContext());

/*Start Example: Read data from MongoDB************************/

JavaMongoRDD<Document> rdd = MongoSpark.load(jsc);

/*End Example**************************************************/

// Analyze data from MongoDB
System.out.println(rdd.count());
System.out.println(rdd.first().toJson());
</code>```

But this not able to connect the localhost DB. This is showing the following error.

```<code>Exception in thread "main" java.lang.NoSuchMethodError: com.mongodb.spark.config.ReadConfig$.apply(Lorg/apache/spark/SparkConf;Lscala/collection/Map;)Ljava/lang/Object;
 at com.mongodb.spark.MongoSpark$Builder.build(MongoSpark.scala:259)
 at com.mongodb.spark.MongoSpark$.load(MongoSpark.scala:375)
 at com.mongodb.spark.MongoSpark.load(MongoSpark.scala)
 at com.mycompany.app.App2.main(App2.java:35)
</code>```

I'm using the following maven dependencies.

```<code><dependency>
  <groupId>org.apache.spark</groupId>
  <artifactId>spark-core_2.11</artifactId>
  <version>2.1.0</version>
</dependency>
<dependency>
    <groupId>org.mongodb.spark</groupId>
    <artifactId>mongo-spark-connector_2.11</artifactId>
    <version>1.1.0</version>
</dependency>
<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>bson</artifactId>
    <version>3.2.2</version>
</dependency>
<dependency>
    <groupId>org.scala-lang</groupId>
    <artifactId>scala-library</artifactId>
    <version>2.11.7</version>
</dependency>
<dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-client</artifactId>
    <version>2.2.0</version>
</dependency>
</code>```

答:
Can you try improving your mongo spark connector version to latest</p>

```<code><dependency>
    <groupId>org.mongodb.spark</groupId>
    <artifactId>mongo-spark-connector_2.11</artifactId>
    <version>2.2.1</version>
</dependency>
</code>```

Body:
I'm trying MongoDB's  Spark connector to read data from MongoDB. I supplied the DB and collection details to Spark conf object while starting the application. And then use the following piece of code to read.

// create configuration
SparkSession spark = SparkSession.builder()
  .master("local")
  .appName("MongoSparkConnectorIntro")
  .config("spark.mongodb.input.uri", "mongodb://localhost:27017/Employee.zipcodes")
  .config("spark.mongodb.output.uri", "mongodb://localhost:27017/Employee.test")
  .getOrCreate();
// Create a JavaSparkContext using the SparkSession's SparkContext object
JavaSparkContext jsc = new JavaSparkContext(spark.sparkContext());

/*Start Example: Read data from MongoDB************************/

JavaMongoRDD<Document> rdd = MongoSpark.load(jsc);

/*End Example**************************************************/

// Analyze data from MongoDB
System.out.println(rdd.count());
System.out.println(rdd.first().toJson());

But this not able to connect the localhost DB. This is showing the following error.

Exception in thread "main" java.lang.NoSuchMethodError: com.mongodb.spark.config.ReadConfig$.apply(Lorg/apache/spark/SparkConf;Lscala/collection/Map;)Ljava/lang/Object;
 at com.mongodb.spark.MongoSpark$Builder.build(MongoSpark.scala:259)
 at com.mongodb.spark.MongoSpark$.load(MongoSpark.scala:375)
 at com.mongodb.spark.MongoSpark.load(MongoSpark.scala)
 at com.mycompany.app.App2.main(App2.java:35)

I'm using the following maven dependencies.

<dependency>
  <groupId>org.apache.spark</groupId>
  <artifactId>spark-core_2.11</artifactId>
  <version>2.1.0</version>
</dependency>
<dependency>
    <groupId>org.mongodb.spark</groupId>
    <artifactId>mongo-spark-connector_2.11</artifactId>
    <version>1.1.0</version>
</dependency>
<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>bson</artifactId>
    <version>3.2.2</version>
</dependency>
<dependency>
    <groupId>org.scala-lang</groupId>
    <artifactId>scala-library</artifactId>
    <version>2.11.7</version>
</dependency>
<dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-client</artifactId>
    <version>2.2.0</version>
</dependency>

Body:
Can you try improving your mongo spark connector version to latest

<dependency>
    <groupId>org.mongodb.spark</groupId>
    <artifactId>mongo-spark-connector_2.11</artifactId>
    <version>2.2.1</version>
</dependency>