问:
Ionic push notifications action buttons not getting displayed
I am using ionic4 with push plugin to send the push notifications with FCM.

I could able to send the notifications, but some reason action buttons are not getting displayed in notifications only title and body content getting displayed.

Following is the payload of my request:

```<code>{
    "to": "eoD5PLNgj3A:APA91bHcrWcEfbEQuKGOozPXtIxO7CrN2Gd993bXcaaHSO8BkOXhwJ4x1o-7SIUEzIUVLxSwcKih1ac0jOkj4Jp8LQZkRiAHAEfRvRGopSAP4JkJVKXoRllxSkAUCAxWGCfUTk3umMsn",
    "registration_ids": null,
    "condition": null,
    "collapse_key": null,
    "content_available": null,
    "mutable_content": null,
    "priority": "high",
    "time_to_live": 900,
    "dry_run": false,
    "data": {
        "title": "New Visitor",
        "message": "Suda Sankara Rao is here to see you at Protoco HQ.\r\n",
        "visit_id": "ae866080-b6af-44cd-944c-6491ae9d2e4b",
        "force-start": 1,
        "visibility": 1,
        "notId": "ae866080-b6af-44cd-944c-6491ae9d2e4b",
        "actions": [{
            "icon": "snooze",
            "title": "Accept",
            "callback": "visit.accept",
            "foreground": false
        }, {
            "icon": "snooze",
            "title": "Reject",
            "callback": "visit.reject",
            "foreground": true
        }]
    },
    "notification": {
        "title": "New Visitor",
        "body": "Suda Sankara Rao is here to see you at Protoco HQ.\r\n",
        "click_action": "visit",
        "badge": null,
        "android_channel_id": null,
        "icon": null,
        "sound": null,
        "tag": "ae866080-b6af-44cd-944c-6491ae9d2e4b",
        "color": null,
        "body_loc_key": null,
        "body_loc_args": null,
        "title_loc_key": null,
        "title_loc_args": null
    }
}
</code>```

Receiving the notification data in below format to a device:

```<code>{
    "title": "New Visitor",
    "message": "Suda Sankara Rao is here to see you at Protoco HQ.",
    "additionalData": {
        "actions": [{
            "callback": "accept",
            "foreground": false,
            "title": "Accept"
        }, {
            "callback": "reject",
            "foreground": true,
            "title": "Reject"
        }],
        "visit_id": "ae866080-b6af-44cd-944c-6491ae9d2e4b",
        "coldstart": false,
        "foreground": true
    }
}

</code>```

Ionic Info:

```<code>Ionic:

   Ionic CLI                     : 5.4.15 (/usr/local/lib/node_modules/ionic)
   Ionic Framework               : @ionic/angular 4.11.8
   @angular-devkit/build-angular : 0.801.3
   @angular-devkit/schematics    : 8.1.3
   @angular/cli                  : 8.1.3
   @ionic/angular-toolkit        : 2.1.2

Cordova:

   Cordova CLI       : 9.0.0 (cordova-lib@9.0.1)
   Cordova Platforms : android 8.1.0, ios 5.1.1
   Cordova Plugins   : cordova-plugin-ionic-keyboard 2.2.0, cordova-plugin-ionic-webview 4.1.3, (and 9 other plugins)
</code>```

Push plugin version: phonegap-plugin-push@2.3.0

I could not able to figure out the issue.

I am using an android emulator to test the notifications.

答:
I could able to identify and resolve the issue.

if the payload has notification object. Action buttons are not visible.

I have removed and worked fine.

Body:
I am using ionic4 with push plugin to send the push notifications with FCM.

I could able to send the notifications, but some reason action buttons are not getting displayed in notifications only title and body content getting displayed.

Following is the payload of my request:

{
    "to": "eoD5PLNgj3A:APA91bHcrWcEfbEQuKGOozPXtIxO7CrN2Gd993bXcaaHSO8BkOXhwJ4x1o-7SIUEzIUVLxSwcKih1ac0jOkj4Jp8LQZkRiAHAEfRvRGopSAP4JkJVKXoRllxSkAUCAxWGCfUTk3umMsn",
    "registration_ids": null,
    "condition": null,
    "collapse_key": null,
    "content_available": null,
    "mutable_content": null,
    "priority": "high",
    "time_to_live": 900,
    "dry_run": false,
    "data": {
        "title": "New Visitor",
        "message": "Suda Sankara Rao is here to see you at Protoco HQ.\r\n",
        "visit_id": "ae866080-b6af-44cd-944c-6491ae9d2e4b",
        "force-start": 1,
        "visibility": 1,
        "notId": "ae866080-b6af-44cd-944c-6491ae9d2e4b",
        "actions": [{
            "icon": "snooze",
            "title": "Accept",
            "callback": "visit.accept",
            "foreground": false
        }, {
            "icon": "snooze",
            "title": "Reject",
            "callback": "visit.reject",
            "foreground": true
        }]
    },
    "notification": {
        "title": "New Visitor",
        "body": "Suda Sankara Rao is here to see you at Protoco HQ.\r\n",
        "click_action": "visit",
        "badge": null,
        "android_channel_id": null,
        "icon": null,
        "sound": null,
        "tag": "ae866080-b6af-44cd-944c-6491ae9d2e4b",
        "color": null,
        "body_loc_key": null,
        "body_loc_args": null,
        "title_loc_key": null,
        "title_loc_args": null
    }
}

Receiving the notification data in below format to a device:

{
    "title": "New Visitor",
    "message": "Suda Sankara Rao is here to see you at Protoco HQ.",
    "additionalData": {
        "actions": [{
            "callback": "accept",
            "foreground": false,
            "title": "Accept"
        }, {
            "callback": "reject",
            "foreground": true,
            "title": "Reject"
        }],
        "visit_id": "ae866080-b6af-44cd-944c-6491ae9d2e4b",
        "coldstart": false,
        "foreground": true
    }
}

Ionic Info:

Ionic:

   Ionic CLI                     : 5.4.15 (/usr/local/lib/node_modules/ionic)
   Ionic Framework               : @ionic/angular 4.11.8
   @angular-devkit/build-angular : 0.801.3
   @angular-devkit/schematics    : 8.1.3
   @angular/cli                  : 8.1.3
   @ionic/angular-toolkit        : 2.1.2

Cordova:

   Cordova CLI       : 9.0.0 (cordova-lib@9.0.1)
   Cordova Platforms : android 8.1.0, ios 5.1.1
   Cordova Plugins   : cordova-plugin-ionic-keyboard 2.2.0, cordova-plugin-ionic-webview 4.1.3, (and 9 other plugins)

Push plugin version: phonegap-plugin-push@2.3.0

I could not able to figure out the issue.

I am using an android emulator to test the notifications.


来源: stackexchange

问:
Get current year in MySQL WHERE clause
How do you get the current year (as a four digit number) for use in a MySql WHERE clause?

I have the following query:

```<code>SELECT * FROM tblfeatured WHERE yeargrad LIKE date('Y')
</code>```

The yeargrad columns stores just a year (e.g  2017) and I would like to find rows where this matches the current year.

答:
```<code>SELECT * FROM tblfeatured WHERE YEAR(yeargrad) = YEAR(CURRENT_DATE())
</code>```

ContentLicense: CC BY-SA 4.0

Title: Get current year in MySQL WHERE clause

Body:
How do you get the current year (as a four digit number) for use in a MySql WHERE clause?

I have the following query:

SELECT * FROM tblfeatured WHERE yeargrad LIKE date('Y')

The yeargrad columns stores just a year (e.g  2017) and I would like to find rows where this matches the current year.


问:
What is a good definition of a "userdata pointer"?
I have searched for a good explanation but can't find one.

I could try to write one myself but I'd prefer if someone with better english could help me explain this for Zan Lynx in the comment here.

...and it seems like there should be a good explanation somewhere, why not here?

答:
When a library manages some data structures on behalf of a program (e.g. windows in a GUI application are managed by the OS), it usually keeps the contents of those structures private.  However, it is typically useful for the program to maintain some additional data specific to the program's use of those structures.  Therefore, a library will often provide access to a field (often called user data) which it stores with each structure.

A common use of the user data field by a program is to allocate some memory each time the program requests the library to create a structure, and to store the pointer to that memory in the user data field provided by the library, hence the term userdata pointer.

OwnerDisplayName: epatel

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Matthew Xavier


问:
Recording audio inside ionic 4 app using media-capture cordova plugin
I'm trying to record audio inside ionic 4 app using media-capture cordova plugin, But the problem is when I hit the record button it opens an external recorder app and records the audio, then I can play it inside my app. I would like to record the audio inside my app itself without opening an external recorder. Please help!

Here's my home.page.html:

```<code><ion-header>
  <ion-toolbar>
    <ion-title>
      Audio Testing App
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <div class="ion-padding">
    <ion-button color="primary" (click)="record()">Record</ion-button>

    <ion-list>
      <ion-item-sliding *ngFor="let f of files">
        <ion-item (click)="openFile(f)">
          <ion-icon name="mic" slot="start"></ion-icon>

          <ion-label class="ion-text-wrap">
            {{ f.name }}
            <p>{{ f.fullPath }}</p>
          </ion-label>
        </ion-item>

        <ion-item-options side="start">
          <ion-item-option (click)="deleteFile(f)" color="danger">
            <ion-icon name="trash" slot="icon-only"></ion-icon>
          </ion-item-option>
        </ion-item-options>
      </ion-item-sliding>
    </ion-list>
  </div>
</ion-content>
</code>```

home.page.ts file:

```<code>import { Component, OnInit } from '@angular/core';
import { NativeAudio } from '@ionic-native/native-audio/ngx';
import { MediaCapture, MediaFile, CaptureError } from '@ionic-native/media-capture/ngx';
import { File, FileEntry } from '@ionic-native/File/ngx';
import { Platform } from '@ionic/angular';
import { Media, MediaObject } from '@ionic-native/media/ngx';

const MEDIA_FOLDER_NAME = 'audio_app_media';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit {
  files = [];

  constructor(private nativeAudio: NativeAudio,
    private mediaCapture: MediaCapture,
    private file: File,
    private media: Media,
    private plt: Platform) { }

  ngOnInit() {
    this.plt.ready().then(() => {
      let path = this.file.dataDirectory;
      this.file.checkDir(path, MEDIA_FOLDER_NAME).then(
        () => {
          this.loadFiles();
        },
        err => {
          this.file.createDir(path, MEDIA_FOLDER_NAME, false);
        }
      );
    });
  }

  loadFiles() {
    this.file.listDir(this.file.dataDirectory, MEDIA_FOLDER_NAME).then(
      res => {
        this.files = res;
      },
      err => console.log('error loading files: ', err)
    );
  }

  record() {
    this.mediaCapture.captureAudio().then(
      (data: MediaFile[]) => {
        if (data.length > 0) {
          this.copyFileToLocalDir(data[0].fullPath);
        }
      },
      (err: CaptureError) => console.error(err)
    );
  }

  openFile(f: FileEntry) {
    const path = f.nativeURL.replace(/^file:\/\//, '');
    const audioFile: MediaObject = this.media.create(path);
    audioFile.play();
  }

  deleteFile(f: FileEntry) {
    const path = f.nativeURL.substr(0, f.nativeURL.lastIndexOf('/') + 1);
    this.file.removeFile(path, f.name).then(() => {
      this.loadFiles();
    }, err => console.log('error remove: ', err));
  }

  copyFileToLocalDir(fullPath) {
    let myPath = fullPath;
    // Make sure we copy from the right location
    if (fullPath.indexOf('file://') < 0) {
      myPath = 'file://' + fullPath;
    }

    const ext = myPath.split('.').pop();
    const d = Date.now();
    const newName = `${d}.${ext}`;

    const name = myPath.substr(myPath.lastIndexOf('/') + 1);
    const copyFrom = myPath.substr(0, myPath.lastIndexOf('/') + 1);
    const copyTo = this.file.dataDirectory + MEDIA_FOLDER_NAME;

    this.file.copyFile(copyFrom, name, copyTo, newName).then(
      success => {
        this.loadFiles();
      },
      error => {
        console.log('error: ', error);
      }
    );
  }

}
</code>```

Here's the screenshots of the app:
Image 1: home page

Image 2: External recorded, on clicking record button this opens up

