问:
How can I add a missing PyQt5 modules on Raspberry Pi
I am using PyQt5 version 5.7, python 3.5.3 and raspbian. My problem is that in my code some modules of PyQt5 get recognized and produce no error and some do.

The error I get: ImportError: cannot import name 'QMultimedia'

So why does QtCore/Widgets/Gui get reconized but not QMultimedia? Do I need to install some extra packages? Do I need to reinstall and do something special? This might be a trivial question but please help me.

Note: I also tried: from PyQt5 import QtMultimedia

```<code>import numpy as np
import sys
from PyQt5 import QtCore
from PyQt5 import QtWidgets
from PyQt5 import QtGui
from PyQt5 import QMultimedia
from PyQt5 import QCameraInfo
from PyQt5 import QVideoWidget
from PyQt5 import QMediaObject
from PyQt5.QtCore import pyqtSignal

class Camera():
    def iniCamera():
        cam = QCamera()
        caminfo = QCameraInfo(cam)
        print (caminfo.description)

        if caminfo.isNull() != True:
           cam = QCamera(caminfo.deviceName())
           print (caminfo.description)

if __name__ == '__main__':

    iniCamera()
</code>```

答:
If you installed the Raspbian pyqt5-dev and pyqt5-dev-tools packages, this will only provide the core PyQt5 modules like QtCore, QtGui, QtWidgets, etc. For other modules like QtMultimedia, you must install separate packages.

If you go to the Raspbian Connect Package List, and look in the Python Packages section, you will find the following extra packages:

python3-pyqt5.qsci

python3-pyqt5.qtmultimedia

python3-pyqt5.qtopengl

python3-pyqt5.qtpositioning

python3-pyqt5.qtquick

python3-pyqt5.qtsensors

python3-pyqt5.qtserialport

python3-pyqt5.qtsql

python3-pyqt5.qtsvg

python3-pyqt5.qtwebchannel

python3-pyqt5.qtwebkit

python3-pyqt5.qtwebsockets

python3-pyqt5.qtx11extras

python3-pyqt5.qtxmlpatterns

So just use apt-get to install whatever else you need.

Body:
I am using PyQt5 version 5.7, python 3.5.3 and raspbian. My problem is that in my code some modules of PyQt5 get recognized and produce no error and some do.

The error I get: ImportError: cannot import name 'QMultimedia'

So why does QtCore/Widgets/Gui get reconized but not QMultimedia? Do I need to install some extra packages? Do I need to reinstall and do something special? This might be a trivial question but please help me.

Note: I also tried: from PyQt5 import QtMultimedia

import numpy as np
import sys
from PyQt5 import QtCore
from PyQt5 import QtWidgets
from PyQt5 import QtGui
from PyQt5 import QMultimedia
from PyQt5 import QCameraInfo
from PyQt5 import QVideoWidget
from PyQt5 import QMediaObject
from PyQt5.QtCore import pyqtSignal

class Camera():
    def iniCamera():
        cam = QCamera()
        caminfo = QCameraInfo(cam)
        print (caminfo.description)

        if caminfo.isNull() != True:
           cam = QCamera(caminfo.deviceName())
           print (caminfo.description)

if __name__ == '__main__':

    iniCamera()


来源: stackexchange

问:
MySQL - How to set to NOW() and NULL while inserting a row into a table?
```<code>INSERT INTO rental (rental_date, last_update, return_date)
    SET rental_date, last_update = NOW()
    AND return_date = NULL.
</code>```

I'm trying to insert rental_date, last_update and return_date into the table rental while also setting their timestamp to NOW() and NULL.

答:
The syntax should be more like this.

```<code>INSERT INTO rental (rental_date, last_update, return_date)
SET
    rental_date = NOW()
  , last_update = NOW()
  , return_date = NULL
</code>```

While MySQL support this INSERT INTO ... SET syntax it is better to use ANSI SQL Standard INSERT INTO ... VALUES like so

