问:
Python: how do I resolve AttributeError: 'module' object has no attribute 'face_recognition_model_v1'
I have downloaded the file and placed it in the same directory from where I am running my code. But here facerec = dlib.face_recognition_model_v1(face_rec_model_path) I am still getting this Atribute error. i have given the full to where it is but still error.

this is my code, I am not able to identify where the problem is ?

```<code>import sys
import os
import dlib
import glob
from skimage import io

predictor_path = '/home/irum/Desktop/DLIB-recognition/shape_predictor_68_face_landmarks.dat'
face_rec_model_path = '/home/irum/Desktop/DLIB-recognition/dlib_face_recognition_resnet_model_v1.dat'
faces_folder_path = '/home/irum/Desktop/DLIB-recognition/att_faces/ERSHIAN'

# Load all the models we need: a detector to find the faces, a shape predictor
# to find face landmarks so we can precisely localize the face, and finally the

# face recognition model.
detector = dlib.get_frontal_face_detector()
sp = dlib.shape_predictor(predictor_path)
facerec = dlib.face_recognition_model_v1(face_rec_model_path)

win = dlib.image_window()

# Now process all the images
for f in glob.glob(os.path.join(faces_folder_path, "*.png")):
    print("Processing file: {}".format(f))
    img = io.imread(f)

    win.clear_overlay()
    win.set_image(img)

    # Ask the detector to find the bounding boxes of each face. The 1 in the
    # second argument indicates that we should upsample the image 1 time. This
    # will make everything bigger and allow us to detect more faces.
    dets = detector(img, 1)
    print("Number of faces detected: {}".format(len(dets)))

    # Now process each face we found.
    for k, d in enumerate(dets):
        print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format(
            k, d.left(), d.top(), d.right(), d.bottom()))
        # Get the landmarks/parts for the face in box d.
        shape = sp(img, d)
        # Draw the face landmarks on the screen so we can see what face is currently being processed.
        win.clear_overlay()
        win.add_overlay(d)
        win.add_overlay(shape)

        face_descriptor = facerec.compute_face_descriptor(img, shape)
        print(face_descriptor)

        dlib.hit_enter_to_continue()
</code>```

答: update dlib. Run this command: pip install dlib==19.4.0

Body:
I have downloaded the file and placed it in the same directory from where I am running my code. But here facerec = dlib.face_recognition_model_v1(face_rec_model_path) I am still getting this Atribute error. i have given the full to where it is but still error.

this is my code, I am not able to identify where the problem is ?

import sys
import os
import dlib
import glob
from skimage import io

predictor_path = '/home/irum/Desktop/DLIB-recognition/shape_predictor_68_face_landmarks.dat'
face_rec_model_path = '/home/irum/Desktop/DLIB-recognition/dlib_face_recognition_resnet_model_v1.dat'
faces_folder_path = '/home/irum/Desktop/DLIB-recognition/att_faces/ERSHIAN'

# Load all the models we need: a detector to find the faces, a shape predictor
# to find face landmarks so we can precisely localize the face, and finally the

# face recognition model.
detector = dlib.get_frontal_face_detector()
sp = dlib.shape_predictor(predictor_path)
facerec = dlib.face_recognition_model_v1(face_rec_model_path)

win = dlib.image_window()

# Now process all the images
for f in glob.glob(os.path.join(faces_folder_path, "*.png")):
    print("Processing file: {}".format(f))
    img = io.imread(f)

    win.clear_overlay()
    win.set_image(img)

    # Ask the detector to find the bounding boxes of each face. The 1 in the
    # second argument indicates that we should upsample the image 1 time. This
    # will make everything bigger and allow us to detect more faces.
    dets = detector(img, 1)
    print("Number of faces detected: {}".format(len(dets)))

    # Now process each face we found.
    for k, d in enumerate(dets):
        print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format(
            k, d.left(), d.top(), d.right(), d.bottom()))
        # Get the landmarks/parts for the face in box d.
        shape = sp(img, d)
        # Draw the face landmarks on the screen so we can see what face is currently being processed.
        win.clear_overlay()
        win.add_overlay(d)
        win.add_overlay(shape)

        face_descriptor = facerec.compute_face_descriptor(img, shape)
        print(face_descriptor)

        dlib.hit_enter_to_continue()


来源: stackexchange

问:
Cannot send push notifications from AWS SNS to my iPad
I'm struggle since 2 days to make push notifications from amazon sns to work on my ipad. After nights spending on google and youtube  i'm desperated and the amazon documentation isn't really helpful.

What i already did until now :

I got the certificate from apple and successfully uploaded the .p12 file to SNS and created the application platform and set the endpoint.

I set my cognito credentials in the viewcontroller in xcode and add some notification listeners in the appdelegate.

So When i run the app on the iPad, this one successfully display the deviceToken in the xcode promp. So i can enter it in SNS console and configure it.

So i created all required stuffs (certificate, .p12, registering the devicetoken etc.)

Unfortunately, when i'm trying to publish to the endpoint (send a notification to my device), i never received any notifications. I don't really know what's going bad. Yet, when i'm trying to do the same by sending a push to an email, its works perfectly.

I watched tons of tutorial in youtube and followed several docs on the web but it seems to definitely not working.

In Xcode i didn't forget to enter the same bundle ID than in my apple developer account (com.XXX.XXX), so i think my app is well configured.

Amazon docs are not dev friendly, most tutorial on the web are outdated,

Is someone know the perfect procedure to send push notifications from Amazon SNS to an Ipad ?

Thank you.

答:
Last night I have successfully integrated AWS SNS.
Yes, the document on AWS are not well documented.

To integrate SNS you need to configure APNS perfectly. I would like to suggest here to first configure all the necessary credentials to get a notification using APNS.
I am expecting here that the developer knows how to create App ID, .p12, .pem and provisioning profile for APNs. Once you successfully get the notification on your device using APNs then you are ready for SNS in quick time. To test the APNs notification you can use this server "www.pushtry.com".

Once everything is successfully done with APNS then jump into your AWS account >> navigate SNS dashboard >> Create platform application.

After hitting Create Application a form will open to mention your application data and some credential entry of certificate.
Please see the below image to follow the steps.
Password entry is optional as per your .p12 certificate.
On press "Load credential from file", Certificate and Private Key entry should fill automatically.

After hitting "Create Platform Application" navigate into application left pane to see the list of created application.

Now you need to create end point.
see the attached image.

Now fill the End point entry, follow the image below.

Now copy the Endpoint ARN to use into AWS console to push the message on your device. The Endpoint is actually an address of your device like token in APNS for AWS. Be sure you copied endpoint completely.

Now again jump into the "SNS Dashboard" to publish the message.

Now paste your copied "Endpoint ARN" and your text message in this form and hit "Publish Message" as per below image.
Here you are done check your device to get the notification.

=================================================================

Above I have explained to push the notification through AWS SNS console.

Now let me add here code to create Application and Endpoint ARN.

```<code>+ (void) initAWSObjectToAccessAccount
{
    // Initialize the Amazon Cognito credentials provider.
    AWSStaticCredentialsProvider* credentialsProvider = [AWSStaticCredentialsProvider
                                                         credentialsWithAccessKey:kAWSAccessKey
                                                         secretKey:kAWSSecretKey];

    AWSServiceConfiguration* configuration = [AWSServiceConfiguration configurationWithRegion:AWSRegionUSWest2
                                                                          credentialsProvider:credentialsProvider];

    [AWSServiceManager defaultServiceManager].defaultServiceConfiguration = configuration;
}

+ (void) createApplicationAndGetAppARN: (void (^) (BOOL isCreated, NSString* appARN))completion
{
    [self initAWSObjectToAccessAccount];

    NSMutableDictionary *myDictionary = [[NSMutableDictionary alloc] init];
    [myDictionary setObject:kCertificateSecretKey forKey:@"PlatformPrincipal"];
    [myDictionary setObject:kCertificatePrivateKey forKey:@"PlatformCredential"];

    /* End Amazon SNS Mobile Push self registration */
    AWSSNSCreatePlatformApplicationInput* platFormAppInput = [AWSSNSCreatePlatformApplicationInput new];
    platFormAppInput.name = @"nFormIOS";
    platFormAppInput.platform = @"APNS";            // When Release
    //platFormAppInput.platform = @"APNS_SANDBOX";  // When Development phase
    platFormAppInput.attributes = myDictionary;

    AWSSNS *snsManager = [AWSSNS defaultSNS];
    [[[snsManager createPlatformApplication:platFormAppInput] continueWithBlock:^id(BFTask *task) {

        if (task.error)
        {
            completion (NO, nil);
        }
        else
        {
            AWSSNSCreatePlatformApplicationResponse* appResponse = task.result;
            NSString* applicationARN = appResponse.platformApplicationArn;
            completion (YES, applicationARN);
        }

        return nil;

    }] waitUntilFinished];
}

+ (void) createSNSEndPoint:(NSString*)applicationARN
                completion:(void (^)(BOOL isSuccess, NSString* endpointARN))completion
{
    /* This is the code to actually register the device with Amazon SNS Mobile Push based on the token received. */
    AWSSNSCreatePlatformEndpointInput* platformEndpointRequest = [AWSSNSCreatePlatformEndpointInput new];
    platformEndpointRequest.customUserData = kUniqueID;     // It could be anything.
    platformEndpointRequest.token = kDeviceTokenNo;         // Device Token No for APNS
    platformEndpointRequest.platformApplicationArn = applicationARN;

    AWSSNS* snsManager = [AWSSNS defaultSNS];

    [[[snsManager createPlatformEndpoint:platformEndpointRequest] continueWithBlock:^id(BFTask *task) {

        if (task.error)
        {
            completion (NO, nil);
        }
        else
        {
            AWSSNSCreateEndpointResponse* endPointRes = task.result;
            completion (YES, endPointRes.endpointArn);
        }

        return nil;
    }] waitUntilFinished];
}
</code>```

===========================

kAWSAccessKey
kAWSSecretKey

This you will get when you will create a credential in AWS account.

kCertificateSecretKey
kCertificatePrivateKey

To get these two follow the steps.

/* STEP 1: Retrieve the SSL certificate (.cer file)

STEP 2: use the following command to convert it into .pem
openssl x509 -in aps.cer -inform DER -out myapnsappcert.pem

STEP 3: Open the file in NotePad. Copy the portion bounded as follows:
-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----

STEP 4: Use it as NSString replacing the special characters (newlines) with escape sequences (\n). It would now resemble this:

-----BEGIN CERTIFICATE-----\nMIIGKTCCBRGgAwIBAgIILZH6mrSmUj8wDQYJKoZIhvcNAQELBQAwgZYxCzAJBgNV\n......\n----END CERTIFICATE-----

STEP 5: Save the .cer file as .p12

STEP 6: Use the following command to get the Private Key:
openssl pkcs12 -in CertificatesSNS.p12 -out myapnsappp
rivatekey.pem -nodes -clcerts

STEP 7: Open the file in NotePad. Copy the portion bounded as follows:

-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----

STEP 8: Repeat Step 4 for this too.

STEP 9: Use the Value retrieved in step4 as "PlatformPrincipal"

STEP 10: Use the Value retrieved in step5 as "PlatformCredential" */

