问:
Angular - Component Binding Issue
I have a component binding issue.  I'm pretty sure that I've got a syntax issue, but I'm not sure what I'm doing wrong.

The full source code is available at https://github.com/TheMagnificent11/LunchVoting in the feature/6_ExtendedInputBug branch (https://github.com/TheMagnificent11/LunchVoting/tree/feature/6_ExtendedInputBug).  The master and develop branches have working code that doesn't use the extended-input component.

input-error.component.ts

This is the component that displays a form field error.

```<code>import { Component, Input } from '@angular/core';

@Component({
    selector: 'input-error',
    template: './input-error.component.html'
})
export class InputErrorComponent {

    @Input()
    errorMessage: string;

    @Input()
    isError: boolean = true;

}
</code>```

input-error.component.html

    {{errorMessage}}

```

<p><strong>extended-input.component.ts</strong></p>

<p>This is the component combines label, input and validation errors (collection of child components <code>input-error</code>) for a single form field.</p>

```import {
    Component,
    Input,
    ContentChildren,
    QueryList
} from '@angular/core';

import { InputErrorComponent } from '../input-error/input-error.component';

@Component({
    selector: 'extended-input',
    template: './extended-input.component.html'
})
export class ExtendedInputComponent {

    @Input()
    inputName: string = '';

    @Input()
    labelText: string = '';

    @Input()
    isError: boolean = false;

    @ContentChildren(InputErrorComponent)
    errors: QueryList<InputErrorComponent>;

}
```

<p><strong>extended-input.component.html</strong></p>

<pre class="lang-html prettyprint-override"><code><div class="form-group" [ngClass]="{'has-error':border border-danger}">
    <label for="{{inputName}}">{{labelText}}</label>
    <ng-content select="input-control"></ng-content>
    <div *ngIf="isError">
        <ng-content select="input-errors"></ng-content>
    </div>
</div>
</code>```

controls.module.ts

Module that has extended-input component

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

import { ExtendedInputComponent } from './extended-input.component.ts';
import { InputErrorComponent } from './input-error.component.ts';

let components = [
    ExtendedInputComponent,
    InputErrorComponent
];

@NgModule({
    declarations: components,
    imports: [
        CommonModule,
        ReactiveFormsModule
    ]
})
export class ControlsModule {
}
</code>```

register.component.ts

This the form component that uses the other extended-input component.

```<code>import { Component } from '@angular/core';
import {
    FormBuilder,
    FormGroup,
    FormControl,
    Validators
} from '@angular/forms';

@Component({
    selector: 'register',
    templateUrl: './register.component.html'
})
export class RegisterComponent {

    registrationForm: FormGroup;

    givenName: FormControl;

    surname: FormControl;

    constructor(private formBuilder: FormBuilder) {
        this.givenName = new FormControl('', [Validators.required, Validators.maxLength(100)]);
        this.surname = new FormControl('', [Validators.required, Validators.maxLength(100)]);

        this.registrationForm = this.formBuilder.group({
            givenName: this.givenName,
            surname: this.surname,
        });
    }

}
</code>```

register.component.html

<form [formGroup]="registrationForm" (submit)="onSubmit()">

    <extended-input [inputName]="'givenName'"
                    [labelText]="'Given Name'"
                    [isError]="givenName.touched && givenName.invalid">
        <input-control>
            <input type="text" formControlName="givenName" />
        </input-control>
        <input-errors>
            <input-error [isError]="givenName.hasError('required')">
                Given Name is required
            </input-error>
        </input-errors>
    </extended-input>

        Surname
        <input type="text" formControlName="surname" />

                Surname is required

    <button type="submit" [disabled]="!registrationForm.valid">
        Register
    </button>

</form>
```

<p><strong>Entry Module</strong></p>

<p>The module that contains <code>register</code> component.</p>

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

import { ControlsModule } from '../controls/controls.module';

import { RegisterComponent } from './register-component';