```<code>INSERT INTO rental
  (rental_date, last_update, return_date)
VALUES
  (NOW(), NOW(), NULL)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
INSERT INTO rental (rental_date, last_update, return_date)
    SET rental_date, last_update = NOW()
    AND return_date = NULL.

I'm trying to insert rental_date, last_update and return_date into the table rental while also setting their timestamp to NOW() and NULL.

Body:
The syntax should be more like this.

INSERT INTO rental (rental_date, last_update, return_date)
SET
    rental_date = NOW()
  , last_update = NOW()
  , return_date = NULL

While MySQL support this INSERT INTO ... SET syntax it is better to use ANSI SQL Standard INSERT INTO ... VALUES like so

INSERT INTO rental
  (rental_date, last_update, return_date)
VALUES
  (NOW(), NOW(), NULL)


问:
Image not load in Google map marker
I am trying to load image in Google map that I have fetched from Firebase Storage in marker window. The thing is, when I try to load it with Glide or Picasso, it's not loading in Google map. Every log I have in the code is visible in logcat. Am I doing something wrong here?

Here is my code

```<code>public class MapInfoWindowAdapter implements GoogleMap.InfoWindowAdapter {

    Context context;
    LayoutInflater inflater;
    private DatabaseReference mDatabase;
    private StorageReference storageReference;
    private Chalet chalet;
    private boolean query;
    private ImageView img;
    private String lat;
    private String log;

    public MapInfoWindowAdapter(Context context, LayoutInflater inflater) {
        this.context = context;
        this.inflater = inflater;
    }

    @Override
    public View getInfoWindow(Marker marker) {
        return null;
    }

    @Override
    public View getInfoContents(final Marker marker) {

        mDatabase = FirebaseDatabase.getInstance().getReference().child("chalets");
        storageReference=FirebaseStorage.getInstance().getReference();

        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View v = inflater.inflate(R.layout.marker_tag,null);

       final LatLng latlng = marker.getPosition();
       Double doubleLat = latlng.latitude;

         lat = String.valueOf(latlng.latitude);
         log = String.valueOf(latlng.longitude);
        Log.i("MarkerPostion",lat);

        img = (ImageView) v.findViewById(R.id.chaletImg);

       // final TextView textView = (TextView) v.findViewById(R.id.markerText);
        final Semaphore semaphore = new Semaphore(0);
       mDatabase.addValueEventListener(new ValueEventListener() {

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                Log.i("MarkerPostion","112211");
                for (DataSnapshot snapm: dataSnapshot.getChildren()) {
                    Log.i("MarkerPostion",snapm.child("latitude").getValue().toString());
                    Log.i("Key",snapm.getKey());
                    if ( lat.equals(snapm.child("latitude").getValue().toString()) && log.equals(snapm.child("longitude").getValue().toString()) ){
                        chalet = snapm.getValue(Chalet.class);
                        Log.i("MarkerPostion","9999");
                        break;
                    }
                }

                storageReference = FirebaseStorage.getInstance().getReference().child(chalet.getOwnerID()).child(chalet.getChaletNm()).child("1");
                storageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {

                    @Override
                    public void onSuccess(Uri uri) {
                        Picasso.with(context).load(uri).into(img);
                        Log.i("MarkerPostion","2222");
                    }
                });
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

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

Here is my XML file:

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:id="@+id/markerFrame">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/chaletImg"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:adjustViewBounds="true"
            android:scaleType="centerCrop"
             />

    </LinearLayout>

</FrameLayout>
</code>```

答:
The problem is that Map markers are rendered as Bitmaps and are not live Views, which means that by the time Picasso finishes loading the image, you're marker has already been rendered and you need to refresh it to display the changes.

What you need to do is implement a Callback on the, either Picasso, or Glide call and call marker.showInfoWindow() once the image is loaded.

EDIT:
I think that this is the only change that you need:

```<code>Picasso.with(context).load(uri).into(img, new com.squareup.picasso.Callback() {
                        @Override
                        public void onSuccess() {
                            marker.showInfoWindow()
                        }

                        @Override
                        public void onError() {

                        }
                    });
</code>```

You could also check if (marker != null && marker.isInfoWindowShown()) before calling marker.showInfoWindow()...

Title: Image not load in Google map marker

Body:
I am trying to load image in Google map that I have fetched from Firebase Storage in marker window. The thing is, when I try to load it with Glide or Picasso, it's not loading in Google map. Every log I have in the code is visible in logcat. Am I doing something wrong here?

Here is my code

public class MapInfoWindowAdapter implements GoogleMap.InfoWindowAdapter {

    Context context;
    LayoutInflater inflater;
    private DatabaseReference mDatabase;
    private StorageReference storageReference;
    private Chalet chalet;
    private boolean query;
    private ImageView img;
    private String lat;
    private String log;

    public MapInfoWindowAdapter(Context context, LayoutInflater inflater) {
        this.context = context;
        this.inflater = inflater;
    }

    @Override
    public View getInfoWindow(Marker marker) {
        return null;
    }

    @Override
    public View getInfoContents(final Marker marker) {

        mDatabase = FirebaseDatabase.getInstance().getReference().child("chalets");
        storageReference=FirebaseStorage.getInstance().getReference();

        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View v = inflater.inflate(R.layout.marker_tag,null);

       final LatLng latlng = marker.getPosition();
       Double doubleLat = latlng.latitude;

         lat = String.valueOf(latlng.latitude);
         log = String.valueOf(latlng.longitude);
        Log.i("MarkerPostion",lat);

        img = (ImageView) v.findViewById(R.id.chaletImg);

       // final TextView textView = (TextView) v.findViewById(R.id.markerText);
        final Semaphore semaphore = new Semaphore(0);
       mDatabase.addValueEventListener(new ValueEventListener() {

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                Log.i("MarkerPostion","112211");
                for (DataSnapshot snapm: dataSnapshot.getChildren()) {
                    Log.i("MarkerPostion",snapm.child("latitude").getValue().toString());
                    Log.i("Key",snapm.getKey());
                    if ( lat.equals(snapm.child("latitude").getValue().toString()) && log.equals(snapm.child("longitude").getValue().toString()) ){
                        chalet = snapm.getValue(Chalet.class);
                        Log.i("MarkerPostion","9999");
                        break;
                    }
                }

                storageReference = FirebaseStorage.getInstance().getReference().child(chalet.getOwnerID()).child(chalet.getChaletNm()).child("1");
                storageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {

                    @Override
                    public void onSuccess(Uri uri) {
                        Picasso.with(context).load(uri).into(img);
                        Log.i("MarkerPostion","2222");
                    }
                });
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        return v;
    }
}

Here is my XML file:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:id="@+id/markerFrame">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/chaletImg"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:adjustViewBounds="true"
            android:scaleType="centerCrop"
             />

    </LinearLayout>

</FrameLayout>

Body:
The problem is that Map markers are rendered as Bitmaps and are not live Views, which means that by the time Picasso finishes loading the image, you're marker has already been rendered and you need to refresh it to display the changes.

What you need to do is implement a Callback on the, either Picasso, or Glide call and call marker.showInfoWindow() once the image is loaded.

EDIT:
I think that this is the only change that you need:

Picasso.with(context).load(uri).into(img, new com.squareup.picasso.Callback() {
                        @Override
                        public void onSuccess() {
                            marker.showInfoWindow()
                        }

                        @Override
                        public void onError() {

                        }
                    });

You could also check if (marker != null && marker.isInfoWindowShown()) before calling marker.showInfoWindow()...


问:
Assigning class based on scroll causing conflict
I need to add/remove css classes when user scroll the page according to the visible div.

I have two blocks (white and black).
Now I'm doing this:

```<code>$(window).scroll(function(event) {

   var scroll = $(window).scrollTop();

   if(scroll >= $('div.white').offset().top){
       //do things
   }

   if(scroll >= $('div.black').offset().top){
       //do things
   }
}
</code>```

The problem occurs when there is an alternance between the two classes, when a .white div follows a .black one. How can I better write this?

Thank you.

答:
Solved editing the calculation considering both the top offset and the element height.

```<code>if(scroll >= $('.bianco').offset().top && scroll <= ($('.bianco').offset().top + $('.bianco').height()) ){
    //code to be executed
}
</code>```

Thank you

Body:
I need to add/remove css classes when user scroll the page according to the visible div.

I have two blocks (white and black).
Now I'm doing this:

$(window).scroll(function(event) {

   var scroll = $(window).scrollTop();

   if(scroll >= $('div.white').offset().top){
       //do things
   }

   if(scroll >= $('div.black').offset().top){
       //do things
   }
}

The problem occurs when there is an alternance between the two classes, when a .white div follows a .black one. How can I better write this?

Thank you.

Body:
Solved editing the calculation considering both the top offset and the element height.

if(scroll >= $('.bianco').offset().top && scroll <= ($('.bianco').offset().top + $('.bianco').height()) ){
    //code to be executed
}

Thank you


问:
Search library dependency in android studio 3.0
After updating to Android Strudio 3.0, I tried adding a library from

project structure -> dependencies -> add library

, but searching doesn't seems to work, nothing is found.
   My build.gradle file looks like this

```<code>buildscript {
repositories {
    jcenter()
    google()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
repositories {
    jcenter()
    google()
}
}

task clean(type: Delete) {
 delete rootProject.buildDir
}
</code>```

and gradle-wrapper.properties:

```<code> distributionBase=GRADLE_USER_HOME
    distributionPath=wrapper/dists
    zipStoreBase=GRADLE_USER_HOME
    zipStorePath=wrapper/dists
    distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip
</code>```

答: It seems only the libraries in com.android.xx and com.google.xx package can be searched.</p>

Body:
After updating to Android Strudio 3.0, I tried adding a library from

project structure -> dependencies -> add library

, but searching doesn't seems to work, nothing is found.
   My build.gradle file looks like this

buildscript {
repositories {
    jcenter()
    google()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
repositories {
    jcenter()
    google()
}
}

task clean(type: Delete) {
 delete rootProject.buildDir
}

and gradle-wrapper.properties:

 distributionBase=GRADLE_USER_HOME
    distributionPath=wrapper/dists
    zipStoreBase=GRADLE_USER_HOME
    zipStorePath=wrapper/dists
    distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip


问:
redux security - is it possible to access previous state after state reset?
I've got an app that will keep user specific data in redux that must be cleared when user logs out i.e. next user that logs into the app in the same browser tab, should not be able to access the data.

So, app fetches user specific data from API using redux middleware and then that data is stored as part app state in redux. When user logs out, I dispatch log out action to clear the state:

```<code>const rootReducer = (state: {}, action: AnyAction) => {
    if( action.type === 'LOG_OUT')
        return {};
    return state;
}
</code>```

All seems good, state is reset to empty state but my question is - when user logs out and user doesn't close browser tab, can someone use dev tools or else to somehow see state before user logged out? Does redux (without using additional persist/history middleware/enhancers) store state somewhere out of the box? or is it all purely in browser memory and when state is reset on logout then previous state is gone and not accessible?

答:
If there's no remaining references to the previous state object, then the browser's JS engine will garbage-collect the old state.  That also implies that there would be no variables that the browser's DevTools could inspect.

The Redux core itself does not retain references to prior state objects.

Body:
I've got an app that will keep user specific data in redux that must be cleared when user logs out i.e. next user that logs into the app in the same browser tab, should not be able to access the data.

So, app fetches user specific data from API using redux middleware and then that data is stored as part app state in redux. When user logs out, I dispatch log out action to clear the state:

const rootReducer = (state: {}, action: AnyAction) => {
    if( action.type === 'LOG_OUT')
        return {};
    return state;
}

All seems good, state is reset to empty state but my question is - when user logs out and user doesn't close browser tab, can someone use dev tools or else to somehow see state before user logged out? Does redux (without using additional persist/history middleware/enhancers) store state somewhere out of the box? or is it all purely in browser memory and when state is reset on logout then previous state is gone and not accessible?


问:
can't understand code about go's print function
i am new to golang, when i read the code example of package "archtive/tar",i read some code like this:

```<code>// Iterate through the files in the archive.
for {
hdr, err := tr.Next()
    if err == io.EOF {
        // end of tar archive
        break
    }
    if err != nil {
        log.Fatalln(err)
    }
    fmt.Printf("Contents of %s:\n", hdr.Name)
    if _, err := io.Copy(os.Stdout, tr); err != nil {
        log.Fatalln(err)
    }
    fmt.Println()
}
</code>```

the output just like this:

```<code>Contents of readme.txt:
This archive contains some text files.
Contents of gopher.txt:
Gopher names:
George
Geoffrey
Gonzo
Contents of todo.txt:
Get animal handling license.
</code>```

can anyone tell me how the programe print the body of the struct? thank you.

答:
You left out a vital piece of the example, the two lines preceding what you posted.

```<code>// Open the tar archive for reading.
r := bytes.NewReader(buf.Bytes())
tr := tar.NewReader(r)
</code>```

This creates a tar.Reader which implements io.Reader. The statement io.Copy(os.Stdout, tr) in the if statement knows how to copy the contents of the reader to Stdout.

Godoc for tar.Reader

Also might be useful to note that the code example in the package documentation doesn't ever write the tar it creates to disk. It is all done in memory using bytes.Buffers. Examples of writing to disk would be in the io package.

Body:
i am new to golang, when i read the code example of package "archtive/tar",i read some code like this:

// Iterate through the files in the archive.
for {
hdr, err := tr.Next()
    if err == io.EOF {
        // end of tar archive
        break
    }
    if err != nil {
        log.Fatalln(err)
    }
    fmt.Printf("Contents of %s:\n", hdr.Name)
    if _, err := io.Copy(os.Stdout, tr); err != nil {
        log.Fatalln(err)
    }
    fmt.Println()
}

the output just like this:

Contents of readme.txt:
This archive contains some text files.
Contents of gopher.txt:
Gopher names:
George
Geoffrey
Gonzo
Contents of todo.txt:
Get animal handling license.

can anyone tell me how the programe print the body of the struct? thank you.

Body:
You left out a vital piece of the example, the two lines preceding what you posted.

// Open the tar archive for reading.
r := bytes.NewReader(buf.Bytes())
tr := tar.NewReader(r)

This creates a tar.Reader which implements io.Reader. The statement io.Copy(os.Stdout, tr) in the if statement knows how to copy the contents of the reader to Stdout.

Godoc for tar.Reader

Also might be useful to note that the code example in the package documentation doesn't ever write the tar it creates to disk. It is all done in memory using bytes.Buffers. Examples of writing to disk would be in the io package.


问:
Visual Studio Code - filename color
For some reason, after the update, some filenames appear yellow.

How do I disable it?

答:
settings.json Ctrl+,

"git.decorations.enabled": false
```

https://code.visualstudio.com/updates/v1_18#_git-status-in-file-explorer

Title: Visual Studio Code - filename color

Body:
settings.json Ctrl+,

"git.decorations.enabled": false

https://code.visualstudio.com/updates/v1_18#_git-status-in-file-explorer


问:
Subclassing UIGestureRecognizer and UILongPressGestureRecognizer
I am in a situation wherein I have a UIView that I have added a subclassed UIGestureRecognizer to.  I am using the following code;

```<code>class ButtonGestureRecognizer: UIGestureRecognizer {

  override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
    //
    state = .began
  }

  override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
    //
    state = .ended
  }
}
</code>```

This allows me to capture the touch "down" and touch "up" event, which I am using to scale the UIView larger when it is pressed down and back to its normal size when it is released.

I also need to add a UILongPressGestureRecognizer to this same view, wherein it will also scale up when held down, and return to its normal size when it is released, but perform a different action.

However, the subclassed Gesture Recognizer seems to be preventing the UILongPressGestureRecognizer from working.  The only solution I've found so far is to give up my subclassed gesture recognizer and use a UITapGestureRecognizer (with minimum taps required set to one) and a UILongPressGestureRecognizer, but then I give up the ability to properly detect the tap/press began and end states.

Any way around this?  Thanks!

答:
There's a protocol called UIGestureRecognizerDelegate and it has this method

```<code>- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
</code>```

If you conform to that protocol and set your object as the delegate of your recognizers, you can return true on that method and your gesture recognizers will work together.

Body:
I am in a situation wherein I have a UIView that I have added a subclassed UIGestureRecognizer to.  I am using the following code;

class ButtonGestureRecognizer: UIGestureRecognizer {

  override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
    //
    state = .began
  }

  override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
    //
    state = .ended
  }
}

This allows me to capture the touch "down" and touch "up" event, which I am using to scale the UIView larger when it is pressed down and back to its normal size when it is released.

I also need to add a UILongPressGestureRecognizer to this same view, wherein it will also scale up when held down, and return to its normal size when it is released, but perform a different action.

However, the subclassed Gesture Recognizer seems to be preventing the UILongPressGestureRecognizer from working.  The only solution I've found so far is to give up my subclassed gesture recognizer and use a UITapGestureRecognizer (with minimum taps required set to one) and a UILongPressGestureRecognizer, but then I give up the ability to properly detect the tap/press began and end states.

Any way around this?  Thanks!

Body:
There's a protocol called UIGestureRecognizerDelegate and it has this method

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer

If you conform to that protocol and set your object as the delegate of your recognizers, you can return true on that method and your gesture recognizers will work together.


问:
Windows semaphores
I need to implement a program which uses a semaphore to limit the number of opened notepad windows to 10. I created a semaphore in  WM_INITDIALOG

```<code>    semafor = CreateSemaphore(0, 1, 10, "semaphore");
</code>```

and every time I click on button to open a new window, I open that semaphore. However it doesn't stop me from opening more than 10 windows.

Here is my code when I click on button in a dialog box to open a new window:

```<code>case WM_COMMAND:
    switch (LOWORD(wParam)) {
        case ID_OK:

            semafor = OpenSemaphore(SEMAPHORE_ALL_ACCESS, TRUE, "semaphore");
            if (semafor == NULL) {
                printf("Eroare deschidere semafor empty: %d \n", GetLastError());
                ExitProcess(1);
            }

            BOOL b = CreateProcess("C:\\Windows\\System32\\notepad.exe",
                NULL, NULL, NULL, TRUE, 0, NULL, NULL,
                &si, &pi);

            process[++i] = GetCurrentProcess();

            if (b) {
                dwWaitForChild = WaitForInputIdle(pi.hProcess, 2000);
                switch (dwWaitForChild) {
                case 0:
                    printf("Procesul fiu este ready!\n");
                    break;
                case WAIT_TIMEOUT:
                    printf("Au trecut 2 sec. si procesul fiu nu este ready!\n");
                    break;
                case 0xFFFFFFFF:
                    printf("Eroare!\n");
                    break;
                }

                WaitForMultipleObjects(i, process, TRUE, INFINITE);

                iRasp = MessageBox(NULL, "Terminam procesul fiu?", "Atentie!", MB_YESNO);
                if (iRasp == IDYES) {
                    if (TerminateProcess(pi.hProcess, 2)) {

                        DWORD dwP;

                        GetExitCodeProcess(pi.hProcess, &dwP);
                        printf("Codul de terminare al procesului fiu: %d\n", dwP);
                        ReleaseSemaphore(semafor, 1, NULL);
                        CloseHandle(pi.hProcess);
                        printf("\nProcesul fiu a fost terminat cu succes\n");
                    }
                    else {
                        //tiparim mesajul de eroare
                        TCHAR buffer[80];
                        LPVOID lpMsgBuf;
                        DWORD dw = GetLastError();

                        FormatMessage(
                            FORMAT_MESSAGE_ALLOCATE_BUFFER |
                            FORMAT_MESSAGE_FROM_SYSTEM,
                            NULL,
                            dw,
                            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                            (LPTSTR)&lpMsgBuf,
                            0, NULL);

                        wsprintf(buffer, "TerminateProcess() a esuat cu eroarea %d: %s",
                            dw, lpMsgBuf);

                        MessageBox(NULL, buffer, "Eroare!", MB_OK);

                        LocalFree(lpMsgBuf);
                    }
                } // rasp YES

            }
            else
                printf("Eroare la crearea procesului fiu!\n");

            return TRUE;
        }
        break;
    }
    return FALSE;
}
</code>```

答:
You aren't ever waiting (or P in semaphore logic) on the semaphore.

Check the winapi example on how to use a semaphore. In their example they use WaitForSingleObject. You are only using OpenSemaphore which just gives you the semaphore handle so you can use it in multiple processes, you then need to actually wait on it if you want to decrement its value and wait/timeout when it's 0.

You should be doing something like this after you open your semaphore and before trying to open the notepad instance:

```<code>// Try to enter the semaphore gate.

dwWaitResult = WaitForSingleObject(
    ghSemaphore,   // handle to semaphore
    0L);           // zero-second time-out interval
</code>```

Title: Windows semaphores

Body:
I need to implement a program which uses a semaphore to limit the number of opened notepad windows to 10. I created a semaphore in  WM_INITDIALOG

    semafor = CreateSemaphore(0, 1, 10, "semaphore");

and every time I click on button to open a new window, I open that semaphore. However it doesn't stop me from opening more than 10 windows.

Here is my code when I click on button in a dialog box to open a new window:

case WM_COMMAND:
    switch (LOWORD(wParam)) {
        case ID_OK:

            semafor = OpenSemaphore(SEMAPHORE_ALL_ACCESS, TRUE, "semaphore");
            if (semafor == NULL) {
                printf("Eroare deschidere semafor empty: %d \n", GetLastError());
                ExitProcess(1);
            }

            BOOL b = CreateProcess("C:\\Windows\\System32\\notepad.exe",
                NULL, NULL, NULL, TRUE, 0, NULL, NULL,
                &si, &pi);

            process[++i] = GetCurrentProcess();

            if (b) {
                dwWaitForChild = WaitForInputIdle(pi.hProcess, 2000);
                switch (dwWaitForChild) {
                case 0:
                    printf("Procesul fiu este ready!\n");
                    break;
                case WAIT_TIMEOUT:
                    printf("Au trecut 2 sec. si procesul fiu nu este ready!\n");
                    break;
                case 0xFFFFFFFF:
                    printf("Eroare!\n");
                    break;
                }

                WaitForMultipleObjects(i, process, TRUE, INFINITE);

                iRasp = MessageBox(NULL, "Terminam procesul fiu?", "Atentie!", MB_YESNO);
                if (iRasp == IDYES) {
                    if (TerminateProcess(pi.hProcess, 2)) {

                        DWORD dwP;

                        GetExitCodeProcess(pi.hProcess, &dwP);
                        printf("Codul de terminare al procesului fiu: %d\n", dwP);
                        ReleaseSemaphore(semafor, 1, NULL);
                        CloseHandle(pi.hProcess);
                        printf("\nProcesul fiu a fost terminat cu succes\n");
                    }
                    else {
                        //tiparim mesajul de eroare
                        TCHAR buffer[80];
                        LPVOID lpMsgBuf;
                        DWORD dw = GetLastError();

                        FormatMessage(
                            FORMAT_MESSAGE_ALLOCATE_BUFFER |
                            FORMAT_MESSAGE_FROM_SYSTEM,
                            NULL,
                            dw,
                            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                            (LPTSTR)&lpMsgBuf,
                            0, NULL);

                        wsprintf(buffer, "TerminateProcess() a esuat cu eroarea %d: %s",
                            dw, lpMsgBuf);

                        MessageBox(NULL, buffer, "Eroare!", MB_OK);

                        LocalFree(lpMsgBuf);
                    }
                } // rasp YES

            }
            else
                printf("Eroare la crearea procesului fiu!\n");

            return TRUE;
        }
        break;
    }
    return FALSE;
}

Body:
You aren't ever waiting (or P in semaphore logic) on the semaphore.

Check the winapi example on how to use a semaphore. In their example they use WaitForSingleObject. You are only using OpenSemaphore which just gives you the semaphore handle so you can use it in multiple processes, you then need to actually wait on it if you want to decrement its value and wait/timeout when it's 0.

You should be doing something like this after you open your semaphore and before trying to open the notepad instance:

// Try to enter the semaphore gate.

dwWaitResult = WaitForSingleObject(
    ghSemaphore,   // handle to semaphore
    0L);           // zero-second time-out interval


问:
gwt export to file
i have a problem with gwt application. i have an array of strings in the client application and i want to export it to a file, but it isn't probably possible so i have to use servlet, right? but i don't really know how.</p>

答:
Here's a guide on How to Call a Servlet in GWT.

Alternatively, use the GWT HTTP client to send a GET or POST request to the servlet.

ContentLicense: CC BY-SA 2.5

Title: gwt export to file


问:
jQuery validate single input in similar forms
I have two forms on a page that are identical, but I'm trying to validate the one field (which is email in this case), but I can't seem to get it to just validate the one input field as it just shows the error for both forms.

HTML:

```<code><div class="general-form">
  <div class="email-error" style="display:none;">
    <p>You need valid email</p>
  </div>
  <div class="form-wrap">
    <div class="form-row">
      <input id="from-email" type="email" name="email" placeholder="Your Email" />
    </div>
    <div class="btn-row">
      <button class="submit-btn">Submit</button>
    </div>
  </div>
</div>

<div class="general-form">
  <div class="email-error" style="display:none;">
    <p>You need valid email</p>
  </div>
  <div class="form-wrap">
    <div class="form-row">
      <input id="from-email" type="email" name="email" placeholder="Your Email" />
    </div>
    <div class="btn-row">
      <button class="submit-btn">Submit</button>
    </div>
  </div>
</div>
</code>```

JS:

```<code>$(".submit-btn").on("click", function() {
  var $this = $(this);
  var valid_email = $this.find("#from-email").val();
  if (/(.+)@(.+){2,}\.(.+){2,}/.test(valid_email)) {
    return true;
  } else {
    $this.parents().find(".email-error").show();
    return false;
  }
});
</code>```

Overall, I can get it to pass through the validation, but the error message shows for both forms and I'm not sure how to get it so it only shows the error message for that particular form. I'm guessing that I'm pushing too far up the chain and it's testing for both of the forms, but I can't remember which one to target specifically if that makes any sense.

答:
You doubled the id from-email that’s why. In your JS you are checking all fields with the id from-email in this case both of the inputs are checked because both the id.

If one of them is wrong you are searching for the email-error in all of your parents which will go up to the body and then find all off the error wrappers.  $this.parents(“.general-form“) will do the deal and only go up to the wrapper of the input and error in your case.

Always make sure your id’s are unique.

Body:
I have two forms on a page that are identical, but I'm trying to validate the one field (which is email in this case), but I can't seem to get it to just validate the one input field as it just shows the error for both forms.

HTML:

You need valid email

      <input id="from-email" type="email" name="email" placeholder="Your Email" />

      <button class="submit-btn">Submit</button>

You need valid email

      <input id="from-email" type="email" name="email" placeholder="Your Email" />

      <button class="submit-btn">Submit</button>

JS:

$(".submit-btn").on("click", function() {
  var $this = $(this);
  var valid_email = $this.find("#from-email").val();
  if (/(.+)@(.+){2,}\.(.+){2,}/.test(valid_email)) {
    return true;
  } else {
    $this.parents().find(".email-error").show();
    return false;
  }
});

Overall, I can get it to pass through the validation, but the error message shows for both forms and I'm not sure how to get it so it only shows the error message for that particular form. I'm guessing that I'm pushing too far up the chain and it's testing for both of the forms, but I can't remember which one to target specifically if that makes any sense.


问:
Python - If I create a variable inside a function, how can I then use it outside the function?
I would like to create a variable inside a function and then use that variable outside the function. Is there a way to do this? For example:

```<code>def Function():
    score = 5

Function()

print(score)
</code>```

Thank you :)