ContentLicense: CC BY-SA 3.0

Body:
Last night I have successfully integrated AWS SNS.
Yes, the document on AWS are not well documented.

To integrate SNS you need to configure APNS perfectly. I would like to suggest here to first configure all the necessary credentials to get a notification using APNS.
I am expecting here that the developer knows how to create App ID, .p12, .pem and provisioning profile for APNs. Once you successfully get the notification on your device using APNs then you are ready for SNS in quick time. To test the APNs notification you can use this server "www.pushtry.com".

Once everything is successfully done with APNS then jump into your AWS account >> navigate SNS dashboard >> Create platform application.

After hitting Create Application a form will open to mention your application data and some credential entry of certificate.
Please see the below image to follow the steps.
Password entry is optional as per your .p12 certificate.
On press "Load credential from file", Certificate and Private Key entry should fill automatically.

After hitting "Create Platform Application" navigate into application left pane to see the list of created application.

Now you need to create end point.
see the attached image.

Now fill the End point entry, follow the image below.

Now copy the Endpoint ARN to use into AWS console to push the message on your device. The Endpoint is actually an address of your device like token in APNS for AWS. Be sure you copied endpoint completely.

Now again jump into the "SNS Dashboard" to publish the message.

Now paste your copied "Endpoint ARN" and your text message in this form and hit "Publish Message" as per below image.
Here you are done check your device to get the notification.

=================================================================

Above I have explained to push the notification through AWS SNS console.

Now let me add here code to create Application and Endpoint ARN.

+ (void) initAWSObjectToAccessAccount
{
    // Initialize the Amazon Cognito credentials provider.
    AWSStaticCredentialsProvider* credentialsProvider = [AWSStaticCredentialsProvider
                                                         credentialsWithAccessKey:kAWSAccessKey
                                                         secretKey:kAWSSecretKey];

    AWSServiceConfiguration* configuration = [AWSServiceConfiguration configurationWithRegion:AWSRegionUSWest2
                                                                          credentialsProvider:credentialsProvider];

    [AWSServiceManager defaultServiceManager].defaultServiceConfiguration = configuration;
}

+ (void) createApplicationAndGetAppARN: (void (^) (BOOL isCreated, NSString* appARN))completion
{
    [self initAWSObjectToAccessAccount];

    NSMutableDictionary *myDictionary = [[NSMutableDictionary alloc] init];
    [myDictionary setObject:kCertificateSecretKey forKey:@"PlatformPrincipal"];
    [myDictionary setObject:kCertificatePrivateKey forKey:@"PlatformCredential"];

    /* End Amazon SNS Mobile Push self registration */
    AWSSNSCreatePlatformApplicationInput* platFormAppInput = [AWSSNSCreatePlatformApplicationInput new];
    platFormAppInput.name = @"nFormIOS";
    platFormAppInput.platform = @"APNS";            // When Release
    //platFormAppInput.platform = @"APNS_SANDBOX";  // When Development phase
    platFormAppInput.attributes = myDictionary;

    AWSSNS *snsManager = [AWSSNS defaultSNS];
    [[[snsManager createPlatformApplication:platFormAppInput] continueWithBlock:^id(BFTask *task) {

        if (task.error)
        {
            completion (NO, nil);
        }
        else
        {
            AWSSNSCreatePlatformApplicationResponse* appResponse = task.result;
            NSString* applicationARN = appResponse.platformApplicationArn;
            completion (YES, applicationARN);
        }

        return nil;

    }] waitUntilFinished];
}

+ (void) createSNSEndPoint:(NSString*)applicationARN
                completion:(void (^)(BOOL isSuccess, NSString* endpointARN))completion
{
    /* This is the code to actually register the device with Amazon SNS Mobile Push based on the token received. */
    AWSSNSCreatePlatformEndpointInput* platformEndpointRequest = [AWSSNSCreatePlatformEndpointInput new];
    platformEndpointRequest.customUserData = kUniqueID;     // It could be anything.
    platformEndpointRequest.token = kDeviceTokenNo;         // Device Token No for APNS
    platformEndpointRequest.platformApplicationArn = applicationARN;

    AWSSNS* snsManager = [AWSSNS defaultSNS];

    [[[snsManager createPlatformEndpoint:platformEndpointRequest] continueWithBlock:^id(BFTask *task) {

        if (task.error)
        {
            completion (NO, nil);
        }
        else
        {
            AWSSNSCreateEndpointResponse* endPointRes = task.result;
            completion (YES, endPointRes.endpointArn);
        }

        return nil;
    }] waitUntilFinished];
}

===========================

kAWSAccessKey
kAWSSecretKey

This you will get when you will create a credential in AWS account.

kCertificateSecretKey
kCertificatePrivateKey

To get these two follow the steps.

/* STEP 1: Retrieve the SSL certificate (.cer file)

STEP 2: use the following command to convert it into .pem
openssl x509 -in aps.cer -inform DER -out myapnsappcert.pem

STEP 3: Open the file in NotePad. Copy the portion bounded as follows:
-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----

STEP 4: Use it as NSString replacing the special characters (newlines) with escape sequences (\n). It would now resemble this:

-----BEGIN CERTIFICATE-----\nMIIGKTCCBRGgAwIBAgIILZH6mrSmUj8wDQYJKoZIhvcNAQELBQAwgZYxCzAJBgNV\n......\n----END CERTIFICATE-----

STEP 5: Save the .cer file as .p12

STEP 6: Use the following command to get the Private Key:
openssl pkcs12 -in CertificatesSNS.p12 -out myapnsappp
rivatekey.pem -nodes -clcerts

STEP 7: Open the file in NotePad. Copy the portion bounded as follows:

-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----

STEP 8: Repeat Step 4 for this too.

STEP 9: Use the Value retrieved in step4 as "PlatformPrincipal"

STEP 10: Use the Value retrieved in step5 as "PlatformCredential" */


问:
MySql PDO - Referring two colowns and displaying the id as result
I have been checking for more than an hour but i cant get the result, my question is, by checking two columns it must display the other columns value as result using PDO.

```<code>$sql ="SELECT column3 FROM tablename WHERE column1 = :request AND column2= :recived";
$conn = $conn->prepare($sql);
$fetch = $conn->execute(array(':request'=> $value1,':recived'=>$value2));
$fetch = $fetch->fetchColumn();
</code>```

please help me with this. Thanks in advance

答:
execute() returns a boolean and you're trying to call fetchColumn() on it. Call fetchColumn() on the statement instead:

```<code>$fetch = $conn->fetchColumn();
</code>```

For future debugging, check your error log because there will be a message indicating the problem here.

Body:
I have been checking for more than an hour but i cant get the result, my question is, by checking two columns it must display the other columns value as result using PDO.

$sql ="SELECT column3 FROM tablename WHERE column1 = :request AND column2= :recived";
$conn = $conn->prepare($sql);
$fetch = $conn->execute(array(':request'=> $value1,':recived'=>$value2));
$fetch = $fetch->fetchColumn();

please help me with this. Thanks in advance

Body:
execute() returns a boolean and you're trying to call fetchColumn() on it. Call fetchColumn() on the statement instead:

$fetch = $conn->fetchColumn();

For future debugging, check your error log because there will be a message indicating the problem here.


问:
Service unavailable message in IIS
I have created a sample ASP.NET website and hosted it in IIS 6.0 . It is working fine , if the identity of the defalut app pool is "local system". But when i changed the identity with some other configurable user id then it is showing as "Service Unavailable".

The following message is found in the event viewver.

"The identity of application pool 'DefaultAppPool' is invalid, so the World Wide Web Publishing Service can not create a worker process to serve the application pool.  Therefore, the application pool has been disabled."

答:
Either the credentials provided for the user is not valid, or the user does not have the needed permissions.

I believe there is a security group on the machine called IIS_WPG that is created when Asp.net is installed, add the user to this group, it should give them the needed permissions.

ContentLicense: CC BY-SA 2.5

Title: Service unavailable message in IIS


问:
create empty workbook in memory openpyxl
```<code>from openpyxl import Workbook
book = Workbook()
for country in "IN US JP UK".split():
    book.create_sheet(title=country)
</code>```

This creates 5 sheets with the first sheet being unwanted.

I know that I can do this:

```<code>book = Workbook()
us_ws = book.active
us_ws.title = "IN"
for country in "US JP UK".split():
    book.create_sheet(title=country)
</code>```

Is there any short cut?

答:
This is the solution as per suggestions from @CharlieClark</p>

```<code>from openpyxl import Workbook

book = Workbook(write_only=True)
for cc in "IN US JP UK".split():
    book.create_sheet(title=cc)
</code>```

Body:
from openpyxl import Workbook
book = Workbook()
for country in "IN US JP UK".split():
    book.create_sheet(title=country)

This creates 5 sheets with the first sheet being unwanted.

I know that I can do this:

book = Workbook()
us_ws = book.active
us_ws.title = "IN"
for country in "US JP UK".split():
    book.create_sheet(title=country)

Is there any short cut?

Body:
This is the solution as per suggestions from @CharlieClark

from openpyxl import Workbook

book = Workbook(write_only=True)
for cc in "IN US JP UK".split():
    book.create_sheet(title=cc)


问:
: Unable to instantiate application and ClassNotFound while sharing apk
when i run the app from android studio it runs fine in simulator and device.

but when i share the debug / release version of apk it got crashed when user taps on a app icon.

following the error that i can see in logs

```<code>03-11 09:16:12.654 25384-25384/com.microtechnicianapp E/AndroidRuntime: FATAL EXCEPTION: main
      Process: com.microtechnicianapp, PID: 25384
      java.lang.RuntimeException: Unable to instantiate application com.microtechnicianapp.App: java.lang.ClassNotFoundException: Didn't find class "com.microtechnicianapp.App" on path: DexPathList[[zip file "/data/app/com.microtechnicianapp-1/base.apk"],nativeLibraryDirectories=[/data/app/com.microtechnicianapp-1/lib/x86, /vendor/lib, /system/lib]]
          at android.app.LoadedApk.makeApplication(LoadedApk.java:563)
          at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4491)
          at android.app.ActivityThread.access$1500(ActivityThread.java:144)
          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1339)
          at android.os.Handler.dispatchMessage(Handler.java:102)
          at android.os.Looper.loop(Looper.java:135)
          at android.app.ActivityThread.main(ActivityThread.java:5221)
          at java.lang.reflect.Method.invoke(Native Method)
          at java.lang.reflect.Method.invoke(Method.java:372)
          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
       Caused by: java.lang.ClassNotFoundException: Didn't find class "com.microtechnicianapp.App" on path: DexPathList[[zip file "/data/app/com.microtechnicianapp-1/base.apk"],nativeLibraryDirectories=[/data/app/com.microtechnicianapp-1/lib/x86, /vendor/lib, /system/lib]]
          at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
          at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
          at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
          at android.app.Instrumentation.newApplication(Instrumentation.java:979)
          at android.app.LoadedApk.makeApplication(LoadedApk.java:558)
          at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4491)
          at android.app.ActivityThread.access$1500(ActivityThread.java:144)
          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1339)
          at android.os.Handler.dispatchMessage(Handler.java:102)
          at android.os.Looper.loop(Looper.java:135)
          at android.app.ActivityThread.main(ActivityThread.java:5221)
          at java.lang.reflect.Method.invoke(Native Method)
          at java.lang.reflect.Method.invoke(Method.java:372)
          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
        Suppressed: java.lang.ClassNotFoundException: com.microtechnicianapp.App
          at java.lang.Class.classForName(Native Method)
          at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
          at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
          at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
                ... 13 more
       Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
</code>```

