问:
Confused behavior with async pipe (Angular)
I will try use async pipe for show/hide some waiting message.

app.component.html

```<code><ng-template #isWait>
    <h1>Please wait</h1>
</ng-template>

<div *ngIf="wait | async; else isWait">
    <hello name="{{ name }}"></hello>

    <p>
        Start editing to see some magic happen :)
    </p>

</div>

<button (click)="toggle()">Toggle</button>

<!-- Doesn't change -->
<div style="margin:1rem;">
    Doesn't change here
    <span style="color:red;">Value is {{wait | async}}</span>
  (AppComponent)
</div>
</code>```

app.component.ts

```<code>@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name: string = 'Angular 5';
  wait: Observable<boolean>;

  constructor(public waitService: WaitService) {
    this.wait = this.waitService.wait;
  }

  toggle() {
    this.waitService.toggle();
  }
}
</code>```

wait.service.ts

```<code>export class WaitService {
  wait: Observable<boolean>;
  private _wait: boolean = false;
  private _onChange: EventEmitter<boolean> = new EventEmitter();

  constructor() {
    this.wait = Observable.create((obs: any) => {
      obs.next(this._wait);
      this._onChange.subscribe((w: boolean) => {
        if (this._wait !== w) {
          this._wait = w;
          obs.next(this._wait);
        }
      });
    });
  }

  toggle() {
    this._onChange.emit(!this._wait);
  }
}
</code>```

I have WaitService with wait property and method toggle for switching wait.
When I try toggle wait, it works in one case, but doesn't work for each others (as I expected).

So, It confused me.
I will try figure out, why it happens.

Example: https://stackblitz.com/edit/angular-fwghfj

If you click on Toggle button nothing happen with wait message, but subscription in Wait2Component will be emitted and and will be write to console output each time when you clicked on toggle.

But after commented line with subscription, show and hide wait message will be work ok, but in other places wait still have no change.

Sure I can change wait to boolean and don't care about this situation with async, but this unexpected behavior for me.

答:
You can write WaitService like this instead:

import { Injectable } from "@angular/core";
import { BehaviorSubject } from "rxjs/BehaviorSubject";

@Injectable()
export class WaitService
{
    private readonly isWaiting = new BehaviorSubject(false);
    public readonly wait$ = this.isWaiting.asObservable();
    public toggle()
    {
        this.isWaiting.next(!this.isWaiting.value);
    }
}
```

Body:
I will try use async pipe for show/hide some waiting message.

app.component.html

<ng-template #isWait>

Please wait

</ng-template>

    <hello name="{{ name }}"></hello>

        Start editing to see some magic happen :)

<button (click)="toggle()">Toggle</button>

    Doesn't change here
    Value is {{wait | async}}
  (AppComponent)

app.component.ts

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name: string = 'Angular 5';
  wait: Observable<boolean>;

  constructor(public waitService: WaitService) {
    this.wait = this.waitService.wait;
  }

  toggle() {
    this.waitService.toggle();
  }
}

wait.service.ts

export class WaitService {
  wait: Observable<boolean>;
  private _wait: boolean = false;
  private _onChange: EventEmitter<boolean> = new EventEmitter();

  constructor() {
    this.wait = Observable.create((obs: any) => {
      obs.next(this._wait);
      this._onChange.subscribe((w: boolean) => {
        if (this._wait !== w) {
          this._wait = w;
          obs.next(this._wait);
        }
      });
    });
  }

  toggle() {
    this._onChange.emit(!this._wait);
  }
}

I have WaitService with wait property and method toggle for switching wait.
When I try toggle wait, it works in one case, but doesn't work for each others (as I expected).

So, It confused me.
I will try figure out, why it happens.

Example: https://stackblitz.com/edit/angular-fwghfj

If you click on Toggle button nothing happen with wait message, but subscription in Wait2Component will be emitted and and will be write to console output each time when you clicked on toggle.

But after commented line with subscription, show and hide wait message will be work ok, but in other places wait still have no change.

Sure I can change wait to boolean and don't care about this situation with async, but this unexpected behavior for me.


来源: stackexchange

问:
Filter has an unconnected output
I am using FFMPEG to merch 2 videos together with a fade effect in between. The console output shows the following error:

```<code>Filter setpts has an unconnected output
</code>```

I have looked up what could be wrong, but can't find anything related to my error that helps me out.

```<code>ffmpeg -i ./temp/1900f421192fcdaf.ts -i ./temp/35c16f3debf9e730.ts -an \
    -filter_complex \
    [0:v]trim=start=0:end=9,setpts=PTS-STARTPTS[firstclip];\
    [1:v]trim=start=1,setpts=PTS-STARTPTS[secondclip];\
    [0:v]trim=start=9:end=10,setpts=PTS-STARTPTS[fadeoutsrc];\
    [1:v]trim=start=0:end=1,setpts=PTS-STARTPTS[fadeinsrc];\
    [fadeinsrc]format=pix_fmts=yuva420p,fade=t=in:st=0:d=1:alpha=1[fadein];\
    [fadeoutsrc]format=pix_fmts=yuva420p,fade=t=out:st=0:d=1:alpha=1[fadeout];\
    [fadein]fifo[fadeinfifo];\
    [fadeout]fifo[fadeoutfifo];\
    [fadeoutfifo][fadeinfifo]overlay[crossfade];\
    [firstclip][crossfade][secondclip]concat=n=3[output]\
-map ./rendered/2017-11-16_11:59:41.mp4
</code>```

Thank you in advance for helping me out.

Edit//
Console output:

```<code>[root@webcasting2 videocuttool]# ffmpeg -i ./temp/1900f421192fcdaf.ts -i ./temp/35c16f3debf9e730.ts -an \
>     -filter_complex \
>     [0:v]trim=start=0:end=9,setpts=PTS-STARTPTS[firstclip];\
>     [1:v]trim=start=1,setpts=PTS-STARTPTS[secondclip];\
>     [0:v]trim=start=9:end=10,setpts=PTS-STARTPTS[fadeoutsrc];\
>     [1:v]trim=start=0:end=1,setpts=PTS-STARTPTS[fadeinsrc];\
>     [fadeinsrc]format=pix_fmts=yuva420p,fade=t=in:st=0:d=1:alpha=1[fadein];\
>     [fadeoutsrc]format=pix_fmts=yuva420p,fade=t=out:st=0:d=1:alpha=1[fadeout];\
>     [fadein]fifo[fadeinfifo];\
>     [fadeout]fifo[fadeoutfifo];\
>     [fadeoutfifo][fadeinfifo]overlay[crossfade];\
>     [firstclip][crossfade][secondclip]concat=n=3[output]\
> -map ./rendered/2017-11-16_11:59:41.mp4
ffmpeg version 3.4-static http://johnvansickle.com/ffmpeg/  Copyright (c) 2000-2017 the FFmpeg developers
  built with gcc 6.4.0 (Debian 6.4.0-7) 20170920
  configuration: --enable-gpl --enable-version3 --enable-static --disable-debug --disable-ffplay --disable-indev=sndio --disable-outdev=sndio --cc=gcc-6 --enable-fontconfig --enable-frei0r --enable-gnutls --enable-gray --enable-libfribidi --enable-libass --enable-libvmaf --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librubberband --enable-librtmp --enable-libsoxr --enable-libspeex --enable-libvorbis --enable-libopus --enable-libtheora --enable-libvidstab --enable-libvo-amrwbenc --enable-libvpx --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxvid --enable-libzimg
  libavutil      55. 78.100 / 55. 78.100
  libavcodec     57.107.100 / 57.107.100
  libavformat    57. 83.100 / 57. 83.100
  libavdevice    57. 10.100 / 57. 10.100
  libavfilter     6.107.100 /  6.107.100
  libswscale      4.  8.100 /  4.  8.100
  libswresample   2.  9.100 /  2.  9.100
  libpostproc    54.  7.100 / 54.  7.100
Trailing options were found on the commandline.
Input #0, mpegts, from './temp/1900f421192fcdaf.ts':
  Duration: 00:00:10.02, start: 1.419856, bitrate: 3291 kb/s
  Program 1
    Metadata:
      service_name    : Service01
      service_provider: FFmpeg
    Stream #0:0[0x100]: Video: mpeg2video (Main) ([2][0][0][0] / 0x0002), yuv420p(tv, progressive), 640x360 [SAR 1:1 DAR 16:9], 24 fps, 24 tbr, 90k tbn, 48 tbc
    Stream #0:1[0x101](eng): Audio: mp2 ([4][0][0][0] / 0x0004), 22050 Hz, stereo, s16p, 160 kb/s
Input #1, mpegts, from './temp/35c16f3debf9e730.ts':
  Duration: 00:00:10.02, start: 1.419856, bitrate: 3291 kb/s
  Program 1
    Metadata:
      service_name    : Service01
      service_provider: FFmpeg
    Stream #1:0[0x100]: Video: mpeg2video (Main) ([2][0][0][0] / 0x0002), yuv420p(tv, progressive), 640x360 [SAR 1:1 DAR 16:9], 24 fps, 24 tbr, 90k tbn, 48 tbc
    Stream #1:1[0x101](eng): Audio: mp2 ([4][0][0][0] / 0x0004), 22050 Hz, stereo, s16p, 160 kb/s
Filter setpts has an unconnected output
-bash: [1:v]trim=start=1,setpts=PTS-STARTPTS[secondclip]: opdracht niet gevonden
-bash: [0:v]trim=start=9:end=10,setpts=PTS-STARTPTS[fadeoutsrc]: opdracht niet gevonden
-bash: [1:v]trim=start=0:end=1,setpts=PTS-STARTPTS[fadeinsrc]: opdracht niet gevonden
-bash: [fadeinsrc]format=pix_fmts=yuva420p,fade=t=in:st=0:d=1:alpha=1[fadein]: opdracht niet gevonden
-bash: [fadeoutsrc]format=pix_fmts=yuva420p,fade=t=out:st=0:d=1:alpha=1[fadeout]: opdracht niet gevonden
-bash: [fadein]fifo[fadeinfifo]: opdracht niet gevonden
-bash: [fadeout]fifo[fadeoutfifo]: opdracht niet gevonden
-bash: [fadeoutfifo][fadeinfifo]overlay[crossfade]: opdracht niet gevonden
-bash: [firstclip][crossfade][secondclip]concat=n=3[output]-map: opdracht niet gevonden
</code>```

答:
This error has nothing to do with setpts, but with the syntax of the parameters for complex_filter, they should be enclosed in quotes.

Changed:

Enclosed filter_complex parameters in quotes

Removed -map parameter

Removed [output]

Added whitespace before every line-break

Editted command:

Remove -report parameter if not debugging.

```<code>ffmpeg -report -i "./video/big_buck_bunny.mp4" -i "./video/big_buck_bunny.mp4" -an \
    -filter_complex \
    "[0:v]trim=start=0:end=9,setpts=PTS-STARTPTS[firstclip]; \
    [1:v]trim=start=1,setpts=PTS-STARTPTS[secondclip]; \
    [0:v]trim=start=9:end=10,setpts=PTS-STARTPTS[fadeoutsrc]; \
    [1:v]trim=start=0:end=1,setpts=PTS-STARTPTS[fadeinsrc]; \
    [fadeinsrc]format=pix_fmts=yuva420p,fade=t=in:st=0:d=1:alpha=1[fadein]; \
    [fadeoutsrc]format=pix_fmts=yuva420p,fade=t=out:st=0:d=1:alpha=1[fadeout]; \
    [fadein]fifo[fadeinfifo]; \
    [fadeout]fifo[fadeoutfifo]; \
    [fadeoutfifo][fadeinfifo]overlay[crossfade]; \
    [firstclip][crossfade][secondclip]concat=n=3" \