答:
Technically you can use global keyword:

```<code>def Function():
    global score
    score = 5

Function()
print(score)
</code>```

Body:
I would like to create a variable inside a function and then use that variable outside the function. Is there a way to do this? For example:

def Function():
    score = 5

Function()

print(score)

Thank you :)

Body:
Technically you can use global keyword:

def Function():
    global score
    score = 5

Function()
print(score)


问:
Call limit exceeds while implementing DocuSign
While implementing the DocuSign we are getting The maximum number of hourly API invocations has been exceeded error message sometimes this is because of the API call rate exceed per 1 hour. Anyone have any idea how to increase the API call rate per account from 1000 to 5000?

答:
You need to contact your DocuSign's Account Manager with a valid usecase why you need the API limit to be increased to 5000. As a defensive check you should always read the header in the API response, DocuSign provide the data as whats your call limit, how many calls are remaining and what is next schedule counter reset for you. By reading these header values, you can make your application pause for sometime so that you don't hit threshold limit and handle the limit scenario properly.

Along with your DocuSign Account Manager, you can contact support@docusign.com also.


问:
How can I return control to the client app and ask for input again from my API?
Writing a pure API seems to be bring up some challenges. For example, I am used to writing winforms/asp.net apps where if the input I have is invalid, I can programatically bring up a dialog box/webpage.