have read lot of threads but nothing works for me since morning.

have tried lot of things in gradle

```<code>apply plugin: 'com.android.application' apply plugin: 'com.neenbedankt.android-apt' apply plugin: 'realm-android' android {
    compileSdkVersion 25
    buildToolsVersion '25.0.0'
    defaultConfig {
        applicationId "com.microtechnicianapp"
        minSdkVersion 19
        targetSdkVersion 24
        versionCode 1
        versionName "1.2"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }
    buildTypes {
        release {
            minifyEnabled false
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    dexOptions {
        preDexLibraries false
    } } repositories {
    maven {
        url  "http://dl.bintray.com/lukaville/maven"
    } }

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:design:25.0.0'
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.bluelinelabs:logansquare:1.3.6'
    compile 'com.github.aurae.retrofit2:converter-logansquare:1.4.1'
    compile 'org.greenrobot:eventbus:3.0.0'
    compile 'com.google.firebase:firebase-messaging:9.8.0'
    compile 'com.google.android.gms:play-services-maps:9.8.0'
    compile 'com.google.android.gms:play-services-location:9.8.0'
    compile 'com.github.gcacace:signature-pad:1.2.0'
    compile 'com.github.davidpizarro:autolabelui:1.0.1'
    compile 'com.nbsp:library:1.1'
    compile 'com.journeyapps:zxing-android-embedded:3.2.0@aar'
    compile 'com.google.zxing:core:3.2.1'
    testCompile 'junit:junit:4.12'
    apt 'com.bluelinelabs:logansquare-compiler:1.3.6'
    compile 'com.google.android.gms:play-services-appindexing:9.8.0'
    compile 'com.mikhaellopez:circularprogressbar:1.1.1'
    compile 'com.android.support:multidex:1.0.0'

}

apply plugin: 'com.google.gms.google-services'
</code>```

I am using android studio 2.3 hence gradle version is gradle-3.3-all.zip

答:
I had the same crash with the debug apk of one of my apps. The release version (signed with release key) worked.
My app uses multidex.

I ended up disabling Instant Run in Android Studio (File -> Settings -> Build -> Instant Run) and after a rebuild the debug apk worked as well!

Found this solution here:
https://codentrick.com/cant-run-app-on-device-when-it-installed-from-debug-apk-file/

Body:
when i run the app from android studio it runs fine in simulator and device.

but when i share the debug / release version of apk it got crashed when user taps on a app icon.

following the error that i can see in logs

03-11 09:16:12.654 25384-25384/com.microtechnicianapp E/AndroidRuntime: FATAL EXCEPTION: main
      Process: com.microtechnicianapp, PID: 25384
      java.lang.RuntimeException: Unable to instantiate application com.microtechnicianapp.App: java.lang.ClassNotFoundException: Didn't find class "com.microtechnicianapp.App" on path: DexPathList[[zip file "/data/app/com.microtechnicianapp-1/base.apk"],nativeLibraryDirectories=[/data/app/com.microtechnicianapp-1/lib/x86, /vendor/lib, /system/lib]]
          at android.app.LoadedApk.makeApplication(LoadedApk.java:563)
          at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4491)
          at android.app.ActivityThread.access$1500(ActivityThread.java:144)
          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1339)
          at android.os.Handler.dispatchMessage(Handler.java:102)
          at android.os.Looper.loop(Looper.java:135)
          at android.app.ActivityThread.main(ActivityThread.java:5221)
          at java.lang.reflect.Method.invoke(Native Method)
          at java.lang.reflect.Method.invoke(Method.java:372)
          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
       Caused by: java.lang.ClassNotFoundException: Didn't find class "com.microtechnicianapp.App" on path: DexPathList[[zip file "/data/app/com.microtechnicianapp-1/base.apk"],nativeLibraryDirectories=[/data/app/com.microtechnicianapp-1/lib/x86, /vendor/lib, /system/lib]]
          at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
          at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
          at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
          at android.app.Instrumentation.newApplication(Instrumentation.java:979)
          at android.app.LoadedApk.makeApplication(LoadedApk.java:558)
          at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4491)
          at android.app.ActivityThread.access$1500(ActivityThread.java:144)
          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1339)
          at android.os.Handler.dispatchMessage(Handler.java:102)
          at android.os.Looper.loop(Looper.java:135)
          at android.app.ActivityThread.main(ActivityThread.java:5221)
          at java.lang.reflect.Method.invoke(Native Method)
          at java.lang.reflect.Method.invoke(Method.java:372)
          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
        Suppressed: java.lang.ClassNotFoundException: com.microtechnicianapp.App
          at java.lang.Class.classForName(Native Method)
          at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
          at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
          at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
                ... 13 more
       Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available

have read lot of threads but nothing works for me since morning.

have tried lot of things in gradle