(DON'T WANT TO GO HERE, INSTEAD RECORD DIRECTLY INSIDE MY APP)

答: You should try cordova-plugin-media.</p>

Body:
I'm trying to record audio inside ionic 4 app using media-capture cordova plugin, But the problem is when I hit the record button it opens an external recorder app and records the audio, then I can play it inside my app. I would like to record the audio inside my app itself without opening an external recorder. Please help!

Here's my home.page.html:

<ion-header>
  <ion-toolbar>
    <ion-title>
      Audio Testing App
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>

    <ion-button color="primary" (click)="record()">Record</ion-button>

    <ion-list>
      <ion-item-sliding *ngFor="let f of files">
        <ion-item (click)="openFile(f)">
          <ion-icon name="mic" slot="start"></ion-icon>

          <ion-label class="ion-text-wrap">
            {{ f.name }}

{{ f.fullPath }}

          </ion-label>
        </ion-item>

        <ion-item-options side="start">
          <ion-item-option (click)="deleteFile(f)" color="danger">
            <ion-icon name="trash" slot="icon-only"></ion-icon>
          </ion-item-option>
        </ion-item-options>
      </ion-item-sliding>
    </ion-list>

</ion-content>

home.page.ts file:

import { Component, OnInit } from '@angular/core';
import { NativeAudio } from '@ionic-native/native-audio/ngx';
import { MediaCapture, MediaFile, CaptureError } from '@ionic-native/media-capture/ngx';
import { File, FileEntry } from '@ionic-native/File/ngx';
import { Platform } from '@ionic/angular';
import { Media, MediaObject } from '@ionic-native/media/ngx';

const MEDIA_FOLDER_NAME = 'audio_app_media';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit {
  files = [];

  constructor(private nativeAudio: NativeAudio,
    private mediaCapture: MediaCapture,
    private file: File,
    private media: Media,
    private plt: Platform) { }

  ngOnInit() {
    this.plt.ready().then(() => {
      let path = this.file.dataDirectory;
      this.file.checkDir(path, MEDIA_FOLDER_NAME).then(
        () => {
          this.loadFiles();
        },
        err => {
          this.file.createDir(path, MEDIA_FOLDER_NAME, false);
        }
      );
    });
  }

  loadFiles() {
    this.file.listDir(this.file.dataDirectory, MEDIA_FOLDER_NAME).then(
      res => {
        this.files = res;
      },
      err => console.log('error loading files: ', err)
    );
  }

  record() {
    this.mediaCapture.captureAudio().then(
      (data: MediaFile[]) => {
        if (data.length > 0) {
          this.copyFileToLocalDir(data[0].fullPath);
        }
      },
      (err: CaptureError) => console.error(err)
    );
  }

  openFile(f: FileEntry) {
    const path = f.nativeURL.replace(/^file:\/\//, '');
    const audioFile: MediaObject = this.media.create(path);
    audioFile.play();
  }

  deleteFile(f: FileEntry) {
    const path = f.nativeURL.substr(0, f.nativeURL.lastIndexOf('/') + 1);
    this.file.removeFile(path, f.name).then(() => {
      this.loadFiles();
    }, err => console.log('error remove: ', err));
  }

  copyFileToLocalDir(fullPath) {
    let myPath = fullPath;
    // Make sure we copy from the right location
    if (fullPath.indexOf('file://') < 0) {
      myPath = 'file://' + fullPath;
    }

    const ext = myPath.split('.').pop();
    const d = Date.now();
    const newName = `${d}.${ext}`;

    const name = myPath.substr(myPath.lastIndexOf('/') + 1);
    const copyFrom = myPath.substr(0, myPath.lastIndexOf('/') + 1);
    const copyTo = this.file.dataDirectory + MEDIA_FOLDER_NAME;

    this.file.copyFile(copyFrom, name, copyTo, newName).then(
      success => {
        this.loadFiles();
      },
      error => {
        console.log('error: ', error);
      }
    );
  }

}

Here's the screenshots of the app:
Image 1: home page

Image 2: External recorded, on clicking record button this opens up

(DON'T WANT TO GO HERE, INSTEAD RECORD DIRECTLY INSIDE MY APP)

Body: You should try cordova-plugin-media.


问:
React useEffect hook does not fire when prop dependency changes
I am using a useEffect hook to make an API call depending on data from a photos prop being passed in.

```<code>const ImageCarousel = ({ src, photos }) => {
  const [photoList, setPhotos] = useState([]);
  const storageRef = firebase.storage().ref();
  console.log("photos prop:", photos);

  const getImage = photoId => {
    return new Promise((resolve, reject) => {
      storageRef
        .child("images/" + photoId)
        .getDownloadURL()
        .then(url => resolve(url))
        .catch(error => reject(error));
    });
  };

  useEffect(() => {
    console.log("trigger");
    Promise.all(
      photos.map(async photoId => {
        const url = await getImage(photoId);
        return url;
      })
    )
      .then(photoUrls => {
        setPhotos(photoUrls);
      })
      .catch(e => console.log(e));
  }, [photos]);

return (...)
}

</code>```

I have passed the photos prop into the dependency array of my useEffect hook, so it should fire when the photos prop changes. I can see that the prop is indeed changing in the console, but my useEffect hook does not fire when the prop change comes through. This is what appears in my console:

Why is the useEffect not firing twice? From my understanding it should fire when the component renders the first time, and fire again every time the photos prop changes.

答:
useEffect will update if you pass the new data, find the sample code below and check the console.log.

```<code>    import React, { useState, useEffect } from "react";

    const EffectCheck = ({value}) => {
        console.log('Component Trigger', value);
        useEffect(() => {
            console.log('Updated Effect', value);
        },[value]);

        return (
            <div>{value}</div>
        )
    }

    export default function() {
        const [checkValue, setCheckValue] = useState(Math.random());
        const [dynamicCheckValue, setdyamicCheckValue] = useState(Math.random());

        return (
            <>
                <div><h3>No Update</h3>
                    <EffectCheck value={checkValue}/>
                </div>
                <div><h3>New Update</h3>
                    <EffectCheck value={dynamicCheckValue}/>
                </div>
                <button onClick={() => setCheckValue('Math.random()')}> No Update</button>
                <button onClick={() => setdyamicCheckValue(Math.random())}> New Update</button>
            </>
        );
    }

</code>```

Body:
I am using a useEffect hook to make an API call depending on data from a photos prop being passed in.

const ImageCarousel = ({ src, photos }) => {
  const [photoList, setPhotos] = useState([]);
  const storageRef = firebase.storage().ref();
  console.log("photos prop:", photos);

  const getImage = photoId => {
    return new Promise((resolve, reject) => {
      storageRef
        .child("images/" + photoId)
        .getDownloadURL()
        .then(url => resolve(url))
        .catch(error => reject(error));
    });
  };

  useEffect(() => {
    console.log("trigger");
    Promise.all(
      photos.map(async photoId => {
        const url = await getImage(photoId);
        return url;
      })
    )
      .then(photoUrls => {
        setPhotos(photoUrls);
      })
      .catch(e => console.log(e));
  }, [photos]);

return (...)
}

I have passed the photos prop into the dependency array of my useEffect hook, so it should fire when the photos prop changes. I can see that the prop is indeed changing in the console, but my useEffect hook does not fire when the prop change comes through. This is what appears in my console:

Why is the useEffect not firing twice? From my understanding it should fire when the component renders the first time, and fire again every time the photos prop changes.

Body:
useEffect will update if you pass the new data, find the sample code below and check the console.log.

    import React, { useState, useEffect } from "react";

    const EffectCheck = ({value}) => {
        console.log('Component Trigger', value);
        useEffect(() => {
            console.log('Updated Effect', value);
        },[value]);

        return (
            <div>{value}</div>
        )
    }

    export default function() {
        const [checkValue, setCheckValue] = useState(Math.random());
        const [dynamicCheckValue, setdyamicCheckValue] = useState(Math.random());

        return (
            <>
                <div><h3>No Update</h3>
                    <EffectCheck value={checkValue}/>
                </div>
                <div><h3>New Update</h3>
                    <EffectCheck value={dynamicCheckValue}/>
                </div>
                <button onClick={() => setCheckValue('Math.random()')}> No Update</button>
                <button onClick={() => setdyamicCheckValue(Math.random())}> New Update</button>
            </>
        );
    }


问:
Script EF6 Migrations in Azure Devops
I have an EF6 project that I would like to generate a script for migrations. Locally, I just run update-database - script, but I would like to create a build pipeline that generates a script for this, and later a deployment pipeline that executes this script when we are ready to push to different environments. Is there anyway to generate such a script in an Azure Devops Build Pipeline?

答:
For this issue , you can try Entity Framework Migration Extensions.

This task allows a Build / Release to provide database connection parameters and execute an Entity Framework 6 migration against the database.

In order to this Task, you'll have to take the following steps:

Build your project to an output folder and include the migrate.exe
executable that comes with Entity Framework 6.

Create an automated build that packages up your files and makes them
accessible during a Release.

Create a Release definition for the relevant Build

Add an EF6 Migration task. Once that task is added to an environment
within the release, you'll need to enter the appropriate parameters
to configure it. All file path parameters should be within the file
system for the build, none of them are for TFS source control paths.

Title: Script EF6 Migrations in Azure Devops


问:
Draw circle of certain radius on map view in Android
I want to draw a circle on map view. I want the user to input the radius and for that radius I have to show circle on map. After that I have to display markers on some locations on that circle.

I know how to display markers on on  map view.

How can I draw circle on map view  and to show markers on that circle boundary.

答:
If you put the following code in your overlay's draw method, it will draw a circle  radius 20 px in the centre of your mapView

```<code>@Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
    ....
    ....

    Paint lp4;
    lp4 = new Paint();
    lp4.setColor(Color.RED);
    lp4.setAntiAlias(true);
    lp4.setStyle(Style.STROKE);
    canvas.drawCircle(mapView.getWidth()/2, mapView.getHeight()/2, 20, lp4);

    ....
    ....
    mapView.invalidate();
}
</code>```

You should be able to adapt it to suit your needs

Body:
If you put the following code in your overlay's draw method, it will draw a circle  radius 20 px in the centre of your mapView

@Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
    ....
    ....

    Paint lp4;
    lp4 = new Paint();
    lp4.setColor(Color.RED);
    lp4.setAntiAlias(true);
    lp4.setStyle(Style.STROKE);
    canvas.drawCircle(mapView.getWidth()/2, mapView.getHeight()/2, 20, lp4);

    ....
    ....
    mapView.invalidate();
}

You should be able to adapt it to suit your needs

ContentLicense: CC BY-SA 3.0


问:
Issue with DVWA website displaying
After DVWA worked perfectly, a few days later, the website is displayed like this:

Instead of:

I tried to remove and recreate the SQL database, re-download DVWA files, checked apache2 and DVWA configuration files (attached), but did not find any problem.

Can anyone point out the problem?

/etc/apache2/apache2.conf

```<code># This is the main Apache server configuration file.  It contains the
# configuration directives that give the server its instructions.
# See http://httpd.apache.org/docs/2.4/ for detailed information about
# the directives and /usr/share/doc/apache2/README.Debian about Debian specific
# hints.
#
#
# Summary of how the Apache 2 configuration works in Debian:
# The Apache 2 web server configuration in Debian is quite different to
# upstream's suggested way to configure the web server. This is because Debian's
# default Apache2 installation attempts to make adding and removing modules,
# virtual hosts, and extra configuration directives as flexible as possible, in
# order to make automating the changes and administering the server as easy as
# possible.

# It is split into several files forming the configuration hierarchy outlined
# below, all located in the /etc/apache2/ directory:
#
#   /etc/apache2/
#   |-- apache2.conf
#   |   `--  ports.conf
#   |-- mods-enabled
#   |   |-- *.load
#   |   `-- *.conf
#   |-- conf-enabled
#   |   `-- *.conf
#   `-- sites-enabled
#       `-- *.conf
#
#
# * apache2.conf is the main configuration file (this file). It puts the pieces
#   together by including all remaining configuration files when starting up the
#   web server.
#
# * ports.conf is always included from the main configuration file. It is
#   supposed to determine listening ports for incoming connections which can be
#   customized anytime.
#
# * Configuration files in the mods-enabled/, conf-enabled/ and sites-enabled/
#   directories contain particular configuration snippets which manage modules,
#   global configuration fragments, or virtual host configurations,
#   respectively.
#
#   They are activated by symlinking available configuration files from their
#   respective *-available/ counterparts. These should be managed by using our
#   helpers a2enmod/a2dismod, a2ensite/a2dissite and a2enconf/a2disconf. See
#   their respective man pages for detailed information.
#
# * The binary is called apache2. Due to the use of environment variables, in
#   the default configuration, apache2 needs to be started/stopped with
#   /etc/init.d/apache2 or apache2ctl. Calling /usr/bin/apache2 directly will not
#   work with the default configuration.

# Global configuration
#

#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# NOTE!  If you intend to place this on an NFS (or otherwise network)
# mounted filesystem then please read the Mutex documentation (available
# at <URL:http://httpd.apache.org/docs/2.4/mod/core.html#mutex>);
# you will save yourself a lot of trouble.
#
# Do NOT add a slash at the end of the directory path.
#
#ServerRoot "/etc/apache2"

#
# The accept serialization lock file MUST BE STORED ON A LOCAL DISK.
#
#Mutex file:${APACHE_LOCK_DIR} default

#
# PidFile: The file in which the server should record its process
# identification number when it starts.
# This needs to be set in /etc/apache2/envvars
#
PidFile ${APACHE_PID_FILE}

#
# Timeout: The number of seconds before receives and sends time out.
#
Timeout 300

#
# KeepAlive: Whether or not to allow persistent connections (more than
# one request per connection). Set to "Off" to deactivate.
#
KeepAlive On

#
# MaxKeepAliveRequests: The maximum number of requests to allow
# during a persistent connection. Set to 0 to allow an unlimited amount.
# We recommend you leave this number high, for maximum performance.
#
MaxKeepAliveRequests 100

#
# KeepAliveTimeout: Number of seconds to wait for the next request from the
# same client on the same connection.
#
KeepAliveTimeout 5

# These need to be set in /etc/apache2/envvars
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}

#
# HostnameLookups: Log the names of clients or just their IP addresses
# e.g., www.apache.org (on) or 204.62.129.132 (off).
# The default is off because it'd be overall better for the net if people
# had to knowingly turn this feature on, since enabling it means that
# each client request will result in AT LEAST one lookup request to the
# nameserver.
#
HostnameLookups Off

# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here.  If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog ${APACHE_LOG_DIR}/error.log

#
# LogLevel: Control the severity of messages logged to the error_log.
# Available values: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the log level for particular modules, e.g.
# "LogLevel info ssl:warn"
#
LogLevel warn

# Include module configuration:
IncludeOptional mods-enabled/*.load
IncludeOptional mods-enabled/*.conf

# Include list of ports to listen on
Include ports.conf

# Sets the default security model of the Apache2 HTTPD server. It does
# not allow access to the root filesystem outside of /usr/share and /var/www.
# The former is used by web applications packaged in Debian,
# the latter may be used for local directories served by the web server. If
# your system is serving content from a sub-directory in /srv you must allow
# access here, or in any related virtual host.
<Directory />
    Options FollowSymLinks
    AllowOverride None
    Require all denied
</Directory>

<Directory /usr/share>
    AllowOverride None
    Require all granted
</Directory>

<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

#<Directory /srv/>
#   Options Indexes FollowSymLinks
#   AllowOverride None
#   Require all granted
#</Directory>

# AccessFileName: The name of the file to look for in each directory
# for additional configuration directives.  See also the AllowOverride
# directive.
#
AccessFileName .htaccess

#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<FilesMatch "^\.ht">
    Require all denied
</FilesMatch>

#
# The following directives define some format nicknames for use with
# a CustomLog directive.
#
# These deviate from the Common Log Format definitions in that they use %O
# (the actual bytes sent including headers) instead of %b (the size of the
# requested file), because the latter makes it impossible to detect partial
# requests.
#
# Note that the use of %{X-Forwarded-For}i instead of %h is not recommended.
# Use mod_remoteip instead.
#
LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent

# Include of directories ignores editors' and dpkg's backup files,
# see README.Debian for details.

# Include generic snippets of statements
IncludeOptional conf-enabled/*.conf

# Include the virtual host configurations:
IncludeOptional sites-enabled/*.conf

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
</code>```

/var/www/html/dvwa/config/config.inc.php

```<code><?php

# If you are having problems connecting to the MySQL database and all of the variables below are correct

# try changing the 'db_server' variable from localhost to 127.0.0.1. Fixes a problem due to sockets.

#   Thanks to @digininja for the fix.

# Database management system to use

$DBMS = 'MySQL';

#$DBMS = 'PGSQL'; // Currently disabled

# Database variables

#   WARNING: The database specified under db_database WILL BE ENTIRELY DELETED during setup.

#   Please use a database dedicated to DVWA.

$_DVWA = array();

$_DVWA[ 'db_server' ]   = 'localhost';

$_DVWA[ 'db_database' ] = 'dvwa';

$_DVWA[ 'db_user' ]     = 'root';

$_DVWA[ 'db_password' ] = '';

# Only used with PostgreSQL/PGSQL database selection.

$_DVWA[ 'db_port '] = '5432';

# ReCAPTCHA settings

#   Used for the 'Insecure CAPTCHA' module

#   You'll need to generate your own keys at: https://www.google.com/recaptcha/admin/create

$_DVWA[ 'recaptcha_public_key' ]  = '';

$_DVWA[ 'recaptcha_private_key' ] = '';

# Default security level

#   Default value for the secuirty level with each session.

#   The default is 'impossible'. You may wish to set this to either 'low', 'medium', 'high' or impossible'.

$_DVWA[ 'default_security_level' ] = 'impossible';

# Default PHPIDS status

#   PHPIDS status with each session.

#   The default is 'disabled'. You can set this to be either 'enabled' or 'disabled'.

$_DVWA[ 'default_phpids_level' ] = 'disabled';

# Verbose PHPIDS messages

#   Enabling this will show why the WAF blocked the request on the blocked request.

#   The default is 'disabled'. You can set this to be either 'true' or 'false'.

$_DVWA[ 'default_phpids_verbose' ] = 'false';

?>
</code>```

THANKS!!

答:
php7.3 worked for me</p>

```<code>$ sudo apt-get install php7.3 libapache2-mod-php7.3

$ sudo a2enmod php7.3

$ service apache2 restart
</code>```

Title: Issue with DVWA website displaying

Body:
After DVWA worked perfectly, a few days later, the website is displayed like this:

Instead of:

I tried to remove and recreate the SQL database, re-download DVWA files, checked apache2 and DVWA configuration files (attached), but did not find any problem.

Can anyone point out the problem?

/etc/apache2/apache2.conf

# This is the main Apache server configuration file.  It contains the
# configuration directives that give the server its instructions.
# See http://httpd.apache.org/docs/2.4/ for detailed information about
# the directives and /usr/share/doc/apache2/README.Debian about Debian specific
# hints.
#
#
# Summary of how the Apache 2 configuration works in Debian:
# The Apache 2 web server configuration in Debian is quite different to
# upstream's suggested way to configure the web server. This is because Debian's
# default Apache2 installation attempts to make adding and removing modules,
# virtual hosts, and extra configuration directives as flexible as possible, in
# order to make automating the changes and administering the server as easy as
# possible.

# It is split into several files forming the configuration hierarchy outlined
# below, all located in the /etc/apache2/ directory:
#
#   /etc/apache2/
#   |-- apache2.conf
#   |   `--  ports.conf
#   |-- mods-enabled
#   |   |-- *.load
#   |   `-- *.conf
#   |-- conf-enabled
#   |   `-- *.conf
#   `-- sites-enabled
#       `-- *.conf
#
#
# * apache2.conf is the main configuration file (this file). It puts the pieces
#   together by including all remaining configuration files when starting up the
#   web server.
#
# * ports.conf is always included from the main configuration file. It is
#   supposed to determine listening ports for incoming connections which can be
#   customized anytime.
#
# * Configuration files in the mods-enabled/, conf-enabled/ and sites-enabled/
#   directories contain particular configuration snippets which manage modules,
#   global configuration fragments, or virtual host configurations,
#   respectively.
#
#   They are activated by symlinking available configuration files from their
#   respective *-available/ counterparts. These should be managed by using our
#   helpers a2enmod/a2dismod, a2ensite/a2dissite and a2enconf/a2disconf. See
#   their respective man pages for detailed information.
#
# * The binary is called apache2. Due to the use of environment variables, in
#   the default configuration, apache2 needs to be started/stopped with
#   /etc/init.d/apache2 or apache2ctl. Calling /usr/bin/apache2 directly will not
#   work with the default configuration.

# Global configuration
#

#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# NOTE!  If you intend to place this on an NFS (or otherwise network)
# mounted filesystem then please read the Mutex documentation (available
# at <URL:http://httpd.apache.org/docs/2.4/mod/core.html#mutex>);
# you will save yourself a lot of trouble.
#
# Do NOT add a slash at the end of the directory path.
#
#ServerRoot "/etc/apache2"

#
# The accept serialization lock file MUST BE STORED ON A LOCAL DISK.
#
#Mutex file:${APACHE_LOCK_DIR} default

#
# PidFile: The file in which the server should record its process
# identification number when it starts.
# This needs to be set in /etc/apache2/envvars
#
PidFile ${APACHE_PID_FILE}

#
# Timeout: The number of seconds before receives and sends time out.
#
Timeout 300

#
# KeepAlive: Whether or not to allow persistent connections (more than
# one request per connection). Set to "Off" to deactivate.
#
KeepAlive On

#
# MaxKeepAliveRequests: The maximum number of requests to allow
# during a persistent connection. Set to 0 to allow an unlimited amount.
# We recommend you leave this number high, for maximum performance.
#
MaxKeepAliveRequests 100

#
# KeepAliveTimeout: Number of seconds to wait for the next request from the
# same client on the same connection.
#
KeepAliveTimeout 5

# These need to be set in /etc/apache2/envvars
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}

#
# HostnameLookups: Log the names of clients or just their IP addresses
# e.g., www.apache.org (on) or 204.62.129.132 (off).
# The default is off because it'd be overall better for the net if people
# had to knowingly turn this feature on, since enabling it means that
# each client request will result in AT LEAST one lookup request to the
# nameserver.
#
HostnameLookups Off

# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here.  If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog ${APACHE_LOG_DIR}/error.log

#
# LogLevel: Control the severity of messages logged to the error_log.
# Available values: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the log level for particular modules, e.g.
# "LogLevel info ssl:warn"
#
LogLevel warn

# Include module configuration:
IncludeOptional mods-enabled/*.load
IncludeOptional mods-enabled/*.conf

# Include list of ports to listen on
Include ports.conf

# Sets the default security model of the Apache2 HTTPD server. It does
# not allow access to the root filesystem outside of /usr/share and /var/www.
# The former is used by web applications packaged in Debian,
# the latter may be used for local directories served by the web server. If
# your system is serving content from a sub-directory in /srv you must allow
# access here, or in any related virtual host.
<Directory />
    Options FollowSymLinks
    AllowOverride None
    Require all denied
</Directory>

<Directory /usr/share>
    AllowOverride None
    Require all granted
</Directory>

<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

#<Directory /srv/>
#   Options Indexes FollowSymLinks
#   AllowOverride None
#   Require all granted
#</Directory>

# AccessFileName: The name of the file to look for in each directory
# for additional configuration directives.  See also the AllowOverride
# directive.
#
AccessFileName .htaccess

#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<FilesMatch "^\.ht">
    Require all denied
</FilesMatch>

#
# The following directives define some format nicknames for use with
# a CustomLog directive.
#
# These deviate from the Common Log Format definitions in that they use %O
# (the actual bytes sent including headers) instead of %b (the size of the
# requested file), because the latter makes it impossible to detect partial
# requests.
#
# Note that the use of %{X-Forwarded-For}i instead of %h is not recommended.
# Use mod_remoteip instead.
#
LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent

# Include of directories ignores editors' and dpkg's backup files,
# see README.Debian for details.

# Include generic snippets of statements
IncludeOptional conf-enabled/*.conf

# Include the virtual host configurations:
IncludeOptional sites-enabled/*.conf

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

/var/www/html/dvwa/config/config.inc.php

<?php

# If you are having problems connecting to the MySQL database and all of the variables below are correct

# try changing the 'db_server' variable from localhost to 127.0.0.1. Fixes a problem due to sockets.

#   Thanks to @digininja for the fix.

# Database management system to use

$DBMS = 'MySQL';

#$DBMS = 'PGSQL'; // Currently disabled

# Database variables

#   WARNING: The database specified under db_database WILL BE ENTIRELY DELETED during setup.

#   Please use a database dedicated to DVWA.

$_DVWA = array();

$_DVWA[ 'db_server' ]   = 'localhost';

$_DVWA[ 'db_database' ] = 'dvwa';

$_DVWA[ 'db_user' ]     = 'root';

$_DVWA[ 'db_password' ] = '';

# Only used with PostgreSQL/PGSQL database selection.

$_DVWA[ 'db_port '] = '5432';

# ReCAPTCHA settings

#   Used for the 'Insecure CAPTCHA' module

#   You'll need to generate your own keys at: https://www.google.com/recaptcha/admin/create

$_DVWA[ 'recaptcha_public_key' ]  = '';

$_DVWA[ 'recaptcha_private_key' ] = '';

# Default security level

#   Default value for the secuirty level with each session.

#   The default is 'impossible'. You may wish to set this to either 'low', 'medium', 'high' or impossible'.

$_DVWA[ 'default_security_level' ] = 'impossible';

# Default PHPIDS status

#   PHPIDS status with each session.

#   The default is 'disabled'. You can set this to be either 'enabled' or 'disabled'.

$_DVWA[ 'default_phpids_level' ] = 'disabled';

# Verbose PHPIDS messages

#   Enabling this will show why the WAF blocked the request on the blocked request.

#   The default is 'disabled'. You can set this to be either 'true' or 'false'.

$_DVWA[ 'default_phpids_verbose' ] = 'false';

?>

THANKS!!

Body:
php7.3 worked for me

$ sudo apt-get install php7.3 libapache2-mod-php7.3

$ sudo a2enmod php7.3

$ service apache2 restart


问:
Regular expression: the string must contains sequence of words
I have such code:

        String regexp = "[\\w\\W]*(London)[\\w\\W]*(Paris)[\\w\\W]*";

        String test1 = "London Paris";
        boolean t1 =  Pattern.matches(regexp, test1);
        System.out.println(t1);

        String test2 = "London to Paris";
        boolean t2 =  Pattern.matches(regexp, test2);
        System.out.println(t2);

        String test3 = "from London to Paris";
        boolean t3 =  Pattern.matches(regexp, test3);
        System.out.println(t3);

        String test4 = "from (London) -> (Paris)";
        boolean t4 =  Pattern.matches(regexp, test4);
        System.out.println(t4);
```

I need all boolean to be true. Now, this condition is met, but the regex seems to me not too effective. How can I change this?

答:
You can go with something faster than a regex:

```<code>public static boolean isValid(String str) {
        int indexOfLondon = str.indexOf("London");
        int indexOfParis = str.indexOf("Paris");

        return indexOfLondon != -1 && indexOfParis != -1 && indexOfLondon < indexOfParis
    }
</code>```

Regex is avoidable here.

Body:
I have such code:

        String regexp = "[\\w\\W]*(London)[\\w\\W]*(Paris)[\\w\\W]*";

        String test1 = "London Paris";
        boolean t1 =  Pattern.matches(regexp, test1);
        System.out.println(t1);

        String test2 = "London to Paris";
        boolean t2 =  Pattern.matches(regexp, test2);
        System.out.println(t2);

        String test3 = "from London to Paris";
        boolean t3 =  Pattern.matches(regexp, test3);
        System.out.println(t3);

        String test4 = "from (London) -> (Paris)";
        boolean t4 =  Pattern.matches(regexp, test4);
        System.out.println(t4);

I need all boolean to be true. Now, this condition is met, but the regex seems to me not too effective. How can I change this?

Body:
You can go with something faster than a regex:

public static boolean isValid(String str) {
        int indexOfLondon = str.indexOf("London");
        int indexOfParis = str.indexOf("Paris");

        return indexOfLondon != -1 && indexOfParis != -1 && indexOfLondon < indexOfParis
    }

Regex is avoidable here.


问:
I have a method withdraw(); that doesnt work, any idea why?
My withdraw method doesnt work, maybe someone see things I dont see?

This is part of my abstract class Account and abstract method withdraw

```<code>import java.util.ArrayList;

public abstract class Account {
private String accountType;
private static double balance = 0;
protected int accountId;
private static int accountNumberCounter = 1000;
private ArrayList<Account> accounts;

public Account(String acType, int acNumber){
    accountType = acType;
    accountNumberCounter ++;
    accountId = accountNumberCounter;
}

public Account() {
    accountNumberCounter++;
    accountId = accountNumberCounter;
}

public abstract boolean withdraw(double value);
</code>```

This is SavingsAccount class and its method withdraw()

```<code>public class SavingsAccount extends Account {
private static double balance = 0;
private static final double RATE = 1.0;
private static  String accountType = "Savings Account";
private int accountId;

public SavingsAccount(){
    super();
}

public double getBalance(){
    return balance;
}

public void deposit(double amount){
    balance = balance + amount;
}

public boolean withdraw(double amount){
    if (balance<= amount){
        System.out.println("You have only" + amount + "left on your account.");
    return false;
    }
    else{
        balance -= amount;
        System.out.println("You took:" + amount);
        return true;
    }
}
</code>```

Method from BankLogic as well, I think this part should be correct:

```<code>  public boolean withdraw(String pNo, int accountId, double amount){
    for(Customer pers: customerList) {
        if (pers.getPersonalNumber().equals(pNo)) {
            for (Account account : pers.getAllAccounts()) {
                if (account.getAccountNumber() == accountId) {
                    account.withdraw(amount);
                }
            }
        }
    }
    return false;
}
</code>```

答:
You never return the result of the withdraw method.

Change the bank code to return the value from the account's withdraw method and it should be fine (as you already fix the static issue)

```<code>public boolean withdraw(String pNo, int accountId, double amount){
    for(Customer pers: customerList) {
        if (pers.getPersonalNumber().equals(pNo)) {
            for (Account account : pers.getAllAccounts()) {
                if (account.getAccountNumber() == accountId) {
                    return account.withdraw(amount); // return the account withdrawing value
                }
            }
        }
    }
    return false; // false as no account found if this line is reached
}
</code>```

Body:
My withdraw method doesnt work, maybe someone see things I dont see?

This is part of my abstract class Account and abstract method withdraw

import java.util.ArrayList;

public abstract class Account {
private String accountType;
private static double balance = 0;
protected int accountId;
private static int accountNumberCounter = 1000;
private ArrayList<Account> accounts;

public Account(String acType, int acNumber){
    accountType = acType;
    accountNumberCounter ++;
    accountId = accountNumberCounter;
}

public Account() {
    accountNumberCounter++;
    accountId = accountNumberCounter;
}

public abstract boolean withdraw(double value);

This is SavingsAccount class and its method withdraw()

public class SavingsAccount extends Account {
private static double balance = 0;
private static final double RATE = 1.0;
private static  String accountType = "Savings Account";
private int accountId;

public SavingsAccount(){
    super();
}

public double getBalance(){
    return balance;
}

public void deposit(double amount){
    balance = balance + amount;
}

public boolean withdraw(double amount){
    if (balance<= amount){
        System.out.println("You have only" + amount + "left on your account.");
    return false;
    }
    else{
        balance -= amount;
        System.out.println("You took:" + amount);
        return true;
    }
}

Method from BankLogic as well, I think this part should be correct:

  public boolean withdraw(String pNo, int accountId, double amount){
    for(Customer pers: customerList) {
        if (pers.getPersonalNumber().equals(pNo)) {
            for (Account account : pers.getAllAccounts()) {
                if (account.getAccountNumber() == accountId) {
                    account.withdraw(amount);
                }
            }
        }
    }
    return false;
}

Body:
You never return the result of the withdraw method.

Change the bank code to return the value from the account's withdraw method and it should be fine (as you already fix the static issue)

public boolean withdraw(String pNo, int accountId, double amount){
    for(Customer pers: customerList) {
        if (pers.getPersonalNumber().equals(pNo)) {
            for (Account account : pers.getAllAccounts()) {
                if (account.getAccountNumber() == accountId) {
                    return account.withdraw(amount); // return the account withdrawing value
                }
            }
        }
    }
    return false; // false as no account found if this line is reached
}


问:
Select concatenated value where two values match across the whole table
My apologies for such a simple question, I am usually relatively OK when applying SQL queries (thanks to StackOverflow) in my work however this one has me stumped.

I have an MS SQL table named [UKStaffList] with the following information in it...

```<code>EmployeeID | FirstName | LastName  | ManagedBy
----------------------------------------------
1001       | Robert    | Anderson  | 1004
1002       | Chris     | Thompson  | 1004
1003       | Mary      | Wright    | 1004
1004       | Andrew    | Denton    | 1005
1005       | Susan     | Rogers    | 1005
1006       | Michael   | Stevens   | 1007
1007       | Alice     | Lee       | 1005
1008       | John      | Clarke    | 1007
</code>```

I'd like to create a view that allows me to see the name of the Manager as well as the other information already in the table. The code below shows the final outcome that i'd like to see...

```<code>EmployeeID | FirstName | LastName  | ManagedBy | Manager
--------------------------------------------------------------
1001       | Robert    | Anderson  | 1004      | Andrew Denton
1002       | Chris     | Thompson  | 1004      | Andrew Denton
1003       | Mary      | Wright    | 1004      | Andrew Denton
1004       | Andrew    | Denton    | 1005      | Susan Rogers
1005       | Susan     | Rogers    | 1005      | Susan Rogers
1006       | Michael   | Stevens   | 1007      | Alice Lee
1007       | Alice     | Lee       | 1005      | Susan Rogers
1008       | John      | Clarke    | 1007      | Alice Lee
</code>```

I have tried the following query...

```<code>SELECT EmployeeID, FirstName, LastName, ManagedBy,
       CASE WHEN ManagedByID = EmployeeID THEN CONCAT(FirstName, ' ', LastName)
            ELSE 'N/A'
       END AS Manager
FROM UKStaffList
</code>```

However this only shows me the 5th row, where Susan Rogers is the manager of themselves and all other rows are N/A. From what I can see, the query is only looking for values where the ManagedBy and EmployeeID match on the same row.

```<code>EmployeeID | FirstName | LastName  | ManagedBy | Manager
--------------------------------------------------------------
1001       | Robert    | Anderson  | 1004      | N/A
1002       | Chris     | Thompson  | 1004      | N/A
1003       | Mary      | Wright    | 1004      | N/A
1004       | Andrew    | Denton    | 1005      | N/A
1005       | Susan     | Rogers    | 1005      | Susan Rogers
1006       | Michael   | Stevens   | 1007      | N/A
1007       | Alice     | Lee       | 1005      | N/A
1008       | John      | Clarke    | 1007      | N/A
</code>```

Ideally, I need to have a query that will show the managers name as a concatenation of their first and last names in a separate column where the ManagedBy column references their EmployeeID.

One caveat is that I need to keep all of the data in this one table.
I think I may need a nested query in this, but I'm not sure where to start.

Can anyone point out where I'm going wrong and provide some guidance?

Any help is greatly appreciated!

答:
As @jarlh commented you just have to join your table with itself, in order to join every employee with its manager.

Remember that when joining a table with itself you have to use aliases : they have the same columns so you will need to use aliases to differentiate the columns from the employees and the managers.

Like this:

```<code>SELECT Staff.EmployeeID, Staff.FirstName, Staff.LastName, Staff.ManagedBy,
       CONCAT(Managers.FirstName, ' ', Managers.LastName) AS Manager
FROM UKStaffList as Staff
     LEFT JOIN UKStaffList as Managers on Managers.EmployeeID = Staff.ManagedBy
</code>```

Body:
My apologies for such a simple question, I am usually relatively OK when applying SQL queries (thanks to StackOverflow) in my work however this one has me stumped.

I have an MS SQL table named [UKStaffList] with the following information in it...

EmployeeID | FirstName | LastName  | ManagedBy
----------------------------------------------
1001       | Robert    | Anderson  | 1004
1002       | Chris     | Thompson  | 1004
1003       | Mary      | Wright    | 1004
1004       | Andrew    | Denton    | 1005
1005       | Susan     | Rogers    | 1005
1006       | Michael   | Stevens   | 1007
1007       | Alice     | Lee       | 1005
1008       | John      | Clarke    | 1007

I'd like to create a view that allows me to see the name of the Manager as well as the other information already in the table. The code below shows the final outcome that i'd like to see...

EmployeeID | FirstName | LastName  | ManagedBy | Manager
--------------------------------------------------------------
1001       | Robert    | Anderson  | 1004      | Andrew Denton
1002       | Chris     | Thompson  | 1004      | Andrew Denton
1003       | Mary      | Wright    | 1004      | Andrew Denton
1004       | Andrew    | Denton    | 1005      | Susan Rogers
1005       | Susan     | Rogers    | 1005      | Susan Rogers
1006       | Michael   | Stevens   | 1007      | Alice Lee
1007       | Alice     | Lee       | 1005      | Susan Rogers
1008       | John      | Clarke    | 1007      | Alice Lee

I have tried the following query...

SELECT EmployeeID, FirstName, LastName, ManagedBy,
       CASE WHEN ManagedByID = EmployeeID THEN CONCAT(FirstName, ' ', LastName)
            ELSE 'N/A'
       END AS Manager
FROM UKStaffList

However this only shows me the 5th row, where Susan Rogers is the manager of themselves and all other rows are N/A. From what I can see, the query is only looking for values where the ManagedBy and EmployeeID match on the same row.

EmployeeID | FirstName | LastName  | ManagedBy | Manager
--------------------------------------------------------------
1001       | Robert    | Anderson  | 1004      | N/A
1002       | Chris     | Thompson  | 1004      | N/A
1003       | Mary      | Wright    | 1004      | N/A
1004       | Andrew    | Denton    | 1005      | N/A
1005       | Susan     | Rogers    | 1005      | Susan Rogers
1006       | Michael   | Stevens   | 1007      | N/A
1007       | Alice     | Lee       | 1005      | N/A
1008       | John      | Clarke    | 1007      | N/A

Ideally, I need to have a query that will show the managers name as a concatenation of their first and last names in a separate column where the ManagedBy column references their EmployeeID.

One caveat is that I need to keep all of the data in this one table.
I think I may need a nested query in this, but I'm not sure where to start.

Can anyone point out where I'm going wrong and provide some guidance?

Any help is greatly appreciated!

Body:
As @jarlh commented you just have to join your table with itself, in order to join every employee with its manager.

Remember that when joining a table with itself you have to use aliases : they have the same columns so you will need to use aliases to differentiate the columns from the employees and the managers.

Like this:

SELECT Staff.EmployeeID, Staff.FirstName, Staff.LastName, Staff.ManagedBy,
       CONCAT(Managers.FirstName, ' ', Managers.LastName) AS Manager
FROM UKStaffList as Staff
     LEFT JOIN UKStaffList as Managers on Managers.EmployeeID = Staff.ManagedBy


问:
Run Python-Script anywhere on Windows
I am looking for a way to run a python script from anywhere.

I have seen this solution but as it is based on Linux I am looking for a way on Windows (10).

Basically what I want to do is, execute a script with a given parameter. Because it could be disturbing for the user, I am using a .pyw-file extension to hide the console.

Things that came to my mind:

a PATH-Variable

PowerShell-Script

Batch-file

Sadly I am not familiar/experienced with neither of those, so I can't really tell if these ideas even provide a way to do that.

Any answer is appreciated.

Edit: I would like to make the command as short as possible for the client so it is not necessary to write a novel to exec one simple task.

Another Edit:
I want the user/client to open its cmd/ps and use a command which executes my python-script, which is not in this directory he is, when opening the cmd. So the script is somewhere on his computer, but shall be executable by command from anywhere.

答: try to create a "code.bat" file with this command "python script.py" inside your .bat file then add the "code.bat" to your path in your environments anytime you want to run the script just type code in your shell.</p>

Title: Run Python-Script anywhere on Windows


问:
Regex for positive float numbers
For example:

10

0.1

1.23234

123.123

0.000001

1.000

.3

And wrong examples:

0001.2

-12

-1.01

+2.3

EDIT: standart JavaScript regex.

答:
This will pass all your test cases, multi-line mode enabled:

```<code>/^(?!0\d)\d*(\.\d+)?$/mg
</code>```

Explanation:

```<code>/^              # start of regex and match start of line
(?!0\d)         # not any number with leading zeros
\d*             # consume and match optional digits
(\.\d+)?        # followed by a decimal and some digits after, optional.
$               # match end of line
/mg             # end of regex, match multi-line, global match
</code>```

RegExr: http://regexr.com?2tpd0

Title: Regex for positive float numbers

Body:
This will pass all your test cases, multi-line mode enabled:

/^(?!0\d)\d*(\.\d+)?$/mg

Explanation:

/^              # start of regex and match start of line
(?!0\d)         # not any number with leading zeros
\d*             # consume and match optional digits
(\.\d+)?        # followed by a decimal and some digits after, optional.
$               # match end of line
/mg             # end of regex, match multi-line, global match

RegExr: http://regexr.com?2tpd0


问:
How to fetch odd columns in oracle
How to fetch odd columns in Oracle using a query when number of columns and name of columns are not known?
E.g.:
I need to get output in below format

Column1  column3  column5  column7
And so on....

答:
This cannot be done simply, but it is possible using the Oracle data dictionary and some dynamic SQL.

To find out the odd-numbered columns you need to look at the ALL_TAB_COLUMNS view.  Column COLUMN_ID sequences the columns 1,2,3.  So this will find all the odd-numbered columns in the SCOTT.EMP table:

```<code>select column_name, column_id
from all_tab_columns
where owner = 'SCOTT'
and table_name = 'EMP'
and mod(column_id,2) = 1
order by column_id;
</code>```

This will return something like:

```<code>COLUMN_NAME  COLUMN_ID
-----------  ---------
EMPNO                1
JOB                  3
HIREDATE             5
COMM                 7
</code>```

We can use the LISTAGG function to make that into a comma-separated list:

```<code>select listagg(column_name,',') within group (order by column_id) as result
from user_tab_columns
where table_name = 'EMP'
and mod(column_id,2) = 1;

RESULT
------
EMPNO,JOB,HIREDATE,COMM
</code>```

Now we can add to that SQL to generate the select statement you want:

```<code>select 'select ' || listagg(column_name,',') within group (order by column_id) || ' from ' || table_name as sql
from user_tab_columns
where table_name = 'EMP'
and mod(column_id,2) = 1
group by table_name;

SQL
---
select EMPNO,JOB,HIREDATE,COMM from EMP
</code>```

(Note I had to add a group by clause because table_name is not being aggregated by LISTAGG).

You could use that SQL within some PL/SQL code to populate a variable v_sql, then use the DBMS_SQL package to run it.  But that is a complex topic in itself and I won't go into it here.

Title: How to fetch odd columns in oracle

Body:
This cannot be done simply, but it is possible using the Oracle data dictionary and some dynamic SQL.

To find out the odd-numbered columns you need to look at the ALL_TAB_COLUMNS view.  Column COLUMN_ID sequences the columns 1,2,3.  So this will find all the odd-numbered columns in the SCOTT.EMP table:

select column_name, column_id
from all_tab_columns
where owner = 'SCOTT'
and table_name = 'EMP'
and mod(column_id,2) = 1
order by column_id;

This will return something like:

COLUMN_NAME  COLUMN_ID
-----------  ---------
EMPNO                1
JOB                  3
HIREDATE             5
COMM                 7

We can use the LISTAGG function to make that into a comma-separated list:

select listagg(column_name,',') within group (order by column_id) as result
from user_tab_columns
where table_name = 'EMP'
and mod(column_id,2) = 1;

RESULT
------
EMPNO,JOB,HIREDATE,COMM

Now we can add to that SQL to generate the select statement you want:

select 'select ' || listagg(column_name,',') within group (order by column_id) || ' from ' || table_name as sql
from user_tab_columns
where table_name = 'EMP'
and mod(column_id,2) = 1
group by table_name;

SQL
---
select EMPNO,JOB,HIREDATE,COMM from EMP

(Note I had to add a group by clause because table_name is not being aggregated by LISTAGG).

You could use that SQL within some PL/SQL code to populate a variable v_sql, then use the DBMS_SQL package to run it.  But that is a complex topic in itself and I won't go into it here.


问:
Flutter pdf download from server
I am trying to download files from nodejs server. But when I implement onTap method on the gridview, it automatically runs the onTap function on start and every file starts downloading. I cannot figure out what am I doing wrong.Here is a preview of my code. I have implemented streambuilder to fetch the data.

```<code>GridView.builder(
                padding: EdgeInsets.all(10),
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 2,
                    crossAxisSpacing: 10,
                    mainAxisSpacing: 10,
                    childAspectRatio: 0.9),
                itemCount: snapshot.data.data.length,
                itemBuilder: (context, i) {
                  return Container(
                    padding: EdgeInsets.all(10),
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(20),
                        color: Colors.blue.withOpacity(0.3)),
                    child: Column(
                      children: <Widget>[
                        Container(
                          height: 50,
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(20),
                              image: DecorationImage(
                                  image: AssetImage('assets/pdf_icon.png'))),
                        ),
                        Divider(),
                        for (var items in snapshot.data.data[i].attachments)
                          ResourceDetail(
                            name: snapshot.data.data[i].title,
                            author: snapshot.data.data[i].user.name,
                            onTap: downloadFile(
                                'url/api/${items.source}',
                                snapshot.data.data[i].title,
                                items.extension),
                          ),
                      ],
                    ),
                  );
                },
              );
</code>```

Here is download file method.

```<code>Future<void> downloadFile(
      String url, String fileName, String extension) async {
    var dio = new Dio();
    var dir = await getExternalStorageDirectory();
    var downloadDir =
        await new io.Directory('${dir.path}/downloads').create(recursive: true);
    io.File('${downloadDir.path}/$fileName.$extension').exists().then((a) async {
      print(a);
      if (a) {
        print("Opening file");
        showDialog(
            context: context,
            builder: (_) {
              return AlertDialog(
                backgroundColor: Color(0xff5b8c85),
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10)),
                title: Text('File is already downloaded'),
                actions: <Widget>[
                  FlatButton(
                      child: Text(
                        'Open',
                        style: TextStyle(color: Colors.white),
                      ),
                      onPressed: () {
                        OpenFile.open('${downloadDir.path}/$fileName.$extension');
                        Navigator.pop(context);
                      })
                ],
              );
            });
        return;
      } else {
        print("Downloading file");
        openDialog();
        await dio.download(url, '${downloadDir.path}/$fileName.$extension',
            onReceiveProgress: (rec, total) {
          if (mounted) {
            setState(() {
              progressValue = (rec / total);
              progressString = ((rec / total) * 100).toStringAsFixed(0) + "%";
              myDialogState.setState(() {
                myDialogState.progressData = progressString;
                myDialogState.progressValue = progressValue;
              });
            });
          }
        });
        if (mounted) {
          setState(() {
            print('${downloadDir.path}');
          });
        }
        print("Download completed");
      }
    });
  }
</code>```

答:
The ResourceDetails in your GridView.builder, try replacing the onTap to this</p>

```<code>onTap: ()=>downloadFile(
    'url/api/${items.source}',
    snapshot.data.data[i].title,
    items.extension)
</code>```

Title: Flutter pdf download from server

Body:
I am trying to download files from nodejs server. But when I implement onTap method on the gridview, it automatically runs the onTap function on start and every file starts downloading. I cannot figure out what am I doing wrong.Here is a preview of my code. I have implemented streambuilder to fetch the data.

GridView.builder(
                padding: EdgeInsets.all(10),
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 2,
                    crossAxisSpacing: 10,
                    mainAxisSpacing: 10,
                    childAspectRatio: 0.9),
                itemCount: snapshot.data.data.length,
                itemBuilder: (context, i) {
                  return Container(
                    padding: EdgeInsets.all(10),
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(20),
                        color: Colors.blue.withOpacity(0.3)),
                    child: Column(
                      children: <Widget>[
                        Container(
                          height: 50,
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(20),
                              image: DecorationImage(
                                  image: AssetImage('assets/pdf_icon.png'))),
                        ),
                        Divider(),
                        for (var items in snapshot.data.data[i].attachments)
                          ResourceDetail(
                            name: snapshot.data.data[i].title,
                            author: snapshot.data.data[i].user.name,
                            onTap: downloadFile(
                                'url/api/${items.source}',
                                snapshot.data.data[i].title,
                                items.extension),
                          ),
                      ],
                    ),
                  );
                },
              );

Here is download file method.

Future<void> downloadFile(
      String url, String fileName, String extension) async {
    var dio = new Dio();
    var dir = await getExternalStorageDirectory();
    var downloadDir =
        await new io.Directory('${dir.path}/downloads').create(recursive: true);
    io.File('${downloadDir.path}/$fileName.$extension').exists().then((a) async {
      print(a);
      if (a) {
        print("Opening file");
        showDialog(
            context: context,
            builder: (_) {
              return AlertDialog(
                backgroundColor: Color(0xff5b8c85),
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10)),
                title: Text('File is already downloaded'),
                actions: <Widget>[
                  FlatButton(
                      child: Text(
                        'Open',
                        style: TextStyle(color: Colors.white),
                      ),
                      onPressed: () {
                        OpenFile.open('${downloadDir.path}/$fileName.$extension');
                        Navigator.pop(context);
                      })
                ],
              );
            });
        return;
      } else {
        print("Downloading file");
        openDialog();
        await dio.download(url, '${downloadDir.path}/$fileName.$extension',
            onReceiveProgress: (rec, total) {
          if (mounted) {
            setState(() {
              progressValue = (rec / total);
              progressString = ((rec / total) * 100).toStringAsFixed(0) + "%";
              myDialogState.setState(() {
                myDialogState.progressData = progressString;
                myDialogState.progressValue = progressValue;
              });
            });
          }
        });
        if (mounted) {
          setState(() {
            print('${downloadDir.path}');
          });
        }
        print("Download completed");
      }
    });
  }

Body:
The ResourceDetails in your GridView.builder, try replacing the onTap to this

onTap: ()=>downloadFile(
    'url/api/${items.source}',
    snapshot.data.data[i].title,
    items.extension)


问:
Is there a simpler function or one liner to check if folder exists if not create it and paste a specific file into it?
I am aiming to create a function that does the following:

Declare a path with a file, not just a folder. e.g. 'C:/Users/Lampard/Desktop/Folder1/File.py'

Create a folder in same folder as the declared file path - Calling it 'Archive'

Cut the file and paste it into the new folder just created.

If the folder 'Archive' already exists - then simply cut and paste the file into there

I have spent approx. 15-20min going through these:

https://www.programiz.com/python-programming/directory

Join all except last x in list

https://docs.python.org/3/library/pathlib.html#operators

And here is what I got to:

```<code>import os
from pathlib import Path, PurePath
from shutil import copy

#This path will change every time - just trying to get function right first
path = 'C:/Users/Lampard/Desktop/Folder1/File.py'

#Used to allow suffix function
p = PurePath(path)

#Check if directory is a file not a folder
if not p.suffix:
    print("Not an extension")

#If it is a file
else:
    #Create new folder before last file
    #Change working directory
    split = path.split('/')
    new_directory = '/'.join(split[:-1])
    apply_new_directory = os.chdir(new_directory)
    #If folder does not exist create it
    try:
        os.mkdir('Archive')#Create new folder
    #If not, continue process to copy file and paste it into Archive
    except FileExistsError:
        copy(path, new_directory + '/Archive/' + split[-1])
</code>```

Is this code okay? - does anyone know a simpler method?

答:
Locate folder/file in path

```<code>print [name for name in os.listdir(".") if os.path.isdir(name)]
</code>```

Create path

```<code>    import os

# define the name of the directory to be created
path = "/tmp/year"

try:
    os.mkdir(path)
except OSError:
    print ("Creation of the directory %s failed" % path)
else:
    print ("Successfully created the directory %s " % path)
</code>```

To move and cut files you can use this library

Body:
I am aiming to create a function that does the following:

Declare a path with a file, not just a folder. e.g. 'C:/Users/Lampard/Desktop/Folder1/File.py'

Create a folder in same folder as the declared file path - Calling it 'Archive'

Cut the file and paste it into the new folder just created.

If the folder 'Archive' already exists - then simply cut and paste the file into there

I have spent approx. 15-20min going through these:

https://www.programiz.com/python-programming/directory

Join all except last x in list

https://docs.python.org/3/library/pathlib.html#operators

And here is what I got to:

import os
from pathlib import Path, PurePath
from shutil import copy

#This path will change every time - just trying to get function right first
path = 'C:/Users/Lampard/Desktop/Folder1/File.py'

#Used to allow suffix function
p = PurePath(path)

#Check if directory is a file not a folder
if not p.suffix:
    print("Not an extension")

#If it is a file
else:
    #Create new folder before last file
    #Change working directory
    split = path.split('/')
    new_directory = '/'.join(split[:-1])
    apply_new_directory = os.chdir(new_directory)
    #If folder does not exist create it
    try:
        os.mkdir('Archive')#Create new folder
    #If not, continue process to copy file and paste it into Archive
    except FileExistsError:
        copy(path, new_directory + '/Archive/' + split[-1])

Is this code okay? - does anyone know a simpler method?

Body:
Locate folder/file in path

print [name for name in os.listdir(".") if os.path.isdir(name)]

Create path

    import os

# define the name of the directory to be created
path = "/tmp/year"

try:
    os.mkdir(path)
except OSError:
    print ("Creation of the directory %s failed" % path)
else:
    print ("Successfully created the directory %s " % path)

To move and cut files you can use this library


问:
Excel formula position of minimum value
EDIT: Likely an easy question, basically I have three values, let's say 9, 4 and 7 in different cells (not in a table), I want to find the minimum in an order then return its relative position, for example: 9,4,7 would return 2 as 4 is the minimum and is positioned second.

What is the correct excel formula to do so? Thanks .

Solution: Thanks all for your help, I didn't think excel could do if it wasn't continuous. I've ended up using a series of nested IF statements, an AND statement and < signs, to get the job done :)

答:
You can simply;

```<code>=ROUND(MIN(A1,B1,C1), 0)
</code>```

Ah, after clarification;

I can't think of a way to do that with a formula, it can be done with VBA (Assumes all numeric cells + the highest index is returned in the result of a clash)

```<code>=OrdinalMin(A2,B2,C2)

//in a module
Public Function OrdinalMin(ParamArray cells() As Variant) As Long
Dim i As Long, min As Double
For i = 0 To UBound(cells)
    If cells(i) <= cells(min) Then min = i
Next
OrdinalMin = min + 1
End Function
</code>```

Title: Excel formula position of minimum value

Body:
You can simply;

=ROUND(MIN(A1,B1,C1), 0)

Ah, after clarification;

I can't think of a way to do that with a formula, it can be done with VBA (Assumes all numeric cells + the highest index is returned in the result of a clash)

=OrdinalMin(A2,B2,C2)

//in a module
Public Function OrdinalMin(ParamArray cells() As Variant) As Long
Dim i As Long, min As Double
For i = 0 To UBound(cells)
    If cells(i) <= cells(min) Then min = i
Next
OrdinalMin = min + 1
End Function


问:
node-sql-parser , parser.astify(sqlquery) not returning exact output
I am trying to parse an sql query in nodejs using node-sql-parser.

```<code>const {Parser} = require('node-sql-parser');
const parser = new Parser();
const ast = parser.astify(sqlQuery)
</code>```

the sqluery used is below

```<code>SELECT * FROM SUBSCRIPTION WHERE COLUMN_1 = 'NORM' AND COLUMN_2 IN ('11','12','13','14','15','16','17','18','42','43','44','45','101','102','103','104','128','129','130','131','159') AND (COLUMN_3 IS NOT NULL OR COLUMN_4 = 1) AND COLUMN_5 <> 1 AND (COLUMN_6 <> '8088' AND COLUMN_7 <>  '9088')
</code>```

while parsing am getting the ouput

```<code>{ with: null,
  type: 'select',
  options: null,
  distinct: null,
  columns: '*',
  from: [ { db: null, table: 'SUBSCRIPTION', as: null } ],
  where:
   { type: 'binary_expr',
     operator: 'AND',
     left:
      { type: 'binary_expr',
        operator: 'AND',
        left: [Object],
        right: [Object] },
     right:
      { type: 'binary_expr',
        operator: 'AND',
        left: [Object],
        right: [Object],
        parentheses: true } },
  groupby: null,
  having: null,
  orderby: null,
  limit: null }
</code>```

Where I am not able to iterate through left:[Object].
Is there any way i can parse through this and only get a list of operators?

答:
You are logging it as an object that is why you see object in that. You need to JSON.stringify(ast) the object before consoling to see everything.

Regarding finding all the operators, you could use this code

```<code>
const sqlQuery = "SELECT * FROM SUBSCRIPTION WHERE COLUMN_1 = 'NORM' AND COLUMN_2 IN ('11','12','13','14','15','16','17','18','42','43','44','45','101','102','103','104','128','129','130','131','159') AND (COLUMN_3 IS NOT NULL OR COLUMN_4 = 1) AND COLUMN_5 <> 1 AND (COLUMN_6 <> '8088' AND COLUMN_7 <>  '9088')";
const {Parser} = require('node-sql-parser');
const parser = new Parser();
const ast = parser.astify(sqlQuery)

function getOperator(obj, result = []) {
  let value;
  Object.keys(obj).forEach(key => {
    value = obj[key];
    if (value instanceof Object) {
      getOperator(value, result);
    } else if (key === "operator") {
      result.push(value);
    }
  });
  return result;
}

console.log(getOperator(ast));

// output will be -  ["AND", "AND","AND","AND","=","IN","OR","IS NOT","=","<>","AND","<>","<>"]

</code>```

Body:
I am trying to parse an sql query in nodejs using node-sql-parser.

const {Parser} = require('node-sql-parser');
const parser = new Parser();
const ast = parser.astify(sqlQuery)

the sqluery used is below

SELECT * FROM SUBSCRIPTION WHERE COLUMN_1 = 'NORM' AND COLUMN_2 IN ('11','12','13','14','15','16','17','18','42','43','44','45','101','102','103','104','128','129','130','131','159') AND (COLUMN_3 IS NOT NULL OR COLUMN_4 = 1) AND COLUMN_5 <> 1 AND (COLUMN_6 <> '8088' AND COLUMN_7 <>  '9088')

while parsing am getting the ouput

{ with: null,
  type: 'select',
  options: null,
  distinct: null,
  columns: '*',
  from: [ { db: null, table: 'SUBSCRIPTION', as: null } ],
  where:
   { type: 'binary_expr',
     operator: 'AND',
     left:
      { type: 'binary_expr',
        operator: 'AND',
        left: [Object],
        right: [Object] },
     right:
      { type: 'binary_expr',
        operator: 'AND',
        left: [Object],
        right: [Object],
        parentheses: true } },
  groupby: null,
  having: null,
  orderby: null,
  limit: null }

Where I am not able to iterate through left:[Object].
Is there any way i can parse through this and only get a list of operators?

Body:
You are logging it as an object that is why you see object in that. You need to JSON.stringify(ast) the object before consoling to see everything.

Regarding finding all the operators, you could use this code

const sqlQuery = "SELECT * FROM SUBSCRIPTION WHERE COLUMN_1 = 'NORM' AND COLUMN_2 IN ('11','12','13','14','15','16','17','18','42','43','44','45','101','102','103','104','128','129','130','131','159') AND (COLUMN_3 IS NOT NULL OR COLUMN_4 = 1) AND COLUMN_5 <> 1 AND (COLUMN_6 <> '8088' AND COLUMN_7 <>  '9088')";
const {Parser} = require('node-sql-parser');
const parser = new Parser();
const ast = parser.astify(sqlQuery)

function getOperator(obj, result = []) {
  let value;
  Object.keys(obj).forEach(key => {
    value = obj[key];
    if (value instanceof Object) {
      getOperator(value, result);
    } else if (key === "operator") {
      result.push(value);
    }
  });
  return result;
}

console.log(getOperator(ast));

// output will be -  ["AND", "AND","AND","AND","=","IN","OR","IS NOT","=","<>","AND","<>","<>"]


问:
Mention multiple path based on existence in Linux
I have two different servers - core and bpm. I will be writing common script. In this case the path just varies on the name of the server as,

In Core server --> /apps/core/SharedLib/
and

In BPM server --> /apps/bpm/SharedLib/

So i have to mention path in same line and the server should decide based on the paths existence.

So i need something like,

```<code>cd /apps/<core|bpm>/SharedLib/
</code>```

How to mention it in correct way?

答:
I have solved similar problem with my servers using syntax: cd /apps/*/SharedLib/

Explanation:

* is wildcard character for bash. It's a regular expression. It looks for all the directories which is inside /apps but selects only that sub directory which has SharedLib inside it. You can run ls /apps/* and other ls commands to understand it's functionality completely

Hope it helps

Body:
I have two different servers - core and bpm. I will be writing common script. In this case the path just varies on the name of the server as,

In Core server --> /apps/core/SharedLib/
and

In BPM server --> /apps/bpm/SharedLib/

So i have to mention path in same line and the server should decide based on the paths existence.

So i need something like,

cd /apps/<core|bpm>/SharedLib/

How to mention it in correct way?


问:
Spark dataFrame taking too long to display after updating its columns
I have a dataFrame of approx. 4 million rows and 35 columns as input.

All I do to this dataFrame is the following steps:

For a list of given columns, I calculate a sum for a given list of group features and joined it as new column to my input dataFrame

I drop each new column sum right after I joined it to the dataFrame.

Therefore we end up with the same dataFrame as we started from (in theory).

However, I noticed that if my list of given columns gets too big (from more than 6 columns), the output dataFrame becomes impossible to manipulate. Even a simple display takes 10 minutes.

Here is an example of my code (df is my input dataFrame):

```<code>  for c in list_columns:
    df = df.join(df.groupby(list_group_features).agg(sum(c).alias('sum_' + c)), list_group_features)
    df = df.drop('sum_' + c)
</code>```

答:
This happens due to the inner workings of Spark and its lazy evaluation.

What Spark does when you call groupby, join, agg, it attaches these calls to the plan of the df object. So even though it is not executing anything on the data, you are creating a large execution plan which is internally stored in the Spark DataFrame object.

Only when you call an action (show, count, write, etc.), Spark optimizes the plan and executes it. If the plan is too large, the optimization step can take a while to perform. Also remember that the plan optimization is happening on the driver, not on the executors. So if your driver is busy or overloaded, it delays spark plan optimization step as well.

It is useful to remember that joins are expensive operations in Spark, both for optimization and execution. If you can, you should always avoid joins when operating on a single DataFrame and utilise the window functionality instead. Joins should only be used if you are joining different dataframes from different sources (different tables).

A way to optimize your code would be:

```<code>import pyspark
import pyspark.sql.functions as f

w = pyspark.sql.Window.partitionBy(list_group_features)
agg_sum_exprs = [f.sum(f.col(c)).alias("sum_" + c).over(w) for c in list_columns]
res_df = df.select(df.columns + agg_sum_exprs)
</code>```

This should be scalable and fast for large list_group_features and list_columns lists.

Body:
I have a dataFrame of approx. 4 million rows and 35 columns as input.

All I do to this dataFrame is the following steps:

For a list of given columns, I calculate a sum for a given list of group features and joined it as new column to my input dataFrame

I drop each new column sum right after I joined it to the dataFrame.

Therefore we end up with the same dataFrame as we started from (in theory).

However, I noticed that if my list of given columns gets too big (from more than 6 columns), the output dataFrame becomes impossible to manipulate. Even a simple display takes 10 minutes.

Here is an example of my code (df is my input dataFrame):

  for c in list_columns:
    df = df.join(df.groupby(list_group_features).agg(sum(c).alias('sum_' + c)), list_group_features)
    df = df.drop('sum_' + c)

Body:
This happens due to the inner workings of Spark and its lazy evaluation.

What Spark does when you call groupby, join, agg, it attaches these calls to the plan of the df object. So even though it is not executing anything on the data, you are creating a large execution plan which is internally stored in the Spark DataFrame object.

Only when you call an action (show, count, write, etc.), Spark optimizes the plan and executes it. If the plan is too large, the optimization step can take a while to perform. Also remember that the plan optimization is happening on the driver, not on the executors. So if your driver is busy or overloaded, it delays spark plan optimization step as well.

It is useful to remember that joins are expensive operations in Spark, both for optimization and execution. If you can, you should always avoid joins when operating on a single DataFrame and utilise the window functionality instead. Joins should only be used if you are joining different dataframes from different sources (different tables).

A way to optimize your code would be:

import pyspark
import pyspark.sql.functions as f

w = pyspark.sql.Window.partitionBy(list_group_features)
agg_sum_exprs = [f.sum(f.col(c)).alias("sum_" + c).over(w) for c in list_columns]
res_df = df.select(df.columns + agg_sum_exprs)

This should be scalable and fast for large list_group_features and list_columns lists.


问:
binding to observable collection silverlight 4, grid
Can I bind a simple 'grid' to an observable collection? So i have a grid with just one column and several rows. The rows get populated at runtime with some hyperlinks which can get deleted/added etc. I don't want to write functions to add/remove them from the grid everytime and would prefer to use an observable collection and let the grid update itself. Can a simple grid do that ? i tried but it didn't even compile.

Thanks

[EDIT] Solved. The marked answer is correct [/EDIT]

答: @ColinE is correct, you can't bind to a Grid, but you can bind an ObservableCollection to a DataGrid or an ItemsControl.


问:
Is it possible to define a 'move-and-swap idiom' equivalent in C++03
I'm bound to C++03 and I have a non-copyable object (e.g. holding a resource).

I need to use move-and-swap semantics to be able to do something similar and avoid copies:

```<code>MyClass returnMyClass(void)
{
    MyClass temp;
    // fill 'temp' members with actual data
    return temp;
}

int main(void)
{
    MyClass test;
    test = returnMyClass(); // need to avoid copies
}
</code>```

Is it possible to respect all these requirements in C++03?

It is basically the same case of this, but for C++03.

To put the question in other words:

Given a non-copyable class MyClass, is it somehow possible in C++03 to do MyClass test = returnMyClass();?

I'm afraid the answer is simply no, but maybe I'm missing some trick.

答:
There is no magic in move semantics. It's just another overload. The rvalue reference thing is a nice convenience that is not really essential.

```<code>template <class T>
struct rref {
    rref (T& t) : t(t) {}
    T& t;
};

template<class T>
rref<T> move(const T& t) {
   return rref<T>(const_cast<T&>(t));
}

// you now can do a "move ctor"
class Foo {
   Foo(rref<Foo>) { ... }
};
</code>```

Now you also need NRVO to kick in for this to work. It is not guaranteed by the standard, but it is provided by pretty much every implementation. To ensure it really happens, you may declare but not define a copy ctor.

Full working demo

Body:
I'm bound to C++03 and I have a non-copyable object (e.g. holding a resource).

I need to use move-and-swap semantics to be able to do something similar and avoid copies:

MyClass returnMyClass(void)
{
    MyClass temp;
    // fill 'temp' members with actual data
    return temp;
}

int main(void)
{
    MyClass test;
    test = returnMyClass(); // need to avoid copies
}

Is it possible to respect all these requirements in C++03?

It is basically the same case of this, but for C++03.

To put the question in other words:

Given a non-copyable class MyClass, is it somehow possible in C++03 to do MyClass test = returnMyClass();?

I'm afraid the answer is simply no, but maybe I'm missing some trick.

Body:
There is no magic in move semantics. It's just another overload. The rvalue reference thing is a nice convenience that is not really essential.

template <class T>
struct rref {
    rref (T& t) : t(t) {}
    T& t;
};

template<class T>
rref<T> move(const T& t) {
   return rref<T>(const_cast<T&>(t));
}

// you now can do a "move ctor"
class Foo {
   Foo(rref<Foo>) { ... }
};

Now you also need NRVO to kick in for this to work. It is not guaranteed by the standard, but it is provided by pretty much every implementation. To ensure it really happens, you may declare but not define a copy ctor.

Full working demo


问:
Add Buttons to Rails ActionText toolbar
What is the best way to configure ActionText to add buttons to the toolbar. For example, an h2 and h3 button?</p>

答:
To add to Will's answer, you can avoid recreating the whole toolbar by using trix after initialize callback :

example, adding a 'Red' button that turns the text red :

var Trix = require("trix");

/* what the newly created button does */
Trix.config.textAttributes.red = {
    style: { color: "red" },
    parser: function(element) {
        return element.style.color === "red"
    },
    inheritable: true
}

/* insert the button visual in the default toolbar */
addEventListener("trix-initialize", function(event) {
    var buttonHTML = '<button type="button" data-trix-attribute="red">RED</button>'

    event.target.toolbarElement.
    querySelector(".trix-button-group").
    insertAdjacentHTML("beforeend", buttonHTML)
})

```

output:

Title: Add Buttons to Rails ActionText toolbar

Body:
To add to Will's answer, you can avoid recreating the whole toolbar by using trix after initialize callback :

example, adding a 'Red' button that turns the text red :

var Trix = require("trix");

/* what the newly created button does */
Trix.config.textAttributes.red = {
    style: { color: "red" },
    parser: function(element) {
        return element.style.color === "red"
    },
    inheritable: true
}

/* insert the button visual in the default toolbar */
addEventListener("trix-initialize", function(event) {
    var buttonHTML = '<button type="button" data-trix-attribute="red">RED</button>'

    event.target.toolbarElement.
    querySelector(".trix-button-group").
    insertAdjacentHTML("beforeend", buttonHTML)
})

output:


问:
Youtube V3 Playlists.List - Post to API without user browser login
I am able to upload a video via the youtube v3 api and authorisation works fine using the YoutubeUpload scope. I am now trying to list all my playlists but i am getting Insufficient Permission: Request had insufficient authentication scopes. I have tried using the YoutubeReadonly, Youtube & YoutubeForceSsl scopes, also tried combinations of them all and it never seems to authenticate. It seems I do not have access to do anything with playlists, create, list or add a video. Strange thing is this code worked about 5 months ago but my dev account got disabled for inactivity, so i created a new one.

I'm happy to post the code here if needed but I believe this may be to do with the way I have set up the OAuth credentials / project. The steps i took to create are below.

Google Developers Console (console.developers.google.com)
    - Create project
    - Configure consent screen
    - Create OAuth credentials (https://console.developers.google.com/apis/credentials)
        - Application type: Other
    - Enable APIs and services (YouTube Data API v3)
        - Enable
    - APIs & Services
        - OAuth consent screen
            - Tick youtube scopes (YouTube, YouTubeForceSSL, ReadOnly, Upload)

Any help would be much appreciated and if i can provide any further information please let me know.

EDIT:
I tried creating another account, added secrets, ran it and my code seemed to work fine. So I went back to the account I was having issues with and it came up in the browser asking for google sign in, this time it worked fine. So I guess my next questions is, can you authorise the application / OAuth creds without having to open a web browser? I will have multiple YouTube accounts to manage so would be great to be able to deal with this before making any requests.

答:
It seems this post has been viewed a few times so i thought i'd mention that my solution was answered here

Auto Upload of Videos to my account, using youtube Data API V3 without user consent

Hope this helps other in future!