However, an API has no knowledge of the GUI app it may be executed from. If I have a method called TakeString (String s), and the string (s) cannot be more than 5 letters, how would I return control to the client if it was so? An exception seems like overkill? A simple return won't work if I am returning something in the method.

Thanks

答:
An exception is exactly the right thing to do. You document that you'll only accept a string as input if it's 5 letters or fewer, and throw ArgumentException otherwise. Why would that be overkill?

In this case, you don't even need to worry about alternative mechanisms if the client can't detect the validity of what they're passing you: if the calling code has any doubt about the arguments they're going to pass you, it's not exactly beyond the wit of man for them to check it themselves.

Trying to make the API forgiving of invalid input is a recipe for disaster. Validate the input as stringently as you can, within reason. If you force the client to behave well, you'll have a lot fewer problems later on.


答: You can use "by" function. It is used in grouping data.</p>

Title: Group a table by unique IDs in R

Body:
I have a table like this below. I need to group then by unique POL, PLAN, ID1 and ID2

Output table is shown below.

Any help is appreciated.

dfx1:

YEAR    POL    CTY    PLAN  TYPE  ID1  ID2  DATE
1998  4680     133    90    11    6    1    10061997
1998  4680     133    90    11    8    2    10041997
1998  4772     133    44    11   10    1    11011997
1998  6407     133    44    11   23    7    10231997
1999  7371     133    44    11   24    1    11041997
1999  4680     133    90    11    6    1    10021998
1999  4680     133    90    11    8    2    10061998
1999  4772     133    44    11   10    1    11051998
1999  6407     133    44    11   23    7    10241998
2000  7371     133    44    11   24    1    11061999

Output:

YEAR    POL    CTY    PLAN  TYPE  ID1  ID2  DATE
1998  4680     133    90    11    6    1    10061997
1999  4680     133    90    11    6    1    10021998
1998  4680     133    90    11    8    2    10041997
1999  4680     133    90    11    8    2    10061998
1998  4772     133    44    11   10    1    11011997
1999  4772     133    44    11   10    1    11051998
1998  6407     133    44    11   23    7    10231997
1999  6407     133    44    11   23    7    10241998
1999  7371     133    44    11   24    1    11041997
2000  7371     133    44    11   24    1    11061999


问:
Google play error when trying to update beta
I'm receiving this error when trying to upload a new apk to my beta channel:

Errors

Resolve these errors before starting the rollout of this release.

You can't rollout this release because it doesn't allow any existing users to upgrade to the newly added APKs.

In my alpha channel, witch is updated far more frequently, I can successfully upload the same apk.

How can I solve it?

答: I was able to get around this error because I had accidentally set my Version Code to a lower number than the Version Code for an APK in production.  Once I increased my version code number to be larger than any previous releases, it worked.


问:
iOS Crash: " this class is not key value coding-compliant for the key url"
I am getting the following crash on crashlytics.

Fatal Exception: NSUnknownKeyException
      [<__NSCFString 0x1742aeb80> valueForUndefinedKey:]: this class is not key value coding-compliant for the key url.

This is where the crash occurred for some of the users.

```<code> id url = [[json[@"data"]valueForKey:@"value"]valueForKey:@"url"];
</code>```

I'm not sure what is the best way to prevent this crash. I believe this is because json[@"data"] is an NSString in certain cases. So I believe I should check if this is an NSDictionary like this.

```<code>if ([json[@"data"] isKindOfClass:[NSDictionary class]]) {
     id url = [[json[@"data"]valueForKey:@"value"]valueForKey:@"url"];
    }
</code>```

Any tips or suggestions are appreciated.

This is my end result after getting answers from here. Does this look okay? I didn't include all my code at first to keep things simple.

```<code>        if ([json isKindOfClass:[NSDictionary class]]) {
            id url = nil;
            id type = nil;

            NSDictionary *data = json[@"data"];

            if ([data isKindOfClass:[NSDictionary class]]) {
                type = data[@"type"];
                NSDictionary *value = data[@"value"];

                if ([value isKindOfClass:[NSArray class]]) {
                    url = [value valueForKey:@"url"];
                }

                if ([type isKindOfClass:[NSString class]] && [url isKindOfClass:[NSArray class]] && [url count] != 0) {
                   // do stuff
              }
            }
         }
</code>```

答:
You should check NSDictionary one by one to prevent crash. Try my code below

```<code>NSDictionary *dictionary = json[@"data"];
NSString *output = @"";
if ([dictionary isKindOfClass:[NSDictionary class]]) {
  dictionary = dictionary[@"value"];
  if ([dictionary isKindOfClass:[NSDictionary class]]) {
    output = dictionary[@"url"];
  }
}
NSLog(@"%@", output);
</code>```

You got crash because of calling valueForKey method on a NSString value. If someone says the reason for crash is call valueForKey when dictionary doesn't have this key, it's wrong. For more information Sending a message to nil in Objective-C

[dictionary isKindOfClass:[NSDictionary class]] always return NO if dictionary is nil so don't need to check dictionary in if statement. It's unnessary.

Body:
I am getting the following crash on crashlytics.

Fatal Exception: NSUnknownKeyException
      [<__NSCFString 0x1742aeb80> valueForUndefinedKey:]: this class is not key value coding-compliant for the key url.

This is where the crash occurred for some of the users.

 id url = [[json[@"data"]valueForKey:@"value"]valueForKey:@"url"];

I'm not sure what is the best way to prevent this crash. I believe this is because json[@"data"] is an NSString in certain cases. So I believe I should check if this is an NSDictionary like this.

if ([json[@"data"] isKindOfClass:[NSDictionary class]]) {
     id url = [[json[@"data"]valueForKey:@"value"]valueForKey:@"url"];
    }

Any tips or suggestions are appreciated.

This is my end result after getting answers from here. Does this look okay? I didn't include all my code at first to keep things simple.

        if ([json isKindOfClass:[NSDictionary class]]) {
            id url = nil;
            id type = nil;

            NSDictionary *data = json[@"data"];

            if ([data isKindOfClass:[NSDictionary class]]) {
                type = data[@"type"];
                NSDictionary *value = data[@"value"];

                if ([value isKindOfClass:[NSArray class]]) {
                    url = [value valueForKey:@"url"];
                }

                if ([type isKindOfClass:[NSString class]] && [url isKindOfClass:[NSArray class]] && [url count] != 0) {
                   // do stuff
              }
            }
         }

Body:
You should check NSDictionary one by one to prevent crash. Try my code below

NSDictionary *dictionary = json[@"data"];
NSString *output = @"";
if ([dictionary isKindOfClass:[NSDictionary class]]) {
  dictionary = dictionary[@"value"];
  if ([dictionary isKindOfClass:[NSDictionary class]]) {
    output = dictionary[@"url"];
  }
}
NSLog(@"%@", output);

You got crash because of calling valueForKey method on a NSString value. If someone says the reason for crash is call valueForKey when dictionary doesn't have this key, it's wrong. For more information Sending a message to nil in Objective-C

[dictionary isKindOfClass:[NSDictionary class]] always return NO if dictionary is nil so don't need to check dictionary in if statement. It's unnessary.


问:
How to normalize disparity data in iOS?
In WWDC session "Image Editing with Depth" they mentioned few times normalizedDisparity and normalizedDisparityImage:

"The basic idea is that we're going to map our normalized disparity
  values into values between 0 and 1"

"So once you know the min and max you can normalize the depth or disparity between 0 and 1."

I tried to first get the disparit image like this:

```<code>let disparityImage = depthImage.applyingFilter(
    "CIDepthToDisparity", withInputParameters: nil)
</code>```

Then I tried to get depthDataMap and do normalization but it didn't work. I'm I on the right track? would be appreciate some hint on what to do.

Edit:

This is my test code, sorry for the quality. I get the min and max then I try to loop over the data to normalize it (let normalizedPoint = (point - min) / (max - min))