./rendered/outputname.mp4
</code>```

ContentLicense: CC BY-SA 3.0

Title: Filter has an unconnected output

Body:
I am using FFMPEG to merch 2 videos together with a fade effect in between. The console output shows the following error:

Filter setpts has an unconnected output

I have looked up what could be wrong, but can't find anything related to my error that helps me out.

ffmpeg -i ./temp/1900f421192fcdaf.ts -i ./temp/35c16f3debf9e730.ts -an \
    -filter_complex \
    [0:v]trim=start=0:end=9,setpts=PTS-STARTPTS[firstclip];\
    [1:v]trim=start=1,setpts=PTS-STARTPTS[secondclip];\
    [0:v]trim=start=9:end=10,setpts=PTS-STARTPTS[fadeoutsrc];\
    [1:v]trim=start=0:end=1,setpts=PTS-STARTPTS[fadeinsrc];\
    [fadeinsrc]format=pix_fmts=yuva420p,fade=t=in:st=0:d=1:alpha=1[fadein];\
    [fadeoutsrc]format=pix_fmts=yuva420p,fade=t=out:st=0:d=1:alpha=1[fadeout];\
    [fadein]fifo[fadeinfifo];\
    [fadeout]fifo[fadeoutfifo];\
    [fadeoutfifo][fadeinfifo]overlay[crossfade];\
    [firstclip][crossfade][secondclip]concat=n=3[output]\
-map ./rendered/2017-11-16_11:59:41.mp4

Thank you in advance for helping me out.

Edit//
Console output:

[root@webcasting2 videocuttool]# ffmpeg -i ./temp/1900f421192fcdaf.ts -i ./temp/35c16f3debf9e730.ts -an \
>     -filter_complex \
>     [0:v]trim=start=0:end=9,setpts=PTS-STARTPTS[firstclip];\
>     [1:v]trim=start=1,setpts=PTS-STARTPTS[secondclip];\
>     [0:v]trim=start=9:end=10,setpts=PTS-STARTPTS[fadeoutsrc];\
>     [1:v]trim=start=0:end=1,setpts=PTS-STARTPTS[fadeinsrc];\
>     [fadeinsrc]format=pix_fmts=yuva420p,fade=t=in:st=0:d=1:alpha=1[fadein];\
>     [fadeoutsrc]format=pix_fmts=yuva420p,fade=t=out:st=0:d=1:alpha=1[fadeout];\
>     [fadein]fifo[fadeinfifo];\
>     [fadeout]fifo[fadeoutfifo];\
>     [fadeoutfifo][fadeinfifo]overlay[crossfade];\
>     [firstclip][crossfade][secondclip]concat=n=3[output]\
> -map ./rendered/2017-11-16_11:59:41.mp4
ffmpeg version 3.4-static http://johnvansickle.com/ffmpeg/  Copyright (c) 2000-2017 the FFmpeg developers
  built with gcc 6.4.0 (Debian 6.4.0-7) 20170920
  configuration: --enable-gpl --enable-version3 --enable-static --disable-debug --disable-ffplay --disable-indev=sndio --disable-outdev=sndio --cc=gcc-6 --enable-fontconfig --enable-frei0r --enable-gnutls --enable-gray --enable-libfribidi --enable-libass --enable-libvmaf --enable-libfreetype --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librubberband --enable-librtmp --enable-libsoxr --enable-libspeex --enable-libvorbis --enable-libopus --enable-libtheora --enable-libvidstab --enable-libvo-amrwbenc --enable-libvpx --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxvid --enable-libzimg
  libavutil      55. 78.100 / 55. 78.100
  libavcodec     57.107.100 / 57.107.100
  libavformat    57. 83.100 / 57. 83.100
  libavdevice    57. 10.100 / 57. 10.100
  libavfilter     6.107.100 /  6.107.100
  libswscale      4.  8.100 /  4.  8.100
  libswresample   2.  9.100 /  2.  9.100
  libpostproc    54.  7.100 / 54.  7.100
Trailing options were found on the commandline.
Input #0, mpegts, from './temp/1900f421192fcdaf.ts':
  Duration: 00:00:10.02, start: 1.419856, bitrate: 3291 kb/s
  Program 1
    Metadata:
      service_name    : Service01
      service_provider: FFmpeg
    Stream #0:0[0x100]: Video: mpeg2video (Main) ([2][0][0][0] / 0x0002), yuv420p(tv, progressive), 640x360 [SAR 1:1 DAR 16:9], 24 fps, 24 tbr, 90k tbn, 48 tbc
    Stream #0:1[0x101](eng): Audio: mp2 ([4][0][0][0] / 0x0004), 22050 Hz, stereo, s16p, 160 kb/s
Input #1, mpegts, from './temp/35c16f3debf9e730.ts':
  Duration: 00:00:10.02, start: 1.419856, bitrate: 3291 kb/s
  Program 1
    Metadata:
      service_name    : Service01
      service_provider: FFmpeg
    Stream #1:0[0x100]: Video: mpeg2video (Main) ([2][0][0][0] / 0x0002), yuv420p(tv, progressive), 640x360 [SAR 1:1 DAR 16:9], 24 fps, 24 tbr, 90k tbn, 48 tbc
    Stream #1:1[0x101](eng): Audio: mp2 ([4][0][0][0] / 0x0004), 22050 Hz, stereo, s16p, 160 kb/s
Filter setpts has an unconnected output
-bash: [1:v]trim=start=1,setpts=PTS-STARTPTS[secondclip]: opdracht niet gevonden
-bash: [0:v]trim=start=9:end=10,setpts=PTS-STARTPTS[fadeoutsrc]: opdracht niet gevonden
-bash: [1:v]trim=start=0:end=1,setpts=PTS-STARTPTS[fadeinsrc]: opdracht niet gevonden
-bash: [fadeinsrc]format=pix_fmts=yuva420p,fade=t=in:st=0:d=1:alpha=1[fadein]: opdracht niet gevonden
-bash: [fadeoutsrc]format=pix_fmts=yuva420p,fade=t=out:st=0:d=1:alpha=1[fadeout]: opdracht niet gevonden
-bash: [fadein]fifo[fadeinfifo]: opdracht niet gevonden
-bash: [fadeout]fifo[fadeoutfifo]: opdracht niet gevonden
-bash: [fadeoutfifo][fadeinfifo]overlay[crossfade]: opdracht niet gevonden
-bash: [firstclip][crossfade][secondclip]concat=n=3[output]-map: opdracht niet gevonden

Body:
This error has nothing to do with setpts, but with the syntax of the parameters for complex_filter, they should be enclosed in quotes.

Changed:

Enclosed filter_complex parameters in quotes

Removed -map parameter

Removed [output]

Added whitespace before every line-break

Editted command:

Remove -report parameter if not debugging.

ffmpeg -report -i "./video/big_buck_bunny.mp4" -i "./video/big_buck_bunny.mp4" -an \
    -filter_complex \
    "[0:v]trim=start=0:end=9,setpts=PTS-STARTPTS[firstclip]; \
    [1:v]trim=start=1,setpts=PTS-STARTPTS[secondclip]; \
    [0:v]trim=start=9:end=10,setpts=PTS-STARTPTS[fadeoutsrc]; \
    [1:v]trim=start=0:end=1,setpts=PTS-STARTPTS[fadeinsrc]; \
    [fadeinsrc]format=pix_fmts=yuva420p,fade=t=in:st=0:d=1:alpha=1[fadein]; \
    [fadeoutsrc]format=pix_fmts=yuva420p,fade=t=out:st=0:d=1:alpha=1[fadeout]; \
    [fadein]fifo[fadeinfifo]; \
    [fadeout]fifo[fadeoutfifo]; \
    [fadeoutfifo][fadeinfifo]overlay[crossfade]; \
    [firstclip][crossfade][secondclip]concat=n=3" \
./rendered/outputname.mp4


问:
Actionscript - Obtain the name of the current function
I want to get the name of a function from inside that function. e.g.:

```<code>function blah() {
    //I want to get the string "blah" here, from the function's name
}
</code>```

Or at least the Function object?

答: when i needed IDs for functions for my event system implementation i didn't find a way to access a name of a non-anonymous function passed as an argument so i had to write a wrapper that stored nothing except the Function and its ID

ContentLicense: CC BY-SA 2.5

Body:
I want to get the name of a function from inside that function. e.g.:

function blah() {
    //I want to get the string "blah" here, from the function's name
}

Or at least the Function object?


问:
Where can I find the source code of some empty Ansible core modules?
I can't figure out how to find the source code of some Ansbile core modules.

For example, modules fetch, template, debug or fail don't have any code in their respective Python file. Only the documentation and some meta-data are there.

I guess these modules are implemented in the core engine, but I can't find the code.

答:
These modules are implemented as action plugins, you can find all of them here:

https://github.com/ansible/ansible/tree/devel/lib/ansible/plugins/action

The difference to other modules is that they are first (or solely) executed on the controller machine.


问:
reading input from a text file and using it in a function in C
How would I use input from a text file so that I could use it in a function, without saving the characters into an array? As I read from the text file a 1 will come up and I will go to "setParameters", where I would enter the rest of the parameters. Also in that function, I will use malloc.(if it does not make sense let me know so that I can clarify it, also I am new to C)</p>

```<code>int val;
int choice;
 FILE *fpointer;
fpointer = fopen("afile.txt","r");
printf("\nError Detection/Correction");
printf("------------------------------\n");