apply plugin: 'com.android.application' apply plugin: 'com.neenbedankt.android-apt' apply plugin: 'realm-android' android {
    compileSdkVersion 25
    buildToolsVersion '25.0.0'
    defaultConfig {
        applicationId "com.microtechnicianapp"
        minSdkVersion 19
        targetSdkVersion 24
        versionCode 1
        versionName "1.2"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }
    buildTypes {
        release {
            minifyEnabled false
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    dexOptions {
        preDexLibraries false
    } } repositories {
    maven {
        url  "http://dl.bintray.com/lukaville/maven"
    } }

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:design:25.0.0'
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.bluelinelabs:logansquare:1.3.6'
    compile 'com.github.aurae.retrofit2:converter-logansquare:1.4.1'
    compile 'org.greenrobot:eventbus:3.0.0'
    compile 'com.google.firebase:firebase-messaging:9.8.0'
    compile 'com.google.android.gms:play-services-maps:9.8.0'
    compile 'com.google.android.gms:play-services-location:9.8.0'
    compile 'com.github.gcacace:signature-pad:1.2.0'
    compile 'com.github.davidpizarro:autolabelui:1.0.1'
    compile 'com.nbsp:library:1.1'
    compile 'com.journeyapps:zxing-android-embedded:3.2.0@aar'
    compile 'com.google.zxing:core:3.2.1'
    testCompile 'junit:junit:4.12'
    apt 'com.bluelinelabs:logansquare-compiler:1.3.6'
    compile 'com.google.android.gms:play-services-appindexing:9.8.0'
    compile 'com.mikhaellopez:circularprogressbar:1.1.1'
    compile 'com.android.support:multidex:1.0.0'

}

apply plugin: 'com.google.gms.google-services'

I am using android studio 2.3 hence gradle version is gradle-3.3-all.zip


问:
Where is $PATH coming from on my mac
So I've been trying to install laravel for quite sometime now on my mac

I run :- export PATH="$PATH:$HOME/.composer/vendor/bin" and everything works for that current terminal session. But if I close and open terminal again, it doesn't work.

I've tried adding path to :-

~/bashrc

~/bash_rc

~/bash_profile

/Users/myusername/bash_profile

but it still doesn't work.

If I run echo $PATH , the out put is "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"

Where is this coming from ? I don't see this anywhere in any files.

答:
The problem is that with the export is only for the session. You need to add it permanently by creating a .bash_profile file. Do the following things in your terminal:

cd (Go to your home directory)

nano .bash_profile (Create a bash profile file with nano editor)

export PATH="$PATH:$HOME/.composer/vendor/bin" (Add this line in your file and save it)

Save the file by hitting Ctrl+O.

When you use now echo $PATH you'll see that your directory is added in this list and it will work now every time, without a new export every time.

Title: Where is $PATH coming from on my mac


问:
Horizontal scroll bar bot working in bootstrap modal
I am having a modal, showing div in 'modal-body'.

```<code><div class="modal-body">
    <div class="scoll-tree">
        <div class="history">
            Report Event Details
        </div>
        <div class="history">
            Report Event Details 1
        </div>
       <div class="history">
            Report Event Details 2
        </div>
       <div class="history">
            Report Event Details 3
        </div>
    </div>
</div>
</code>```

Set the class as bellow :

```<code>.scoll-tree{
   width: 400px;
   height:80px;
   overflow-x: scroll;
}

.history {
    background: rgba(255, 255, 255, 0.7);
    float: left;
    min-width: 5em;
    width: 25ex;
    max-height: 3em;
    margin: 2em;
    padding: 1em;
    border: 1px solid rgba(0, 0, 0, 0.2);
    border-radius: 16px;
    box-shadow: 2px 5px 5px rgba(0,0,0,0.2);
    vertical-align: central;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
</code>```

I want horizontal scroll bar to 'scoll-tree' container,  when 'history' div exceed the width.

Currently it give vertical scroll bar, i want only horizontal scroll bar.

https://jsfiddle.net/hemantmalpote/4duq2svh/35/

答:
Very Simple -
Just use max-width instead of width & set overflow-x: auto.
So it will be -

```<code>.scoll-tree{
   max-width: 400px;
   height:80px;
   overflow-x: auto;
}
</code>```

You may first set it to 200px for testing whether scroll appears or not.

Body:
I am having a modal, showing div in 'modal-body'.

            Report Event Details

            Report Event Details 1

            Report Event Details 2

            Report Event Details 3

Set the class as bellow :

.scoll-tree{
   width: 400px;
   height:80px;
   overflow-x: scroll;
}

.history {
    background: rgba(255, 255, 255, 0.7);
    float: left;
    min-width: 5em;
    width: 25ex;
    max-height: 3em;
    margin: 2em;
    padding: 1em;
    border: 1px solid rgba(0, 0, 0, 0.2);
    border-radius: 16px;
    box-shadow: 2px 5px 5px rgba(0,0,0,0.2);
    vertical-align: central;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

I want horizontal scroll bar to 'scoll-tree' container,  when 'history' div exceed the width.

Currently it give vertical scroll bar, i want only horizontal scroll bar.

https://jsfiddle.net/hemantmalpote/4duq2svh/35/

Body:
Very Simple -
Just use max-width instead of width & set overflow-x: auto.
So it will be -

.scoll-tree{
   max-width: 400px;
   height:80px;
   overflow-x: auto;
}

You may first set it to 200px for testing whether scroll appears or not.


问:
How to define an animation?
I'm looking for a way to let a variable equal an animation. So that later I can refer to it and change the speed of the animation.

```<code>   // Image Animation
UIView.animate(withDuration: 2.5, delay: 0.8, options: [.repeat, .curveLinear], animations: {
    self.image.frame = CGRect(x: 250, y: 1200, width: 45, height: 45)

    }, completion: nil)
</code>```

// Function Speed Check

```<code>func speedcheck() {

    if score > 25 {

        Image.stopAnimating()

        // Image Animation
        UIView.animate(withDuration: 1.0, delay: 0.8, options: [.repeat, .curveLinear], animations: {
            self.Image.frame = CGRect(x: 250, y: 1200, width: 45, height: 45)

        }, completion: nil)

        UIView.commitAnimations()

            }
}
</code>```

"Image.stopAnimating()"

As shown in the example, this line does not stop the animation that was previously executed above, because it does not know what to cease. Therefore, I'm wondering how to define the initial animation, so from there I can increase the speed.

What's the best way to speed up an animation when the score is greater than 25?

Any help would be appreciated.

答:
You actually don't need to assign the animation to a variable. I don't think that is even possible.

By speeding up the animation, you mean reducing the duration of the animation.
To do that just hold the animationDuration value in a global variable say animationSpeed.

Just use this animationSpeed variable value in the UIView.animate() method for the duration param.

Declare a global speed param:

```<code>var animationSpeed = TimeInterval.init(5.0)
</code>```

Use this in your UIView.animate() method:

```<code>UIView.animate(withDuration: animationSpeed) {

}
</code>```

Now you can change this animationSpeed param value when a condition is satisfied:

```<code>if condition {
 self.animationSpeed = TimeInterval.init(2.5)
}
</code>```

When you give the animation options as .repeat, the values captured initially while entering the animation block will be used throughout the animation. This is not something that we want. Use something like this

```<code>func animateView() {

        UIView.animate(withDuration: self.speed, delay: 0.0, options: [.curveLinear], animations: {

            // Your animation

        }, completion: { flag in

            if flag {
              if speed > 25 {
                self.speed = TimeInterval.init(2.0)
                self.view.layer.removeAllAnimations()
              }

                self.animateView()
            }
        })
    }
</code>```

Title: How to define an animation?

Body:
I'm looking for a way to let a variable equal an animation. So that later I can refer to it and change the speed of the animation.

   // Image Animation
UIView.animate(withDuration: 2.5, delay: 0.8, options: [.repeat, .curveLinear], animations: {
    self.image.frame = CGRect(x: 250, y: 1200, width: 45, height: 45)

    }, completion: nil)

// Function Speed Check

func speedcheck() {

    if score > 25 {

        Image.stopAnimating()

        // Image Animation
        UIView.animate(withDuration: 1.0, delay: 0.8, options: [.repeat, .curveLinear], animations: {
            self.Image.frame = CGRect(x: 250, y: 1200, width: 45, height: 45)

        }, completion: nil)

        UIView.commitAnimations()

            }
}

"Image.stopAnimating()"

As shown in the example, this line does not stop the animation that was previously executed above, because it does not know what to cease. Therefore, I'm wondering how to define the initial animation, so from there I can increase the speed.

What's the best way to speed up an animation when the score is greater than 25?

Any help would be appreciated.

Body:
You actually don't need to assign the animation to a variable. I don't think that is even possible.

By speeding up the animation, you mean reducing the duration of the animation.
To do that just hold the animationDuration value in a global variable say animationSpeed.

Just use this animationSpeed variable value in the UIView.animate() method for the duration param.

Declare a global speed param:

var animationSpeed = TimeInterval.init(5.0)

Use this in your UIView.animate() method:

UIView.animate(withDuration: animationSpeed) {

}

Now you can change this animationSpeed param value when a condition is satisfied:

if condition {
 self.animationSpeed = TimeInterval.init(2.5)
}

When you give the animation options as .repeat, the values captured initially while entering the animation block will be used throughout the animation. This is not something that we want. Use something like this

func animateView() {

        UIView.animate(withDuration: self.speed, delay: 0.0, options: [.curveLinear], animations: {

            // Your animation

        }, completion: { flag in

            if flag {
              if speed > 25 {
                self.speed = TimeInterval.init(2.0)
                self.view.layer.removeAllAnimations()
              }

                self.animateView()
            }
        })
    }


问:
Click anywhere remove class jQuery
I am trying to take a mobile open menu and close it by clicking anywhere except for the actual navigation items.

Here is my HTML

```<code><nav class="site-nav">
  <ul>
    <li><a title="About Riad Kilani - Front End Developer" href="#">About</a></li>
    <li><a title="Portfolio of Riad Kilani - Front End Developer" href="#">Portfolio</a></li>
    <li><a title="Front End Development News and Tutorials from Riad Kilani" href="#">Blog</a></li>
    <li><a title="Contact Riad Kilani" href="#">Contact</a></li>
  </ul>
</nav>

<div id="content">
  <section id="featured">
    <a href="#" class="mobile-button"><i class="fa fa-bars"> Site Name</i></a>
  </section>
</div>
</code>```

And Here is my JS

```<code>$(document).ready(function(e) {
  $(".mobile-button").click(function() {
    $("#content").addClass("mobile-open");
  });

  $(document).click(function(event){
    if (event.target.id === 'site-nav') {
    } else {
        $("#content").removeClass("mobile-open");
    }
  });
});
</code>```

What am I doing wrong??

答:
You can use this JQuery:

```<code>*:not(.site-nav).click(fuction() {
  // code that does stuff
});
</code>```

To select everything except .site-nav.

Title: Click anywhere remove class jQuery

Body:
I am trying to take a mobile open menu and close it by clicking anywhere except for the actual navigation items.

Here is my HTML

About

Portfolio

Blog

Contact

     Site Name

And Here is my JS

$(document).ready(function(e) {
  $(".mobile-button").click(function() {
    $("#content").addClass("mobile-open");
  });

  $(document).click(function(event){
    if (event.target.id === 'site-nav') {
    } else {
        $("#content").removeClass("mobile-open");
    }
  });
});

What am I doing wrong??

Body:
You can use this JQuery:

*:not(.site-nav).click(fuction() {
  // code that does stuff
});

To select everything except .site-nav.


问:
Assets don't show on staging but do on production
I have this issue I can't figure out. I did some googling and I didn't find a suitable answer, so I am asking the community.

I have a Rails app with 4 environments: development, test, staging and production. Everything works great in development, test and production, but for some reason, the assets are not being served in staging.

Staging is a copy of production basically. I use Capistrano to deploy the site. The assets are being compiled on the server and are of type asset-xxxxx.ext on the server. This works as expected.

The scripts and stylesheets are also being used being compile in the same way (application-xxxxx.css, application-xxxxx.js). This also works as expected.

Problem

The image-url in my stylesheets are not changed to reflect the path set by sproket. For example, the file sprite.png was changed to sprite-25d57a117a61de097e8f943ff745e8b0.png, but the css remains sprite.png.

What is confusing is the environments/staging.rb is the same as environments/production.rb and I have no problem in production.

Failures

I have try to play with the following values:

```<code>config.serve_static_assets = false
config.assets.compress = true
config.assets.compile = false
config.assets.digest = true
</code>```

but nothing works. And as I said, the exact same setting work in production...

Thank you for your help!!!

答:
try below code:

in staging.rb

```<code>config.assets.compile = true
</code>```

then run commad:

```<code>RAILS_ENV=staging rake assets:precompile
</code>```

and push the compiled files with menifest file.

Hope it works!!!

Body:
I have this issue I can't figure out. I did some googling and I didn't find a suitable answer, so I am asking the community.

I have a Rails app with 4 environments: development, test, staging and production. Everything works great in development, test and production, but for some reason, the assets are not being served in staging.

Staging is a copy of production basically. I use Capistrano to deploy the site. The assets are being compiled on the server and are of type asset-xxxxx.ext on the server. This works as expected.

The scripts and stylesheets are also being used being compile in the same way (application-xxxxx.css, application-xxxxx.js). This also works as expected.

Problem

The image-url in my stylesheets are not changed to reflect the path set by sproket. For example, the file sprite.png was changed to sprite-25d57a117a61de097e8f943ff745e8b0.png, but the css remains sprite.png.

What is confusing is the environments/staging.rb is the same as environments/production.rb and I have no problem in production.

Failures

I have try to play with the following values:

config.serve_static_assets = false
config.assets.compress = true
config.assets.compile = false
config.assets.digest = true

but nothing works. And as I said, the exact same setting work in production...

Thank you for your help!!!

Body:
try below code:

in staging.rb

config.assets.compile = true

then run commad:

RAILS_ENV=staging rake assets:precompile

and push the compiled files with menifest file.

Hope it works!!!


问:
Shell script to parse through a file ( csv ) and process line by line
Hi Need a shell script to parse through the csv file - Line by line and then field by field ]

the file will look like this

```<code>X1,X2,X3,X4
Y1,Y2,Y3,Y4
</code>```

I need to extract each of these X1,X2....

I wrote a script but it fails if the line exceeds one line..

答:
Since eykanal mentioned AWk and and sed, I thought I'd show how you could use them.

```<code>awk -F, 'BEGIN{OFS="\n"}{$1=$1; print}' inputfile
</code>```

or

```<code>sed 's/,/\n/' inputfile
</code>```

Then a shell script could process their output:

```<code>awk_or_sed_cmd | while read -r field
do
    do_something "$field"
done
</code>```

Of course, you could do the processing within the AWK script:

```<code>awk -F, '{for (i=1;i<=NF;i++) do_something($i)}' inputfile
</code>```

Body:
Hi Need a shell script to parse through the csv file - Line by line and then field by field ]

the file will look like this

X1,X2,X3,X4
Y1,Y2,Y3,Y4

I need to extract each of these X1,X2....

I wrote a script but it fails if the line exceeds one line..

Body:
Since eykanal mentioned AWk and and sed, I thought I'd show how you could use them.

awk -F, 'BEGIN{OFS="\n"}{$1=$1; print}' inputfile

or

sed 's/,/\n/' inputfile

Then a shell script could process their output:

awk_or_sed_cmd | while read -r field
do
    do_something "$field"
done

Of course, you could do the processing within the AWK script:

awk -F, '{for (i=1;i<=NF;i++) do_something($i)}' inputfile


问:
set number picker am pm value dynamically
I am working on custom number picker for displaying AM and PM values.Please check the below code for number picker.

```<code><com.naushad.kenocustomer.util.NumberPicker
                    android:id="@+id/np_ampm"
                    android:layout_width="wrap_content"
                    android:layout_height="130dp"
                    android:layout_marginTop="10dp"
                    android:layout_marginBottom="10dp"
                    android:layout_centerHorizontal="true"/>
</code>```

XML code looks like this and below is the java code.

```<code>    final String ampm[] = {"AM", "PM"};
            datetimeBinding.npAmpm.setFormatter(R.string.number_picker_formatter);

            datetimeBinding.npAmpm.setSelectedTextColor(Color.parseColor("#09bcf2"));
            datetimeBinding.npAmpm.setTextColor(Color.parseColor("#babdc2"));
            datetimeBinding.npAmpm.setDefaultSelectedTextSize(20);
            datetimeBinding.npAmpm.setTextSize(getResources().getDimension(R.dimen.fifteen));

            datetimeBinding.npAmpm.setMinValue(1);
            datetimeBinding.npAmpm.setMaxValue(ampm.length);
            datetimeBinding.npAmpm.setDisplayedValues(ampm);
int isAM = c.get(Calendar.AM_PM);
        int myValue = Arrays.asList(ampm).indexOf(String.valueOf(isAM));
        if(isAM == 0)
            datetimeBinding.npAmpm.setValue(Integer.parseInt(ampm[1].toString()));
        else
            datetimeBinding.npAmpm.setValue(Integer.parseInt(ampm[1].toString()));
</code>```