```<code>let depthDataMap = depthData!.depthDataMap
let width = CVPixelBufferGetWidth(depthDataMap) //768 on an iPhone 7+
let height = CVPixelBufferGetHeight(depthDataMap) //576 on an iPhone 7+
CVPixelBufferLockBaseAddress(depthDataMap, CVPixelBufferLockFlags(rawValue: 0))
// Convert the base address to a safe pointer of the appropriate type
let floatBuffer = unsafeBitCast(CVPixelBufferGetBaseAddress(depthDataMap),
    to: UnsafeMutablePointer<Float32>.self)
var min = floatBuffer[0]
var max = floatBuffer[0]
for x in 0..<width{
    for y in 0..<height{
        let distanceAtXYPoint = floatBuffer[Int(x * y)]
        if(distanceAtXYPoint < min){
            min = distanceAtXYPoint
        }
        if(distanceAtXYPoint > max){
            max = distanceAtXYPoint
        }
    }
}
</code>```

What I expected is the the data will reflect the disparity where the user clicked on the image but it didn't match. The code to find the disparity where the user clicked is here:

```<code>// Apply the filter with the sampleRect from the user’s tap. Don’t forget to clamp!
let minMaxImage = normalized?.clampingToExtent().applyingFilter(
    "CIAreaMinMaxRed", withInputParameters:
        [kCIInputExtentKey : CIVector(cgRect:rect2)])
// A four-byte buffer to store a single pixel value
var pixel = [UInt8](repeating: 0, count: 4)
// Render the image to a 1x1 rect. Be sure to use a nil color space.
context.render(minMaxImage!, toBitmap: &pixel, rowBytes: 4,
    bounds: CGRect(x:0, y:0, width:1, height:1),
    format:  kCIFormatRGBA8, colorSpace: nil)
// The max is stored in the green channel. Min is in the red.
let disparity = Float(pixel[1]) / 255.0
</code>```

答:
There's a new blog post on raywenderlich.com called "Image Depth Maps Tutorial for iOS" contains sample app and details related to working with depth. The sample code shows how to normalize the depth data using a CVPixelBuffer extension:

```<code>extension CVPixelBuffer {

  func normalize() {

    let width = CVPixelBufferGetWidth(self)
    let height = CVPixelBufferGetHeight(self)

    CVPixelBufferLockBaseAddress(self, CVPixelBufferLockFlags(rawValue: 0))
    let floatBuffer = unsafeBitCast(CVPixelBufferGetBaseAddress(self), to: UnsafeMutablePointer<Float>.self)

    var minPixel: Float = 1.0
    var maxPixel: Float = 0.0

    for y in 0 ..< height {
      for x in 0 ..< width {
        let pixel = floatBuffer[y * width + x]
        minPixel = min(pixel, minPixel)
        maxPixel = max(pixel, maxPixel)
      }
    }

    let range = maxPixel - minPixel

    for y in 0 ..< height {
      for x in 0 ..< width {
        let pixel = floatBuffer[y * width + x]
        floatBuffer[y * width + x] = (pixel - minPixel) / range
      }
    }

    CVPixelBufferUnlockBaseAddress(self, CVPixelBufferLockFlags(rawValue: 0))
  }
}
</code>```

Something to keep in mind when working with depth data that they are lower resolution than the actual image so you need to scale up (more info in the blog and in the WWDC video)

Title: How to normalize disparity data in iOS?

Body:
In WWDC session "Image Editing with Depth" they mentioned few times normalizedDisparity and normalizedDisparityImage:

"The basic idea is that we're going to map our normalized disparity
  values into values between 0 and 1"

"So once you know the min and max you can normalize the depth or disparity between 0 and 1."

I tried to first get the disparit image like this:

let disparityImage = depthImage.applyingFilter(
    "CIDepthToDisparity", withInputParameters: nil)

Then I tried to get depthDataMap and do normalization but it didn't work. I'm I on the right track? would be appreciate some hint on what to do.

Edit:

This is my test code, sorry for the quality. I get the min and max then I try to loop over the data to normalize it (let normalizedPoint = (point - min) / (max - min))

let depthDataMap = depthData!.depthDataMap
let width = CVPixelBufferGetWidth(depthDataMap) //768 on an iPhone 7+
let height = CVPixelBufferGetHeight(depthDataMap) //576 on an iPhone 7+
CVPixelBufferLockBaseAddress(depthDataMap, CVPixelBufferLockFlags(rawValue: 0))
// Convert the base address to a safe pointer of the appropriate type
let floatBuffer = unsafeBitCast(CVPixelBufferGetBaseAddress(depthDataMap),
    to: UnsafeMutablePointer<Float32>.self)
var min = floatBuffer[0]
var max = floatBuffer[0]
for x in 0..<width{
    for y in 0..<height{
        let distanceAtXYPoint = floatBuffer[Int(x * y)]
        if(distanceAtXYPoint < min){
            min = distanceAtXYPoint
        }
        if(distanceAtXYPoint > max){
            max = distanceAtXYPoint
        }
    }
}

What I expected is the the data will reflect the disparity where the user clicked on the image but it didn't match. The code to find the disparity where the user clicked is here:

// Apply the filter with the sampleRect from the user’s tap. Don’t forget to clamp!
let minMaxImage = normalized?.clampingToExtent().applyingFilter(
    "CIAreaMinMaxRed", withInputParameters:
        [kCIInputExtentKey : CIVector(cgRect:rect2)])
// A four-byte buffer to store a single pixel value
var pixel = [UInt8](repeating: 0, count: 4)
// Render the image to a 1x1 rect. Be sure to use a nil color space.
context.render(minMaxImage!, toBitmap: &pixel, rowBytes: 4,
    bounds: CGRect(x:0, y:0, width:1, height:1),
    format:  kCIFormatRGBA8, colorSpace: nil)
// The max is stored in the green channel. Min is in the red.
let disparity = Float(pixel[1]) / 255.0

Body:
There's a new blog post on raywenderlich.com called "Image Depth Maps Tutorial for iOS" contains sample app and details related to working with depth. The sample code shows how to normalize the depth data using a CVPixelBuffer extension:

extension CVPixelBuffer {

  func normalize() {

    let width = CVPixelBufferGetWidth(self)
    let height = CVPixelBufferGetHeight(self)

    CVPixelBufferLockBaseAddress(self, CVPixelBufferLockFlags(rawValue: 0))
    let floatBuffer = unsafeBitCast(CVPixelBufferGetBaseAddress(self), to: UnsafeMutablePointer<Float>.self)

    var minPixel: Float = 1.0
    var maxPixel: Float = 0.0

    for y in 0 ..< height {
      for x in 0 ..< width {
        let pixel = floatBuffer[y * width + x]
        minPixel = min(pixel, minPixel)
        maxPixel = max(pixel, maxPixel)
      }
    }

    let range = maxPixel - minPixel

    for y in 0 ..< height {
      for x in 0 ..< width {
        let pixel = floatBuffer[y * width + x]
        floatBuffer[y * width + x] = (pixel - minPixel) / range
      }
    }

    CVPixelBufferUnlockBaseAddress(self, CVPixelBufferLockFlags(rawValue: 0))
  }
}

Something to keep in mind when working with depth data that they are lower resolution than the actual image so you need to scale up (more info in the blog and in the WWDC video)


问:
$ dont work with JsonPath
I Post one Json with RestAssured and After I need to verify that all fields are stored in the database with the correct values.My Json is :

```<code>{
    "id": "1",
    "name": "name1",
    "description": "description1",
    "source": "source1",
    "target": "target1",
    "domain": "PM",
    "transformation_rules": [
        {
            "name": "name2",
            "filters": [
                {
                    "object": "object1",
                    "pattern": "pattern1"
                }
            ],
            "operations": [
                {
                    "pattern": "pattern2",
                    "replacement": "replacement1"
                }
            ]
        },
        {
            "name": "name3",
            "filters": [
                {
                    "object": "object2",
                    "pattern": "pattern2"
                }
            ],
            "operations": [
                {
                    "pattern": "pattern3",
                    "replacement": "replacement2"
                },
                {
                    "pattern": "pattern3",
                    "replacement": "replacement3"
                },
                {
                    "pattern": "pattern4",
                    "replacement": "replacement4"
                }
            ]
        }
    ],
    "conflict_policy": "ACCEPT_SOURCE"
}
</code>```

So, I have  :

```<code>responseGet = RestAssured.given().contentType(ContentType.JSON).when().get(urlApi + "/" + id);
</code>```

My first verification is :

```<code>responseGet.then().body("$[0]['id']", equalTo("1"));
</code>```

to verify that the field "id" equals to 1 it doesn't execute well and I change to :

```<code>responseGet.then().body("$.id", equalTo("1"));
</code>```

and the same result ---> fails

Please, can you give me your suggestions for testing all the Json ?
Just for information, I try to apply : https://github.com/json-path/JsonPath.

Thank you very much in Advance,

Best Regards,

答:
You can directly use jsonPath() for checking this:

For example:

```<code>responseGet.body().jsonPath().getString("id").equals("1");
</code>```

For reading JsonPath

Title: $ dont work with JsonPath

Body:
I Post one Json with RestAssured and After I need to verify that all fields are stored in the database with the correct values.My Json is :

{
    "id": "1",
    "name": "name1",
    "description": "description1",
    "source": "source1",
    "target": "target1",
    "domain": "PM",
    "transformation_rules": [
        {
            "name": "name2",
            "filters": [
                {
                    "object": "object1",
                    "pattern": "pattern1"
                }
            ],
            "operations": [
                {
                    "pattern": "pattern2",
                    "replacement": "replacement1"
                }
            ]
        },
        {
            "name": "name3",
            "filters": [
                {
                    "object": "object2",
                    "pattern": "pattern2"
                }
            ],
            "operations": [
                {
                    "pattern": "pattern3",
                    "replacement": "replacement2"
                },
                {
                    "pattern": "pattern3",
                    "replacement": "replacement3"
                },
                {
                    "pattern": "pattern4",
                    "replacement": "replacement4"
                }
            ]
        }
    ],
    "conflict_policy": "ACCEPT_SOURCE"
}

So, I have  :

responseGet = RestAssured.given().contentType(ContentType.JSON).when().get(urlApi + "/" + id);

My first verification is :

responseGet.then().body("$[0]['id']", equalTo("1"));

to verify that the field "id" equals to 1 it doesn't execute well and I change to :

responseGet.then().body("$.id", equalTo("1"));

and the same result ---> fails

Please, can you give me your suggestions for testing all the Json ?
Just for information, I try to apply : https://github.com/json-path/JsonPath.

Thank you very much in Advance,

Best Regards,

Body:
You can directly use jsonPath() for checking this:

For example:

responseGet.body().jsonPath().getString("id").equals("1");

For reading JsonPath