@NgModule({
    declarations: components,
    imports: [
        CommonModule,
        ReactiveFormsModule,
        ControlsModule
    ]
})
export class EntryModule {
}
```

<p><strong>Error</strong></p>

```Uncaught Error: Template parse errors:
Can't bind to 'inputName' since it isn't a known property of 'extended-input'.
1. If 'extended-input' is an Angular component and it has 'inputName' input, then verify that it is part of this module.
2. If 'extended-input' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("
        <form [formGroup]="registrationForm" (submit)="onSubmit()">

            <extended-input [ERROR ->][inputName]="'givenName'"
                            [labelText]="'Given Name'"
                 "): ng:///EntryModule/RegisterComponent.html@9:28
Can't bind to 'labelText' since it isn't a known property of 'extended-input'.
1. If 'extended-input' is an Angular component and it has 'labelText' input, then verify that it is part of this module.
2. If 'extended-input' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("

            <extended-input [inputName]="'givenName'"
                            [ERROR ->][labelText]="'Given Name'"
                            [isError]="givenName.touched && givenName.inv"): ng:///EntryModule/RegisterComponent.html@10:28
Can't bind to 'isError' since it isn't a known property of 'extended-input'.
1. If 'extended-input' is an Angular component and it has 'isError' input, then verify that it is part of this module.
2. If 'extended-input' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. (""'givenName'"
                            [labelText]="'Given Name'"
                            [ERROR ->][isError]="givenName.touched && givenName.invalid">
                <input-control>
               "): ng:///EntryModule/RegisterComponent.html@11:28
'input-control' is not a known element:
1. If 'input-control' is an Angular component, then verify that it is part of this module.
2. If 'input-control' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. (""
                            [isError]="givenName.touched && givenName.invalid">
                [ERROR ->]<input-control>
                    <input type="text" formControlName="givenName" />
             "): ng:///EntryModule/RegisterComponent.html@12:16
Can't bind to 'isError' since it isn't a known property of 'input-error'.
1. If 'input-error' is an Angular component and it has 'isError' input, then verify that it is part of this module.
2. If 'input-error' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("
                </input-control>
                <input-errors>
                    <input-error [ERROR ->][isError]="givenName.hasError('required')">
                        Given Name is required
        "): ng:///EntryModule/RegisterComponent.html@16:33
'input-error' is not a known element:
1. If 'input-error' is an Angular component, then verify that it is part of this module.
2. If 'input-error' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("
                </input-control>
                <input-errors>
                    [ERROR ->]<input-error [isError]="givenName.hasError('required')">
                        Given Name is requi"): ng:///EntryModule/RegisterComponent.html@16:20
'input-errors' is not a known element:
1. If 'input-errors' is an Angular component, then verify that it is part of this module.
2. If 'input-errors' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("input type="text" formControlName="givenName" />
                </input-control>
                [ERROR ->]<input-errors>
                    <input-error [isError]="givenName.hasError('required')">
       "): ng:///EntryModule/RegisterComponent.html@15:16
'extended-input' is not a known element:
1. If 'extended-input' is an Angular component, then verify that it is part of this module.
2. If 'extended-input' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("
        <form [formGroup]="registrationForm" (submit)="onSubmit()">

            [ERROR ->]<extended-input [inputName]="'givenName'"
                            [labelText]="'Given Name'"
 "): ng:///EntryModule/RegisterComponent.html@9:12
    at syntaxError (vendor.js:sourcemap:38524)
    at TemplateParser.parse (vendor.js:sourcemap:49621)
    at JitCompiler._compileTemplate (vendor.js:sourcemap:63824)
    at vendor.js:sourcemap:63743
    at Set.forEach (<anonymous>)
    at JitCompiler._compileComponents (vendor.js:sourcemap:63743)
    at vendor.js:sourcemap:63630
    at Object.then (vendor.js:sourcemap:38513)
    at JitCompiler._compileModuleAndComponents (vendor.js:sourcemap:63629)
    at JitCompiler.compileModuleAsync (vendor.js:sourcemap:63558)
```

Does anyone know what I've done wrong?

答:
1. If 'extended-input' is an Angular component and it has 'inputName' input, then verify that it is part of this module.

Make sure your components are imported properly. I noticed that the RegisterComponent has the 'Component' suffix at the end of the class name but the other ones, InputError and ExtendedInput, don't. Did you create one with the CLI but not the other ones? Maybe you forgot to import them into your module manually if you didn't use the CLI.

After that, there is an issue with property binding that I saw. It expects an expression inside quotes, so if you want to pass in literal text you need to have quotes inside quotes. It's weird. [labelText]="Given Name" is going to look for variables Given and Name, so it needs to be [labelText]="'Given Name'". That's this error from above:

[ERROR ->][labelText]="Given Name"

Your app seems to have some other components input-control and input-errors but I don't see the code for those here, so couldn't get everything working on my end but that's a start. I can't completely follow the strategy with the ng-content/transclusion but that part of angular is not my forte.

Title: Angular - Component Binding Issue

Body:
I have a component binding issue.  I'm pretty sure that I've got a syntax issue, but I'm not sure what I'm doing wrong.

The full source code is available at https://github.com/TheMagnificent11/LunchVoting in the feature/6_ExtendedInputBug branch (https://github.com/TheMagnificent11/LunchVoting/tree/feature/6_ExtendedInputBug).  The master and develop branches have working code that doesn't use the extended-input component.

input-error.component.ts

This is the component that displays a form field error.

import { Component, Input } from '@angular/core';

@Component({
    selector: 'input-error',
    template: './input-error.component.html'
})
export class InputErrorComponent {

    @Input()
    errorMessage: string;

    @Input()
    isError: boolean = true;

}

input-error.component.html

    {{errorMessage}}

extended-input.component.ts

This is the component combines label, input and validation errors (collection of child components input-error) for a single form field.

import {
    Component,
    Input,
    ContentChildren,
    QueryList
} from '@angular/core';

import { InputErrorComponent } from '../input-error/input-error.component';

@Component({
    selector: 'extended-input',
    template: './extended-input.component.html'
})
export class ExtendedInputComponent {

    @Input()
    inputName: string = '';

    @Input()
    labelText: string = '';

    @Input()
    isError: boolean = false;

    @ContentChildren(InputErrorComponent)
    errors: QueryList<InputErrorComponent>;

}

extended-input.component.html

    {{labelText}}
    <ng-content select="input-control"></ng-content>

        <ng-content select="input-errors"></ng-content>

controls.module.ts

Module that has extended-input component

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

import { ExtendedInputComponent } from './extended-input.component.ts';
import { InputErrorComponent } from './input-error.component.ts';

let components = [
    ExtendedInputComponent,
    InputErrorComponent
];

@NgModule({
    declarations: components,
    imports: [
        CommonModule,
        ReactiveFormsModule
    ]
})
export class ControlsModule {
}

register.component.ts

This the form component that uses the other extended-input component.

import { Component } from '@angular/core';
import {
    FormBuilder,
    FormGroup,
    FormControl,
    Validators
} from '@angular/forms';

@Component({
    selector: 'register',
    templateUrl: './register.component.html'
})
export class RegisterComponent {

    registrationForm: FormGroup;

    givenName: FormControl;

    surname: FormControl;

    constructor(private formBuilder: FormBuilder) {
        this.givenName = new FormControl('', [Validators.required, Validators.maxLength(100)]);
        this.surname = new FormControl('', [Validators.required, Validators.maxLength(100)]);

        this.registrationForm = this.formBuilder.group({
            givenName: this.givenName,
            surname: this.surname,
        });
    }

}

register.component.html

<form [formGroup]="registrationForm" (submit)="onSubmit()">

    <extended-input [inputName]="'givenName'"
                    [labelText]="'Given Name'"
                    [isError]="givenName.touched && givenName.invalid">
        <input-control>
            <input type="text" formControlName="givenName" />
        </input-control>
        <input-errors>
            <input-error [isError]="givenName.hasError('required')">
                Given Name is required
            </input-error>
        </input-errors>
    </extended-input>

        Surname
        <input type="text" formControlName="surname" />

                Surname is required

    <button type="submit" [disabled]="!registrationForm.valid">
        Register
    </button>

</form>

Entry Module

The module that contains register component.

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

import { ControlsModule } from '../controls/controls.module';

import { RegisterComponent } from './register-component';

@NgModule({
    declarations: components,
    imports: [
        CommonModule,
        ReactiveFormsModule,
        ControlsModule
    ]
})
export class EntryModule {
}

Error

Uncaught Error: Template parse errors:
Can't bind to 'inputName' since it isn't a known property of 'extended-input'.
1. If 'extended-input' is an Angular component and it has 'inputName' input, then verify that it is part of this module.
2. If 'extended-input' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("
        <form [formGroup]="registrationForm" (submit)="onSubmit()">

            <extended-input [ERROR ->][inputName]="'givenName'"
                            [labelText]="'Given Name'"
                 "): ng:///EntryModule/RegisterComponent.html@9:28
Can't bind to 'labelText' since it isn't a known property of 'extended-input'.
1. If 'extended-input' is an Angular component and it has 'labelText' input, then verify that it is part of this module.
2. If 'extended-input' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("

            <extended-input [inputName]="'givenName'"
                            [ERROR ->][labelText]="'Given Name'"
                            [isError]="givenName.touched && givenName.inv"): ng:///EntryModule/RegisterComponent.html@10:28
Can't bind to 'isError' since it isn't a known property of 'extended-input'.
1. If 'extended-input' is an Angular component and it has 'isError' input, then verify that it is part of this module.
2. If 'extended-input' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. (""'givenName'"
                            [labelText]="'Given Name'"
                            [ERROR ->][isError]="givenName.touched && givenName.invalid">
                <input-control>
               "): ng:///EntryModule/RegisterComponent.html@11:28
'input-control' is not a known element:
1. If 'input-control' is an Angular component, then verify that it is part of this module.
2. If 'input-control' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. (""
                            [isError]="givenName.touched && givenName.invalid">
                [ERROR ->]<input-control>
                    <input type="text" formControlName="givenName" />
             "): ng:///EntryModule/RegisterComponent.html@12:16
Can't bind to 'isError' since it isn't a known property of 'input-error'.
1. If 'input-error' is an Angular component and it has 'isError' input, then verify that it is part of this module.
2. If 'input-error' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("
                </input-control>
                <input-errors>
                    <input-error [ERROR ->][isError]="givenName.hasError('required')">
                        Given Name is required
        "): ng:///EntryModule/RegisterComponent.html@16:33
'input-error' is not a known element:
1. If 'input-error' is an Angular component, then verify that it is part of this module.
2. If 'input-error' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("
                </input-control>
                <input-errors>
                    [ERROR ->]<input-error [isError]="givenName.hasError('required')">
                        Given Name is requi"): ng:///EntryModule/RegisterComponent.html@16:20
'input-errors' is not a known element:
1. If 'input-errors' is an Angular component, then verify that it is part of this module.
2. If 'input-errors' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("input type="text" formControlName="givenName" />
                </input-control>
                [ERROR ->]<input-errors>
                    <input-error [isError]="givenName.hasError('required')">
       "): ng:///EntryModule/RegisterComponent.html@15:16
'extended-input' is not a known element:
1. If 'extended-input' is an Angular component, then verify that it is part of this module.
2. If 'extended-input' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("
        <form [formGroup]="registrationForm" (submit)="onSubmit()">

            [ERROR ->]<extended-input [inputName]="'givenName'"
                            [labelText]="'Given Name'"
 "): ng:///EntryModule/RegisterComponent.html@9:12
    at syntaxError (vendor.js:sourcemap:38524)
    at TemplateParser.parse (vendor.js:sourcemap:49621)
    at JitCompiler._compileTemplate (vendor.js:sourcemap:63824)
    at vendor.js:sourcemap:63743
    at Set.forEach (<anonymous>)
    at JitCompiler._compileComponents (vendor.js:sourcemap:63743)
    at vendor.js:sourcemap:63630
    at Object.then (vendor.js:sourcemap:38513)
    at JitCompiler._compileModuleAndComponents (vendor.js:sourcemap:63629)
    at JitCompiler.compileModuleAsync (vendor.js:sourcemap:63558)

Does anyone know what I've done wrong?


来源: stackexchange

问:
How to replace letters with numbers in c++?
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.

This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.

E.g, "localization" will be spelled as "l10n", and "internationalization» will be spelled as "i18n.

 Input:

localization

internationalization

Output:
 l10n

i18n

答:
```<code>std::string s;
while (std::cin >> s)
    std::cout << s.at(0) << s.length() - 2 << s.at(s.length() - 1) << "\n";
</code>```

ContentLicense: CC BY-SA 3.0


问:
Why is this userscript only doing the first if?
I am working on a User script but it seems to work just for the first comparison:

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

var noError = document.getElementsByClassName("noMistakeButton");
var next = document.getElementsByClassName("nextButton");
var wait = document.getElementsByClassName("understoodButton");
var okko = document.getElementsByClassName("buttonKo");
var exitOkko = document.getElementsByClassName("exitButton");

while(1)
{
    if( noError !== null)
    {
        noError.click();
    }

    if( next !== null)
    {
        exit.click();
    }

    if( wait !== null)
    {
        wait.click();
    }
    sleep(2);
    if( okko !== null)
    {
        exit.click();
    }

    if( exitOkko !== null)
    {
        exitOkko.click();
    }

} })();
</code>```

My goal is the run this script freely while AFK.
There are, as you can see, many buttons on the web page and each button cant be :visible or :hidden. My goal is just to click on them.

Here is the target page (static URL).

Some buttons only have class and no ID. Others have them both.

The console reports:

ERROR: Execution of script 'AutoVoltair' failed!   noError.click is not
  a function

答:
It is unclear what you hope to accomplish.  If you are trying to step through a sequence of controls, use the approach illustrated in Choosing and activating the right controls on an AJAX-driven site.

The kind of code shown in the question would just play "Whac-A-Mole" with whatever button "popped up" next. (And only if the preceding buttons had been deleted.)

Anyway, to answer the question: "why this code is only doing the first if?".

It's because userscripts (and javascript) stop running at the first critical error (with a few exceptions).  Additionally:

noError.click is not a function because noError is a collection of elements, not a button.

All the getElementsByClassName calls are only done once.  If it's going to continually loop, you need to recheck inside the loop.

There is no such thing as sleep().

while (1) is a very bad idea and can freeze your browser, or even help crash your PC.  Use setInterval for polling the page.

Here's the "Whac-A-Mole" code with those errors corrected:

```<code>setInterval ( () => {
        var noError     = document.getElementsByClassName ("noMistakeButton");
        var next        = document.getElementsByClassName ("nextButton");
        var wait        = document.getElementsByClassName ("understoodButton");
        var okko        = document.getElementsByClassName ("buttonKo");
        var exitOkko    = document.getElementsByClassName ("exitButton");

        if (noError.length) {
            noError[0].click ();
        }
        if (next.length) {
            next[0].click ();
        }
        if (wait.length) {
            wait[0].click ();
        }
        if (okko.length) {
            okko[0].click ();
        }
        if (exitOkko.length) {
            exitOkko[0].click ();
        }
    },
    222  //  Almost 5 times per second, plenty fast enough
);
</code>```

If you want to sequence clicks, use chained waitForKeyElements() calls as shown in this answer.

Body:
I am working on a User script but it seems to work just for the first comparison:

(function() {
'use strict';

var noError = document.getElementsByClassName("noMistakeButton");
var next = document.getElementsByClassName("nextButton");
var wait = document.getElementsByClassName("understoodButton");
var okko = document.getElementsByClassName("buttonKo");
var exitOkko = document.getElementsByClassName("exitButton");

while(1)
{
    if( noError !== null)
    {
        noError.click();
    }

    if( next !== null)
    {
        exit.click();
    }

    if( wait !== null)
    {
        wait.click();
    }
    sleep(2);
    if( okko !== null)
    {
        exit.click();
    }

    if( exitOkko !== null)
    {
        exitOkko.click();
    }

} })();

My goal is the run this script freely while AFK.
There are, as you can see, many buttons on the web page and each button cant be :visible or :hidden. My goal is just to click on them.

Here is the target page (static URL).

Some buttons only have class and no ID. Others have them both.

The console reports:

ERROR: Execution of script 'AutoVoltair' failed!   noError.click is not
  a function

Body:
It is unclear what you hope to accomplish.  If you are trying to step through a sequence of controls, use the approach illustrated in Choosing and activating the right controls on an AJAX-driven site.

The kind of code shown in the question would just play "Whac-A-Mole" with whatever button "popped up" next. (And only if the preceding buttons had been deleted.)

Anyway, to answer the question: "why this code is only doing the first if?".

It's because userscripts (and javascript) stop running at the first critical error (with a few exceptions).  Additionally:

noError.click is not a function because noError is a collection of elements, not a button.

All the getElementsByClassName calls are only done once.  If it's going to continually loop, you need to recheck inside the loop.

There is no such thing as sleep().

while (1) is a very bad idea and can freeze your browser, or even help crash your PC.  Use setInterval for polling the page.

Here's the "Whac-A-Mole" code with those errors corrected:

setInterval ( () => {
        var noError     = document.getElementsByClassName ("noMistakeButton");
        var next        = document.getElementsByClassName ("nextButton");
        var wait        = document.getElementsByClassName ("understoodButton");
        var okko        = document.getElementsByClassName ("buttonKo");
        var exitOkko    = document.getElementsByClassName ("exitButton");

        if (noError.length) {
            noError[0].click ();
        }
        if (next.length) {
            next[0].click ();
        }
        if (wait.length) {
            wait[0].click ();
        }
        if (okko.length) {
            okko[0].click ();
        }
        if (exitOkko.length) {
            exitOkko[0].click ();
        }
    },
    222  //  Almost 5 times per second, plenty fast enough
);

If you want to sequence clicks, use chained waitForKeyElements() calls as shown in this answer.


问:
Open start form and close all other Forms with Xamarin Crossplatform
At the start of my project I open a Dashboard form, each time I am calling other forms with the Navigation.PushAsync. But when the User logs out I want to close all forms and stacks and open my Dashboard again without going back option. How do i do this?</p>

答:
Use Navigation.PushModalAsync (modalPage);
It will create new navigation stack, thereby back button won't be visible.</p>


问:
JMeter listener log.info messages do not appear in Jenkins
I wrote a JSR223 Listener that has log.info messages.  Why do these log.info messages not appear in the Jenkins Console Output?  I have BeanShell Assertions with log.info messages that will appear in the Jenkins Console Output.  I'm just curious why Listener log.info messages won't show</p>

答:
log is writing to jmeter log which isn't display in Jenkins

You can write to output strem using OUT as:

```<code> OUT.println("Hello Jenkins");
</code>```

Body:
log is writing to jmeter log which isn't display in Jenkins

You can write to output strem using OUT as:

 OUT.println("Hello Jenkins");


问:
Remove padding from PreferenceScreen that is created programatically in PreferencesListFragment
I have settings screen which is Fragment extending PreferencesListFragment. In which first there is main PreferenceScreen in which there are multiple nested PreferenceScreen like below layout:

```<code><PreferenceScreen>
   //general settings
   <PreferenceScreen android:key="adv_settings">
    //more advanced settings
   </PreferenceScreen>
</PreferenceScreen>
</code>```

Main Settings list is looks fine as shown below:

But when i clicked on one of PreferenceScreen say "Call" then Call PreferenceScreen opens as shown below with added left and right side padding.

I am using Custom layout for PreferenceScreen in which i do not give any padding to layout.

I am creating PreferenceScreen programatically

I have followed this and this about removing padding by setting padding to ListView but i did not helped.

Any help will be appreciated.

答: In my case I had to use R.id.list instead of android.R.id.list

Body:
I have settings screen which is Fragment extending PreferencesListFragment. In which first there is main PreferenceScreen in which there are multiple nested PreferenceScreen like below layout:

<PreferenceScreen>
   //general settings
   <PreferenceScreen android:key="adv_settings">
    //more advanced settings
   </PreferenceScreen>
</PreferenceScreen>

Main Settings list is looks fine as shown below:

But when i clicked on one of PreferenceScreen say "Call" then Call PreferenceScreen opens as shown below with added left and right side padding.

I am using Custom layout for PreferenceScreen in which i do not give any padding to layout.

I am creating PreferenceScreen programatically

I have followed this and this about removing padding by setting padding to ListView but i did not helped.

Any help will be appreciated.


问:
asp.net core web api, how to inject the connection string
Here is my asp.net core project structure

1- ASP.NET CORE Web API (contains aspsettings.json)

```<code>"ConnectionStrings": {
    "DefaultConnection": "Server=(local)\\SQLEXPRESS;Database=testdb;Trusted_Connection=True;"

  }
</code>```

2-SERVICES Project (Web API Call method from Services Project)

3-REPOSITORY Project (Services call method from Repository Project and Repository Project include the DATA Project where all the models are)

4-DATA Project where it's contain all the model with code first

```<code>public class TtEntities : DbContext
    {

        public virtual DbSet<RoomMessage> RoomMessage { get; set; }
        public virtual DbSet<UserRoom> UserRoom { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
           optionsBuilder.UseSqlServer(@"Server=(local)\SQLEXPRESS;Database=testdb;Trusted_Connection=True;");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
....
</code>```

As you can see, I hardcoded the connection on the method OnConfiguring which is not the best practice for sure.

Is there a way to pass the connection string from the configuration file of the Web API Project?

Is update database command will still work if we pass the connection from the file aspsettings.json from web api project ?

Thanks a lot

答:
DI solves this problem perfectly and .NET Core 2.0 has Microsoft DI thats provides clearly experience with DI.

oh, lets starts(i think that DATA Project and REPOSITORY Project should be one)

from REPOSITORY Project
change your REPOSITORYClass to

```<code>    public class REPOSITORYClass
    {
        private readonly TtEntities _db;

        public REPOSITORYClass (TtEntities db){
            _db = db;
        }

        //some your staff of REPOSITORYClass thats uses _db
    }
</code>```

now go to SERVICES Project

lets change some service that uses REPOSITORYClass

```<code>public class SomeService
    {
        private readonly REPOSITORYClass _repo;

        public SomeService (REPOSITORYClass repo){
            _repo = repo;
        }

        //other staff of SomeService thats uses _repo
    }
</code>```

after that go to ASP.NET CORE Web API startup file and add to

public void ConfigureServices

```<code>        // Get connection of your repo
        string connection = Configuration.GetConnectionString("DefaultConnection");
        // add TtEntities as service
        services.AddDbContext<TtEntities>(options =>
                        options.UseSqlServer(connection));

//add your repo
        services.AddTransient<REPOSITORYClass>();
//add your service
        services.AddTransient<SomeService>();
</code>```

now go to the contoller thats uses your SomeService

```<code>    public class SomeController: Controller
        {
            private readonly SomeService _someService;

            public SomeController(SomeService someService){
                _someService = someService;
            }

            //And use whatever your wants from your service that injected with deps of repo and injected db entity with connection
            public string SomeMethod()
            {
                 return _someService.SomeMethod();
            }
        }
</code>```

And use whatever your wants from your service that injected with deps of repo and injected db entity with connection

thats all

PS also recommend to read this Introduction to Dependency Injection in ASP.NET Core

Body:
Here is my asp.net core project structure

1- ASP.NET CORE Web API (contains aspsettings.json)

"ConnectionStrings": {
    "DefaultConnection": "Server=(local)\\SQLEXPRESS;Database=testdb;Trusted_Connection=True;"

  }

2-SERVICES Project (Web API Call method from Services Project)

3-REPOSITORY Project (Services call method from Repository Project and Repository Project include the DATA Project where all the models are)

4-DATA Project where it's contain all the model with code first

public class TtEntities : DbContext
    {

        public virtual DbSet<RoomMessage> RoomMessage { get; set; }
        public virtual DbSet<UserRoom> UserRoom { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
           optionsBuilder.UseSqlServer(@"Server=(local)\SQLEXPRESS;Database=testdb;Trusted_Connection=True;");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
....

As you can see, I hardcoded the connection on the method OnConfiguring which is not the best practice for sure.

Is there a way to pass the connection string from the configuration file of the Web API Project?

Is update database command will still work if we pass the connection from the file aspsettings.json from web api project ?

Thanks a lot

Body:
DI solves this problem perfectly and .NET Core 2.0 has Microsoft DI thats provides clearly experience with DI.

oh, lets starts(i think that DATA Project and REPOSITORY Project should be one)

from REPOSITORY Project
change your REPOSITORYClass to

    public class REPOSITORYClass
    {
        private readonly TtEntities _db;

        public REPOSITORYClass (TtEntities db){
            _db = db;
        }

        //some your staff of REPOSITORYClass thats uses _db
    }

now go to SERVICES Project

lets change some service that uses REPOSITORYClass

public class SomeService
    {
        private readonly REPOSITORYClass _repo;

        public SomeService (REPOSITORYClass repo){
            _repo = repo;
        }

        //other staff of SomeService thats uses _repo
    }

after that go to ASP.NET CORE Web API startup file and add to

public void ConfigureServices

        // Get connection of your repo
        string connection = Configuration.GetConnectionString("DefaultConnection");
        // add TtEntities as service
        services.AddDbContext<TtEntities>(options =>
                        options.UseSqlServer(connection));

//add your repo
        services.AddTransient<REPOSITORYClass>();
//add your service
        services.AddTransient<SomeService>();

now go to the contoller thats uses your SomeService

    public class SomeController: Controller
        {
            private readonly SomeService _someService;

            public SomeController(SomeService someService){
                _someService = someService;
            }

            //And use whatever your wants from your service that injected with deps of repo and injected db entity with connection
            public string SomeMethod()
            {
                 return _someService.SomeMethod();
            }
        }

And use whatever your wants from your service that injected with deps of repo and injected db entity with connection

thats all

PS also recommend to read this Introduction to Dependency Injection in ASP.NET Core


问:
python image processing library has filters(distortion, lights) used for generate dataset

I'm try to generate a dataset used for object detection(about 1e6 pictures). I have images of objects, and backgrounds. But I think adding some filters on objects & objects+background is good for model training. After investigation, I found I have to use those following filters:

distortion, including shear with curve, distortion with sphere

cast lights on the img.

other simple filter like rotate, resize, blur, noisy, color gradation...

I wonder if there is any library, which is simple to use(input args + [w, h, 4], return [w, h, 4]), natural, fast, and most of all, it can add lights and lens light on img and distort it.

Or any library that can work with python during mxnet training.

ORG IMG1

Distortion1

ORG2

Distortion2

Lights

After observing Photoshop, I have tried to make my own filters using sphere, ellipse and para-curve formulas by PIL, opencv and scimage, However, those filters are not natural and not as good as Photoshop does.

I also tried gimp-python, but I want to use it in a pure python program and I want to process the pictures during training. Maybe speed is really important.

答: These blog seems a practical way of distortion: http://paulbourke.net/miscellaneous/imagewarp/</p>


问:
Deserialization of object in Class Library while accepting an interface parameter (C#, MVC)
Given the interface:

```<code>interface IObject
{
   public string Name {get;set}
}
</code>```

And the following objects:

```<code>class A: IObject
{
   public string Name {get;set}
   public int ID {get;set;}
}

class B: IObject
{
   public string Name {get;set}
   public Guid ID {get;set;}
}
</code>```

I have two consuming applications which are using different database schemae, but do the same job.  This is a matter of maintaining an old app while a team writes a new one.  Requirements include that both use the same library, which is why this problem exists. The apps both call the same external API, and that call is in its own static class and is accessed like so:

```<code>public static IEnumerable<IObject> List(Guid listUniqueIdentifier)
 {
       //a custom class to call the API
       using (var cmd = new WebApiCommand())
       {
                               //custom enum
             cmd.CommandType = ApiComType.GET;
             cmd.Command = "ListObjects";
             cmd.Filter = listUniqueIdentifier.ToString();
             IEnumerable<object> data = cmd.Execute();
             var result = new List<IObject>();
             foreach(var d in data)
             {
               result.add(JsonConvert.DeserializeObject<IObject>(Convert.ToString(d)));
             }
             return result;
       }

}
</code>```

Obviously, you can't instantiate an interface, so

```<code>result.add(JsonConvert.DeserializeObject<IObject>(Convert.ToString(d)));
</code>```

breaks. I don't want to just attempt to construct the GUID-using version and if it fails, use the integer version.  Not only is that a little hacky, but it's the newer DB that is using the integer, so I'd be using a try block as flow control in just about the worse possible way.  How can I deserialize to the right object instance type (A or B) without writing different methods for each type?  Edit: The solutions I've found usually involve either serializing the $type or otherwise saving the instance type during serialization.  That is not possible, as the API is connected to a third party application and cannot store this datum.

答:
You can use a custom JsonConverter to detect the type of ID and then instantiate and populate the correct type of object during deserialization:

```<code>class CustomIObjectConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return typeof(IObject).IsAssignableFrom(objectType);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JObject jo = JObject.Load(reader);
        IObject target;
        if (jo["ID"].Type == JTokenType.Integer)
        {
            target = Activator.CreateInstance<A>();
        }
        else  // Guid
        {
            target = Activator.CreateInstance<B>();
        }
        serializer.Populate(jo.CreateReader(), target);
        return target;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}
</code>```

To use the converter, just pass an instance of it to DeserializeObject():

```<code>var converter = new CustomIObjectConverter();
...
foreach(var d in data)
{
    result.add(JsonConvert.DeserializeObject<IObject>(Convert.ToString(d), converter));
}
</code>```

Here is a short demo to prove the concept: https://dotnetfiddle.net/p2HzsL

Body:
Given the interface:

interface IObject
{
   public string Name {get;set}
}

And the following objects:

class A: IObject
{
   public string Name {get;set}
   public int ID {get;set;}
}

class B: IObject
{
   public string Name {get;set}
   public Guid ID {get;set;}
}

I have two consuming applications which are using different database schemae, but do the same job.  This is a matter of maintaining an old app while a team writes a new one.  Requirements include that both use the same library, which is why this problem exists. The apps both call the same external API, and that call is in its own static class and is accessed like so:

public static IEnumerable<IObject> List(Guid listUniqueIdentifier)
 {
       //a custom class to call the API
       using (var cmd = new WebApiCommand())
       {
                               //custom enum
             cmd.CommandType = ApiComType.GET;
             cmd.Command = "ListObjects";
             cmd.Filter = listUniqueIdentifier.ToString();
             IEnumerable<object> data = cmd.Execute();
             var result = new List<IObject>();
             foreach(var d in data)
             {
               result.add(JsonConvert.DeserializeObject<IObject>(Convert.ToString(d)));
             }
             return result;
       }

}

Obviously, you can't instantiate an interface, so

result.add(JsonConvert.DeserializeObject<IObject>(Convert.ToString(d)));

breaks. I don't want to just attempt to construct the GUID-using version and if it fails, use the integer version.  Not only is that a little hacky, but it's the newer DB that is using the integer, so I'd be using a try block as flow control in just about the worse possible way.  How can I deserialize to the right object instance type (A or B) without writing different methods for each type?  Edit: The solutions I've found usually involve either serializing the $type or otherwise saving the instance type during serialization.  That is not possible, as the API is connected to a third party application and cannot store this datum.

Body:
You can use a custom JsonConverter to detect the type of ID and then instantiate and populate the correct type of object during deserialization:

class CustomIObjectConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return typeof(IObject).IsAssignableFrom(objectType);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JObject jo = JObject.Load(reader);
        IObject target;
        if (jo["ID"].Type == JTokenType.Integer)
        {
            target = Activator.CreateInstance<A>();
        }
        else  // Guid
        {
            target = Activator.CreateInstance<B>();
        }
        serializer.Populate(jo.CreateReader(), target);
        return target;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

To use the converter, just pass an instance of it to DeserializeObject():

var converter = new CustomIObjectConverter();
...
foreach(var d in data)
{
    result.add(JsonConvert.DeserializeObject<IObject>(Convert.ToString(d), converter));
}

Here is a short demo to prove the concept: https://dotnetfiddle.net/p2HzsL


问:
Method to go in which class?
I have 2 classes, player and game and a method called get_player_games($player_id). Which class does this method belong to?

I seem to run into this problem a bit, where I'm not 100% sure which class the method should go in. Is it just a matter of preference?

Thanks

答:
I see it as:

Game

Class Game stores information about a game.
Game includes current game details such as score, players (in game), and other details.
There may be one or more games at one time.

Player

Class Player stores information about a player in a game.
Player includes details about the player, such as name, UID, contact, and other details.

So, if you need a player's list of current games, you need to have a list of games, and a list to store players. This feels like a static method.

So... Where does it go? I would say in neither Game nor Player class. Why not a Games class? One that...

Referenced current games (and associated players)

High score charts

Game histories (who has played, when, how long, etc...)

So, to me, you need a Games class that allowed you to statically call lists of information related to what games were in progress, who is playing, high score lists, etc...

ContentLicense: CC BY-SA 2.5

Title: Method to go in which class?


问:
Making a responsive UI without using a webview
I want to develop Android applications

I am good in Java

But not good in designing XML UIs

There are lot of UI frameworks which use webviews.

but i am not interested in it

Is there any framework which deals with only XML part?

Or anything which can convert Html to Android XML?

The point is I just want the XML part

Is it possible?

答: You have to use constraint layout or Relative layout for this. My choice is use constraint layout for best UI.</p>


问:
Append a clone of a div to the child of an another div using $(this) selector
How can I clone a div to the child of an another div, and I may need to access the destination div by $(this).find(). My html structure is similar to

```<code><div class="destination-wrapper">
  <div class="destination">
  </div>
</div>

<div class="source">
  <p>Content</p>
</div>
</code>```

So i need to clone the 'source' to the 'destination' When I click on the 'destination-wrapper'. There are many 'destination-wrapper' in the page, So I may need to use $(this).find('.destination')

the jquery I used is the following

```<code>$('.destination-wrapper').click(function(){
  $('.source').clone().appendTo($(this).find('.destination'));
});
</code>```

答:
You could do something like this, if .source is next element, after destination wrapper...

```<code>$('.destination-wrapper').click(function(){

destination=$(this).find('.destination');
  clone=$(this).next('.source').clone();
  clone.appendTo(destination);

});
</code>```

Demo:

$('.destination-wrapper').click(function(){

destination=$(this).find('.destination');
  clone=$(this).next('.source').clone();
  clone.appendTo(destination);

});```
<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="destination-wrapper">
wrapper
  <div class="destination">
  destination
  </div>
</div>

<div class="source">
  <p>Content</p>
</div>

<div class="destination-wrapper">
wrapper
  <div class="destination">
  destination
  </div>
</div>

<div class="source">
  <p>Content</p>
</div></code>```

Body:
How can I clone a div to the child of an another div, and I may need to access the destination div by $(this).find(). My html structure is similar to

Content

So i need to clone the 'source' to the 'destination' When I click on the 'destination-wrapper'. There are many 'destination-wrapper' in the page, So I may need to use $(this).find('.destination')

the jquery I used is the following

$('.destination-wrapper').click(function(){
  $('.source').clone().appendTo($(this).find('.destination'));
});

Body:
You could do something like this, if .source is next element, after destination wrapper...

$('.destination-wrapper').click(function(){

destination=$(this).find('.destination');
  clone=$(this).next('.source').clone();
  clone.appendTo(destination);

});

Demo:

$('.destination-wrapper').click(function(){

destination=$(this).find('.destination');
  clone=$(this).next('.source').clone();
  clone.appendTo(destination);

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="destination-wrapper">
wrapper
  <div class="destination">
  destination
  </div>
</div>

<div class="source">
  <p>Content</p>
</div>

<div class="destination-wrapper">
wrapper
  <div class="destination">
  destination
  </div>
</div>

<div class="source">
  <p>Content</p>
</div>


问:
MySQL Recursive get all child from parent
i have this case using recursive query on Mysql to find lv 2 and lv3 child on one table...

database structure i'm using:

```<code>id name parent
1    A    0
2    B    0
3    C    0
4    D    1
5    E    1
6    F    2
7    G    2
8    H    3
9    I    3
10   J    4
11   K    4
</code>```

The result i was expecting, when filtering the data, where id=1, it will generate the result i'm expecting.

```<code>id name parent
4   D     1
5   E     1
10  J     4
11  K     4
</code>```

or this is the illustration.

i've been looking everywhere, and reading this http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/, but i didn't find the result i was looking for..
any help would be appreciated, thanks

答:
if you want to get all level child of a particular parent then you should try this</p>

```<code>select  id,
        name,
        parent
from    (select * from tablename
         order by parent, id) tablename,
        (select @pv := '1') initialisation
where   find_in_set(parent, @pv) > 0
and     @pv := concat(@pv, ',', id)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
i have this case using recursive query on Mysql to find lv 2 and lv3 child on one table...

database structure i'm using:

id name parent
1    A    0
2    B    0
3    C    0
4    D    1
5    E    1
6    F    2
7    G    2
8    H    3
9    I    3
10   J    4
11   K    4

The result i was expecting, when filtering the data, where id=1, it will generate the result i'm expecting.

id name parent
4   D     1
5   E     1
10  J     4
11  K     4

or this is the illustration.

i've been looking everywhere, and reading this http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/, but i didn't find the result i was looking for..
any help would be appreciated, thanks

Body:
if you want to get all level child of a particular parent then you should try this

select  id,
        name,
        parent
from    (select * from tablename
         order by parent, id) tablename,
        (select @pv := '1') initialisation
where   find_in_set(parent, @pv) > 0
and     @pv := concat(@pv, ',', id)


问:
Multi-stage Docker: RUN wget vs ADD
The best practices section of the Docker docs says this:

Because image size matters, using ADD to fetch packages from remote
  URLs is strongly discouraged; you should use curl or wget instead.
  That way you can delete the files you no longer need after they’ve
  been extracted and you won’t have to add another layer in your image.
  For example, you should avoid doing things like:

```<code>ADD http://example.com/big.tar.xz /usr/src/things/
RUN tar -xJf /usr/src/things/big.tar.xz -C /usr/src/things
RUN make -C /usr/src/things all
</code>```

And instead, do something like:

```<code>RUN mkdir -p /usr/src/things \
    && curl -SL http://example.com/big.tar.xz \
    | tar -xJC /usr/src/things \
    && make -C /usr/src/things all
</code>```

On the other hand, later on it notes:

Prior to Docker 17.05, and even more, prior to Docker 1.10, it was
  important to minimize the number of layers in your image. [...] Docker
  17.05 and higher add support for multi-stage builds, which allow you to copy only the artifacts you need into the final image.

and even

compress[ing] two RUN commands together using the Bash && operator
  [is] failure-prone and hard to maintain.

It seems to me that if you are using multi-stage builds, the advice about ADD is inaccurate. The extra layers are unlikely to be a problem unless you are downloading something truly huge, as local disk space is cheap and it's easy to clean out old images. Indeed, when coding one doesn't usually have build commands clean their intermediate artefacts to save space!

In addition, ADD has a major advantage over RUN wget: it detects when its target has changed.

Am I missing something, or do multi-stage builds rehabilitate ADD?

答:
It does look like it: ADD is used for instance in the Katakoda "Creating optimized Docker Images using Multi-Stage Builds" example (for the first image, before the second stage.

With two steps, you can focus on minimizing the (42-max for aufs, hard-limit 127) layers in the second stage only.

Title: Multi-stage Docker: RUN wget vs ADD

Body:
The best practices section of the Docker docs says this:

Because image size matters, using ADD to fetch packages from remote
  URLs is strongly discouraged; you should use curl or wget instead.
  That way you can delete the files you no longer need after they’ve
  been extracted and you won’t have to add another layer in your image.
  For example, you should avoid doing things like:

ADD http://example.com/big.tar.xz /usr/src/things/
RUN tar -xJf /usr/src/things/big.tar.xz -C /usr/src/things
RUN make -C /usr/src/things all

And instead, do something like:

RUN mkdir -p /usr/src/things \
    && curl -SL http://example.com/big.tar.xz \
    | tar -xJC /usr/src/things \
    && make -C /usr/src/things all

On the other hand, later on it notes:

Prior to Docker 17.05, and even more, prior to Docker 1.10, it was
  important to minimize the number of layers in your image. [...] Docker
  17.05 and higher add support for multi-stage builds, which allow you to copy only the artifacts you need into the final image.

and even

compress[ing] two RUN commands together using the Bash && operator
  [is] failure-prone and hard to maintain.

It seems to me that if you are using multi-stage builds, the advice about ADD is inaccurate. The extra layers are unlikely to be a problem unless you are downloading something truly huge, as local disk space is cheap and it's easy to clean out old images. Indeed, when coding one doesn't usually have build commands clean their intermediate artefacts to save space!

In addition, ADD has a major advantage over RUN wget: it detects when its target has changed.

Am I missing something, or do multi-stage builds rehabilitate ADD?


问:
gitlab-runner randomly runs as root rather than user gitlab-runner
I have a simple gitlab-runner setup on its own ubuntu server. It was registered using:

```<code>sudo gitlab-runner register -n --url https://gitlab.com/ --registration-token {{GITLAB_REGISTRATION_TOKEN}} --executor shell --description "{{GITLAB_RUNNER_DESCRIPTION}}"
</code>```

The only gitlab-runner process (ps -ef) that is running is:

```<code>/usr/bin/gitlab-runner run --working-directory /home/gitlab-runner --config /etc/gitlab-runner/config.toml --service gitlab-runner --syslog --user gitlab-runner
</code>```

My /etc/gitlab-runner/config.toml config file contains:

```<code>concurrent = 1
check_interval = 0

[[runners]]
  name = "iouze/landing"
  url = "https://gitlab.com/"
  token = "0530b.....6f9"
  executor = "shell"
  [runners.cache]
</code>```

When my CI pipeline triggers, jobs sometimes gets picked up as user gitlab-runner user, in which case they run correctly (as a sheell executor).

But sometimes, it runs as root, in which case it runs as a docker executor, and then gives errors (because the script is running in an unexpected environment).

Why would it run sometimes as root when there is clearly a --user on the service?

答: I am running on gitlab.com and the pipeline jobs were sometimes getting picked up by the shared runners that are already configured there. I disabled the shared runners</p>

Body:
I have a simple gitlab-runner setup on its own ubuntu server. It was registered using:

sudo gitlab-runner register -n --url https://gitlab.com/ --registration-token {{GITLAB_REGISTRATION_TOKEN}} --executor shell --description "{{GITLAB_RUNNER_DESCRIPTION}}"

The only gitlab-runner process (ps -ef) that is running is:

/usr/bin/gitlab-runner run --working-directory /home/gitlab-runner --config /etc/gitlab-runner/config.toml --service gitlab-runner --syslog --user gitlab-runner

My /etc/gitlab-runner/config.toml config file contains:

concurrent = 1
check_interval = 0

[[runners]]
  name = "iouze/landing"
  url = "https://gitlab.com/"
  token = "0530b.....6f9"
  executor = "shell"
  [runners.cache]

When my CI pipeline triggers, jobs sometimes gets picked up as user gitlab-runner user, in which case they run correctly (as a sheell executor).

But sometimes, it runs as root, in which case it runs as a docker executor, and then gives errors (because the script is running in an unexpected environment).

Why would it run sometimes as root when there is clearly a --user on the service?


问:
How to trigger broadcast receiver when gps is turn on/off?
```<code>public class BootReceiver extends BroadcastReceiver  {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
            Toast.makeText(context, "in android.location.PROVIDERS_CHANGED",
                Toast.LENGTH_SHORT).show();
            Intent pushIntent = new Intent(context, LocalService.class);
            context.startService(pushIntent);
        } else {
            Toast.makeText(context, "not in android.location.PROVIDERS_CHANGED",
                Toast.LENGTH_SHORT).show();
            Intent pushIntent = new Intent(context, LocalService.class);
            context.startService(pushIntent);
        }
    }

    @Override
    public void onLocationChanged(Location arg0) {

    }
}
</code>```

In my app , i need to  trigger broadcast receiver when gps is turn on/off.
 look into the matter and suggest best one to implement in app.

答:
you can try this

Manifest

```<code><receiver android:name=".MyReceiver">
        <intent-filter>
            <action android:name="android.location.GPS_ENABLED_CHANGE" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </receiver>
</code>```

MyReceiver

```<code>if (intent.getAction().matches("android.location.GPS_ENABLED_CHANGE"))
    {
        boolean enabled = intent.getBooleanExtra("enabled",false);

        Toast.makeText(context, "GPS : " + enabled,
                Toast.LENGTH_SHORT).show();
    }
</code>```

Body:
public class BootReceiver extends BroadcastReceiver  {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
            Toast.makeText(context, "in android.location.PROVIDERS_CHANGED",
                Toast.LENGTH_SHORT).show();
            Intent pushIntent = new Intent(context, LocalService.class);
            context.startService(pushIntent);
        } else {
            Toast.makeText(context, "not in android.location.PROVIDERS_CHANGED",
                Toast.LENGTH_SHORT).show();
            Intent pushIntent = new Intent(context, LocalService.class);
            context.startService(pushIntent);
        }
    }

    @Override
    public void onLocationChanged(Location arg0) {

    }
}

In my app , i need to  trigger broadcast receiver when gps is turn on/off.
 look into the matter and suggest best one to implement in app.

Body:
you can try this

Manifest

<receiver android:name=".MyReceiver">
        <intent-filter>
            <action android:name="android.location.GPS_ENABLED_CHANGE" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </receiver>

MyReceiver

if (intent.getAction().matches("android.location.GPS_ENABLED_CHANGE"))
    {
        boolean enabled = intent.getBooleanExtra("enabled",false);

        Toast.makeText(context, "GPS : " + enabled,
                Toast.LENGTH_SHORT).show();
    }


问:
search and remove specific file using linux command
I using this command for search all file contain this word . I want to remove all file contain this word in specific directory . grep command perfectly. suggest me how can I used

```<code>     rm -rf
</code>```

with below command

```<code>     grep -l -r  -i  "Pending" . | grep -n  . | wc -l
</code>```

答:
This could be done by using the l flag and piping the filenames to xargs:

-l
      (The letter ell.) Write only the names of files containing selected
      lines to standard output. Pathnames are written once per file searched.
      If the standard input is searched, a pathname of (standard input) will
      be written, in the POSIX locale. In other locales, standard input may be
      replaced by something more appropriate in those locales.

```<code>grep -l -r 'Pending' . | xargs rm
</code>```

The above will delete all files in the current directory containing the word Pending.

Body:
I using this command for search all file contain this word . I want to remove all file contain this word in specific directory . grep command perfectly. suggest me how can I used

     rm -rf

with below command

     grep -l -r  -i  "Pending" . | grep -n  . | wc -l

Body:
This could be done by using the l flag and piping the filenames to xargs:

-l
      (The letter ell.) Write only the names of files containing selected
      lines to standard output. Pathnames are written once per file searched.
      If the standard input is searched, a pathname of (standard input) will
      be written, in the POSIX locale. In other locales, standard input may be
      replaced by something more appropriate in those locales.

grep -l -r 'Pending' . | xargs rm

The above will delete all files in the current directory containing the word Pending.


问:
How to print diamond shape w/ c++
I need help, I created a short little program a while ago where it would print a simple pyramid with "*" like this:

```<code>  *
 ***
*****
</code>```

but I decided to challenge myself and see if I could create a simple diamond shape like this:

```<code>  *
 ***
*****
 ***
  *
</code>```

Here is my code so far.
I should also add that the value you input, for example 5, determines how big the diamond is.

```<code>#include <iostream>
#include <sstream>
using namespace std;

int main() {

int value = 0;
cout << "Please enter in a value: ";
cin >> value;
cout << endl;

for (int i = 0; i < value; i++) {
    //print spaces v v v
    for (int x = 0; x < (value - i - 1); x++) {
        cout << " ";
    }
    //print * v v v
    for (int y = 0; y < (2 * i + 1); y++) {
        cout << "*";
    }
    cout << endl;
}

for (int i = 0; i < value; i++) {
    int number = 0;
    number+= 2;
    //print spaces v v v
    for (int x = 0; x < (value - value + i + 1); x++) {
        cout << " ";
    }
    //print * v v v
    for (int y = 0; y < (/*ATTENTION: What do I do here? Plz help*/); y++) {
        cout << "*";
    }
    cout << endl;
}

return 0;
}
</code>```

What I've been trying to do is figure out what to put inside the parenthesis where it says (//ATTENTION). I've been working for at least an hour trying to do random things, and one time it worked when I input 4, but not for 5, and it's just been very hard. This is key to building the diamond, try putting in just value and compile to see what happens. I need it to be symmetrical.

I need to know what to put inside the parenthesis please. I'm sorry this is very long but the help would be appreciated thanks.

I also apologize if my code is messy and hard to read.

答:
This code should resolve the problem:</p>

```<code>#include <sstream>
using namespace std;

void printSpaces(int howMany) {
    for(int i = 0; i < howMany; i++) cout << " ";
}

void figure(int size) {
    bool oddSize = size % 2 == 1;
    int center = size / 2;
    int spaces = size / 2;
    // If figure is of an odd size adjust center
    if (oddSize) {
        center++;
    } else { // Else if figure is of even size adjust spaces
        spaces--;
    }

    for (int i = 1; i <= center; i++) {
        printSpaces(spaces);
        for(int j = 0; j <  1 + (i - 1) * 2; j++) cout << "*";
        cout << endl;
        spaces--;
    }

    spaces = oddSize ? 1 : 0; // If the figure's size is odd number adjust spaces to 1
    center -= oddSize ? 1 : 0; // Adjust center if it's an odd size figure
    for(int i = center; i >= 1; i--) {
        printSpaces(spaces);
        for(int j = 0; j <  1 + (i - 1) * 2; j++)
           cout << "*";
        cout << endl;
        spaces++;
    }

}

int main() {
    int value = 0;
    while(value < 3) {
        cout << "Please enter in a value (>= 3): ";
        cin >> value;
        cout << endl;
    }
    figure(value);
    return 0;
}
</code>```

Title: How to print diamond shape w/ c++

Body:
I need help, I created a short little program a while ago where it would print a simple pyramid with "*" like this:

  *
 ***
*****

but I decided to challenge myself and see if I could create a simple diamond shape like this:

  *
 ***
*****
 ***
  *

Here is my code so far.
I should also add that the value you input, for example 5, determines how big the diamond is.

#include <iostream>
#include <sstream>
using namespace std;

int main() {

int value = 0;
cout << "Please enter in a value: ";
cin >> value;
cout << endl;

for (int i = 0; i < value; i++) {
    //print spaces v v v
    for (int x = 0; x < (value - i - 1); x++) {
        cout << " ";
    }
    //print * v v v
    for (int y = 0; y < (2 * i + 1); y++) {
        cout << "*";
    }
    cout << endl;
}

for (int i = 0; i < value; i++) {
    int number = 0;
    number+= 2;
    //print spaces v v v
    for (int x = 0; x < (value - value + i + 1); x++) {
        cout << " ";
    }
    //print * v v v
    for (int y = 0; y < (/*ATTENTION: What do I do here? Plz help*/); y++) {
        cout << "*";
    }
    cout << endl;
}

return 0;
}

What I've been trying to do is figure out what to put inside the parenthesis where it says (//ATTENTION). I've been working for at least an hour trying to do random things, and one time it worked when I input 4, but not for 5, and it's just been very hard. This is key to building the diamond, try putting in just value and compile to see what happens. I need it to be symmetrical.

I need to know what to put inside the parenthesis please. I'm sorry this is very long but the help would be appreciated thanks.

I also apologize if my code is messy and hard to read.

Body:
This code should resolve the problem:

#include <sstream>
using namespace std;

void printSpaces(int howMany) {
    for(int i = 0; i < howMany; i++) cout << " ";
}

void figure(int size) {
    bool oddSize = size % 2 == 1;
    int center = size / 2;
    int spaces = size / 2;
    // If figure is of an odd size adjust center
    if (oddSize) {
        center++;
    } else { // Else if figure is of even size adjust spaces
        spaces--;
    }

    for (int i = 1; i <= center; i++) {
        printSpaces(spaces);
        for(int j = 0; j <  1 + (i - 1) * 2; j++) cout << "*";
        cout << endl;
        spaces--;
    }

    spaces = oddSize ? 1 : 0; // If the figure's size is odd number adjust spaces to 1
    center -= oddSize ? 1 : 0; // Adjust center if it's an odd size figure
    for(int i = center; i >= 1; i--) {
        printSpaces(spaces);
        for(int j = 0; j <  1 + (i - 1) * 2; j++)
           cout << "*";
        cout << endl;
        spaces++;
    }

}

int main() {
    int value = 0;
    while(value < 3) {
        cout << "Please enter in a value (>= 3): ";
        cin >> value;
        cout << endl;
    }
    figure(value);
    return 0;
}


问:
Mongoose .count not working when nested?
Maybe I'm overlooking something but I have a pretty simple setup.  What I'm trying to do is find all 'App' documents in my database and then for each App get the number of User documents associated with that App.

```<code>AppObject.find({}).exec((err, apps) => {
  if (err) {

  } else if (!apps) {

  } else {
    apps.forEach((app, index) => {

      (function (app) {
        console.log('app ID ' + app._id);
        User.find({ appId: app._id }).count((countErr, count) => {
          console.log('COUNT ERR ' + JSON.stringify(countErr));
          console.log('Number of docs: ', count);
          // do more things with the App and the count
        });
      }(app));

    });
  }
});
</code>```

When I look at the console logs, what I'm seeing is the line

```<code>console.log('app ID ' + app._id);
</code>```

correctly prints the app ID, but then

```<code>console.log('Number of docs: ', count);
</code>```

shows up as 0.

When I run the query outside of the forEach loop (and provide the app ID manually) it correctly returns the number of documents.

I'm kind of at a loss, any help is appreciated.

Thanks!

答:
I started recently working on project to migrate Nodejs from callback hell to Async/Await provided in latest Node version 8.x, please find the below solution and give it a shot. Thank you.

```<code>//Create a async/await function with ES6 syntax
const findAllCount = async () => {
try{
  const apps = await AppObject.find({})
  await apps.forEach( app, async () => {
  console.log('app ID ' + app._id)
  const count = await User.find({ appId: await app._id }).count()
  console.log('Number of docs: ', count)
  // Here you can continue to use app and count for more things
 })
}
 catch(error){console.error('Error at findAllCount function: '+error)}
}

// Invoke Function
findAllCount()
</code>```

Hope this helps. If not please provide the collection schema to reproduce scenario at my end. Thank you and wish all the best.

Body:
Maybe I'm overlooking something but I have a pretty simple setup.  What I'm trying to do is find all 'App' documents in my database and then for each App get the number of User documents associated with that App.

AppObject.find({}).exec((err, apps) => {
  if (err) {

  } else if (!apps) {

  } else {
    apps.forEach((app, index) => {

      (function (app) {
        console.log('app ID ' + app._id);
        User.find({ appId: app._id }).count((countErr, count) => {
          console.log('COUNT ERR ' + JSON.stringify(countErr));
          console.log('Number of docs: ', count);
          // do more things with the App and the count
        });
      }(app));

    });
  }
});

When I look at the console logs, what I'm seeing is the line

console.log('app ID ' + app._id);

correctly prints the app ID, but then

console.log('Number of docs: ', count);

shows up as 0.

When I run the query outside of the forEach loop (and provide the app ID manually) it correctly returns the number of documents.

I'm kind of at a loss, any help is appreciated.

Thanks!

Body:
I started recently working on project to migrate Nodejs from callback hell to Async/Await provided in latest Node version 8.x, please find the below solution and give it a shot. Thank you.

//Create a async/await function with ES6 syntax
const findAllCount = async () => {
try{
  const apps = await AppObject.find({})
  await apps.forEach( app, async () => {
  console.log('app ID ' + app._id)
  const count = await User.find({ appId: await app._id }).count()
  console.log('Number of docs: ', count)
  // Here you can continue to use app and count for more things
 })
}
 catch(error){console.error('Error at findAllCount function: '+error)}
}

// Invoke Function
findAllCount()

Hope this helps. If not please provide the collection schema to reproduce scenario at my end. Thank you and wish all the best.


问:
Javascript count object's key having dot notation
Trying to count the arrays inside javascript object. This response is coming back from laravel validator

```<code>  {
   "message":"The given data was invalid.",
   "errors":{
      "roomtype_id":[
         "Please select a room type"
      ],
      "price":[
         "Price cannot be empty"
      ],
      "amenities":[
         "Atleast select one amenities"
      ],
      "floor.0":[
         "Please select a floor"
      ],
      "floor.1":[
         "Please select a floor"
      ],
      "floor.2":[
         "Please select a floor"
      ],
      "floor.3":[
         "Please select a floor"
      ],
      "floor.4":[
         "Please select a floor"
      ],
      "room_number.0":[
         "Room number cannot be empty"
      ],
      "room_number.1":[
         "Room number cannot be empty"
      ],
      "room_number.2":[
         "Room number cannot be empty"
      ],
      "room_number.3":[
         "Room number cannot be empty"
      ],
      "room_number.4":[
         "Room number cannot be empty"
      ],
      "room_number.5":[
         "Room number cannot be empty"
      ],
      "room_number.6":[
         "Room number cannot be empty"
      ],
      "room_number.7":[
         "Room number cannot be empty"
      ],
      "room_number.8":[
         "Room number cannot be empty"
      ],
      "room_number.9":[
         "Room number cannot be empty"
      ],
      "room_number.10":[
         "Room number cannot be empty"
      ],
      "room_number.11":[
         "Room number cannot be empty"
      ],
      "room_number.12":[
         "Room number cannot be empty"
      ],
      "room_number.13":[
         "Room number cannot be empty"
      ],
      "room_number.14":[
         "Room number cannot be empty"
      ],
      "room_number.15":[
         "Room number cannot be empty"
      ],
      "room_number.16":[
         "Room number cannot be empty"
      ],
      "room_number.17":[
         "Room number cannot be empty"
      ],
      "room_number.18":[
         "Room number cannot be empty"
      ],
      "room_number.19":[
         "Room number cannot be empty"
      ],
      "room_number.20":[
         "Room number cannot be empty"
      ],
      "room_number.21":[
         "Room number cannot be empty"
      ],
      "room_number.22":[
         "Room number cannot be empty"
      ],
      "room_number.23":[
         "Room number cannot be empty"
      ],
      "room_number.24":[
         "Room number cannot be empty"
      ],
      "room_number.25":[
         "Room number cannot be empty"
      ],
      "room_number.26":[
         "Room number cannot be empty"
      ],
      "room_number.27":[
         "Room number cannot be empty"
      ],
      "room_number.28":[
         "Room number cannot be empty"
      ]
   }
}
</code>```

In the above js object, the error object contains "floor.0":["Please select a floor"],"floor.1":["Please select a floor"],"floor.2":["Please select a floor"] and so on.

I want to count how many floor.* arrays is present

Note:
I am accessing the single values like the below

```<code>$("#floor_error_1").text(data.responseJSON.errors["floor.0"]);
$("#floor_error_2").text(data.responseJSON.errors["floor.1"]);
</code>```

how to count? and loop through and print the errors?

答:
You can loop and count the errors by doing this:

    var data = {};
 data.responseJSON = '{"message":"The given data was invalid.","errors":{"roomtype_id":["Please select a room type"],"price":["Price cannot be empty"],"amenities":["Atleast select one amenities"],"floor.0":["Please select a floor"],"floor.1":["Please select a floor"],"floor.2":["Please select a floor"],"floor.3":["Please select a floor"],"floor.4":["Please select a floor"],"room_number.0":["Room number cannot be empty"],"room_number.1":["Room number cannot be empty"],"room_number.2":["Room number cannot be empty"],"room_number.3":["Room number cannot be empty"],"room_number.4":["Room number cannot be empty"],"room_number.5":["Room number cannot be empty"],"room_number.6":["Room number cannot be empty"],"room_number.7":["Room number cannot be empty"],"room_number.8":["Room number cannot be empty"],"room_number.9":["Room number cannot be empty"],"room_number.10":["Room number cannot be empty"],"room_number.11":["Room number cannot be empty"],"room_number.12":["Room number cannot be empty"],"room_number.13":["Room number cannot be empty"],"room_number.14":["Room number cannot be empty"],"room_number.15":["Room number cannot be empty"],"room_number.16":["Room number cannot be empty"],"room_number.17":["Room number cannot be empty"],"room_number.18":["Room number cannot be empty"],"room_number.19":["Room number cannot be empty"],"room_number.20":["Room number cannot be empty"],"room_number.21":["Room number cannot be empty"],"room_number.22":["Room number cannot be empty"],"room_number.23":["Room number cannot be empty"],"room_number.24":["Room number cannot be empty"],"room_number.25":["Room number cannot be empty"],"room_number.26":["Room number cannot be empty"],"room_number.27":["Room number cannot be empty"],"room_number.28":["Room number cannot be empty"]}}';
 data.responseJSON = JSON.parse( data.responseJSON );

        //Start of looping here
 var counter = 0;
 for ( var key in data.responseJSON.errors ) {
                //Check if 'floor' is found on kkey
  if ( key.indexOf( "floor." ) !== -1 ) {
   //the key has text floor.
   counter++;
   console.log( data.responseJSON.errors[ key ][0] );
  }
 }

 console.log( "Total error is " + counter );```

This will show all the errors for floor and count it. Hitting 2 birds with one stone.

Body:
Trying to count the arrays inside javascript object. This response is coming back from laravel validator

  {
   "message":"The given data was invalid.",
   "errors":{
      "roomtype_id":[
         "Please select a room type"
      ],
      "price":[
         "Price cannot be empty"
      ],
      "amenities":[
         "Atleast select one amenities"
      ],
      "floor.0":[
         "Please select a floor"
      ],
      "floor.1":[
         "Please select a floor"
      ],
      "floor.2":[
         "Please select a floor"
      ],
      "floor.3":[
         "Please select a floor"
      ],
      "floor.4":[
         "Please select a floor"
      ],
      "room_number.0":[
         "Room number cannot be empty"
      ],
      "room_number.1":[
         "Room number cannot be empty"
      ],
      "room_number.2":[
         "Room number cannot be empty"
      ],
      "room_number.3":[
         "Room number cannot be empty"
      ],
      "room_number.4":[
         "Room number cannot be empty"
      ],
      "room_number.5":[
         "Room number cannot be empty"
      ],
      "room_number.6":[
         "Room number cannot be empty"
      ],
      "room_number.7":[
         "Room number cannot be empty"
      ],
      "room_number.8":[
         "Room number cannot be empty"
      ],
      "room_number.9":[
         "Room number cannot be empty"
      ],
      "room_number.10":[
         "Room number cannot be empty"
      ],
      "room_number.11":[
         "Room number cannot be empty"
      ],
      "room_number.12":[
         "Room number cannot be empty"
      ],
      "room_number.13":[
         "Room number cannot be empty"
      ],
      "room_number.14":[
         "Room number cannot be empty"
      ],
      "room_number.15":[
         "Room number cannot be empty"
      ],
      "room_number.16":[
         "Room number cannot be empty"
      ],
      "room_number.17":[
         "Room number cannot be empty"
      ],
      "room_number.18":[
         "Room number cannot be empty"
      ],
      "room_number.19":[
         "Room number cannot be empty"
      ],
      "room_number.20":[
         "Room number cannot be empty"
      ],
      "room_number.21":[
         "Room number cannot be empty"
      ],
      "room_number.22":[
         "Room number cannot be empty"
      ],
      "room_number.23":[
         "Room number cannot be empty"
      ],
      "room_number.24":[
         "Room number cannot be empty"
      ],
      "room_number.25":[
         "Room number cannot be empty"
      ],
      "room_number.26":[
         "Room number cannot be empty"
      ],
      "room_number.27":[
         "Room number cannot be empty"
      ],
      "room_number.28":[
         "Room number cannot be empty"
      ]
   }
}

In the above js object, the error object contains "floor.0":["Please select a floor"],"floor.1":["Please select a floor"],"floor.2":["Please select a floor"] and so on.

I want to count how many floor.* arrays is present

Note:
I am accessing the single values like the below

$("#floor_error_1").text(data.responseJSON.errors["floor.0"]);
$("#floor_error_2").text(data.responseJSON.errors["floor.1"]);

how to count? and loop through and print the errors?

Body:
You can loop and count the errors by doing this:

    var data = {};
 data.responseJSON = '{"message":"The given data was invalid.","errors":{"roomtype_id":["Please select a room type"],"price":["Price cannot be empty"],"amenities":["Atleast select one amenities"],"floor.0":["Please select a floor"],"floor.1":["Please select a floor"],"floor.2":["Please select a floor"],"floor.3":["Please select a floor"],"floor.4":["Please select a floor"],"room_number.0":["Room number cannot be empty"],"room_number.1":["Room number cannot be empty"],"room_number.2":["Room number cannot be empty"],"room_number.3":["Room number cannot be empty"],"room_number.4":["Room number cannot be empty"],"room_number.5":["Room number cannot be empty"],"room_number.6":["Room number cannot be empty"],"room_number.7":["Room number cannot be empty"],"room_number.8":["Room number cannot be empty"],"room_number.9":["Room number cannot be empty"],"room_number.10":["Room number cannot be empty"],"room_number.11":["Room number cannot be empty"],"room_number.12":["Room number cannot be empty"],"room_number.13":["Room number cannot be empty"],"room_number.14":["Room number cannot be empty"],"room_number.15":["Room number cannot be empty"],"room_number.16":["Room number cannot be empty"],"room_number.17":["Room number cannot be empty"],"room_number.18":["Room number cannot be empty"],"room_number.19":["Room number cannot be empty"],"room_number.20":["Room number cannot be empty"],"room_number.21":["Room number cannot be empty"],"room_number.22":["Room number cannot be empty"],"room_number.23":["Room number cannot be empty"],"room_number.24":["Room number cannot be empty"],"room_number.25":["Room number cannot be empty"],"room_number.26":["Room number cannot be empty"],"room_number.27":["Room number cannot be empty"],"room_number.28":["Room number cannot be empty"]}}';
 data.responseJSON = JSON.parse( data.responseJSON );

        //Start of looping here
 var counter = 0;
 for ( var key in data.responseJSON.errors ) {
                //Check if 'floor' is found on kkey
  if ( key.indexOf( "floor." ) !== -1 ) {
   //the key has text floor.
   counter++;
   console.log( data.responseJSON.errors[ key ][0] );
  }
 }

 console.log( "Total error is " + counter );

This will show all the errors for floor and count it. Hitting 2 birds with one stone.


问:
how to select record based on max value and where clause in LINQ to Entities
i have following records in my table tbl_JobMaster

```<code>ID  CIN   JobNumber Version
1   ABC   100           1.0
2   ABC   100           2.0
3   ABC   200           1.0
4   ABC   200           2.0
5   ABC   200           3.0
6   XYZ   300           1.0
</code>```

i want list of records based on CIN column and MAX(Version) and unique JobNumber

for e.g. CIN=ABC
so output should be as follows

```<code>ID  CIN   JobNumber Version
2   ABC   100           2.0
5   ABC   200           3.0
</code>```

I tried following code but it isn't working

```<code>var result=(from job in entity.tbl_JobMaster
            where job.CIN=="ABC" && job.Version==entity.tbl_JobMaster.Where(p=>p.ID==job.ID).Max(p=>p.Version)
            select job).Distinct();
</code>```

答:
Here's an example using LINQ extension methods:</p>

```<code>var selection = entity.tbl_JobMaster
  .Where(job => job.CIN == "ABC")
  .GroupBy(job => job.JobNumber)
  .Select(group => group
    .OrderByDescending(job => job.Version)
    .First()
);
</code>```

Body:
i have following records in my table tbl_JobMaster

ID  CIN   JobNumber Version
1   ABC   100           1.0
2   ABC   100           2.0
3   ABC   200           1.0
4   ABC   200           2.0
5   ABC   200           3.0
6   XYZ   300           1.0

i want list of records based on CIN column and MAX(Version) and unique JobNumber

for e.g. CIN=ABC
so output should be as follows

ID  CIN   JobNumber Version
2   ABC   100           2.0
5   ABC   200           3.0

I tried following code but it isn't working

var result=(from job in entity.tbl_JobMaster
            where job.CIN=="ABC" && job.Version==entity.tbl_JobMaster.Where(p=>p.ID==job.ID).Max(p=>p.Version)
            select job).Distinct();

Body:
Here's an example using LINQ extension methods:

var selection = entity.tbl_JobMaster
  .Where(job => job.CIN == "ABC")
  .GroupBy(job => job.JobNumber)
  .Select(group => group
    .OrderByDescending(job => job.Version)
    .First()
);


问:
Calling a double array with parameters from field as method
disclaimer: Sorry if I used the terms incorrectly. It would be great if you could provide the correct terms (if I used them incorrectly!)

This is my class with the field and constructor:

```<code>double[] studentMathScores = {81.5,89.0,45.5,99.0,55.0,34.5,56.0,78.0,76.0,80.0};
public StudentDashboard(double[] studentMathScores)
    {
        this.studentMathScores = studentMathScores;
    }
</code>```

How do I declare an object in my main class using studentMathScores?

```<code>StudentDashboard test = new StudentDashboard(studentMathScores);
</code>```

`

答:
If you want to keep current constructor/class syntax you should declare in your main method.

double[] studentMathScores = {81.5,89.0,45.5,99.0,55.0,34.5,56.0,78.0,76.0,80.0};

In this case your declaration of studentMathScores in StudentDashboard shoul look like double[] studentMathScores;

Then have it like this:

public class Main {
    public static void main(String[] args) {
        double[] studentMathScores = {81.5,89.0,45.5,99.0,55.0,34.5,56.0,78.0,76.0,80.0};
        StudentDashboard test = new StudentDashboard(studentMathScores);
    }
}

If class syntax could be changed and studentMathScores can be static you can have it this way:

```<code>public class StudentDashboard {

static double[] studentMathScores ={81.5,89.0,45.5,99.0,55.0,34.5,56.0,78.0,76.0,80.0};

public StudentDashboard()
{
}

public static double[] getStudentMathScores() {
    return studentMathScores;
}

public class Main {

public static void main(String[] args) {
    StudentDashboard test = new StudentDashboard();
    double[] studentMathScores = StudentDashboard.getStudentMathScores();
}
</code>```

}

Body:
disclaimer: Sorry if I used the terms incorrectly. It would be great if you could provide the correct terms (if I used them incorrectly!)

This is my class with the field and constructor:

double[] studentMathScores = {81.5,89.0,45.5,99.0,55.0,34.5,56.0,78.0,76.0,80.0};
public StudentDashboard(double[] studentMathScores)
    {
        this.studentMathScores = studentMathScores;
    }

How do I declare an object in my main class using studentMathScores?

StudentDashboard test = new StudentDashboard(studentMathScores);

`

Body:
If you want to keep current constructor/class syntax you should declare in your main method.

double[] studentMathScores = {81.5,89.0,45.5,99.0,55.0,34.5,56.0,78.0,76.0,80.0};

In this case your declaration of studentMathScores in StudentDashboard shoul look like double[] studentMathScores;

Then have it like this:

public class Main {
    public static void main(String[] args) {
        double[] studentMathScores = {81.5,89.0,45.5,99.0,55.0,34.5,56.0,78.0,76.0,80.0};
        StudentDashboard test = new StudentDashboard(studentMathScores);
    }
}

If class syntax could be changed and studentMathScores can be static you can have it this way:

public class StudentDashboard {

static double[] studentMathScores ={81.5,89.0,45.5,99.0,55.0,34.5,56.0,78.0,76.0,80.0};

public StudentDashboard()
{
}

public static double[] getStudentMathScores() {
    return studentMathScores;
}

public class Main {

public static void main(String[] args) {
    StudentDashboard test = new StudentDashboard();
    double[] studentMathScores = StudentDashboard.getStudentMathScores();
}

}