choice = fscanf(fpointer,"%d",&val);
while(choice != 3)
{
    printf("1. Enter Parameters\n2. Enter Hamming Code\n3. Quit\n");
    switch(choice)
    {
        case 1: setParameters();
            break;

        case 2: checkError();
            break;

        case 3: printf("*** Program Terminated Normally");
            break;

        default:
            printf("Not a valid entry");
        break;

    }//end of switch statment
</code>```

答:
To take input from file in C (using fscanf):

You need to initialize FILE pointer using fopen and then scan each input using fopen.

```<code>FILE *fpointer;
fpointer = fopen("afile.txt","r");
int ret;
while(ret = fscanf(fpointer," %d ",&val))
{
     if(ret == EOF)
     {
          break;
     }
     else
     {
         // use val variable here in code which is taken as input from file
     }
}
</code>```

here, it is important to understand what ret variable is:

EOF, if the pointer is reached end of file.

0, if no input matched with the variable

>0, number of matched variables with the file input

To take input from file in C++ (using fstrean):

it is very easy to get input from a file. we just need to change cin to get input from file stream instead of standard input.

```<code>#include <fstream.h>

void main() {
    ifstream cin("afile.txt");
    int val;
    cin  >> val;

    // use val as variable in code.
}
</code>```

this approach is very easy but only works in C++. it requires no file operations like fscanf . just changing cin will do the work :)

Body:
How would I use input from a text file so that I could use it in a function, without saving the characters into an array? As I read from the text file a 1 will come up and I will go to "setParameters", where I would enter the rest of the parameters. Also in that function, I will use malloc.(if it does not make sense let me know so that I can clarify it, also I am new to C)

int val;
int choice;
 FILE *fpointer;
fpointer = fopen("afile.txt","r");
printf("\nError Detection/Correction");
printf("------------------------------\n");

choice = fscanf(fpointer,"%d",&val);
while(choice != 3)
{
    printf("1. Enter Parameters\n2. Enter Hamming Code\n3. Quit\n");
    switch(choice)
    {
        case 1: setParameters();
            break;

        case 2: checkError();
            break;

        case 3: printf("*** Program Terminated Normally");
            break;

        default:
            printf("Not a valid entry");
        break;

    }//end of switch statment

Body:
To take input from file in C (using fscanf):

You need to initialize FILE pointer using fopen and then scan each input using fopen.

FILE *fpointer;
fpointer = fopen("afile.txt","r");
int ret;
while(ret = fscanf(fpointer," %d ",&val))
{
     if(ret == EOF)
     {
          break;
     }
     else
     {
         // use val variable here in code which is taken as input from file
     }
}

here, it is important to understand what ret variable is:

EOF, if the pointer is reached end of file.

0, if no input matched with the variable

>0, number of matched variables with the file input

To take input from file in C++ (using fstrean):

it is very easy to get input from a file. we just need to change cin to get input from file stream instead of standard input.

#include <fstream.h>

void main() {
    ifstream cin("afile.txt");
    int val;
    cin  >> val;

    // use val as variable in code.
}

this approach is very easy but only works in C++. it requires no file operations like fscanf . just changing cin will do the work :)


问:
compare with previous number percentage algorithm flaw
I have 8 items in an array, I want to calculate the difference btw them. But my code has flaw, the output is wrong with different set of array.

What's wrong here?

```<code>const calculate_different_in_percentage = (num1, num2) => {

  //zero handling
  if (num2 === 0 && num1 > num2) {
    return 100
  }

  if (num1 === 0 && num1 < num2) {
    return 100
  }

  let result = 0
  if (num1 > num2) {
    result = ((num1 - num2) / num1) * 100
  } else if (num2 > num1) {
    result = ((num2 - num1) / num2) * 100
  } else {
    result = 0
  }

  if (!Number.isFinite(result)) result = 0

  return result.toFixed(1)
}
</code>```

https://jsfiddle.net/5ptfqgcw/2/

from 362 to 1916 the difference should be 529% but it didn't happens in my case, couldn't spot what's wrong.

答:
from 362 to 1916 the difference should be 529% but it didn't happens
  in my case, couldn't spot what's wrong.

You are calculating the percentage of difference between two elements in the order of appearance rather than just the percentage as you mentioned in your question.

To simply get the percentage use this simple code

```<code>const calculate_different_in_percentage = (num1, num2) =>    (num2 != 0 && num1 != 0) ? ((num2/num1)*100).toFixed(1) : 0;
</code>```

Explanation

If num1 and num2 are not same and both numbers are not 0, then return ((num2/num1)*100).toFixed(1)

Else, return 0

Demo

let arr = [{ "total_count": 40}, {  "total_count": 20},{"total_count": 0}, {"total_count": 100}, {"total_count": 362}, {"total_count": 1916}, {"total_count": 4046}, {"total_count": 2473}];

const calculate_different_in_percentage = (num1, num2) => (num2 != 0 && num1 != 0) ? ((num2 / num1) * 100).toFixed(1) : 0;

const result = [];

arr.forEach((obj, i) => {
  if (!i) return
  result.push({
    count: obj.total_count,
    difference: calculate_different_in_percentage(arr[i - 1].total_count, obj.total_count)
  })
})

console.log(result);```

Body:
I have 8 items in an array, I want to calculate the difference btw them. But my code has flaw, the output is wrong with different set of array.

What's wrong here?

const calculate_different_in_percentage = (num1, num2) => {

  //zero handling
  if (num2 === 0 && num1 > num2) {
    return 100
  }

  if (num1 === 0 && num1 < num2) {
    return 100
  }

  let result = 0
  if (num1 > num2) {
    result = ((num1 - num2) / num1) * 100
  } else if (num2 > num1) {
    result = ((num2 - num1) / num2) * 100
  } else {
    result = 0
  }

  if (!Number.isFinite(result)) result = 0

  return result.toFixed(1)
}

https://jsfiddle.net/5ptfqgcw/2/

from 362 to 1916 the difference should be 529% but it didn't happens in my case, couldn't spot what's wrong.

Body:
from 362 to 1916 the difference should be 529% but it didn't happens
  in my case, couldn't spot what's wrong.

You are calculating the percentage of difference between two elements in the order of appearance rather than just the percentage as you mentioned in your question.

To simply get the percentage use this simple code

const calculate_different_in_percentage = (num1, num2) =>    (num2 != 0 && num1 != 0) ? ((num2/num1)*100).toFixed(1) : 0;

Explanation

If num1 and num2 are not same and both numbers are not 0, then return ((num2/num1)*100).toFixed(1)

Else, return 0

Demo

let arr = [{ "total_count": 40}, {  "total_count": 20},{"total_count": 0}, {"total_count": 100}, {"total_count": 362}, {"total_count": 1916}, {"total_count": 4046}, {"total_count": 2473}];

const calculate_different_in_percentage = (num1, num2) => (num2 != 0 && num1 != 0) ? ((num2 / num1) * 100).toFixed(1) : 0;

const result = [];

arr.forEach((obj, i) => {
  if (!i) return
  result.push({
    count: obj.total_count,
    difference: calculate_different_in_percentage(arr[i - 1].total_count, obj.total_count)
  })
})

console.log(result);


问:
Swift 3 better way to write this if-statement
I am comparing values in a GKNoise field and then setting tiles into a tileMap based on the level of noise

This if-statement is comparing the values by rounding up to the nearest tenth, is there a better way to write it?

```<code>if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -1.0 {
    tileMap.setTileGroup(tileGroup4, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.9 {
    tileMap.setTileGroup(tileGroup4, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.8 {
    tileMap.setTileGroup(tileGroup4, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.7 {
    tileMap.setTileGroup(tileGroup4, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.6 {
    tileMap.setTileGroup(tileGroup4, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.5 {
    tileMap.setTileGroup(tileGroup3, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.4 {
    tileMap.setTileGroup(tileGroup3, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.3 {
    tileMap.setTileGroup(tileGroup3, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.2 {
    tileMap.setTileGroup(tileGroup3, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.1 {
    tileMap.setTileGroup(tileGroup3, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.0 {
    tileMap.setTileGroup(tileGroup2, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.1 {
    tileMap.setTileGroup(tileGroup2, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.2 {
    tileMap.setTileGroup(tileGroup2, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.3 {
    tileMap.setTileGroup(tileGroup2, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.4 {
    tileMap.setTileGroup(tileGroup2, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.5 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.6 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.7 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.8 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.9 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 1.0 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}
</code>```

It seems a little drawn out and not very efficient.

答:
Your could use a switch and interval matching

```<code>switch round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) {
case -1.0...(-0.6):
    tileMap.setTileGroup(tileGroup4, forColumn: columns, row: rows)
case -0.5...(-0.1):
    tileMap.setTileGroup(tileGroup3, forColumn: columns, row: rows)
case 0.0...0.4:
    tileMap.setTileGroup(tileGroup2, forColumn: columns, row: rows)
case 0.5...1.0:
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
default:
    break
}
</code>```

Body:
I am comparing values in a GKNoise field and then setting tiles into a tileMap based on the level of noise

This if-statement is comparing the values by rounding up to the nearest tenth, is there a better way to write it?

if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -1.0 {
    tileMap.setTileGroup(tileGroup4, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.9 {
    tileMap.setTileGroup(tileGroup4, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.8 {
    tileMap.setTileGroup(tileGroup4, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.7 {
    tileMap.setTileGroup(tileGroup4, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.6 {
    tileMap.setTileGroup(tileGroup4, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.5 {
    tileMap.setTileGroup(tileGroup3, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.4 {
    tileMap.setTileGroup(tileGroup3, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.3 {
    tileMap.setTileGroup(tileGroup3, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.2 {
    tileMap.setTileGroup(tileGroup3, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.1 {
    tileMap.setTileGroup(tileGroup3, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.0 {
    tileMap.setTileGroup(tileGroup2, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.1 {
    tileMap.setTileGroup(tileGroup2, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.2 {
    tileMap.setTileGroup(tileGroup2, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.3 {
    tileMap.setTileGroup(tileGroup2, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.4 {
    tileMap.setTileGroup(tileGroup2, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.5 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.6 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.7 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.8 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.9 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 1.0 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}

It seems a little drawn out and not very efficient.

Body:
Your could use a switch and interval matching

switch round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) {
case -1.0...(-0.6):
    tileMap.setTileGroup(tileGroup4, forColumn: columns, row: rows)
case -0.5...(-0.1):
    tileMap.setTileGroup(tileGroup3, forColumn: columns, row: rows)
case 0.0...0.4:
    tileMap.setTileGroup(tileGroup2, forColumn: columns, row: rows)
case 0.5...1.0:
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
default:
    break
}


问:
Java Version Maven Issue
I have a Java Project.
My System's Java version is 1.8
My Maven Version is pointed to 1.8 Java version

Now i intentionally added a nio package in my project. I ran the maven clean install before changing the pom.xml. Added below snippet

```<code><properties>
    <maven.compiler.target>1.5</maven.compiler.target>
    <maven.compiler.source>1.5</maven.compiler.source>
</properties
</code>```

I expected the program to fail. But it was successful. Can anyone tell the reason why. i have also tried the snippet under plugin tag under build but to no avail. Please help

答:
Java nio package exists in previous versions (like 1.5). Did you import one of the existins classes at that time? Perhaps you meant NIO.2?

More info here

Title: Java Version Maven Issue

Body:
I have a Java Project.
My System's Java version is 1.8
My Maven Version is pointed to 1.8 Java version

Now i intentionally added a nio package in my project. I ran the maven clean install before changing the pom.xml. Added below snippet

<properties>
    <maven.compiler.target>1.5</maven.compiler.target>
    <maven.compiler.source>1.5</maven.compiler.source>
</properties

I expected the program to fail. But it was successful. Can anyone tell the reason why. i have also tried the snippet under plugin tag under build but to no avail. Please help


问:
PL/SQL exception handling in function
I am trying to generate DIVIDE_BY_ZERO exception in my oracle PL/SQL program. I using function but when I run my program I am getting error which is shown below. Can anyone tell me what is wrong in my program ?

code:

```<code> CREATE OR REPLACE
PACKAGE CALCULATOR AS

  FUNCTION AddNumber(addend IN Number, Addend2 IN Number) RETURN NUMBER;
  FUNCTION DivNumber(divend IN Number, divend2 IN Number) RETURN NUMBER;

END CALCULATOR;
/

CREATE OR REPLACE
PACKAGE BODY CALCULATOR AS

  FUNCTION AddNumber(addend IN Number, Addend2 IN Number) RETURN NUMBER AS
  BEGIN
     return addend + addend2;

  END AddNumber;

  FUNCTION DivNumber(divend IN Number, divend2 IN Number) RETURN NUMBER AS
  BEGIN
         return divend / divend2;
         EXCEPTION
         WHEN ZERO_DIVIDE THEN
         NULL;
  END DivNumber;

END CALCULATOR;
/

select calculator.AddNumber(3,4) from dual;
select calculator.DivNumber(12,0) from dual;
</code>```

output:

答:
you can deal with exceptions like this</p>

```<code>FUNCTION DivNumber(divend IN Number, divend2 IN Number) RETURN NUMBER AS
 e_ZERO_DIVIDE EXCEPTION;
 BEGIN
-- the condition
  IF divend2 = 0 THEN
    Raise e_ZERO_DIVIDE;
   END IF;
 return divend / divend2;
--Exception handling
EXCEPTION
WHEN e_ZERO_DIVIDE THEN
   dbms_output.put_line('Division by 0 or null');
   RETURN 1; -- or 0 or null
 WHEN OTHERS THEN
  dbms_output.put_line('ERROR: '||sqlerrm);
  RETURN 1; -- or 0 or null
 END DivNumber;
</code>```

Title: PL/SQL exception handling in function

Body:
I am trying to generate DIVIDE_BY_ZERO exception in my oracle PL/SQL program. I using function but when I run my program I am getting error which is shown below. Can anyone tell me what is wrong in my program ?

code:

 CREATE OR REPLACE
PACKAGE CALCULATOR AS

  FUNCTION AddNumber(addend IN Number, Addend2 IN Number) RETURN NUMBER;
  FUNCTION DivNumber(divend IN Number, divend2 IN Number) RETURN NUMBER;

END CALCULATOR;
/

CREATE OR REPLACE
PACKAGE BODY CALCULATOR AS

  FUNCTION AddNumber(addend IN Number, Addend2 IN Number) RETURN NUMBER AS
  BEGIN
     return addend + addend2;

  END AddNumber;

  FUNCTION DivNumber(divend IN Number, divend2 IN Number) RETURN NUMBER AS
  BEGIN
         return divend / divend2;
         EXCEPTION
         WHEN ZERO_DIVIDE THEN
         NULL;
  END DivNumber;

END CALCULATOR;
/

select calculator.AddNumber(3,4) from dual;
select calculator.DivNumber(12,0) from dual;

output:

Body:
you can deal with exceptions like this

FUNCTION DivNumber(divend IN Number, divend2 IN Number) RETURN NUMBER AS
 e_ZERO_DIVIDE EXCEPTION;
 BEGIN
-- the condition
  IF divend2 = 0 THEN
    Raise e_ZERO_DIVIDE;
   END IF;
 return divend / divend2;
--Exception handling
EXCEPTION
WHEN e_ZERO_DIVIDE THEN
   dbms_output.put_line('Division by 0 or null');
   RETURN 1; -- or 0 or null
 WHEN OTHERS THEN
  dbms_output.put_line('ERROR: '||sqlerrm);
  RETURN 1; -- or 0 or null
 END DivNumber;

ContentLicense: CC BY-SA 4.0


答:
The problem is that for each subscriber the callback for Observable.create is called and that's the place where you modify the state of this._wait. In other words, when you call toggle() the this._onChange.subscribe()'s next handle is called eg. five times or maybe even more. But only the first call notifies its observer because of this._wait !== w.

One simple way to avoid this is to share the same source Observable with the share() operator.

```<code>this.wait = Observable.create((obs: any) => {
  // ...
}).share();
</code>```

But even better solution would be not calling subscribe() inside Observable.create and just using an operator chain with do() to perform any side effects:

```<code>this.wait = this._onChange
  .filter((w: boolean) => w !== this._wait)
  .do((w: boolean) => this._wait = w)
  .share();
</code>```

This should produce the same results.

See you updated demo: https://stackblitz.com/edit/angular-nbgmz7?file=app%2Fservices%2Fwait.service.ts

Title: Confused behavior with async pipe (Angular)

Body:
The problem is that for each subscriber the callback for Observable.create is called and that's the place where you modify the state of this._wait. In other words, when you call toggle() the this._onChange.subscribe()'s next handle is called eg. five times or maybe even more. But only the first call notifies its observer because of this._wait !== w.

One simple way to avoid this is to share the same source Observable with the share() operator.

this.wait = Observable.create((obs: any) => {
  // ...
}).share();

But even better solution would be not calling subscribe() inside Observable.create and just using an operator chain with do() to perform any side effects:

this.wait = this._onChange
  .filter((w: boolean) => w !== this._wait)
  .do((w: boolean) => this._wait = w)
  .share();

This should produce the same results.

See you updated demo: https://stackblitz.com/edit/angular-nbgmz7?file=app%2Fservices%2Fwait.service.ts


问:
Passing csv file as command like argument in nodeJs
I can't for the life of me think of a way to do this. I've previously worked with importing csv files into js files, but for this challenge I've got to create a js file that executable from a shell with the data file passed as input.

Any ideas how can this be done?

~The challenge description~

The program must be executable from a shell and take the CSV file as input. For example:

```<code>node score_calculator.js data.csv
</code>```

答:
Sounds like you are trying to figure out how to pass and read parameters

You could do node score_calculator.js data.csv

then in your js

```<code>const csv = process.argv[2];
</code>```

However. If you are passing in parameters I would recommend using minimist then you can do

```<code>node score_calculator.js --file=data.csv
</code>```

And you js file would be

```<code>const argv = require('minimist')(process.argv.slice(2));
const csv = argv.file;
</code>```

Body:
I can't for the life of me think of a way to do this. I've previously worked with importing csv files into js files, but for this challenge I've got to create a js file that executable from a shell with the data file passed as input.

Any ideas how can this be done?

~The challenge description~

The program must be executable from a shell and take the CSV file as input. For example:

node score_calculator.js data.csv

Body:
Sounds like you are trying to figure out how to pass and read parameters

You could do node score_calculator.js data.csv

then in your js

const csv = process.argv[2];

However. If you are passing in parameters I would recommend using minimist then you can do

node score_calculator.js --file=data.csv

And you js file would be

const argv = require('minimist')(process.argv.slice(2));
const csv = argv.file;


问:
Loop with RxSwift
I'm new to Reactive Programming and I have a big problem that I can't solve alone... I need to upload several video assets and in a orderly sequence but I do not know how to do it, I have an array of PHAssets and I'm trying to iterate thru each element and send it over the network
Here is my code so far with comments:</p>

```<code>for item in items {
                    let fileName = item.media.localIdentifier

                    //Observable to generate local url to be used to save the compressed video
                    let compressedVideoOutputUrl = videoHelper.getDocumentsURL().appendingPathComponent(fileName)

                    //Observable to generate a thumbnail image for the video
                    let thumbnailObservable =  videoHelper.getBase64Thumbnail(myItem: item)

                    //Observable to request the video from the iPhone library
                    let videoObservable = videoHelper.requestVideo(myItem: item)

                        //Compress the video and save it on the previously generated local url
                        .flatMap { videoHelper.compressVideo(inputURL: $0, outputURL: compressedVideoOutputUrl) }
                    //Generate the thumbnail and share the video to send over the network
                    let send = videoObservable.flatMap { _ in thumbnailObservable }
                        .flatMap { api.uploadSharedFiles(item, filename: fileName, base64String: $0) }

                    //subscribe the observable
                    send.subscribe(onNext: { data in
                        print("- Done chain sharing Video -")
                    },
                                   onError: { error in
                                    print("Error sharing Video-> \(error.localizedDescription)")
                    }).disposed(by: actionDisposeBag)

                }
</code>```

答:
Make observable from collection elements and .flatMap() them to your existing code -

Observable
  .from(items)
  .flatMap { (item) -> Any in
    // your code
      return send
  }
  .subscribe( /* your code */ )
  .disposed(by: actionDisposeBag)
```

Title: Loop with RxSwift

Body:
I'm new to Reactive Programming and I have a big problem that I can't solve alone... I need to upload several video assets and in a orderly sequence but I do not know how to do it, I have an array of PHAssets and I'm trying to iterate thru each element and send it over the network
Here is my code so far with comments:

for item in items {
                    let fileName = item.media.localIdentifier

                    //Observable to generate local url to be used to save the compressed video
                    let compressedVideoOutputUrl = videoHelper.getDocumentsURL().appendingPathComponent(fileName)

                    //Observable to generate a thumbnail image for the video
                    let thumbnailObservable =  videoHelper.getBase64Thumbnail(myItem: item)

                    //Observable to request the video from the iPhone library
                    let videoObservable = videoHelper.requestVideo(myItem: item)

                        //Compress the video and save it on the previously generated local url
                        .flatMap { videoHelper.compressVideo(inputURL: $0, outputURL: compressedVideoOutputUrl) }
                    //Generate the thumbnail and share the video to send over the network
                    let send = videoObservable.flatMap { _ in thumbnailObservable }
                        .flatMap { api.uploadSharedFiles(item, filename: fileName, base64String: $0) }

                    //subscribe the observable
                    send.subscribe(onNext: { data in
                        print("- Done chain sharing Video -")
                    },
                                   onError: { error in
                                    print("Error sharing Video-> \(error.localizedDescription)")
                    }).disposed(by: actionDisposeBag)

                }


问:
Simple query with arangodb and nodejs
I want to execute a simple query in my database arangodb with nodejs for a login page.

```<code>var arango = require('arangojs');
/*---*/
Database = arango.Database;
db = new Database('http://127.0.0.1:8529');
db.useDatabase('MyDB');
db.useBasicAuth('root', 'root');
/*---*/

//Post Methods
var username;
var passworddb;

//Login method
app.post('/', function (request, response) {

    username = request.body.user.name;

    db.query('FOR u IN User FILTER u.firstname == "'+username+'" RETURN u.password').then(
      cursor => cursor.all()
    ).then(
      key => console.log('key:', key),
      //key => passworddb = key,
      err => console.error('Failed to execute query')
    );

    console.log(passworddb)
});
</code>```

It's working, but i can't save in my var passworddb the result of the key...
I don't undertand...
the request is asynchronous in arangodb

Console.write(passworddb) return "undefined"
and after console.log('key:', key) return correctly the key... Twice.

My question is : how can i get only the password in arangodb (What is the query for once request) and how to store the value in my var ?

Thank you for your answers.

答:
The line console.log(passworddb) gets executed before //key => passworddb = key happens because of the asynchronous request. So by the time you try to log the password, the db response has not arrived yet. The password gets saved correctly in passworddb, you just console.log too soon. You could do

```<code>key => {
  passworddb = key;
  console.log(passworddb);
}
</code>```

to confirm that the assignment works.

Title: Simple query with arangodb and nodejs

Body:
I want to execute a simple query in my database arangodb with nodejs for a login page.

var arango = require('arangojs');
/*---*/
Database = arango.Database;
db = new Database('http://127.0.0.1:8529');
db.useDatabase('MyDB');
db.useBasicAuth('root', 'root');
/*---*/

//Post Methods
var username;
var passworddb;

//Login method
app.post('/', function (request, response) {

    username = request.body.user.name;

    db.query('FOR u IN User FILTER u.firstname == "'+username+'" RETURN u.password').then(
      cursor => cursor.all()
    ).then(
      key => console.log('key:', key),
      //key => passworddb = key,
      err => console.error('Failed to execute query')
    );

    console.log(passworddb)
});

It's working, but i can't save in my var passworddb the result of the key...
I don't undertand...
the request is asynchronous in arangodb

Console.write(passworddb) return "undefined"
and after console.log('key:', key) return correctly the key... Twice.

My question is : how can i get only the password in arangodb (What is the query for once request) and how to store the value in my var ?

Thank you for your answers.

Body:
The line console.log(passworddb) gets executed before //key => passworddb = key happens because of the asynchronous request. So by the time you try to log the password, the db response has not arrived yet. The password gets saved correctly in passworddb, you just console.log too soon. You could do

key => {
  passworddb = key;
  console.log(passworddb);
}

to confirm that the assignment works.


问:
Conditional ftplugin settings in vim
I am trying to achieve different ts, sts, sw and (no)et settings depending on project.

My idea was to have an alias, kvim f.ex., looking like alias kvim="vim -u ~/.kvimrc" with ~/.kvimrc containing only:

```<code>let g:IsKernelCode="yes"
source ~/.vimrc
</code>```

And then in my ~/.vim/ftplugin/c/c.vim I could have sections like:

```<code>if exists("g:IsKernelCode")
     "kernel-code-settings
...
</code>```

This seams to work when I open a single file. But kvim -p a_bunch_of_files*.c will result in only the first file having my kernel-code-settings.

What am I missing?

答:
You should have a look at the following Q/A which enumerates most solutions: Vim: apply settings on files in directory

Since then, for simple settings like the ones you're interested in, you also have editor-config solutions.

Regarding your approach: having a bash alias that runs vim with a global variable set, and testing this variable from your ftplugin: this won't scale.

Every time you'll want to work with a project having different stylistic settings, you'll need to edit your ftplugins.

Also, you won't be able to edit files from different projects with the correct stylistic settings applied to each individual buffer.

Title: Conditional ftplugin settings in vim

Body:
I am trying to achieve different ts, sts, sw and (no)et settings depending on project.

My idea was to have an alias, kvim f.ex., looking like alias kvim="vim -u ~/.kvimrc" with ~/.kvimrc containing only:

let g:IsKernelCode="yes"
source ~/.vimrc

And then in my ~/.vim/ftplugin/c/c.vim I could have sections like:

if exists("g:IsKernelCode")
     "kernel-code-settings
...

This seams to work when I open a single file. But kvim -p a_bunch_of_files*.c will result in only the first file having my kernel-code-settings.

What am I missing?


问:
how to zip files from a given directory in codeigniter
I created a files in the directory

application/files_to_download

in files to download folder there are two files which are created dynamicaly
a.pdf
b.pdf

now I want to zip this two files from files_to_download folder
note:only file not the directory

i tried

```<code>$files = array('a.pdf', 'b.pdf');
            $zipname = 'zip_app_t.zip';
            $zip = new ZipArchive;
            $zip->open($zipname, ZipArchive::CREATE);
            foreach ($files as $file) {
            $zip->addFile($file);
            }
            $zip->close();
    header('Content-type: application/zip');
    header('Content-Disposition: attachment; filename="'.$zipname.'"');
</code>```

答:
```<code>    $path = "Your path";
    $this->load->library('zip');
    $this->zip->read_dir($path,FALSE);
    ob_end_clean();
    $this->zip->download('filename.zip');
</code>```

Body:
I created a files in the directory

application/files_to_download

in files to download folder there are two files which are created dynamicaly
a.pdf
b.pdf

now I want to zip this two files from files_to_download folder
note:only file not the directory

i tried

$files = array('a.pdf', 'b.pdf');
            $zipname = 'zip_app_t.zip';
            $zip = new ZipArchive;
            $zip->open($zipname, ZipArchive::CREATE);
            foreach ($files as $file) {
            $zip->addFile($file);
            }
            $zip->close();
    header('Content-type: application/zip');
    header('Content-Disposition: attachment; filename="'.$zipname.'"');


问:
Why xmlrpc wordpress do not work in some live site but in some it is working.
I am trying to post to site 2 (demo.com) from site 1 (test.com) using code below.  it is not working. </p>

<p>But when i try to post from localhost to site 1(demo.com) with same code it works.
I do not know what is the problem. Please help me. Thank you </p>

```<code>   $client = new IXR_Client("http://demo.com/xmlrpc.php");
   $postcontent = array(
                'post_type' => 'post',
                'post_title' => 'wwww',
                'post_name' => 'wwww',
                'post_content' => 'wwww'

            );

   $res = $client -> query('wp.newPost',1, "username", "password", $postcontent);
   $postID =  $client->getResponse();
</code>```

答:
Most likely the wordpress server you are trying to post to has IP based whitelisting or blacklisting enabled.

.htaccess file on the server would have the rules for the same.

The server has to allow xmlrpc.php file for your client.

Body:
I am trying to post to site 2 (demo.com) from site 1 (test.com) using code below.  it is not working.

But when i try to post from localhost to site 1(demo.com) with same code it works.
I do not know what is the problem. Please help me. Thank you

   $client = new IXR_Client("http://demo.com/xmlrpc.php");
   $postcontent = array(
                'post_type' => 'post',
                'post_title' => 'wwww',
                'post_name' => 'wwww',
                'post_content' => 'wwww'

            );

   $res = $client -> query('wp.newPost',1, "username", "password", $postcontent);
   $postID =  $client->getResponse();


问:
MySQL BETWEEN query w/ BETWEEN ? AND?
Can anyone guide me to or provide how the dual question marks work in a BETWEEN comparison.. I can't get it to work and I can't locate or search these data on the MySQL site and Google - bunches of random results.</p>

答:
Guessing here.

You probably encountered a query like

```<code>SELECT `foo` FROM `bar` WHERE `datetime` BETWEEN ? AND ?
</code>```

The question marks are placeholders for the actual values to be queried. Usually, the values are properly escaped prior to being "inserted" in the query in order to prevent SQL injection.

Title: MySQL BETWEEN query w/ BETWEEN ? AND?

Body:
Guessing here.

You probably encountered a query like

SELECT `foo` FROM `bar` WHERE `datetime` BETWEEN ? AND ?

The question marks are placeholders for the actual values to be queried. Usually, the values are properly escaped prior to being "inserted" in the query in order to prevent SQL injection.


问:
CSS: html and body set to height: 100%, but divs don't resize height
I have

```<code>html, body { width: 100%; height: 100%; }
</code>```

When i put a div with

```<code>div { height: 20%; }
</code>```

it doesn't resize, it's height depends on its content.
I wish i can obtain a 20%.

Can you help me?

答:
Technically your code should work. Check the demo here:

html, body { width: 100%; height: 100%; }
div{width: 20%}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <!doctype html>
<html>
<body>
  <div class="test">
    <p>Lorem ipsum dolor sit amet, dicat oportere in duo, te sea movet nominati. Liber exerci partem ei sed, ius eu denique lucilius expetendis. Pro et consectetuer definitiones, vix id augue singulis quaerendum. Ut vis accusamus reformidans, nam te similique omittantur.

An tincidunt dissentiet per, case timeam vix ad, ad modus affert has. Eu fastidii temporibus accommodare sit, percipit vituperata ne duo. Iriure dissentias te vis, est labore possim meliore cu, doming timeam ne sit. Ei has dico modus definitiones, dolorum atomorum suscipiantur ad eam. Facer mollis prodesset ad vis, est pertinax necessitatibus te. Has id iusto argumentum, ut ullum omnium forensibus vel.

Oblique indoctum vis ut. Eam an elitr ignota. Dico maiorum eu sea. Mel illum eirmod nostrud ei, movet malorum nostrud vel ne. Volumus mediocritatem vis ex, ad nostrum appellantur sea, in paulo aliquando vel.

Ea mea dolor accusam intellegat, adhuc phaedrum ei vis. Nam ea atqui homero salutandi, eu laudem quaerendum per. Cu vim legere graeco, vis facer summo albucius ex, pro utinam vulputate in. Ei debitis offendit qui, debet viris copiosae ius ea.

Nam utinam voluptatibus ex, et perfecto repudiandae nec. Ea dolore ponderum partiendo sea, est an fugit ceteros, te vis suas voluptatibus. Falli iuvaret pro ex. Ius at volutpat posidonium contentiones.</p>
  </div>
</body>
<html></code>```

Body:
I have

html, body { width: 100%; height: 100%; }

When i put a div with

div { height: 20%; }

it doesn't resize, it's height depends on its content.
I wish i can obtain a 20%.

Can you help me?

Body:
Technically your code should work. Check the demo here:

html, body { width: 100%; height: 100%; }
div{width: 20%}

 <!doctype html>
<html>
<body>
  <div class="test">
    <p>Lorem ipsum dolor sit amet, dicat oportere in duo, te sea movet nominati. Liber exerci partem ei sed, ius eu denique lucilius expetendis. Pro et consectetuer definitiones, vix id augue singulis quaerendum. Ut vis accusamus reformidans, nam te similique omittantur.

An tincidunt dissentiet per, case timeam vix ad, ad modus affert has. Eu fastidii temporibus accommodare sit, percipit vituperata ne duo. Iriure dissentias te vis, est labore possim meliore cu, doming timeam ne sit. Ei has dico modus definitiones, dolorum atomorum suscipiantur ad eam. Facer mollis prodesset ad vis, est pertinax necessitatibus te. Has id iusto argumentum, ut ullum omnium forensibus vel.

Oblique indoctum vis ut. Eam an elitr ignota. Dico maiorum eu sea. Mel illum eirmod nostrud ei, movet malorum nostrud vel ne. Volumus mediocritatem vis ex, ad nostrum appellantur sea, in paulo aliquando vel.

Ea mea dolor accusam intellegat, adhuc phaedrum ei vis. Nam ea atqui homero salutandi, eu laudem quaerendum per. Cu vim legere graeco, vis facer summo albucius ex, pro utinam vulputate in. Ei debitis offendit qui, debet viris copiosae ius ea.

Nam utinam voluptatibus ex, et perfecto repudiandae nec. Ea dolore ponderum partiendo sea, est an fugit ceteros, te vis suas voluptatibus. Falli iuvaret pro ex. Ius at volutpat posidonium contentiones.</p>
  </div>
</body>
<html>


问:
How to insert 1 image in 2 different directories using codeigniter
I am trying to insert 1 image in 2 different directories but it is saving only in the first directory but not in the second directory.I am unable find the mistake in my code,please check the below code and help us.Thanks in advance.</p>

```<code>public function image()
{
    $data = array();
    $error = array();
    $config1=array(
        'upload_path'=>'upload/',
        'allowed_types'=>'jpg|jpeg|png|bmp',
        'max_size'=>0,
        'filename'=>url_title($this->input->post('file'))
    );

    $this->load->library('upload',$config1);
    if($this->upload->do_upload('file')){
        $error = array('error' => $this->upload->display_errors());
        echo "```";
        print_r($error);
        exit();
    }else {
        $fdata = $this->upload->data();
        $data['image'] = 'upload/' . $fdata['file_name'];
    }

    $config2=array(
        'upload_path'=>'upload/images/',
        'allowed_types'=>'jpg|jpeg|png|bmp',
        'max_size'=>0,
        'filename'=>url_title($this->input->post('file'))
    );
    $this->upload->initialize($config2);

    if (!$this->upload->do_upload('file')){
        $error = array('error' => $this->upload->display_errors());
        echo "```";
        print_r($error);
        exit();
    } else {
        $fdata = $this->upload->data();
        $data['file2'] = 'upload/images' . $fdata['file_name'];
    }

    $data['name'] = $this->input->post('dname', TRUE);
    $data['email'] = $this->input->post('demail', TRUE);
    $data['mobile'] = $this->input->post('dmobile', TRUE);
    $data['mobile'] = $this->input->post('daddress', TRUE);

    $result = $this->insert_model->insert($data);
    $sdata = array();
    $sdata['message'] = "Well done!</strong> You successfully add the
    Product Details.";
    $this->session->set_userdata($sdata);
    redirect('super_admin/add_product', 'refresh');
}
</code>```

答:
Try this</p>

```<code>public function image()
{
    $data = array();
    $error = array();
    $config1=array(
        'upload_path'=>'upload/',
        'allowed_types'=>'jpg|jpeg|png|bmp',
        'max_size'=>0,
        'filename'=>url_title($this->input->post('file'))
    );

    $this->load->library('upload',$config1,'file1'); // Create custom object for file 1 upload
    if($this->file1->do_upload('file')){
        $error = array('error' => $this->file1->display_errors());
        echo "```";
        print_r($error);
        exit();
    }else {
        $fdata = $this->file1->data();
        $data['image'] = 'upload/' . $fdata['file_name'];
    }

    $config2=array(
        'upload_path'=>'upload/images/',
        'allowed_types'=>'jpg|jpeg|png|bmp',
        'max_size'=>0,
        'filename'=>url_title($this->input->post('file'))
    );

    $this->load->library('upload', $config2, 'file2'); // Create custom object for file 2 upload
    $this->file2->initialize($config2);
    if (!$this->file2->do_upload('file')){
        $error = array('error' => $this->file2->display_errors());
        echo "```";
        print_r($error);
        exit();
    } else {
        $fdata = $this->file2->data();
        $data['file2'] = 'upload/images' . $fdata['file_name'];
    }

    $data['name'] = $this->input->post('dname', TRUE);
    $data['email'] = $this->input->post('demail', TRUE);
    $data['mobile'] = $this->input->post('dmobile', TRUE);
    $data['mobile'] = $this->input->post('daddress', TRUE);

    $result = $this->insert_model->insert($data);
    $sdata = array();
    $sdata['message'] = "Well done!</strong> You successfully add the
    Product Details.";
    $this->session->set_userdata($sdata);
    redirect('super_admin/add_product', 'refresh');
}
</code>```

Body:
I am trying to insert 1 image in 2 different directories but it is saving only in the first directory but not in the second directory.I am unable find the mistake in my code,please check the below code and help us.Thanks in advance.

public function image()
{
    $data = array();
    $error = array();
    $config1=array(
        'upload_path'=>'upload/',
        'allowed_types'=>'jpg|jpeg|png|bmp',
        'max_size'=>0,
        'filename'=>url_title($this->input->post('file'))
    );

    $this->load->library('upload',$config1);
    if($this->upload->do_upload('file')){
        $error = array('error' => $this->upload->display_errors());
        echo "
";
        print_r($error);
        exit();
    }else {
        $fdata = $this->upload->data();
        $data['image'] = 'upload/' . $fdata['file_name'];
    }

    $config2=array(
        'upload_path'=>'upload/images/',
        'allowed_types'=>'jpg|jpeg|png|bmp',
        'max_size'=>0,
        'filename'=>url_title($this->input->post('file'))
    );
    $this->upload->initialize($config2);

    if (!$this->upload->do_upload('file')){
        $error = array('error' => $this->upload->display_errors());
        echo "
";
        print_r($error);
        exit();
    } else {
        $fdata = $this->upload->data();
        $data['file2'] = 'upload/images' . $fdata['file_name'];
    }

    $data['name'] = $this->input->post('dname', TRUE);
    $data['email'] = $this->input->post('demail', TRUE);
    $data['mobile'] = $this->input->post('dmobile', TRUE);
    $data['mobile'] = $this->input->post('daddress', TRUE);

    $result = $this->insert_model->insert($data);
    $sdata = array();
    $sdata['message'] = "Well done! You successfully add the
    Product Details.";
    $this->session->set_userdata($sdata);
    redirect('super_admin/add_product', 'refresh');
}

Body:
Try this

public function image()
{
    $data = array();
    $error = array();
    $config1=array(
        'upload_path'=>'upload/',
        'allowed_types'=>'jpg|jpeg|png|bmp',
        'max_size'=>0,
        'filename'=>url_title($this->input->post('file'))
    );

    $this->load->library('upload',$config1,'file1'); // Create custom object for file 1 upload
    if($this->file1->do_upload('file')){
        $error = array('error' => $this->file1->display_errors());
        echo "<pre>";
        print_r($error);
        exit();
    }else {
        $fdata = $this->file1->data();
        $data['image'] = 'upload/' . $fdata['file_name'];
    }

    $config2=array(
        'upload_path'=>'upload/images/',
        'allowed_types'=>'jpg|jpeg|png|bmp',
        'max_size'=>0,
        'filename'=>url_title($this->input->post('file'))
    );

    $this->load->library('upload', $config2, 'file2'); // Create custom object for file 2 upload
    $this->file2->initialize($config2);
    if (!$this->file2->do_upload('file')){
        $error = array('error' => $this->file2->display_errors());
        echo "<pre>";
        print_r($error);
        exit();
    } else {
        $fdata = $this->file2->data();
        $data['file2'] = 'upload/images' . $fdata['file_name'];
    }

    $data['name'] = $this->input->post('dname', TRUE);
    $data['email'] = $this->input->post('demail', TRUE);
    $data['mobile'] = $this->input->post('dmobile', TRUE);
    $data['mobile'] = $this->input->post('daddress', TRUE);

    $result = $this->insert_model->insert($data);
    $sdata = array();
    $sdata['message'] = "Well done!</strong> You successfully add the
    Product Details.";
    $this->session->set_userdata($sdata);
    redirect('super_admin/add_product', 'refresh');
}


问:
What could be causing a System.TypeLoadException?
I'm developing, with VS2008 using C#, an application for Honeywell Dolphin 6100, a mobile computer with a barcode scanner that uses Windows CE 5.0 like OS.

I want to add a functionality that can send files from the local device to the distant server. I found the library "Tamir.SharpSSH" which can guarantee this. I tested the code on a console application and on normal windows forms application and it works perfectly. But when I tried to use the same code on the winCE device, I get a TypeLoadException and I have the error message:

```
Could not load type 'Tamir.SharpSsh.SshTransferProtocolBase' from assembly 'Tamir.SharpSSH,
Version=1.1.1.13, Culture=neutral, PublicKeyToken=null'.
```

the code that I'm use is like below :

```<code>SshTransferProtocolBase sshCp = new Scp(Tools.GlobalVarMeth.hostName, Tools.GlobalVarMeth.serverUserName);
sshCp.Password = Tools.GlobalVarMeth.serverUserpassword;
sshCp.Connect();

string localFile = Tools.GlobalVarMeth.applicationPath + "/" + fileName + ".csv";
string remoteFile = Tools.GlobalVarMeth.serverRemoteFilePath + "/" + fileName + ".csv";

sshCp.Put(localFile, remoteFile);

sshCp.Close();
</code>```

Any one have any idea on this ? I will be really grateful !!!

答:
In my case problem was that I had two projects that used the same libraries in one solution. I've updated DLLs only in first project.
So when I built solution, second project its override DLLs from first project(project build order).

Example:

Solution:

--MainProject

------MyDll v5.3.2.0

--Prototype

------MyDll v5.0.0.0

Problem gone after update DLLs in second project.

Body:
I'm developing, with VS2008 using C#, an application for Honeywell Dolphin 6100, a mobile computer with a barcode scanner that uses Windows CE 5.0 like OS.

I want to add a functionality that can send files from the local device to the distant server. I found the library "Tamir.SharpSSH" which can guarantee this. I tested the code on a console application and on normal windows forms application and it works perfectly. But when I tried to use the same code on the winCE device, I get a TypeLoadException and I have the error message:

Could not load type 'Tamir.SharpSsh.SshTransferProtocolBase' from assembly 'Tamir.SharpSSH,
Version=1.1.1.13, Culture=neutral, PublicKeyToken=null'.

the code that I'm use is like below :

SshTransferProtocolBase sshCp = new Scp(Tools.GlobalVarMeth.hostName, Tools.GlobalVarMeth.serverUserName);
sshCp.Password = Tools.GlobalVarMeth.serverUserpassword;
sshCp.Connect();

string localFile = Tools.GlobalVarMeth.applicationPath + "/" + fileName + ".csv";
string remoteFile = Tools.GlobalVarMeth.serverRemoteFilePath + "/" + fileName + ".csv";

sshCp.Put(localFile, remoteFile);

sshCp.Close();

Any one have any idea on this ? I will be really grateful !!!


问:
AWK: increment a field based on values from previous line
Given the following input for AWK:

```<code>10;20;20
8;41;41
15;52;52
</code>```

How could I increase/decrease the values so that:

$1 = remains unchanged

$2 = $2 of previous line + $1 of previous line + 1

$3 = $3 of previous line + $1 of previous line + 1

So the desired output would be:

```<code>10;20;20
8;31;31
15;40;40
</code>```

I need to auto-increment and loop over the lines,
using associative arrays, but it's confusing for me.
Surely, this doesn't work as desired:

```<code>#!/bin/awk -f

BEGIN { FS = ";" }

{
print ln, st, of
ln=$1
st=$2 + ln + 1
of=$3 + ln + 1
}
</code>```

答:
Following awk may help you in same.

```<code>awk -F";" '
FNR==1{
 val=$1;
 val1=$2;
 val2=$3;
 print;
 next
}
{
$2=val+val1+1;
$3=val+val2+1;
print;
val=$1;
val1=$2;
val2=$3;
}' OFS=";"   Input_file
</code>```

For your given Input_file, output will be as follows.

```<code>10;20;20
8;31;31
15;40;40
</code>```

Body:
Given the following input for AWK:

10;20;20
8;41;41
15;52;52

How could I increase/decrease the values so that:

$1 = remains unchanged

$2 = $2 of previous line + $1 of previous line + 1

$3 = $3 of previous line + $1 of previous line + 1

So the desired output would be:

10;20;20
8;31;31
15;40;40

I need to auto-increment and loop over the lines,
using associative arrays, but it's confusing for me.
Surely, this doesn't work as desired:

#!/bin/awk -f

BEGIN { FS = ";" }

{
print ln, st, of
ln=$1
st=$2 + ln + 1
of=$3 + ln + 1
}

Body:
Following awk may help you in same.

awk -F";" '
FNR==1{
 val=$1;
 val1=$2;
 val2=$3;
 print;
 next
}
{
$2=val+val1+1;
$3=val+val2+1;
print;
val=$1;
val1=$2;
val2=$3;
}' OFS=";"   Input_file

For your given Input_file, output will be as follows.

10;20;20
8;31;31
15;40;40


问:
Get Max value from range (multiple sheets) grouped by Name
I have 3 sheets that have the exact same format

Sheet1

```<code>A           B          C         D
George      10         2         8
Nick        15         89        0
Mike        13         1         50
Lucas       9         -5         12
</code>```

Sheet2

```<code>A           B          C         D
Nick        1          9         5
Mike        1          10        6
George      11         22        5
Lucas       10         5         2
Panos       55         0         1
</code>```

Sheet3

```<code>A            B         C         D
Panos        0         9         1
George       1         2         5
Nick         7         2         1
Lucas        1         5         1
</code>```

I want to query the range {'Sheet1'!A1:D5; 'Sheet2'!A1:D5; 'Sheet3'!A1:D5}

And get something like MAX(Col2:Col4) Group By Col1

Which would return something like:

```<code>George 22
Nick   89
Mike   50
Lucas  12
Panos  55
</code>```

I tried:

```<code>=sort(query({'Sheet1'!A1:D5; 'Sheet2'!A1:D5;'Sheet3'!A1:D5}, "select Col1, MAX(Col2:Col4) Group by Col1 Label MAX(Col2:Col4) '' " ),2, FALSE)
</code>```

and

```<code>=sort(query({'Sheet1'!A1:D5; 'Sheet2'!A1:D5;'Sheet3'!A1:D5}, "select Col1, MAX(MAX(Col2),MAX(Col3), MAX(Col4)) Group by Col1 " ),2, FALSE)
</code>```

Both didn't work. Any ideas?

答:
To sum up your question, It requires finding the MAX across the columns to the right as well as down. As such, QUERY does NOT have such 2D function.

So, Use a Helper column E&F in each sheet:

Max of B&C:

E2:

```<code>=ARRAYFORMULA(IF(B2:B>C2:C,B2:B,C2:C))
</code>```

Max of B,C&D:

F2:

```<code>=ARRAYFORMULA(IF(D2:D>E2:E,D2:D,E2:E))
</code>```

Now, Use Query:

Query:

```<code>=ARRAYFORMULA(QUERY({Sheet1!A2:F;Sheet2!A2:F;Sheet3!A2:F}, "Select Col1,max(Col5) where Col1 is not null group by Col1 order by max(Col5) desc"))
</code>```

Notes:

Change ranges to suit

You could also simply use MAX for each row without the ARRAYFORMULA

Theoretically,  For a single cell solution, You could enter this formula to find the max of 3 real numbers

Body:
I have 3 sheets that have the exact same format

Sheet1

A           B          C         D
George      10         2         8
Nick        15         89        0
Mike        13         1         50
Lucas       9         -5         12

Sheet2

A           B          C         D
Nick        1          9         5
Mike        1          10        6
George      11         22        5
Lucas       10         5         2
Panos       55         0         1

Sheet3

A            B         C         D
Panos        0         9         1
George       1         2         5
Nick         7         2         1
Lucas        1         5         1

I want to query the range {'Sheet1'!A1:D5; 'Sheet2'!A1:D5; 'Sheet3'!A1:D5}

And get something like MAX(Col2:Col4) Group By Col1

Which would return something like:

George 22
Nick   89
Mike   50
Lucas  12
Panos  55

I tried:

=sort(query({'Sheet1'!A1:D5; 'Sheet2'!A1:D5;'Sheet3'!A1:D5}, "select Col1, MAX(Col2:Col4) Group by Col1 Label MAX(Col2:Col4) '' " ),2, FALSE)

and

=sort(query({'Sheet1'!A1:D5; 'Sheet2'!A1:D5;'Sheet3'!A1:D5}, "select Col1, MAX(MAX(Col2),MAX(Col3), MAX(Col4)) Group by Col1 " ),2, FALSE)

Both didn't work. Any ideas?

Body:
To sum up your question, It requires finding the MAX across the columns to the right as well as down. As such, QUERY does NOT have such 2D function.

So, Use a Helper column E&F in each sheet:

Max of B&C:

E2:

=ARRAYFORMULA(IF(B2:B>C2:C,B2:B,C2:C))

Max of B,C&D:

F2:

=ARRAYFORMULA(IF(D2:D>E2:E,D2:D,E2:E))

Now, Use Query:

Query:

=ARRAYFORMULA(QUERY({Sheet1!A2:F;Sheet2!A2:F;Sheet3!A2:F}, "Select Col1,max(Col5) where Col1 is not null group by Col1 order by max(Col5) desc"))

Notes:

Change ranges to suit

You could also simply use MAX for each row without the ARRAYFORMULA

Theoretically,  For a single cell solution, You could enter this formula to find the max of 3 real numbers


问:
To find no.of columns in a data set with correlation more than certain percentage in R
I am working on a data set with 48 variables and by seeing the correlation plot in R, most of the variables are highly correlated. I am trying to find the number of variables that are correlated > 70%

My data frame is called diagnosed_data and the code I use is:

```<code>cor_data <- cor(diagnosed_data)
corrplot::corrplot(cor_data, method = "number",
                   title = "correlation plot b/w the attributes")
</code>```

From this plot I can figure out visually how many variables have high correlation, but I would like to find this using code instead.

How can I find those variables? Any help would me much appreciated. Thanks!

答:
This will help you store results in a dataframe and analyse it further. Using the mtcars dataset as well.

```<code>library(dplyr)

t(combn(names(mtcars), 2)) %>%                          # get all pairwise combinations of variables
  data.frame(., stringsAsFactors = F) %>%               # save as dataframe
  rowwise() %>%                                         # for each row (pair)
  mutate(cor_value = cor(mtcars[X1], mtcars[X2])) %>%   # calculate correlation value
  ungroup()                                             # forget the grouping

# # A tibble: 55 x 3
#      X1    X2  cor_value
#   <chr> <chr>      <dbl>
# 1   mpg   cyl -0.8521620
# 2   mpg  disp -0.8475514
# 3   mpg    hp -0.7761684
# 4   mpg  drat  0.6811719
# 5   mpg    wt -0.8676594
# 6   mpg  qsec  0.4186840
# 7   mpg    vs  0.6640389
# 8   mpg    am  0.5998324
# 9   mpg  gear  0.4802848
# 10   mpg  carb -0.5509251
# # ... with 45 more rows
</code>```

You can try different correlation thresholds, you can get all pairs of variables that are correlated above a specified threshold, you can get the variables that appear in most pairs, etc.

And a version without grouping, but by using a user specified vectorised function:

```<code>f_get_cor = function(x,y) { cor(mtcars[x], mtcars[y]) }
f_get_cor = Vectorize(f_get_cor)

t(combn(names(mtcars), 2)) %>%
  data.frame(., stringsAsFactors = F) %>%
  mutate(cor_value = f_get_cor(X1, X2))
</code>```

Body:
I am working on a data set with 48 variables and by seeing the correlation plot in R, most of the variables are highly correlated. I am trying to find the number of variables that are correlated > 70%

My data frame is called diagnosed_data and the code I use is:

cor_data <- cor(diagnosed_data)
corrplot::corrplot(cor_data, method = "number",
                   title = "correlation plot b/w the attributes")

From this plot I can figure out visually how many variables have high correlation, but I would like to find this using code instead.

How can I find those variables? Any help would me much appreciated. Thanks!

Body:
This will help you store results in a dataframe and analyse it further. Using the mtcars dataset as well.

library(dplyr)

t(combn(names(mtcars), 2)) %>%                          # get all pairwise combinations of variables
  data.frame(., stringsAsFactors = F) %>%               # save as dataframe
  rowwise() %>%                                         # for each row (pair)
  mutate(cor_value = cor(mtcars[X1], mtcars[X2])) %>%   # calculate correlation value
  ungroup()                                             # forget the grouping

# # A tibble: 55 x 3
#      X1    X2  cor_value
#   <chr> <chr>      <dbl>
# 1   mpg   cyl -0.8521620
# 2   mpg  disp -0.8475514
# 3   mpg    hp -0.7761684
# 4   mpg  drat  0.6811719
# 5   mpg    wt -0.8676594
# 6   mpg  qsec  0.4186840
# 7   mpg    vs  0.6640389
# 8   mpg    am  0.5998324
# 9   mpg  gear  0.4802848
# 10   mpg  carb -0.5509251
# # ... with 45 more rows

You can try different correlation thresholds, you can get all pairs of variables that are correlated above a specified threshold, you can get the variables that appear in most pairs, etc.

And a version without grouping, but by using a user specified vectorised function:

f_get_cor = function(x,y) { cor(mtcars[x], mtcars[y]) }
f_get_cor = Vectorize(f_get_cor)

t(combn(names(mtcars), 2)) %>%
  data.frame(., stringsAsFactors = F) %>%
  mutate(cor_value = f_get_cor(X1, X2))


问:
Create array of objects based off the same property names
I have form inputs that are generated based off an XML file.

We keep a reference of nested elements in the XML file via data-* attributes which can later be used to build an object. For example:

```<code><parent>
 <child>
  <grandchild1>first</grandchild1>
  <grandchild2>second</grandchild2>
 </child>
</parent>
</code>```

Becomes

<input type="text" data-nest="parent.child.grandchild1" value="first"/>
<input type="text" data-nest="parent.child.grandchild2" value="second"/>

When we submit the form, I create an object (with nested objects) based off of their data-nest attribute. The above would become

```<code>parent:{
 child:{
  grandchild1: first,
  grandchild2: second
  }
}
</code>```

The issue that I am running into is where multiple of the same tag are found in the XML file, e.g.

```<code><child>
 <grandchild>first</grandchild>
 <grandchildFriend>firstFriend</grandchildFriend>
</child>
<child>
 <grandchild>second</grandchild>
 <grandchildFriend>secondFriend</grandchildFriend>
</child>
</code>```

When I create my object, I would like it so that if multiple occurrences of the same data-nest value are found, they are nested inside of an array in order to maintain the different values.

With the current setup, the second occurrence of the tag will understandably overwrite the first.

This is the final object structure I desire:

```<code>parent:{
 child:[
  {
   grandchild: first,
   grandchildFriend: firstFriend
  },
  {
   grandchild: second,
   grandchildFriend: secondFriend
  }
  ]
 }
</code>```

TL;DR

I'd like to change an object to an array of nested objects if they have the same data-* attribute

Here's a fiddle of how the current code works to help give a better understanding.

答:
Update your config.set() as follows:

var json = {};

config = {
  set: function(keyValueString) {

    var pair = keyValueString.split('=');

    // left of the = is the key path
    var keyPath = pair[0];

    // right of the = is the value to set
    var value = pair[1];

    // split keyPath into an array of keys
    var keys = keyPath.split('.');
    var key;

    var currentObj = json;

    // loop through all keys in the key path, except the last one.
    // this creates the object structure implied by the key path.
    // we want to do something different on the last iteration.
    for (var i=0; i < keys.length-1; i++) {

      // Get the current key we are looping
      key = keys[i];
      // if the requested level on the current object doesn't exist,
      // make a blank object.
      if (typeof currentObj[key] === 'undefined') {
        currentObj[key] = {};
      }

      currentObj = currentObj[key];
    }

    // our loop doesn't handle the last key, because that's when we
    // want to set the actual value.
    var lastKey = keys[keys.length-1]

    if (typeof currentObj[lastKey] === 'undefined') {
      // set string if nothing exists
       currentObj[lastKey] = value;

    } else if(!Array.isArray(currentObj[lastKey])) {
      // if exists and is not an array,
      // create an array with two items
      // previously stored value (string) with lastKey key
      // current value
      var previous = { [lastKey]: currentObj[lastKey] };
      var current  = { [lastKey]: value };
      currentObj[lastKey] = [previous, current];

    } else if(Array.isArray(currentObj[key])){
      // if exists and is an array
      // push the new object to it
      var current = { [lastKey]: value }
      currentObj[lastKey].push(current);

    }
  }
};

// iterate through all of our inputs, and nest them based off their data-* attribute
$('input').each(function(){
 // set nest = value setup, e.g. parent.child.grandchild = first
  // we then break this
 var key = $(this).attr('data-nest') + '=' + $(this).val();
  config.set(key);
});

// as a bonus - this is how I went about breaking multiple values within a single input into an array
function traverseObject(object){
  // iterate through the object
  for (var i in object){
    var value = [object[i]];

    // EDIT: continue only if value is not an array
    if(!Array.isArray(object[i])) {
      // if the value contains a comma
      if(value.toString().indexOf(',') > -1){
        // set the *nested* key to the
        // value as an array by splitting at the commas
        object[i] = value.toString().split(',').filter(function(el){
          // remove the extra entry after splitting
          return el.length != 0;
        });
      }
      // if the next key exists, run again
      if(object[i] !== null && typeof(object[i])=="object"){
        traverseObject(object[i]);
      }
    }
  }
}

traverseObject(json);

$('#test').on('click', function(){
 console.log(json)
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#test{
  padding: 5px;
  border: 1px solid black;
  font-size: 15px;
  cursor: pointer;
  width: 150px;
  margin: 5px;
  text-align: center;
}
input{
  display: block;
  margin: 5px;
  padding: 5px;
  width: 150px;
}</code>```

Below are unique tags (working fine)
<input type="text" data-nest="parent.child.grandchild1" value="gchild1-first"/>
<input type="text" data-nest="parent.child.grandchild2" value="gchild2-second"/>

Below is multiple occurances of the same tag (find a way to break these into an array of objects)
<input type="text" data-nest="parent.child.grandchild" value="gchild-first"/>
<input type="text" data-nest="parent.child.grandchild" value="gchild-second"/>

Single array example
<input type="text" data-nest="parent.child.array" value="this,is,an,array"/>

  Test

```

Body:
I have form inputs that are generated based off an XML file.

We keep a reference of nested elements in the XML file via data-* attributes which can later be used to build an object. For example:

<parent>
 <child>
  <grandchild1>first</grandchild1>
  <grandchild2>second</grandchild2>
 </child>
</parent>

Becomes

<input type="text" data-nest="parent.child.grandchild1" value="first"/>
<input type="text" data-nest="parent.child.grandchild2" value="second"/>

When we submit the form, I create an object (with nested objects) based off of their data-nest attribute. The above would become

parent:{
 child:{
  grandchild1: first,
  grandchild2: second
  }
}

The issue that I am running into is where multiple of the same tag are found in the XML file, e.g.

<child>
 <grandchild>first</grandchild>
 <grandchildFriend>firstFriend</grandchildFriend>
</child>
<child>
 <grandchild>second</grandchild>
 <grandchildFriend>secondFriend</grandchildFriend>
</child>

When I create my object, I would like it so that if multiple occurrences of the same data-nest value are found, they are nested inside of an array in order to maintain the different values.

With the current setup, the second occurrence of the tag will understandably overwrite the first.

This is the final object structure I desire:

parent:{
 child:[
  {
   grandchild: first,
   grandchildFriend: firstFriend
  },
  {
   grandchild: second,
   grandchildFriend: secondFriend
  }
  ]
 }

TL;DR

I'd like to change an object to an array of nested objects if they have the same data-* attribute

Here's a fiddle of how the current code works to help give a better understanding.

Body:
Update your config.set() as follows:

var json = {};

config = {
  set: function(keyValueString) {

    var pair = keyValueString.split('=');

    // left of the = is the key path
    var keyPath = pair[0];

    // right of the = is the value to set
    var value = pair[1];

    // split keyPath into an array of keys
    var keys = keyPath.split('.');
    var key;

    var currentObj = json;

    // loop through all keys in the key path, except the last one.
    // this creates the object structure implied by the key path.
    // we want to do something different on the last iteration.
    for (var i=0; i < keys.length-1; i++) {

      // Get the current key we are looping
      key = keys[i];
      // if the requested level on the current object doesn't exist,
      // make a blank object.
      if (typeof currentObj[key] === 'undefined') {
        currentObj[key] = {};
      }

      currentObj = currentObj[key];
    }

    // our loop doesn't handle the last key, because that's when we
    // want to set the actual value.
    var lastKey = keys[keys.length-1]

    if (typeof currentObj[lastKey] === 'undefined') {
      // set string if nothing exists
       currentObj[lastKey] = value;

    } else if(!Array.isArray(currentObj[lastKey])) {
      // if exists and is not an array,
      // create an array with two items
      // previously stored value (string) with lastKey key
      // current value
      var previous = { [lastKey]: currentObj[lastKey] };
      var current  = { [lastKey]: value };
      currentObj[lastKey] = [previous, current];

    } else if(Array.isArray(currentObj[key])){
      // if exists and is an array
      // push the new object to it
      var current = { [lastKey]: value }
      currentObj[lastKey].push(current);

    }
  }
};

// iterate through all of our inputs, and nest them based off their data-* attribute
$('input').each(function(){
 // set nest = value setup, e.g. parent.child.grandchild = first
  // we then break this
 var key = $(this).attr('data-nest') + '=' + $(this).val();
  config.set(key);
});

// as a bonus - this is how I went about breaking multiple values within a single input into an array
function traverseObject(object){
  // iterate through the object
  for (var i in object){
    var value = [object[i]];

    // EDIT: continue only if value is not an array
    if(!Array.isArray(object[i])) {
      // if the value contains a comma
      if(value.toString().indexOf(',') > -1){
        // set the *nested* key to the
        // value as an array by splitting at the commas
        object[i] = value.toString().split(',').filter(function(el){
          // remove the extra entry after splitting
          return el.length != 0;
        });
      }
      // if the next key exists, run again
      if(object[i] !== null && typeof(object[i])=="object"){
        traverseObject(object[i]);
      }
    }
  }
}

traverseObject(json);

$('#test').on('click', function(){
 console.log(json)
});

#test{
  padding: 5px;
  border: 1px solid black;
  font-size: 15px;
  cursor: pointer;
  width: 150px;
  margin: 5px;
  text-align: center;
}
input{
  display: block;
  margin: 5px;
  padding: 5px;
  width: 150px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Below are unique tags (working fine)</label>
<input type="text" data-nest="parent.child.grandchild1" value="gchild1-first"/>
<input type="text" data-nest="parent.child.grandchild2" value="gchild2-second"/>

<label>Below is multiple occurances of the same tag (find a way to break these into an array of objects)</label>
<input type="text" data-nest="parent.child.grandchild" value="gchild-first"/>
<input type="text" data-nest="parent.child.grandchild" value="gchild-second"/>

<label>Single array example</label>
<input type="text" data-nest="parent.child.array" value="this,is,an,array"/>

<div id="test">
  Test
</div>


问:
JS: add onclick function to table cell
I've created a minimal example: https://jsfiddle.net/n2r5t91v/

var myvalue = 20 // abbreviating how I calculate myvalue
var cell = document.getElementById("mytd");
cell.setAttribute('onclick', 'addToCell(' + myvalue + ');');

function addToCell(value) {
  var td_cell = document.getElementById("mytd");
  td_cell.value = td_cell.value + ' ' + value;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <td id="mytd">
      test
    </td>
  </tr>
</table></code>```

I expect the value of that  cell to change from "test" to "test 20" upon clicking. Why doesn't it work like this?

答:
You just need to do this way. There's no value attribute for . Use innerHTML:

var myvalue = 20;
var cell = document.getElementById("mytd");
cell.setAttribute('onclick', 'addToCell(' + myvalue + ');');

function addToCell(value) {
  var td_cell = document.getElementById("mytd");
  td_cell.innerHTML = td_cell.innerHTML + ' ' + value;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <td id="mytd">
      test
    </td>
  </tr>
</table></code>```

You can also do in a different way in this part:

```<code>td_cell.innerHTML += ' ' + value;
</code>```

Title: JS: add onclick function to table cell

Body:
I've created a minimal example: https://jsfiddle.net/n2r5t91v/

var myvalue = 20 // abbreviating how I calculate myvalue
var cell = document.getElementById("mytd");
cell.setAttribute('onclick', 'addToCell(' + myvalue + ');');

function addToCell(value) {
  var td_cell = document.getElementById("mytd");
  td_cell.value = td_cell.value + ' ' + value;
}

      test

I expect the value of that  cell to change from "test" to "test 20" upon clicking. Why doesn't it work like this?

Body:
You just need to do this way. There's no value attribute for <td>. Use innerHTML:

var myvalue = 20;
var cell = document.getElementById("mytd");
cell.setAttribute('onclick', 'addToCell(' + myvalue + ');');

function addToCell(value) {
  var td_cell = document.getElementById("mytd");
  td_cell.innerHTML = td_cell.innerHTML + ' ' + value;
}

<table>
  <tr>
    <td id="mytd">
      test
    </td>
  </tr>
</table>

You can also do in a different way in this part:

td_cell.innerHTML += ' ' + value;


问:
Angular service instantiated twice?
somehow I've got a service that seems to be instantiated twice (its properties are not in sync), by doing the following:

```<code>@Component
export class MyComponent extends someOtherComponent {
  constructor(service: Service, service2: Service2) {
    super(service, service2);
  }

  isStateEqual() {
    return this.service.serviceState === this.service2.service.serviceState;
  }
}

@Injectable
export class Service {
  serviceState = {}
}

@Injectable
export class Service2 {
  constructor(service: Service) {}
}
</code>```

This is just a very basic example, but that's what it comes down to. To be more precise: We're building our own datepicker and extending NgbDatepicker component which has KeyMapService (this uses NgbDatepickerService) and a local NgbDatepickerService.
Here is a link to the component: https://ng-bootstrap.github.io/#/components/datepicker/examples

In our app isStateEqual will always return false (even right after initialising the component) while in the demo you can find in the link above it will always return true (which is how it should be).

Anyone knows why it could be like that?

Thanks in advance.

Regards
Dennis

答: It depends where you declare the provider for your services - this determines the scoping. You don't specify in your question where you've done this - try doing it in AppModule, for example.</p>

Title: Angular service instantiated twice?

Body:
somehow I've got a service that seems to be instantiated twice (its properties are not in sync), by doing the following:

@Component
export class MyComponent extends someOtherComponent {
  constructor(service: Service, service2: Service2) {
    super(service, service2);
  }

  isStateEqual() {
    return this.service.serviceState === this.service2.service.serviceState;
  }
}

@Injectable
export class Service {
  serviceState = {}
}

@Injectable
export class Service2 {
  constructor(service: Service) {}
}

This is just a very basic example, but that's what it comes down to. To be more precise: We're building our own datepicker and extending NgbDatepicker component which has KeyMapService (this uses NgbDatepickerService) and a local NgbDatepickerService.
Here is a link to the component: https://ng-bootstrap.github.io/#/components/datepicker/examples

In our app isStateEqual will always return false (even right after initialising the component) while in the demo you can find in the link above it will always return true (which is how it should be).

Anyone knows why it could be like that?

Thanks in advance.

Regards
Dennis


问:
i need a query which returns 1 column 5 rows and 2nd column 10 rows
here is my query

```<code>SELECT
ISNULL(
     (
     select subjectshrt from subject_definition sd  join student_subject ss
     on(sd.sdsrno =ss.sdsrno1) where sd.tpbp LIKE ('p%')
      )
,0)A,
ISNULL(
     (
     select subjectshrt from subject_definition sd  join student_subject ss
     on(sd.sdsrno =ss.sdsrno2) where sd.tpbp LIKE ('p%')
      )
,0)b
</code>```

here first select query return 1 row and 2nd returns multiple rows
and am getting a error like

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

so what should i do to make this query work

答:
try using something like</p>

```<code>SELECT isnull(sd1.subjectshrt,0) as A , isnull(sd2.subjectshrt,0) as B
from student_subject ss left join subject_definition sd1 on sd1.sdsrno =ss.sdsrno1,
left join subject_definition sd2 on sd2.sdsrno =ss.sdsrno2
</code>```

Body:
here is my query

SELECT
ISNULL(
     (
     select subjectshrt from subject_definition sd  join student_subject ss
     on(sd.sdsrno =ss.sdsrno1) where sd.tpbp LIKE ('p%')
      )
,0)A,
ISNULL(
     (
     select subjectshrt from subject_definition sd  join student_subject ss
     on(sd.sdsrno =ss.sdsrno2) where sd.tpbp LIKE ('p%')
      )
,0)b

here first select query return 1 row and 2nd returns multiple rows
and am getting a error like

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

so what should i do to make this query work

Body:
try using something like

SELECT isnull(sd1.subjectshrt,0) as A , isnull(sd2.subjectshrt,0) as B
from student_subject ss left join subject_definition sd1 on sd1.sdsrno =ss.sdsrno1,
left join subject_definition sd2 on sd2.sdsrno =ss.sdsrno2