问:
Is there a way to install and run a local server on my Windows XP Home laptop?
I'm looking to set up a local server on my laptop which is running Windows XP Home Edition. I've noticed that it is impossible to install IIS on the Home Edition, but is there a way around this? Is there other software that I can install to run a server?

the purpose behind this is to mess around and play with ASP to create dynamic websites and my only computer I own has Home Edition.

Also, would running a server on my 5 year old laptop with 2GB of RAM be a good idea?

答:
Yes there are ways like http://www.15seconds.com/issue/020118.htm
If you are developing using Visual Studio 2005, 8 , 10 you don't need IIS.

The hardware should be fine as you will be the only user accessing the website :)


问:
regionprops orientation behaves differently with logical and integers
It seems that regionprops 'orientation' behaves differentlty if we give a logical or an integer :

```<code>A = [ 0 0 0 1 1 0 ;
    0 0 0 1 0 0 ;
    1 1 0 0 0 0 ;
    0 0 0 0 0 0 ;
    0 0 0 0 1 0 ;
    0 0 0 0 0 0 ]

a_orientation = regionprops(A,'Orientation')

% Orientation: 28.1550

B = logical(A)

b_orientation = regionprops(B,'Orientation')

% 3x1 struct array with fields:
%     Orientation

b_orientation.Orientation

% ans =
%      0
%
% ans =
%    45.0000
%
% ans =
%      0
%
</code>```

How could I make regionprops behave with logical the same way as with integers without changing the type ?

答:
When you pass A (a double precision matrix) into regionprops, it is treated as a label matrix with only one labeled region corresponding to the ones. It essentially assumes the data you are giving to it is the output from bwlabel. The metrics are computed across all the pixels labeled 1.

When you pass B (a logical matrix), it is treated as a binary image, in which there are three distinct regions of ones (i.e. 8-connected components) found. Metrics are returned for each region.

I don't believe there is any way to get regionprops to treat a logical input differently without first converting its type. Logical inputs appear to always undergo a connected-component processing step that identifies each "island" of ones as separate regions to analyze.

Body:
It seems that regionprops 'orientation' behaves differentlty if we give a logical or an integer :

A = [ 0 0 0 1 1 0 ;
    0 0 0 1 0 0 ;
    1 1 0 0 0 0 ;
    0 0 0 0 0 0 ;
    0 0 0 0 1 0 ;
    0 0 0 0 0 0 ]

a_orientation = regionprops(A,'Orientation')

% Orientation: 28.1550

B = logical(A)

b_orientation = regionprops(B,'Orientation')

% 3x1 struct array with fields:
%     Orientation

b_orientation.Orientation

% ans =
%      0
%
% ans =
%    45.0000
%
% ans =
%      0
%

How could I make regionprops behave with logical the same way as with integers without changing the type ?


问:
How can I get padding in a scrollable flex-grow?
I have a pretty simple layout consisting of one parent element with a fixed height and two children, one with flex-grow: 1, flex-shrink: 1, a padding, and overflow: auto, and the other with flex-grow: 0 and flex-shrink: 0.

What I want to happen is for the 1 1 child to get a scrollbar when it overflows, but for it to still have a padding all around. It's best illustrated by this JSBin. If you scroll the foos, you'll see that there is no padding on the bottom.

The padding is there if I set flex-shrink: 0 on the element, but then it no longer scrolls.

Code:

#a {
 border: 1px solid black;
 height: 300px;
 display: flex;
 flex-direction: column;
}

#b {
  flex-grow: 1;
  flex-shrink: 1;
  background: blue;
  overflow: auto;
  padding: 1rem;
}

#c {
  flex-shrink: 0;
  background: red;
  height: 3rem;
}

p {
  background: green;
  margin: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div id="a">
    <div id="b">

      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
    </div>

      <div id="c">
        thing
      </div>
      </div>
</body>
</html></code>```

答:
This seems to be one of the many shortfalls of using flex with IE.  A workaround is to wrap the content of b and then put the padding on the wrapper:

#a {
 border: 1px solid black;
 height: 300px;
 display: flex;
 flex-direction: column;
}

#b {
  flex-grow: 1;
  background: blue;
  overflow:auto;
}

#b-inner {
  padding: 1rem;
}

#c {
  background: red;
  height: 3rem;
}

p {
  background: green;
  margin:0;
}

#hack {
  height: 1rem;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="a">
  <div id="b">
    <div id="b-inner">
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
    </div>
  </div>

  <div id="c">
    thing
  </div>
</div></code>```

Body:
I have a pretty simple layout consisting of one parent element with a fixed height and two children, one with flex-grow: 1, flex-shrink: 1, a padding, and overflow: auto, and the other with flex-grow: 0 and flex-shrink: 0.

What I want to happen is for the 1 1 child to get a scrollbar when it overflows, but for it to still have a padding all around. It's best illustrated by this JSBin. If you scroll the foos, you'll see that there is no padding on the bottom.

The padding is there if I set flex-shrink: 0 on the element, but then it no longer scrolls.

Code:

#a {
 border: 1px solid black;
 height: 300px;
 display: flex;
 flex-direction: column;
}

#b {
  flex-grow: 1;
  flex-shrink: 1;
  background: blue;
  overflow: auto;
  padding: 1rem;
}

#c {
  flex-shrink: 0;
  background: red;
  height: 3rem;
}

p {
  background: green;
  margin: 0;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

foo

foo

foo

foo

foo

foo

foo

foo

foo

foo

foo

foo

foo

foo

foo

foo

foo

foo

foo

foo

        thing

Body:
This seems to be one of the many shortfalls of using flex with IE.  A workaround is to wrap the content of b and then put the padding on the wrapper:

#a {
 border: 1px solid black;
 height: 300px;
 display: flex;
 flex-direction: column;
}

#b {
  flex-grow: 1;
  background: blue;
  overflow:auto;
}

#b-inner {
  padding: 1rem;
}

#c {
  background: red;
  height: 3rem;
}

p {
  background: green;
  margin:0;
}

#hack {
  height: 1rem;
}

<div id="a">
  <div id="b">
    <div id="b-inner">
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
      <p>foo</p>
    </div>
  </div>

  <div id="c">
    thing
  </div>
</div>


问:
covariance with struct constraint
I'm wondering why is such thing allowed after all?

```<code>interface IProducer<out T> where T : struct
</code>```

if struct is value type then covariance doesn't work because struct is value type. what am I missing here?

答:
If you look at MSDN for Generic out modifier there is stated that a typed parameter declared out must satisfy two conditions:

The type parameter is used only as a return type of interface methods and not used as a type of method arguments.

The type parameter is not used as a generic constraint for the interface methods.

In terms of code, here is the difference:

```<code>interface ITest<out T1, T2>
{
    T1 GetValue();
    T2 GetValue2();
    void SetValue(T1 Arg1); //Compile Error, Condition 1
    void SetValue(T2 Arg1);
    void SetValue2<T3>(int Arg) where T3 : T1; //Compile Error, Condition 2
    void SetValue<T3>(int Arg) where T3 : T2;
}
</code>```

So your T1 cannot be used as an input parameter for methods and neither can it be used as another generic constraint.

Since you have a constraint stating T must be a structure, condition 2 is automatically satisfied.

So the addition of these 2 statements means:

a structure (where T: struct) that can only be used as return value (out).

Title: covariance with struct constraint

Body:
I'm wondering why is such thing allowed after all?

interface IProducer<out T> where T : struct

if struct is value type then covariance doesn't work because struct is value type. what am I missing here?

Body:
If you look at MSDN for Generic out modifier there is stated that a typed parameter declared out must satisfy two conditions:

The type parameter is used only as a return type of interface methods and not used as a type of method arguments.

The type parameter is not used as a generic constraint for the interface methods.

In terms of code, here is the difference:

interface ITest<out T1, T2>
{
    T1 GetValue();
    T2 GetValue2();
    void SetValue(T1 Arg1); //Compile Error, Condition 1
    void SetValue(T2 Arg1);
    void SetValue2<T3>(int Arg) where T3 : T1; //Compile Error, Condition 2
    void SetValue<T3>(int Arg) where T3 : T2;
}

So your T1 cannot be used as an input parameter for methods and neither can it be used as another generic constraint.

Since you have a constraint stating T must be a structure, condition 2 is automatically satisfied.

So the addition of these 2 statements means:

a structure (where T: struct) that can only be used as return value (out).


问:
how to use multiple ngx-bootstrap date pickers in a component
My requirement is to use more than two date pickers in the same html. I am using ngx-bootstrap date picker. My date picker has an image on click of which date picker shows up. but when I am using more than two date picker date picker is not working as it should work. Just say i have two date pickers with image on it A and B. When i click on the image of A date-picker shows up of A but when i click on the image of B and it toggles for the A only and vice-versa. on click of the image I am calling dp.toggle() function which is same for the other date pickers as well.I can be terribly wrong but I think because it refers to the same old instance of dp instead.
I cannot use date-range picker as in date range picker selecting values for both the dates are mandatory and for me this is not the case.

I tried googling but didn't find any relevant information. Any help/suggestions will be highly appreciated. Thanks