now i am going to set number picker value dynamically as per the current time.but i have written code in following way and getting the number format exception.

I want to set am pm value to number picker as per the current time.Please suggest me how can i achieve that.thanks in advance..

答:
I guess you are getting your error somewhere around here?

```<code> if(isAM == 0)
        datetimeBinding.npAmpm.setValue(Integer.parseInt(ampm[1].toString()));
    else
        datetimeBinding.npAmpm.setValue(Integer.parseInt(ampm[1].toString()));
</code>```

That seems reasonable since ampm[1] contains the String "AM" and in

```<code>Integer.parseInt(ampm[1].toString())
</code>```

you try to parse that into an integer but "AM" is not a Number but a String. Therefore a

```<code>java.lang.NumberFormatException: For input string: "PM"
</code>```

Exception is totally reasonable. If you want to display it as a string get rid of the Integer.parseInt(...). I don't know what your datetimeBinding.npAmpm exactly is, but if it is a normal label set it like this?

```<code>datetimeBinding.npAmpm.setValue(ampm[1]);
</code>```

(Also: In both cases of if(isAM == 0) you are using ampm[1], I guess one of those should be ampm[0])

Body:
I am working on custom number picker for displaying AM and PM values.Please check the below code for number picker.

<com.naushad.kenocustomer.util.NumberPicker
                    android:id="@+id/np_ampm"
                    android:layout_width="wrap_content"
                    android:layout_height="130dp"
                    android:layout_marginTop="10dp"
                    android:layout_marginBottom="10dp"
                    android:layout_centerHorizontal="true"/>

XML code looks like this and below is the java code.

    final String ampm[] = {"AM", "PM"};
            datetimeBinding.npAmpm.setFormatter(R.string.number_picker_formatter);

            datetimeBinding.npAmpm.setSelectedTextColor(Color.parseColor("#09bcf2"));
            datetimeBinding.npAmpm.setTextColor(Color.parseColor("#babdc2"));
            datetimeBinding.npAmpm.setDefaultSelectedTextSize(20);
            datetimeBinding.npAmpm.setTextSize(getResources().getDimension(R.dimen.fifteen));

            datetimeBinding.npAmpm.setMinValue(1);
            datetimeBinding.npAmpm.setMaxValue(ampm.length);
            datetimeBinding.npAmpm.setDisplayedValues(ampm);
int isAM = c.get(Calendar.AM_PM);
        int myValue = Arrays.asList(ampm).indexOf(String.valueOf(isAM));
        if(isAM == 0)
            datetimeBinding.npAmpm.setValue(Integer.parseInt(ampm[1].toString()));
        else
            datetimeBinding.npAmpm.setValue(Integer.parseInt(ampm[1].toString()));

now i am going to set number picker value dynamically as per the current time.but i have written code in following way and getting the number format exception.

I want to set am pm value to number picker as per the current time.Please suggest me how can i achieve that.thanks in advance..

Body:
I guess you are getting your error somewhere around here?

 if(isAM == 0)
        datetimeBinding.npAmpm.setValue(Integer.parseInt(ampm[1].toString()));
    else
        datetimeBinding.npAmpm.setValue(Integer.parseInt(ampm[1].toString()));

That seems reasonable since ampm[1] contains the String "AM" and in

Integer.parseInt(ampm[1].toString())

you try to parse that into an integer but "AM" is not a Number but a String. Therefore a

java.lang.NumberFormatException: For input string: "PM"

Exception is totally reasonable. If you want to display it as a string get rid of the Integer.parseInt(...). I don't know what your datetimeBinding.npAmpm exactly is, but if it is a normal label set it like this?

datetimeBinding.npAmpm.setValue(ampm[1]);

(Also: In both cases of if(isAM == 0) you are using ampm[1], I guess one of those should be ampm[0])


问:
Creating a new list from a list of tuples in python
I have a list of tuples

```<code>a = [(1,'a'),(2,'b'),(3,'c'),(4,'d')]
</code>```

and another list

```<code>b = [1,2,4]
</code>```

Now, using lists a and b I want to generate a list c which contains the corresponding elements of a which are present in list b.

That means c should be

```<code>c = ['a','b','d']
</code>```

how can I do that?

答:
Nested loops:

```<code>c = []
for b_number in b:
    for a_number, a_letter in a:
        if b_number == a_number:
            c.append(a_letter)
            break
</code>```

or a less efficient (no break) list comprehension:

```<code>c = [a_letter for a_number, a_letter in a for b_number in b if b_number == a_number]
</code>```

Assuming the numbers in a are unique it will be easier to use a dictionary:

```<code>a = {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
b = [1, 2, 4]
c = [a[b_number] for b_number in b]
</code>```

Body:
I have a list of tuples

a = [(1,'a'),(2,'b'),(3,'c'),(4,'d')]

and another list

b = [1,2,4]

Now, using lists a and b I want to generate a list c which contains the corresponding elements of a which are present in list b.

That means c should be

c = ['a','b','d']

how can I do that?

Body:
Nested loops:

c = []
for b_number in b:
    for a_number, a_letter in a:
        if b_number == a_number:
            c.append(a_letter)
            break

or a less efficient (no break) list comprehension:

c = [a_letter for a_number, a_letter in a for b_number in b if b_number == a_number]

Assuming the numbers in a are unique it will be easier to use a dictionary:

a = {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
b = [1, 2, 4]
c = [a[b_number] for b_number in b]


问:
Casting in Load vs. in separate step
I have following Data:

```<code>John,fl,3
John,wt,3
John,sp,4
John,sm,3
Mary,fl,3
Mary,wt,3
Mary,sp,4
Mary,sm,4
</code>```

I want to calculate average gpa (3rd column) in the data by name (first column). For this I created following pig script and it works just fine.

```<code>a = LOAD '/root/sample.txt' using PigStorage(',') as (name:chararray, other:chararray, gpa:int);
b = group a by name;
c = foreach b generate group, AVG(a.gpa);
</code>```

Then I rewrite the same script as below. This time casting columns in a separate step rather than load but below code gives me cast exception error:

```<code>java.lang.Exception: java.lang.ClassCastException: org.apache.pig.data.DataByteArray cannot be cast to java.lang.String
    at org.apache.hadoop.mapred.LocalJobRunner$Job.runTasks(LocalJobRunner.java:462)

a = LOAD '/root/sample.txt' using PigStorage(',');
b = foreach a generate $0 as name:chararray, $1 as other:chararray, $2 as gpa:int;
c = group b by name;
d = foreach c generate group, AVG(b.gpa);
</code>```

I am unable to understand why??? how are the two code samples different?

答:
This looks like a bug which might get fixed from version - 0.17.

Ref : Run a String through Java using Pig and https://issues.apache.org/jira/browse/PIG-2315 for details.

As of now, for second approach to work an explicit type casting is required.

```<code>b = foreach a generate (chararray)$0 as name:chararray, (chararray)$1 as other:chararray, (int)$2 as gpa:int;
</code>```

Title: Casting in Load vs. in separate step

Body:
I have following Data:

John,fl,3
John,wt,3
John,sp,4
John,sm,3
Mary,fl,3
Mary,wt,3
Mary,sp,4
Mary,sm,4

I want to calculate average gpa (3rd column) in the data by name (first column). For this I created following pig script and it works just fine.

a = LOAD '/root/sample.txt' using PigStorage(',') as (name:chararray, other:chararray, gpa:int);
b = group a by name;
c = foreach b generate group, AVG(a.gpa);

Then I rewrite the same script as below. This time casting columns in a separate step rather than load but below code gives me cast exception error:

java.lang.Exception: java.lang.ClassCastException: org.apache.pig.data.DataByteArray cannot be cast to java.lang.String
    at org.apache.hadoop.mapred.LocalJobRunner$Job.runTasks(LocalJobRunner.java:462)

a = LOAD '/root/sample.txt' using PigStorage(',');
b = foreach a generate $0 as name:chararray, $1 as other:chararray, $2 as gpa:int;
c = group b by name;
d = foreach c generate group, AVG(b.gpa);

I am unable to understand why??? how are the two code samples different?

Body:
This looks like a bug which might get fixed from version - 0.17.

Ref : Run a String through Java using Pig and https://issues.apache.org/jira/browse/PIG-2315 for details.

As of now, for second approach to work an explicit type casting is required.

b = foreach a generate (chararray)$0 as name:chararray, (chararray)$1 as other:chararray, (int)$2 as gpa:int;


问:
entryset vs keyset in java collection
Which one better for Performance
entryset() OR keyset() in Java Collection ?

(I) Using enrtySet() in for each loop

```<code>for (Map.Entry<String,Integer> entry : testMap.entrySet()) {
  entry.getKey();
  entry.getValue();`enter code here`
}
</code>```

(II) Using keySet() in for each loop

```<code>for (String key : testMap.keySet()) {
  testMap.get(key);`enter code here`
}
</code>```

答:
It really depends on your requirements. Those sets simply represent three different use cases: if your "iterating" code

needs only keys, iterate keySet()

needs access to key + value; use entrySet()

needs the values, use values()

That's it. Meaning: when you just want to print the value of the map, there is no point in working on iterating keys and then getting values for example.

If you need both key+value, I would recommend for clarity to use entrySet(). Don't worry about performance until you run into real issues. And then start benchmarking your code to understand what happens.

Title: entryset vs keyset in java collection

Body:
Which one better for Performance
entryset() OR keyset() in Java Collection ?

(I) Using enrtySet() in for each loop

for (Map.Entry<String,Integer> entry : testMap.entrySet()) {
  entry.getKey();
  entry.getValue();`enter code here`
}

(II) Using keySet() in for each loop

for (String key : testMap.keySet()) {
  testMap.get(key);`enter code here`
}


问:
LINQ query does not return child fields
I think I'm getting stupid because I can't get my LINQ query to work as I expect. I have one class that has 3 relationships to other classes.

This is the main class

```<code>[Table(Name = "scanResult")]
public class SniffResult
{
    public SniffResult()
    {

    }

    public SniffResult(Address address)
    {
        this.address = address;
    }

    private int _pk_SniffResult;

    [Column(IsPrimaryKey = true, IsDbGenerated = true, Storage = "_pk_SniffResult", Name ="pk_scanResult")]
    public int pk_SniffResult { get { return _pk_SniffResult; } set { this._pk_SniffResult = value; } }

    private int _fk_scan;

    [Column(Storage = "_fk_scan", Name = "scan")]
    public int fk_scan { get { return _fk_scan; } set { this._fk_scan = value; } }

    private Scan _scan;

    [Association(Storage = "_scan", IsForeignKey = true, ThisKey = "fk_scan", OtherKey = "pk_scan")]
    public Scan scan { get { return _scan; } set { this._scan = value; } }

    private int _fk_address;

    [Column(Storage = "_fk_address", Name = "address")]
    public int fk_adress { get { return _fk_address; } set { this._fk_address = value; } }

    private Address _address;

    [Association(Storage ="_address", IsForeignKey = true, ThisKey = "fk_adress", OtherKey = "pk_address")]
    public Address address { get { return _address; } set { this._address = value; } }

    private string _rawResult;

    [Column(Storage = "_rawResult", Name = "raw")]
    public string rawResult { get { return _rawResult; } set { this._rawResult = value; } }

    private int _code = -5;

    [Column(Storage = "_code")]
    public int code { get { return _code; } set { this._code = value; } }

    private DateTime _scanDate = DateTime.Now;

    [Column(Storage = "_scanDate")]
    public DateTime scanDate { get { return _scanDate; } set { this._scanDate = value; } }

    private int? _fk_proxy;

    [Column(Storage = "_fk_proxy", Name = "usedProxy", CanBeNull = true)]
    public int? fk_proxy { get { return _fk_proxy; } set { this._fk_proxy = value; } }

    private ProxyData _usedProxy;

    [Association(Storage = "_usedProxy", IsForeignKey = true, ThisKey = "fk_proxy", OtherKey = "pk_proxy")]
    public ProxyData usedProxy { get { return _usedProxy; } set { this._usedProxy = value; } }

    public string message { get; set; } = "";

    public bool availability { get; set; }

    public int planCode { get; set; }

    public string planning { get; set; }

    public override string ToString()
    {
        return string.Format("availability={0}, code={1}, message={2}", availability, code, message);
    }
}
</code>```

This is one of the child classes

```<code>[Table(Name = "address")]
public class Address
{
    private int _pk_address;

    [Column(IsPrimaryKey = true, IsDbGenerated = true, Storage = "_pk_address")]
    public int pk_address { get { return _pk_address; } set { this._pk_address = value; } }

    private string _provId;

    [Column(Storage = "_provId")]
    public string provId { get { return _provId; } set { this._provId = value; } }

    private string _zipcode;

    [Column(Storage = "_zipcode")]
    public string zipcode { get { return _zipcode; } set { this._zipcode = value; } }

    private int _houseNumber;

    [Column(Storage = "_houseNumber")]
    public int houseNumber { get { return _houseNumber; } set { this._houseNumber = value; } }

    private string _addressAddition;

    [Column(Storage = "_addressAddition")]
    public string addressAddition { get { return _addressAddition; } set { this._addressAddition = value; } }

    public string ToAddresString()
    {
        return string.Format("{0} {1}{2}", this.provId, zipcode, houseNumber, addressAddition);
    }

    public override string ToString()
    {
        return string.Format("{0}:\t{1}\t{2}{3}", this.provId, zipcode, houseNumber, addressAddition);
    }
}
</code>```

I want to get SniffResult including the associated fields. But they are all null. This is the code I use:

```<code>         SniffDAO dao = new SniffDAO();

         var test =  from sr in dao.SniffResults
                    where sr.fk_scan == 3
                    select sr;

        foreach (var one in test)
        {
            Console.WriteLine(one.pk_SniffResult);
            Console.WriteLine(one.address);
        }
</code>```

one.address gives me a null, what am I doing wrong?

This is the Dao class

```<code>public class SniffDAO
{
    private string currentDir;
    private DataContext db;
    public Table<Scan> Scans { get; set; }
    public Table<SniffResult> SniffResults { get; set; }
    public Table<Address> Addresses { get; set; }

    public SniffDAO()
    {
        db = new DataContext(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=********;Integrated Security=True;Asynchronous Processing=True");

        db.ObjectTrackingEnabled = true;

        Scans = db.GetTable<Scan>();
        SniffResults = db.GetTable<SniffResult>();
        Addresses = db.GetTable<Address>();

        currentDir = Directory.GetCurrentDirectory();
    }

    public void save()
    {
        db.SubmitChanges();
    }

}
</code>```

答:
You need to Include related entities like this:</p>

```<code>    SniffDAO dao = new SniffDAO();

    var test = dao.SniffResults.Include(x=>x.address).Where(sr.fk_scan == 3);

    foreach (var one in test)
    {
        Console.WriteLine(one.pk_SniffResult);
        Console.WriteLine(one.address);
    }
</code>```

Title: LINQ query does not return child fields

Body:
I think I'm getting stupid because I can't get my LINQ query to work as I expect. I have one class that has 3 relationships to other classes.

This is the main class

[Table(Name = "scanResult")]
public class SniffResult
{
    public SniffResult()
    {

    }

    public SniffResult(Address address)
    {
        this.address = address;
    }

    private int _pk_SniffResult;

    [Column(IsPrimaryKey = true, IsDbGenerated = true, Storage = "_pk_SniffResult", Name ="pk_scanResult")]
    public int pk_SniffResult { get { return _pk_SniffResult; } set { this._pk_SniffResult = value; } }

    private int _fk_scan;

    [Column(Storage = "_fk_scan", Name = "scan")]
    public int fk_scan { get { return _fk_scan; } set { this._fk_scan = value; } }

    private Scan _scan;

    [Association(Storage = "_scan", IsForeignKey = true, ThisKey = "fk_scan", OtherKey = "pk_scan")]
    public Scan scan { get { return _scan; } set { this._scan = value; } }

    private int _fk_address;

    [Column(Storage = "_fk_address", Name = "address")]
    public int fk_adress { get { return _fk_address; } set { this._fk_address = value; } }

    private Address _address;

    [Association(Storage ="_address", IsForeignKey = true, ThisKey = "fk_adress", OtherKey = "pk_address")]
    public Address address { get { return _address; } set { this._address = value; } }

    private string _rawResult;

    [Column(Storage = "_rawResult", Name = "raw")]
    public string rawResult { get { return _rawResult; } set { this._rawResult = value; } }

    private int _code = -5;

    [Column(Storage = "_code")]
    public int code { get { return _code; } set { this._code = value; } }

    private DateTime _scanDate = DateTime.Now;

    [Column(Storage = "_scanDate")]
    public DateTime scanDate { get { return _scanDate; } set { this._scanDate = value; } }

    private int? _fk_proxy;

    [Column(Storage = "_fk_proxy", Name = "usedProxy", CanBeNull = true)]
    public int? fk_proxy { get { return _fk_proxy; } set { this._fk_proxy = value; } }

    private ProxyData _usedProxy;

    [Association(Storage = "_usedProxy", IsForeignKey = true, ThisKey = "fk_proxy", OtherKey = "pk_proxy")]
    public ProxyData usedProxy { get { return _usedProxy; } set { this._usedProxy = value; } }

    public string message { get; set; } = "";

    public bool availability { get; set; }

    public int planCode { get; set; }

    public string planning { get; set; }

    public override string ToString()
    {
        return string.Format("availability={0}, code={1}, message={2}", availability, code, message);
    }
}

This is one of the child classes

[Table(Name = "address")]
public class Address
{
    private int _pk_address;

    [Column(IsPrimaryKey = true, IsDbGenerated = true, Storage = "_pk_address")]
    public int pk_address { get { return _pk_address; } set { this._pk_address = value; } }

    private string _provId;

    [Column(Storage = "_provId")]
    public string provId { get { return _provId; } set { this._provId = value; } }

    private string _zipcode;

    [Column(Storage = "_zipcode")]
    public string zipcode { get { return _zipcode; } set { this._zipcode = value; } }

    private int _houseNumber;

    [Column(Storage = "_houseNumber")]
    public int houseNumber { get { return _houseNumber; } set { this._houseNumber = value; } }

    private string _addressAddition;

    [Column(Storage = "_addressAddition")]
    public string addressAddition { get { return _addressAddition; } set { this._addressAddition = value; } }

    public string ToAddresString()
    {
        return string.Format("{0} {1}{2}", this.provId, zipcode, houseNumber, addressAddition);
    }

    public override string ToString()
    {
        return string.Format("{0}:\t{1}\t{2}{3}", this.provId, zipcode, houseNumber, addressAddition);
    }
}

I want to get SniffResult including the associated fields. But they are all null. This is the code I use:

         SniffDAO dao = new SniffDAO();

         var test =  from sr in dao.SniffResults
                    where sr.fk_scan == 3
                    select sr;

        foreach (var one in test)
        {
            Console.WriteLine(one.pk_SniffResult);
            Console.WriteLine(one.address);
        }

one.address gives me a null, what am I doing wrong?

This is the Dao class

public class SniffDAO
{
    private string currentDir;
    private DataContext db;
    public Table<Scan> Scans { get; set; }
    public Table<SniffResult> SniffResults { get; set; }
    public Table<Address> Addresses { get; set; }

    public SniffDAO()
    {
        db = new DataContext(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=********;Integrated Security=True;Asynchronous Processing=True");

        db.ObjectTrackingEnabled = true;

        Scans = db.GetTable<Scan>();
        SniffResults = db.GetTable<SniffResult>();
        Addresses = db.GetTable<Address>();

        currentDir = Directory.GetCurrentDirectory();
    }

    public void save()
    {
        db.SubmitChanges();
    }

}

Body:
You need to Include related entities like this:

    SniffDAO dao = new SniffDAO();

    var test = dao.SniffResults.Include(x=>x.address).Where(sr.fk_scan == 3);

    foreach (var one in test)
    {
        Console.WriteLine(one.pk_SniffResult);
        Console.WriteLine(one.address);
    }


问:
How to match two values independently of their respectiv postions in a string
I'm searching for the best way to match two values simultaneously.

I'd like to get a true value if both values are in a string but i don't know in which order they appear in the string (e.g. abcdef or bedfa in case i want to match a and b)

Is there a better solution (especially if later I would need more complex values to match) than:

```<code>$string =~ m/(a.*b)|(b.*a)/i
</code>```

答:
You can use positive lookahead as:

```<code>$string =~ /^(?=.*a)(?=.*b).*$/i
</code>```

In general if you want to check the existence of foo and bar anywhere in the string you can do:

```<code>$string =~ /^(?=.*foo)(?=.*bar).*$/i
</code>```

And if you want the foo and bar as separate words and not as substring of any other word, you can add the word boundary as:

```<code>$string =~ /^(?=.*\bfoo\b)(?=.*\bbar\b).*$/i
</code>```

Later if you want to add the check for existence of baz you can just do:

```<code>$string =~ /^(?=.*\bfoo\b)(?=.*\bbar\b)(?=.*\bbaz\b).*$/i
</code>```

Body:
I'm searching for the best way to match two values simultaneously.

I'd like to get a true value if both values are in a string but i don't know in which order they appear in the string (e.g. abcdef or bedfa in case i want to match a and b)

Is there a better solution (especially if later I would need more complex values to match) than:

$string =~ m/(a.*b)|(b.*a)/i

Body:
You can use positive lookahead as:

$string =~ /^(?=.*a)(?=.*b).*$/i

In general if you want to check the existence of foo and bar anywhere in the string you can do:

$string =~ /^(?=.*foo)(?=.*bar).*$/i

And if you want the foo and bar as separate words and not as substring of any other word, you can add the word boundary as:

$string =~ /^(?=.*\bfoo\b)(?=.*\bbar\b).*$/i

Later if you want to add the check for existence of baz you can just do:

$string =~ /^(?=.*\bfoo\b)(?=.*\bbar\b)(?=.*\bbaz\b).*$/i


问:
How to manage connection to database SQL
I have a SQL database and a machine running a java code to fetch information from it.

The machine is listening on a port all the time.

At first I closed the connection after every query, but the increased latency was high.

So I switched to never closing the connection, and now the connection is closed after some time with no use (the latency was low though).

So obviously the solution is somewhere between never closing and always closing.

What is the recommended heuristics to handle connection to SQL database?

Now I am in testing of the server and the amount of requests is low. When the server will run, users will use the server more than it is used now. I can't predict how much more.

答:
Use any connection pool for your use case.If you are using app server you can use app server connection pool or use opensource dbcp connection pool mechanism.

```<code><!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
<dependency>
    <groupId>commons-dbcp</groupId>
    <artifactId>commons-dbcp</artifactId>
    <version>1.2.2</version>
</dependency>
</code>```

dbcp configuration link

```<code>import org.apache.commons.dbcp2.BasicDataSource;

public class DataBaseUtility
{
    private static BasicDataSource dataSource;

    private static BasicDataSource getDataSource()
    {

        if (dataSource == null)
        {
            BasicDataSource ds = new BasicDataSource();
            ds.setUrl("jdbc:mysql://localhost/test");
            ds.setUsername("root");
            ds.setPassword("password");

            ds.setMinIdle(5);
            ds.setMaxIdle(10);
            ds.setMaxOpenPreparedStatements(100);

            dataSource = ds;
        }
        return dataSource;
    }

    public static void main(String[] args) throws SQLException
    {

        try (BasicDataSource dataSource = DataBaseUtility.getDataSource();
                Connection connection = dataSource.getConnection();
                PreparedStatement pstmt = connection.prepareStatement("SELECT * FROM account");)
        {
System.out.println("The Connection Object is of Class: "+connection.getClass());
            try (ResultSet resultSet = pstmt.executeQuery();)
            {
                while (resultSet.next())
                {
                    System.out.println(resultSet.getString(1) + "," + resultSet.getString(2) + "," + resultSet.getString(3));
                }
            }
            catch (Exception e)
            {
                connection.rollback();
                e.printStackTrace();
            }
        }
    }

}
</code>```

Body:
Use any connection pool for your use case.If you are using app server you can use app server connection pool or use opensource dbcp connection pool mechanism.

<!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
<dependency>
    <groupId>commons-dbcp</groupId>
    <artifactId>commons-dbcp</artifactId>
    <version>1.2.2</version>
</dependency>

dbcp configuration link

import org.apache.commons.dbcp2.BasicDataSource;

public class DataBaseUtility
{
    private static BasicDataSource dataSource;

    private static BasicDataSource getDataSource()
    {

        if (dataSource == null)
        {
            BasicDataSource ds = new BasicDataSource();
            ds.setUrl("jdbc:mysql://localhost/test");
            ds.setUsername("root");
            ds.setPassword("password");

            ds.setMinIdle(5);
            ds.setMaxIdle(10);
            ds.setMaxOpenPreparedStatements(100);

            dataSource = ds;
        }
        return dataSource;
    }

    public static void main(String[] args) throws SQLException
    {

        try (BasicDataSource dataSource = DataBaseUtility.getDataSource();
                Connection connection = dataSource.getConnection();
                PreparedStatement pstmt = connection.prepareStatement("SELECT * FROM account");)
        {
System.out.println("The Connection Object is of Class: "+connection.getClass());
            try (ResultSet resultSet = pstmt.executeQuery();)
            {
                while (resultSet.next())
                {
                    System.out.println(resultSet.getString(1) + "," + resultSet.getString(2) + "," + resultSet.getString(3));
                }
            }
            catch (Exception e)
            {
                connection.rollback();
                e.printStackTrace();
            }
        }
    }

}


问:
ElasticSearch cannot find newly written document
In my logic, application writes documents into elasticsearch and it sometimes tries to read it from another thread. But when it tries to read it, query is not returning any hits.

I assume that in POST request (insertion), when I get 201 , it means the document is created.

Is my assumption wrong? What am I missing in here?

Thx for your responses

Neron

EDIT:

save response {“_index”:“customers”,“_type”:“customers”,“_id”:“123",“_version”:1,“result”:“created”,“_shards”:{“total”:2,“successful”:2,“failed”:0},“created”:true}

query request:

```<code>{
  "size": 1,
  "from": 0,
  "query": {
    "bool": {
      "must": [
        {
          "match_phrase": {
            "id": "123"
          }
        }
      ]
    }
  }
}
</code>```

query-response:

```<code>{"took":1,"timed_out":false,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":0,"max_score":null,"hits":[]}}
</code>```

after some time, it gets the response and hits is not now then.

答:
The query request seems to be not correct. You should try "_id" instead of "id":</p>

```<code>    {
     "size": 1,
     "from": 0,
     "query": {
              "bool": {
                       "must": [
                                {
                                 "match_phrase": {
                                 "_id": "123"
                                    }
                                }
                               ]
                     }
             }
    }
</code>```

Body:
In my logic, application writes documents into elasticsearch and it sometimes tries to read it from another thread. But when it tries to read it, query is not returning any hits.

I assume that in POST request (insertion), when I get 201 , it means the document is created.

Is my assumption wrong? What am I missing in here?

Thx for your responses

Neron

EDIT:

save response {“_index”:“customers”,“_type”:“customers”,“_id”:“123",“_version”:1,“result”:“created”,“_shards”:{“total”:2,“successful”:2,“failed”:0},“created”:true}

query request:

{
  "size": 1,
  "from": 0,
  "query": {
    "bool": {
      "must": [
        {
          "match_phrase": {
            "id": "123"
          }
        }
      ]
    }
  }
}

query-response:

{"took":1,"timed_out":false,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":0,"max_score":null,"hits":[]}}

after some time, it gets the response and hits is not now then.

Body:
The query request seems to be not correct. You should try "_id" instead of "id":

    {
     "size": 1,
     "from": 0,
     "query": {
              "bool": {
                       "must": [
                                {
                                 "match_phrase": {
                                 "_id": "123"
                                    }
                                }
                               ]
                     }
             }
    }


问:
NamedParameterJdbcTemplate set params with OR operator and check for null
```<code>class Request{
    private string f1;
    private string f2;
    private string f3;
}
</code>```

I have the following query

```<code>SELECT * FROM tbl WHERE f1  = 'val' OR f2  = 'val2' OR f3  = 'va3'
</code>```

fields from Request can be null. I need to create NamedParameterJdbcTemplate query and check each field for null.

```<code>String query = "SELECT * FROM tbl";
if (request.getF1() !=null && !request.getF1().isEmpty()){
            query += ....
        }
</code>```

This is a very bad solution....

Can I create something like

```<code> Map<String, Object> namedParameters = new HashMap<>();
</code>```

to check all fields for null and if not null add to map and set to query? And set operator OR

答:
in jdbc-template you can't do dynamically-query builder out of box (if value is null exclude it from where section). You should create your own builder.

if you need to ececute dynamic query in one- two places you can do that :

just to refactor request.getF1() !=null && !request.getF1().isEmpty() into something readable and supportable , something like :

```<code>String select = SqlDynamicWhereSectionWithOrHelper.getInstance().
                applyIfPresentValue(fieldName1 , value1).
                applyIfPresentValue("" , null).
                applyIfPresentValue(fieldName2 , value2)
                .buildSqlWithWhere(GIVEN_SELECT);

public final class SqlDynamicWhereSectionWithOrHelper {
    private StringBuffer whereSqlQuery = new StringBuffer();
    public static final String WHERE = " where ";
    public static final String OR = " or ";
    private boolean whereNotPresent = true;

    private SqlDynamicWhereSectionWithOrHelper() {
    }

    public static SqlDynamicWhereSectionWithOrHelper getInstance() {
        return new SqlDynamicWhereSectionWithOrHelper();
    }

    public SqlDynamicWhereSectionWithOrHelper applyIfPresentValue(String fieldName, String fieldValue) {
        if (isNotEmpty(fieldValue) && isNotEmpty(fieldName)) {
            applyWhereOrOr(fieldName + "=" + wrapValue(fieldValue));
        }
        return this;
    }

    public String buildSqlWithWhere(String mainQueryWithoutWhere) {
        return mainQueryWithoutWhere + whereSqlQuery.toString();
    }

    //private section
    private String wrapValue(String fieldValue) {
        return "'" + fieldValue + "'";
    }

    private void applyWhereOrOr(String predicate) {
        String prefix = OR;
        if (whereNotPresent) {
            whereNotPresent = false;
            prefix = WHERE;
        }
        whereSqlQuery.append(prefix);
        whereSqlQuery.append(predicate);
    }

    //if you have apache common(or some other implementation) use  method from lib StringUtils.isEmpty(String value)
    private boolean isNotEmpty(String value) {
        return value != null && value.trim().length() > 0;
    }

}
</code>```

and test for it

```<code> private static final String GIVEN_SELECT = "select * from table";

 @Test
    public void testForWithParamsWithNull(){
        //set-up data
        String fieldName1 = "field1";
        String value1 = "value for field1";

        String fieldName2 = "field2";
        String value2 = "value for field2";

        StringBuffer expectedSelectBuffer = new StringBuffer(GIVEN_SELECT);
        expectedSelectBuffer.append(SqlDynamicWhereSectionWithOrHelper.WHERE);
        expectedSelectBuffer.append(fieldName1+"='"+value1+"'");
        expectedSelectBuffer.append(SqlDynamicWhereSectionWithOrHelper.OR);
        expectedSelectBuffer.append(fieldName2+"='"+value2+"'");
        String expectedSelect = expectedSelectBuffer.toString();

        //execution

        String resultSelect = SqlDynamicWhereSectionWithOrHelper.getInstance().
                applyIfPresentValue(fieldName1 , value1).
                applyIfPresentValue("" , null).
                applyIfPresentValue(fieldName2 , value2)
                .buildSqlWithWhere(GIVEN_SELECT);

        //verification
        assertThat(resultSelect , is(notNullValue()));
        assertThat(resultSelect ,equalTo(expectedSelect));
    }
</code>```

Also you can try to fix it in SQL with checking on empty, but if you have lots of data to go through, this technique will slow down your request.

```<code>SELECT * FROM tbl WHERE (f1  = 'val' or f1 = null) OR (f2  = 'val2' or f2 = null ) OR (f3  = 'va3' or f3=null)
</code>```

Body:
class Request{
    private string f1;
    private string f2;
    private string f3;
}

I have the following query

SELECT * FROM tbl WHERE f1  = 'val' OR f2  = 'val2' OR f3  = 'va3'

fields from Request can be null. I need to create NamedParameterJdbcTemplate query and check each field for null.

String query = "SELECT * FROM tbl";
if (request.getF1() !=null && !request.getF1().isEmpty()){
            query += ....
        }

This is a very bad solution....

Can I create something like

 Map<String, Object> namedParameters = new HashMap<>();

to check all fields for null and if not null add to map and set to query? And set operator OR

Body:
in jdbc-template you can't do dynamically-query builder out of box (if value is null exclude it from where section). You should create your own builder.

if you need to ececute dynamic query in one- two places you can do that :

just to refactor request.getF1() !=null && !request.getF1().isEmpty() into something readable and supportable , something like :

String select = SqlDynamicWhereSectionWithOrHelper.getInstance().
                applyIfPresentValue(fieldName1 , value1).
                applyIfPresentValue("" , null).
                applyIfPresentValue(fieldName2 , value2)
                .buildSqlWithWhere(GIVEN_SELECT);

public final class SqlDynamicWhereSectionWithOrHelper {
    private StringBuffer whereSqlQuery = new StringBuffer();
    public static final String WHERE = " where ";
    public static final String OR = " or ";
    private boolean whereNotPresent = true;

    private SqlDynamicWhereSectionWithOrHelper() {
    }

    public static SqlDynamicWhereSectionWithOrHelper getInstance() {
        return new SqlDynamicWhereSectionWithOrHelper();
    }

    public SqlDynamicWhereSectionWithOrHelper applyIfPresentValue(String fieldName, String fieldValue) {
        if (isNotEmpty(fieldValue) && isNotEmpty(fieldName)) {
            applyWhereOrOr(fieldName + "=" + wrapValue(fieldValue));
        }
        return this;
    }

    public String buildSqlWithWhere(String mainQueryWithoutWhere) {
        return mainQueryWithoutWhere + whereSqlQuery.toString();
    }

    //private section
    private String wrapValue(String fieldValue) {
        return "'" + fieldValue + "'";
    }

    private void applyWhereOrOr(String predicate) {
        String prefix = OR;
        if (whereNotPresent) {
            whereNotPresent = false;
            prefix = WHERE;
        }
        whereSqlQuery.append(prefix);
        whereSqlQuery.append(predicate);
    }

    //if you have apache common(or some other implementation) use  method from lib StringUtils.isEmpty(String value)
    private boolean isNotEmpty(String value) {
        return value != null && value.trim().length() > 0;
    }

}

and test for it

 private static final String GIVEN_SELECT = "select * from table";

 @Test
    public void testForWithParamsWithNull(){
        //set-up data
        String fieldName1 = "field1";
        String value1 = "value for field1";

        String fieldName2 = "field2";
        String value2 = "value for field2";

        StringBuffer expectedSelectBuffer = new StringBuffer(GIVEN_SELECT);
        expectedSelectBuffer.append(SqlDynamicWhereSectionWithOrHelper.WHERE);
        expectedSelectBuffer.append(fieldName1+"='"+value1+"'");
        expectedSelectBuffer.append(SqlDynamicWhereSectionWithOrHelper.OR);
        expectedSelectBuffer.append(fieldName2+"='"+value2+"'");
        String expectedSelect = expectedSelectBuffer.toString();

        //execution

        String resultSelect = SqlDynamicWhereSectionWithOrHelper.getInstance().
                applyIfPresentValue(fieldName1 , value1).
                applyIfPresentValue("" , null).
                applyIfPresentValue(fieldName2 , value2)
                .buildSqlWithWhere(GIVEN_SELECT);

        //verification
        assertThat(resultSelect , is(notNullValue()));
        assertThat(resultSelect ,equalTo(expectedSelect));
    }

Also you can try to fix it in SQL with checking on empty, but if you have lots of data to go through, this technique will slow down your request.

SELECT * FROM tbl WHERE (f1  = 'val' or f1 = null) OR (f2  = 'val2' or f2 = null ) OR (f3  = 'va3' or f3=null)


问:
custom class init issue
Hi I've made my own custom class:

with this init method:

```<code>-(id)init:(NSString*) strFilename withImageData:(NSData*) objImageData withUploadTaskDelegate:(id<NSURLSessionTaskDelegate>) objUploadTaskDelegate
{
    filename = strFilename;
    uploadTaskDelegate = objUploadTaskDelegate;
    imageData = objImageData;
    return self;
}
</code>```

I've made sure that the .h file also have the definition of this init file:

```<code>-(id)init:(NSString*) strFilename withImageData:(NSData*) objImageData withUploadTaskDelegate:(id<NSURLSessionTaskDelegate>) objUploadTaskDelegate;
</code>```

however when I try to use it like this:

```<code>UploadQueueCellData *objTest =[UploadQueueCellData init:strImageName withImageData:objData withUploadTaskDelegate:objUploadDelegate];
</code>```

it gives this error:

No known class method for selector
  'init:withImageData:withUploadTaskDelegate:'

this is my 3th day trying to develop in objective c code so I'm sure I'm missing something but I do not seem to be able to spot what I'm doing wrong ?

答:
Your init method is an instance method, not the class method, check below example:

For instance method, you've to create an instance before using it.

```<code>@interface MyClass : NSObject

+ (void)aClassMethod;
- (void)anInstanceMethod;

@end
</code>```

To call a method of MyClass, for instance method:

```<code>[[MyClass alloc] anInstanceMethod]
</code>```

For Class method:

```<code>[MyClass aClassMethod]
</code>```

In your case do this:

```<code>[[UploadQueueCellData alloc] init:strImageName withImageData:objData withUploadTaskDelegate:objUploadDelegate]
</code>```

Class Method

A class method is applied to the class as a whole. If you check the alloc method, that's a class method denoted by the + before the method declaration. It's a class method because it is applied to the class to make a specific instance of that class.

Instance Method

You use an instance method to modify a specific instance of a class that is unique to that instance, rather than to the class as a whole. init for example (denoted with a - before the method declaration), is an instance method because you are normally modifying the properties of that class after it has been created with alloc.

Title: custom class init issue

Body:
Hi I've made my own custom class:

with this init method:

-(id)init:(NSString*) strFilename withImageData:(NSData*) objImageData withUploadTaskDelegate:(id<NSURLSessionTaskDelegate>) objUploadTaskDelegate
{
    filename = strFilename;
    uploadTaskDelegate = objUploadTaskDelegate;
    imageData = objImageData;
    return self;
}

I've made sure that the .h file also have the definition of this init file:

-(id)init:(NSString*) strFilename withImageData:(NSData*) objImageData withUploadTaskDelegate:(id<NSURLSessionTaskDelegate>) objUploadTaskDelegate;

however when I try to use it like this:

UploadQueueCellData *objTest =[UploadQueueCellData init:strImageName withImageData:objData withUploadTaskDelegate:objUploadDelegate];

it gives this error:

No known class method for selector
  'init:withImageData:withUploadTaskDelegate:'

this is my 3th day trying to develop in objective c code so I'm sure I'm missing something but I do not seem to be able to spot what I'm doing wrong ?

Body:
Your init method is an instance method, not the class method, check below example:

For instance method, you've to create an instance before using it.

@interface MyClass : NSObject

+ (void)aClassMethod;
- (void)anInstanceMethod;

@end

To call a method of MyClass, for instance method:

[[MyClass alloc] anInstanceMethod]

For Class method:

[MyClass aClassMethod]

In your case do this:

[[UploadQueueCellData alloc] init:strImageName withImageData:objData withUploadTaskDelegate:objUploadDelegate]

Class Method

A class method is applied to the class as a whole. If you check the alloc method, that's a class method denoted by the + before the method declaration. It's a class method because it is applied to the class to make a specific instance of that class.

Instance Method

You use an instance method to modify a specific instance of a class that is unique to that instance, rather than to the class as a whole. init for example (denoted with a - before the method declaration), is an instance method because you are normally modifying the properties of that class after it has been created with alloc.


问:
The applicationCache is 'undefined' in a shared webworker (HTML5)
I'm trying to access the offline application cache of a shared webworker (HTML5) with no luck. I've been banging my head against this problem for many hours, so I must be missing something... Any help from a JavaScript Ninja out there would be highly appreciated!

The W3C the spec says that:

```<code>cache = self.applicationCache
</code>```

(in a shared worker) should return the ApplicationCache object that applies to the current shared worker.

I'm spawning a shared worker from my app's main script via:

```<code>var worker = new SharedWorker('js/test.js');
worker.port.addEventListener('message', function(e) {
    alert('got message: ' + e.data);
}, false);
worker.port.start();
worker.port.postMessage('hi there...');
</code>```

And here's the code of my shared worker (test.js):

```<code>var cache = self.applicationCache;

onconnect = function(e) {
    var port = e.ports[0];
    port.onmessage = function(e) {
        // test.html contains a <html manifest='test.manifest'> tag
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.open("GET", "test.html", false);
        xmlHttp.send(null);
        var result = xmlHttp.responseText;
        port.postMessage(result);
        port.postMessage('cache: '+ cache);
}
</code>```

}

The alerts I'm getting are:

the contents of test.html (as I expected)

the message "cache : undefined" (oops!)

I tried this on Google Chrome 7.0.517.44 and Safari 5.0.2 (Mac OS X 10.6.4). I also tried to trigger the HTTP GET before accessing the cache and many other variations, but all of these attempts resulted with the same outcome.

Am I missing something obvious? Is this is a known limitations of the browsers I've tested?

Many Thanks,

Ori

答:
I found the same thing - though to be honest, I'm not even sure WHY we'd want access to the applicationCache object... I thought it just, cached things?! Anyway - when I was trying to get it to work I found this thread talking about it:

http://lists.w3.org/Archives/Public/public-webapps/2009OctDec/0519.html

I assumed that I could just stick and entry in my cache.manifest file of the main page that referenced the worker file and it would populate the applicationCache magically. But it didn't appear to (I just got undefined like you did).

In the w3c spec, in the Processing Model section it says:

If worker global scope is actually a SharedWorkerGlobalScope object (i.e. the worker is a shared worker), and there are any relevant application caches that are identified by a manifest URL with the same origin as url and that have url as one of their entries, not excluding entries marked as foreign, then associate the worker global scope with the most appropriate application cache of those that match.

But I can't make it work!

Body:
I'm trying to access the offline application cache of a shared webworker (HTML5) with no luck. I've been banging my head against this problem for many hours, so I must be missing something... Any help from a JavaScript Ninja out there would be highly appreciated!

The W3C the spec says that:

cache = self.applicationCache

(in a shared worker) should return the ApplicationCache object that applies to the current shared worker.

I'm spawning a shared worker from my app's main script via:

var worker = new SharedWorker('js/test.js');
worker.port.addEventListener('message', function(e) {
    alert('got message: ' + e.data);
}, false);
worker.port.start();
worker.port.postMessage('hi there...');

And here's the code of my shared worker (test.js):

var cache = self.applicationCache;

onconnect = function(e) {
    var port = e.ports[0];
    port.onmessage = function(e) {
        // test.html contains a  tag
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.open("GET", "test.html", false);
        xmlHttp.send(null);
        var result = xmlHttp.responseText;
        port.postMessage(result);
        port.postMessage('cache: '+ cache);
}

}

The alerts I'm getting are:

the contents of test.html (as I expected)

the message "cache : undefined" (oops!)

I tried this on Google Chrome 7.0.517.44 and Safari 5.0.2 (Mac OS X 10.6.4). I also tried to trigger the HTTP GET before accessing the cache and many other variations, but all of these attempts resulted with the same outcome.

Am I missing something obvious? Is this is a known limitations of the browsers I've tested?

Many Thanks,

Ori