答:
You have duplicated template references (#dp="bsDatepicker" is used for both datepickers). Changing template variable name for second datepicker will solve this.
https://plnkr.co/edit/FGOcj79X1mx3ZPMBKX6C?p=preview


问:
Tomcat 7 not auto unpacking war
I want to deploy my app as root app so I renamed my war to ROOT.war. Default server.xml looks like -

```<code>  <Host name="localhost"  appBase="webapps"
        unpackWARs="true" autoDeploy="true">

    <!-- SingleSignOn valve, share authentication between web applications
         Documentation at: /docs/config/valve.html -->
    <!--
    <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
    -->

    <!-- Access log processes all example.
         Documentation at: /docs/config/valve.html
         Note: The pattern used is equivalent to using pattern="common" -->
    <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
           prefix="localhost_access_log." suffix=".txt"
           pattern="%h %l %u %t "%r" %s %b" />

  </Host>
</code>```

I also need to serve some static content. So I added Context tag-

```<code>  <Host name="localhost"  appBase="webapps"
        unpackWARs="true" autoDeploy="true">

    <!-- SingleSignOn valve, share authentication between web applications
         Documentation at: /docs/config/valve.html -->
    <!--
    <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
    -->

    <Context docBase="/home/athakur/Documents/UI" path="/" />

    <!-- Access log processes all example.
         Documentation at: /docs/config/valve.html
         Note: The pattern used is equivalent to using pattern="common" -->
    <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
           prefix="localhost_access_log." suffix=".txt"
           pattern="%h %l %u %t "%r" %s %b" />

  </Host>
</code>```

I want to serve static content from this path and apis from my ROOT.war.  But as soon as I add context element ROOT.war is not expanding and getting deployed. When I remove the context path it does. Also UI is correctly rendered from the path post adding context tag. So don't want to change that behavior either.

答:
Looks like we cannot do this. We cannot have two context with same path and different docBase under same host. So you cannot have -

```<code><Context docBase="/home/athakur/Documents/UI" path="/" />
<Context docBase="ROOT" path="/" />
</code>```

So I had to settle for

```<code><Context docBase="/home/athakur/Documents/UI" path="/" />
<Context docBase="ROOT" path="/apis" />
</code>```

If you however want to do it at root level only then you need to do it from inside your webapp.
Docs - https://tomcat.apache.org/tomcat-8.0-doc/config/context.html

Title: Tomcat 7 not auto unpacking war

Body:
I want to deploy my app as root app so I renamed my war to ROOT.war. Default server.xml looks like -

  <Host name="localhost"  appBase="webapps"
        unpackWARs="true" autoDeploy="true">

    <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
           prefix="localhost_access_log." suffix=".txt"
           pattern="%h %l %u %t "%r" %s %b" />

  </Host>

I also need to serve some static content. So I added Context tag-

  <Host name="localhost"  appBase="webapps"
        unpackWARs="true" autoDeploy="true">

    <Context docBase="/home/athakur/Documents/UI" path="/" />

    <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
           prefix="localhost_access_log." suffix=".txt"
           pattern="%h %l %u %t "%r" %s %b" />

  </Host>

I want to serve static content from this path and apis from my ROOT.war.  But as soon as I add context element ROOT.war is not expanding and getting deployed. When I remove the context path it does. Also UI is correctly rendered from the path post adding context tag. So don't want to change that behavior either.

Body:
Looks like we cannot do this. We cannot have two context with same path and different docBase under same host. So you cannot have -

<Context docBase="/home/athakur/Documents/UI" path="/" />
<Context docBase="ROOT" path="/" />

So I had to settle for

<Context docBase="/home/athakur/Documents/UI" path="/" />
<Context docBase="ROOT" path="/apis" />

If you however want to do it at root level only then you need to do it from inside your webapp.
Docs - https://tomcat.apache.org/tomcat-8.0-doc/config/context.html


问:
How do I build a custom role based authorization in ASP Core 2?
I have a database that has a user table, access table and a join table assigning a user to multiple access. The site will verify a user by matching the Identity Username from AD with an username in the Users table to verify they can see the site (Intranet). The access table is used to specify which pages they are allow to visit.

In ASP Core 2 how can I use Authorization to perform the same check at Startup to verify they are in the Users table and then take it a step further and use Roles to allow the user access to specific web pages.

I've gone through the documentation but I can't figure out which way to go as the examples use a login that is not necessary in my case using AD.

I have a users table and don't use AD roles because we have a admin for exchange and I do not have access to that.

Thanks in advance

答:
Authorize attribute is the what you are looking for. For example,

```<code>[Authorize(Roles = "Admin, User")]
</code>```

If you are using OAuth for authentication, you will create a ClaimsIdentity while authenticating. Based on the claim, the Authorize attribute will work out of the box. For example,

```<code>public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

        ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

        if (user == null)
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return;
        }

        ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
           OAuthDefaults.AuthenticationType);

        AuthenticationProperties properties = CreateProperties(user.UserName);
        AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
        context.Validated(ticket);
        context.Request.Context.Authentication.SignIn(oAuthIdentity);
    }
</code>```

You can refer to this post, where I have explained a similar scenario in a bit more detail.

Body:
Authorize attribute is the what you are looking for. For example,

[Authorize(Roles = "Admin, User")]

If you are using OAuth for authentication, you will create a ClaimsIdentity while authenticating. Based on the claim, the Authorize attribute will work out of the box. For example,

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

        ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

        if (user == null)
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return;
        }

        ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
           OAuthDefaults.AuthenticationType);

        AuthenticationProperties properties = CreateProperties(user.UserName);
        AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
        context.Validated(ticket);
        context.Request.Context.Authentication.SignIn(oAuthIdentity);
    }

You can refer to this post, where I have explained a similar scenario in a bit more detail.


问:
Why isnt my javascript function being run?
I'm trying to create a log-in page that validates data before it gets submitted to my php page that handles it. I'm using javascript to validate. This is my code:

```<code> <div class = mainInfo>
    <?php include "header.php"; ?>
    <form name = SignUpForm action = signUpHandler.php method ='POST' class = inputLists>
       username: <input type = text name = "userName">
       password: <input id= "p1" type = password name = "password">
       reenter password:  <input id ="p2" type = password name = "passwordConfirmation">

       <input type="submit" name =" submitButton" value ="submit">
    </form>
    <div id="feedback">
    </div>
 </div>
<script>
function validate()
{
    document.getElementById("feedback").innerHTML = "functionbeingcalled";
    var p1 = document.getElementById("p1").value,
                p2 = document.getElementById("p2").value);
    if( ! p1===p2 )
    {

        document.getElementById("feedback").innerHTML = "passwords dont match";
    }
    if(p1==="")
    {
         document.getElementById("feedback").innerHTML = "Must have a password";
    }
}
window.setInterval(validate(),1000);
</script>

<?php include "footer.php"; ?>
</code>```

I would've thought that this script should run every second from the time that the page loads, but the script isn't being run at all.  This line:

```<code> document.getElementById("feedback").innerHTML = "functionbeingcalled";
</code>```

isn't working either.

Besides for this question, is it possible to validate data before submitting using only php? I'm new to web programming.

答:
I would suggest that you add listeners on your input fields! ;)

It will then only run the validation code when changes are made. In other words; only when necessary.

It will run the validation code "immediately" when input is changes. Instead of validation every 1000 ms.

I see you are not using jQuery (yet)? If you want to validate on 'change' using plain js, here is a solution: Plain js solution

If you are okay with adding the jQuery library to you code, then it can be done very easy like this jQuery solution

Body:
I'm trying to create a log-in page that validates data before it gets submitted to my php page that handles it. I'm using javascript to validate. This is my code:

    <?php include "header.php"; ?>
    <form name = SignUpForm action = signUpHandler.php method ='POST' class = inputLists>
       username: <input type = text name = "userName">
       password: <input id= "p1" type = password name = "password">
       reenter password:  <input id ="p2" type = password name = "passwordConfirmation">

       <input type="submit" name =" submitButton" value ="submit">
    </form>

<?php include "footer.php"; ?>

I would've thought that this script should run every second from the time that the page loads, but the script isn't being run at all.  This line:

 document.getElementById("feedback").innerHTML = "functionbeingcalled";

isn't working either.

Besides for this question, is it possible to validate data before submitting using only php? I'm new to web programming.


问:
MpChart doesn't show xaxis label right below the bar
This is the output which i get:

This is my code snippet to show bar graph:
Given all the combinations, doesn't work for me. Also if i limit xaxis label to 4 it still shows 5 values. Have seen so much of solutions but doesn't work for me.

```<code>mChart.setMaxVisibleValueCount(60);
            mChart.setDrawGridBackground(false);
            mChart.setDragEnabled(true);
            mChart.getDescription().setEnabled(false);
            mChart.setFitBars(true);
            mChart.setPinchZoom(false);
            mChart.setDoubleTapToZoomEnabled(false);

            XAxis xAxis = mChart.getXAxis();
            xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
            xAxis.setDrawGridLines(false);
            xAxis.setGranularity(0.5f);
            xAxis.setGranularityEnabled(true);
            xAxis.setValueFormatter(new IAxisValueFormatter() {
                @Override
                public String getFormattedValue(float value, AxisBase axis) {
                    Float dfloat = value;
                    long dateInMillis = dfloat.longValue();
                    return ChartUtils.getMonthYearFromMillis(dateInMillis);
                }
            });

            YAxis leftAxis = mChart.getAxisLeft();
            leftAxis.setValueFormatter(new ChartUtils.YAxisValueRsFormatter(context));
            leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
            leftAxis.setSpaceTop(15f);
            leftAxis.setDrawGridLines(false);

            YAxis rightAxis = mChart.getAxisRight();
            rightAxis.setEnabled(false);

            Legend l = mChart.getLegend();
            l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
            l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
            l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
            l.setDrawInside(false);
            l.setForm(Legend.LegendForm.SQUARE);
            l.setFormSize(9f);
            l.setTextSize(11f);
            l.setXEntrySpace(4f);

            final Map<Long, Double> monthMap = new HashMap<>();
            for (Map.Entry<Long, Double> cMap : chartMap.entrySet()) {
                long month = ChartUtils.getFirstDateMonthYear(cMap.getKey());
                Double amount = monthMap.get(month);
                if (null == amount) {
                    amount = cMap.getValue();
                } else {
                    amount += cMap.getValue();
                }
                monthMap.put(month, amount);
            }
            final Map<Long, Double> treeMap = new TreeMap<>(monthMap);

            final ArrayList<BarEntry> yVals1 = new ArrayList<>();
            for (Map.Entry<Long, Double> cMap : treeMap.entrySet()) {
                yVals1.add(new BarEntry(cMap.getKey(), cMap.getValue().floatValue()));
            }

            final BarDataSet set1;

            if (mChart.getData() != null && mChart.getData().getDataSetCount() > 0) {
                set1 = (BarDataSet) mChart.getData().getDataSetByIndex(0);
                set1.setValues(yVals1);
                mChart.getData().notifyDataChanged();
                mChart.notifyDataSetChanged();
            } else {
                set1 = new BarDataSet(yVals1, "Amounts");
                set1.setValueTextColor(context.getResources().getColor(R.color.dark_gray_primary));
                set1.setColor(context.getResources().getColor(R.color.colorPrimaryLight));
                set1.setHighLightColor(context.getResources().getColor(R.color.colorPrimaryLight));
                set1.setDrawValues(false);

                ArrayList<IBarDataSet> dataSets = new ArrayList<>();
                dataSets.add(set1);

                BarData data = new BarData(dataSets);
                data.setValueTextSize(10f);
                if (monthMap.size() >= 4) {
                    data.setBarWidth(2000000000f);
                } else {
                    data.setBarWidth(2500000000f);
                }

                mChart.setData(data);
            }

            final CustomBarChartMarkerView mv = new CustomBarChartMarkerView(context, R.layout.view_custom_marker);
            mChart.setMarker(mv);
            mChart.setHighlightFullBarEnabled(true);
            if (monthMap.size() > 1) {
                if (monthMap.size() >= 4) {
                    xAxis.setLabelCount(4);
                } else {
                    xAxis.setLabelCount(monthMap.size());
                }
                mChart.setVisibility(View.VISIBLE);
            } else {
                mChart.setVisibility(View.GONE);
            }
</code>```

Have tried all the options and combinations. still doesnt get the desired output. The bar xaxis (date in this case) doesnt show right below the bar.

答:
xAxis.setCenterAxisLabels(true);

Centers the axis labels instead of drawing them at their original position. This is useful especially for grouped BarChart.

From the javadocs

Body:
This is the output which i get:

This is my code snippet to show bar graph:
Given all the combinations, doesn't work for me. Also if i limit xaxis label to 4 it still shows 5 values. Have seen so much of solutions but doesn't work for me.

mChart.setMaxVisibleValueCount(60);
            mChart.setDrawGridBackground(false);
            mChart.setDragEnabled(true);
            mChart.getDescription().setEnabled(false);
            mChart.setFitBars(true);
            mChart.setPinchZoom(false);
            mChart.setDoubleTapToZoomEnabled(false);

            XAxis xAxis = mChart.getXAxis();
            xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
            xAxis.setDrawGridLines(false);
            xAxis.setGranularity(0.5f);
            xAxis.setGranularityEnabled(true);
            xAxis.setValueFormatter(new IAxisValueFormatter() {
                @Override
                public String getFormattedValue(float value, AxisBase axis) {
                    Float dfloat = value;
                    long dateInMillis = dfloat.longValue();
                    return ChartUtils.getMonthYearFromMillis(dateInMillis);
                }
            });

            YAxis leftAxis = mChart.getAxisLeft();
            leftAxis.setValueFormatter(new ChartUtils.YAxisValueRsFormatter(context));
            leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
            leftAxis.setSpaceTop(15f);
            leftAxis.setDrawGridLines(false);

            YAxis rightAxis = mChart.getAxisRight();
            rightAxis.setEnabled(false);

            Legend l = mChart.getLegend();
            l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
            l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
            l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
            l.setDrawInside(false);
            l.setForm(Legend.LegendForm.SQUARE);
            l.setFormSize(9f);
            l.setTextSize(11f);
            l.setXEntrySpace(4f);

            final Map<Long, Double> monthMap = new HashMap<>();
            for (Map.Entry<Long, Double> cMap : chartMap.entrySet()) {
                long month = ChartUtils.getFirstDateMonthYear(cMap.getKey());
                Double amount = monthMap.get(month);
                if (null == amount) {
                    amount = cMap.getValue();
                } else {
                    amount += cMap.getValue();
                }
                monthMap.put(month, amount);
            }
            final Map<Long, Double> treeMap = new TreeMap<>(monthMap);

            final ArrayList<BarEntry> yVals1 = new ArrayList<>();
            for (Map.Entry<Long, Double> cMap : treeMap.entrySet()) {
                yVals1.add(new BarEntry(cMap.getKey(), cMap.getValue().floatValue()));
            }

            final BarDataSet set1;

            if (mChart.getData() != null && mChart.getData().getDataSetCount() > 0) {
                set1 = (BarDataSet) mChart.getData().getDataSetByIndex(0);
                set1.setValues(yVals1);
                mChart.getData().notifyDataChanged();
                mChart.notifyDataSetChanged();
            } else {
                set1 = new BarDataSet(yVals1, "Amounts");
                set1.setValueTextColor(context.getResources().getColor(R.color.dark_gray_primary));
                set1.setColor(context.getResources().getColor(R.color.colorPrimaryLight));
                set1.setHighLightColor(context.getResources().getColor(R.color.colorPrimaryLight));
                set1.setDrawValues(false);

                ArrayList<IBarDataSet> dataSets = new ArrayList<>();
                dataSets.add(set1);

                BarData data = new BarData(dataSets);
                data.setValueTextSize(10f);
                if (monthMap.size() >= 4) {
                    data.setBarWidth(2000000000f);
                } else {
                    data.setBarWidth(2500000000f);
                }

                mChart.setData(data);
            }

            final CustomBarChartMarkerView mv = new CustomBarChartMarkerView(context, R.layout.view_custom_marker);
            mChart.setMarker(mv);
            mChart.setHighlightFullBarEnabled(true);
            if (monthMap.size() > 1) {
                if (monthMap.size() >= 4) {
                    xAxis.setLabelCount(4);
                } else {
                    xAxis.setLabelCount(monthMap.size());
                }
                mChart.setVisibility(View.VISIBLE);
            } else {
                mChart.setVisibility(View.GONE);
            }

Have tried all the options and combinations. still doesnt get the desired output. The bar xaxis (date in this case) doesnt show right below the bar.


问:
What's the best practice for saving initial data in JHipster?
I'm working on a project where some entities are supposed to contain initial data that should be set up when the application is started for the first time.

As of now, we have a function executing when a service is used and if the corresponding entity is empty. But this forces us to check this entity with an if statement everytime the service is called. It was supposed to be a temporary solution.

Now I'm wondering what could be the best way to save that initial data. Is it by using an insertion query that would be executed after setting up the database with all its tables structure (in master.xml for example) ? If so, how can we make sure the data won't be inserted again after restarting the application ? Or is the best way still using the entity services, but then how to do it effectively ?

答:
You can do one of these:

Liquibase

Using Liquibase with a changelog to insert data with the loadData tag (like jhipster inserts initial users). This changelog must be appended to the master.xml. Liquibase takes care of executing each changelog only once.

We did not use this one, because when the initial data changes, you will need another csv with a new changelog and this could be very confusing. Furthermore, you will need the data in a form that matches the form of the table. So, in turn it must be (more or less) static data.

Application Listener

So we use a "startup-hook", so we can already access the database and are able to dynamically define entities, calculating stuff etc.

For this, we hookup the application start event by implementing implements ApplicationListener<ContextRefreshedEvent> in a component, e.g.

```<code>@Component
public class StartupService implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        //...loading stuff
    }
}
</code>```

You will need something to check, if you already inserted the data or not. A simple one, would be to check if the repository is empty. We have somekind of an own migration-table for that, which is checked in the onApplicationEvent. This allows us to "register" different migration-steps to this startup-method.

Body:
You can do one of these:

Liquibase

Using Liquibase with a changelog to insert data with the loadData tag (like jhipster inserts initial users). This changelog must be appended to the master.xml. Liquibase takes care of executing each changelog only once.

We did not use this one, because when the initial data changes, you will need another csv with a new changelog and this could be very confusing. Furthermore, you will need the data in a form that matches the form of the table. So, in turn it must be (more or less) static data.

Application Listener

So we use a "startup-hook", so we can already access the database and are able to dynamically define entities, calculating stuff etc.

For this, we hookup the application start event by implementing implements ApplicationListener<ContextRefreshedEvent> in a component, e.g.

@Component
public class StartupService implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        //...loading stuff
    }
}

You will need something to check, if you already inserted the data or not. A simple one, would be to check if the repository is empty. We have somekind of an own migration-table for that, which is checked in the onApplicationEvent. This allows us to "register" different migration-steps to this startup-method.


问:
Server access Error: java.security.cert.CertificateException: No subject alternative DNS name matching repo1.maven.org found
I am doing: sbt clean and I started getting the following errors:

Server access Error: java.security.cert.CertificateException: No subject alternative DNS name matching repo1.maven.org found

This worked as recently as a few hours back. How do I fix this issue? I cannot do a build.

答: For anyone getting this problem recently, there's currently a bug with the maven repo ssl certificates:  https://issues.sonatype.org/browse/MVNCENTRAL-2870</p>


问:
For high scalability & performance needs, is it preferable to have C++ or Java implementation at the backend of a PHP application?
For high scalability & performance needs for a social portal, is it advisable to have C++ or Java implementation at the backend of an PHP application ?

What are the benefits & trade-offs of the same ?

答: It depends on your definition of "high" and dozens of other factors. Usually performance should be just "enough". From my experience, trying to write the fastest possible implementation from start can backfire badly. As to language choice IMO it depends more on people writing the code and their experience with the problem domain.</p>


问:
Powershell Get-FileMetaData not recognized
I am trying to use the PowerShell command 'Get-FileMetaData' however PowerShell ISE outputs the following error:

```<code>Get-FileMetaData : The term 'Get-FileMetaData' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path
was included, verify that the path is correct and try again.
At line:1 char:1
+ Get-FileMetaData E:\Test_Output
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo          : ObjectNotFound: (Get-FileMetaData:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
</code>```

The path is correct, I have also tried various existing paths. I cant find anything about what version this command requires, but using $PSVersionTable.PSVersion output states 'Major 5' so I believe I am using PS v5.

Has anyone else had issue with this command? I have found various forums mentioning its function, but cant find much on troubleshooting it.

Thanks for any help!

答:
Using the free tool 'exiftool' I have put together to following script:

```<code>$creator = C:\Windows\exiftool.exe "-Creator" $Image.FullName
</code>```

This allows $creator to be the files Creator which in the case of our production images is the same as the Author.

Body:
I am trying to use the PowerShell command 'Get-FileMetaData' however PowerShell ISE outputs the following error:

Get-FileMetaData : The term 'Get-FileMetaData' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path
was included, verify that the path is correct and try again.
At line:1 char:1
+ Get-FileMetaData E:\Test_Output
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo          : ObjectNotFound: (Get-FileMetaData:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

The path is correct, I have also tried various existing paths. I cant find anything about what version this command requires, but using $PSVersionTable.PSVersion output states 'Major 5' so I believe I am using PS v5.

Has anyone else had issue with this command? I have found various forums mentioning its function, but cant find much on troubleshooting it.

Thanks for any help!

Body:
Using the free tool 'exiftool' I have put together to following script:

$creator = C:\Windows\exiftool.exe "-Creator" $Image.FullName

This allows $creator to be the files Creator which in the case of our production images is the same as the Author.