问:
UIAlertController is Crashed (iPad)
I am using Xcode 6 to develop an iOS Application.

When I used UIAlertController, it can be worked well on iPhone 6 simulator, but crashes on iPad simulator.

My problem while clicking "share", then it could be crashed.
How could I solve it?

Here is my Code:

```<code>override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject] {

    var shareAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Share", handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in

        let shareMenu = UIAlertController(title: nil, message: "Share using", preferredStyle: .ActionSheet)
        let twitterAction = UIAlertAction(title: "Twitter", style: UIAlertActionStyle.Default, handler: nil)
        let facebookAction = UIAlertAction(title: "Facebook", style: UIAlertActionStyle.Default, handler: nil)
        let emailAction = UIAlertAction(title: "Email", style: UIAlertActionStyle.Default, handler: nil)
        let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)

        shareMenu.addAction(twitterAction)
        shareMenu.addAction(facebookAction)
        shareMenu.addAction(emailAction)
        shareMenu.addAction(cancelAction)

        self.presentViewController(shareMenu, animated: true, completion: nil)
        }
    )
</code>```

Xcode showed this message:

```<code>******Terminating app due to uncaught exception 'NSGenericException', reason: 'Your application has presented a UIAlertController (<UIAlertController: 0xaf71c80>) of style UIAlertControllerStyleActionSheet. The modalPresentationStyle of a UIAlertController with this style is UIModalPresentationPopover. You must provide location information for this popover through the alert controller's popoverPresentationController. You must provide either a sourceView and sourceRect or a barButtonItem.  If this information is not known when you present the alert controller, you may provide it in the UIPopoverPresentationControllerDelegate method -prepareForPopoverPresentation.'
*** First throw call stack:
(
    0   CoreFoundation                      0x0023c746 __exceptionPreprocess + 182
    1   libobjc.A.dylib                     0x01c7aa97 objc_exception_throw + 44
    2   UIKit                               0x012c4062 -[UIPopoverPresentationController presentationTransitionWillBegin] + 3086
    3   UIKit                               0x00bda174 __71-[UIPresentationController _initViewHierarchyForPresentationSuperview:]_block_invoke + 1549
    4   UIKit                               0x00bd8247 __56-[UIPresentationController runTransitionForCurrentState]_block_invoke + 198
    5   UIKit                               0x00c0d31b __40+[UIViewController _scheduleTransition:]_block_invoke + 18
    6   UIKit                               0x00ac6862 ___afterCACommitHandler_block_invoke + 15
    7   UIKit                               0x00ac680d _applyBlockToCFArrayCopiedToStack + 415
    8   UIKit                               0x00ac6622 _afterCACommitHandler + 549
    9   CoreFoundation                      0x0015d86e __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 30
    10  CoreFoundation                      0x0015d7b0 __CFRunLoopDoObservers + 400
    11  CoreFoundation                      0x001531ea __CFRunLoopRun + 1226
    12  CoreFoundation                      0x00152a5b CFRunLoopRunSpecific + 443
    13  CoreFoundation                      0x0015288b CFRunLoopRunInMode + 123
    14  GraphicsServices                    0x047b82c9 GSEventRunModal + 192
    15  GraphicsServices                    0x047b8106 GSEventRun + 104
    16  UIKit                               0x00a9c106 UIApplicationMain + 1526
    17  Mars I                              0x0001c724 main + 180
    18  libdyld.dylib                       0x02392ac9 start + 1
    19  ???                                 0x00000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException******
</code>```

答:
I use this code, very easy and understand, maybe i can help for any  </p>

```<code>//if iPhone
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
        [self presentViewController:actionSheet animated:YES completion:nil];
    }
    //if iPad
    else {
        // Change Rect to position Popover
        UIPopoverController *popup = [[UIPopoverController alloc] initWithContentViewController:actionSheet];
        [popup presentPopoverFromRect:CGRectMake(self.view.frame.size.width/2, self.view.frame.size.height/4, 0, 0)inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
    }
</code>```

Title: UIAlertController is Crashed (iPad)

Body:
I am using Xcode 6 to develop an iOS Application.

When I used UIAlertController, it can be worked well on iPhone 6 simulator, but crashes on iPad simulator.

My problem while clicking "share", then it could be crashed.
How could I solve it?

Here is my Code:

override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject] {

    var shareAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Share", handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in

        let shareMenu = UIAlertController(title: nil, message: "Share using", preferredStyle: .ActionSheet)
        let twitterAction = UIAlertAction(title: "Twitter", style: UIAlertActionStyle.Default, handler: nil)
        let facebookAction = UIAlertAction(title: "Facebook", style: UIAlertActionStyle.Default, handler: nil)
        let emailAction = UIAlertAction(title: "Email", style: UIAlertActionStyle.Default, handler: nil)
        let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)

        shareMenu.addAction(twitterAction)
        shareMenu.addAction(facebookAction)
        shareMenu.addAction(emailAction)
        shareMenu.addAction(cancelAction)

        self.presentViewController(shareMenu, animated: true, completion: nil)
        }
    )

Xcode showed this message:

******Terminating app due to uncaught exception 'NSGenericException', reason: 'Your application has presented a UIAlertController (<UIAlertController: 0xaf71c80>) of style UIAlertControllerStyleActionSheet. The modalPresentationStyle of a UIAlertController with this style is UIModalPresentationPopover. You must provide location information for this popover through the alert controller's popoverPresentationController. You must provide either a sourceView and sourceRect or a barButtonItem.  If this information is not known when you present the alert controller, you may provide it in the UIPopoverPresentationControllerDelegate method -prepareForPopoverPresentation.'
*** First throw call stack:
(
    0   CoreFoundation                      0x0023c746 __exceptionPreprocess + 182
    1   libobjc.A.dylib                     0x01c7aa97 objc_exception_throw + 44
    2   UIKit                               0x012c4062 -[UIPopoverPresentationController presentationTransitionWillBegin] + 3086
    3   UIKit                               0x00bda174 __71-[UIPresentationController _initViewHierarchyForPresentationSuperview:]_block_invoke + 1549
    4   UIKit                               0x00bd8247 __56-[UIPresentationController runTransitionForCurrentState]_block_invoke + 198
    5   UIKit                               0x00c0d31b __40+[UIViewController _scheduleTransition:]_block_invoke + 18
    6   UIKit                               0x00ac6862 ___afterCACommitHandler_block_invoke + 15
    7   UIKit                               0x00ac680d _applyBlockToCFArrayCopiedToStack + 415
    8   UIKit                               0x00ac6622 _afterCACommitHandler + 549
    9   CoreFoundation                      0x0015d86e __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 30
    10  CoreFoundation                      0x0015d7b0 __CFRunLoopDoObservers + 400
    11  CoreFoundation                      0x001531ea __CFRunLoopRun + 1226
    12  CoreFoundation                      0x00152a5b CFRunLoopRunSpecific + 443
    13  CoreFoundation                      0x0015288b CFRunLoopRunInMode + 123
    14  GraphicsServices                    0x047b82c9 GSEventRunModal + 192
    15  GraphicsServices                    0x047b8106 GSEventRun + 104
    16  UIKit                               0x00a9c106 UIApplicationMain + 1526
    17  Mars I                              0x0001c724 main + 180
    18  libdyld.dylib                       0x02392ac9 start + 1
    19  ???                                 0x00000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException******

Body:
I use this code, very easy and understand, maybe i can help for any

//if iPhone
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
        [self presentViewController:actionSheet animated:YES completion:nil];
    }
    //if iPad
    else {
        // Change Rect to position Popover
        UIPopoverController *popup = [[UIPopoverController alloc] initWithContentViewController:actionSheet];
        [popup presentPopoverFromRect:CGRectMake(self.view.frame.size.width/2, self.view.frame.size.height/4, 0, 0)inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
    }


来源: stackexchange

问:
Right align button in form
I'm having some trouble using float: right; on a button.

Whatever I do, the button just doesn't wanna go to the right.
It's the second button, the one with the "advanced-search-button" class.

I'm using Bootstrap 4.

HTML

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>

Opgaver

        <form action="" class="form-inline">

                <input type="text" class="form-control" placeholder="Rekvirent">

                <input type="text" class="form-control" placeholder="Tildelt til">

                <select name="select_Afsluttet" id="select_Afsluttet" class="custom-select mb-2 mr-sm-2 mb-sm-0">
                    <option selected hidden value="">Afsluttet</option>
                    <option value="">Ja</option>
                    <option value="">Nej</option>
                    <option value="">Alle</option>
                </select>

                <select name="select_Godkendt" id="select_Godkendt" class="custom-select mb-2 mr-sm-2 mb-sm-0">
                    <option selected hidden value="">Godkendt</option>
                    <option value="">Ja</option>
                    <option value="">Nej</option>
                    <option value="">Alle</option>
                </select>

                <button type="button" class="btn btn-success btn-sm" style="margin-right: 15px;">Søg</button>
                <button type="button" class="btn btn-primary btn-sm advanced-search-button" onclick="advancedSearch(this)">Avanceret søgning</button>

        </form>
        <form action="" class="form-inline form-custom advanced-search">

                <select name="select_Prioritet" id="select_Prioritet" class="custom-select mb-2 mr-sm-2 mb-sm-0">
                    <option selected hidden value="">Prioritet</option>
                    <option value="">Lav</option>
                    <option value="">Middel</option>
                    <option value="">Høj</option>
                    <option value="">Straks</option>
                    <option value="">Driftfejl</option>
                </select>

                <select name="select_Opgavestatus" id="select_Opgavestatus" class="custom-select mb-2 mr-sm-2 mb-sm-0">
                    <option selected hidden value="">Opgavestatus</option>
                    <option value="">Arkiveret</option>
                    <option value="">Sendt til DUC</option>
                    <option value="">Venter på bruger</option>
                    <option value="">Venter på kunde</option>
                    <option value="">Venter på AO</option>
                </select>

                <select name="select_Opgavetype" id="select_Opgavetype" class="custom-select mb-2 mr-sm-2 mb-sm-0">
                    <option selected hidden value="">Opgavetype</option>
                    <option value="">Andet</option>
                    <option value="">Sendt til DUC</option>
                    <option value="">Venter på bruger</option>
                    <option value="">Venter på kunde</option>
                    <option value="">Venter på AO</option>
                </select>

                <select name="select_Underkategori" id="select_Underkategori" class="custom-select mb-2 mr-sm-2 mb-sm-0">
                    <option selected hidden value="">Underkategori</option>
                    <option value="">Via telefon</option>
                    <option value="">Via email</option>
                    <option value="">Internet</option>
                    <option value="">Intranet</option>
                    <option value="">VMS</option>
                </select>

                <input type="text" class="form-control" placeholder="Søg efter">

        </form>

                    Dato
                    ID
                    Rekv
                    Tildelt
                    Beskrivelse
                    Type
                    Seneste log besked
                    Deadline

                    22-11-2017
                    70935
                    HJR
                    LUC
                    Docking Station...
                    Bestilling - Via Telefon
                    8 dage
                    22-11-2017

                    28-11-2017
                    71049
                    LLJ
                    LUC
                    Kan ikke scanne fra sin printe....
                    IT-Drift - Via Telefon
                    3 dage
                    28-11-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

```

I hope you can help me :)

I don't have any custom CSS for this part, I only use the classes for JS.

答: U can as well use the CSS property of top n left.  Set the values in pixel.  And the button should have a position property value to absolute.  It worked for mine. </p>

ContentLicense: CC BY-SA 3.0

Title: Right align button in form

Body:
I'm having some trouble using float: right; on a button.

Whatever I do, the button just doesn't wanna go to the right.
It's the second button, the one with the "advanced-search-button" class.

I'm using Bootstrap 4.

HTML

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>

Opgaver

        <form action="" class="form-inline">

                <input type="text" class="form-control" placeholder="Rekvirent">

                <input type="text" class="form-control" placeholder="Tildelt til">

                <select name="select_Afsluttet" id="select_Afsluttet" class="custom-select mb-2 mr-sm-2 mb-sm-0">
                    <option selected hidden value="">Afsluttet</option>
                    <option value="">Ja</option>
                    <option value="">Nej</option>
                    <option value="">Alle</option>
                </select>

                <select name="select_Godkendt" id="select_Godkendt" class="custom-select mb-2 mr-sm-2 mb-sm-0">
                    <option selected hidden value="">Godkendt</option>
                    <option value="">Ja</option>
                    <option value="">Nej</option>
                    <option value="">Alle</option>
                </select>

                <button type="button" class="btn btn-success btn-sm" style="margin-right: 15px;">Søg</button>
                <button type="button" class="btn btn-primary btn-sm advanced-search-button" onclick="advancedSearch(this)">Avanceret søgning</button>

        </form>
        <form action="" class="form-inline form-custom advanced-search">

                <select name="select_Prioritet" id="select_Prioritet" class="custom-select mb-2 mr-sm-2 mb-sm-0">
                    <option selected hidden value="">Prioritet</option>
                    <option value="">Lav</option>
                    <option value="">Middel</option>
                    <option value="">Høj</option>
                    <option value="">Straks</option>
                    <option value="">Driftfejl</option>
                </select>

                <select name="select_Opgavestatus" id="select_Opgavestatus" class="custom-select mb-2 mr-sm-2 mb-sm-0">
                    <option selected hidden value="">Opgavestatus</option>
                    <option value="">Arkiveret</option>
                    <option value="">Sendt til DUC</option>
                    <option value="">Venter på bruger</option>
                    <option value="">Venter på kunde</option>
                    <option value="">Venter på AO</option>
                </select>

                <select name="select_Opgavetype" id="select_Opgavetype" class="custom-select mb-2 mr-sm-2 mb-sm-0">
                    <option selected hidden value="">Opgavetype</option>
                    <option value="">Andet</option>
                    <option value="">Sendt til DUC</option>
                    <option value="">Venter på bruger</option>
                    <option value="">Venter på kunde</option>
                    <option value="">Venter på AO</option>
                </select>

                <select name="select_Underkategori" id="select_Underkategori" class="custom-select mb-2 mr-sm-2 mb-sm-0">
                    <option selected hidden value="">Underkategori</option>
                    <option value="">Via telefon</option>
                    <option value="">Via email</option>
                    <option value="">Internet</option>
                    <option value="">Intranet</option>
                    <option value="">VMS</option>
                </select>

                <input type="text" class="form-control" placeholder="Søg efter">

        </form>

                    Dato
                    ID
                    Rekv
                    Tildelt
                    Beskrivelse
                    Type
                    Seneste log besked
                    Deadline

                    22-11-2017
                    70935
                    HJR
                    LUC
                    Docking Station...
                    Bestilling - Via Telefon
                    8 dage
                    22-11-2017

                    28-11-2017
                    71049
                    LLJ
                    LUC
                    Kan ikke scanne fra sin printe....
                    IT-Drift - Via Telefon
                    3 dage
                    28-11-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

I hope you can help me :)

I don't have any custom CSS for this part, I only use the classes for JS.


问:
suddenly got error in gradle sync - build tool version 27.0.1 and support version 27.0.1 etc. not found in android studio project
Failed to resolve: com.android.support:support-v13:27.0.1

in my project I am using 25 , but it is showing error for 27.

I opened Android studio project, which was already developed.
Project was built successfully, but after few days suddenly this error came up in gradle sync.
I have installed build tools for 27 and sync with that, but it is still giving same error.
I think it is because of vcs or git used in project, is it possible?
or any other reason ? how to solve it?

Thanks

答:
Add this code in your gradle</p>

```<code> allprojects {
        repositories {
            jcenter()
            mavenCentral()
            maven {
                url "https://maven.google.com"
            }
        }
    }
</code>```

Body:
Add this code in your gradle

 allprojects {
        repositories {
            jcenter()
            mavenCentral()
            maven {
                url "https://maven.google.com"
            }
        }
    }


问:
Android AlarmManager setExact() is not exact
I need to plan sheduled task every 10 minutes.

As in Lollipop and higher version setRepeating() is inexact, I use setExact() and (on alarm firing) I set new exact alarm in 10 minutes.

```<code>private void setAlarm(long triggerTime, PendingIntent pendingIntent) {
        int ALARM_TYPE = AlarmManager.ELAPSED_REALTIME_WAKEUP;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarmManager.setExact(ALARM_TYPE, triggerTime, pendingIntent);
        } else {
            alarmManager.set(ALARM_TYPE, triggerTime, pendingIntent);
        }
    }
</code>```

triggerTime is calculated SystemClock.elapsedRealtime() + 600_000;

When alarm fires, firstly I plan new one, only after that I run my sheduled task.

```<code>setAlarm();
mySheduledTask;
</code>```

I do have WAKE_LOCK permission in my manifest.

When I test this on Android 4 - it works perfect (deviation might be 12-15 milliseconds).

But when I run app on Xiaomi Redmi Note 3 Pro (5.1.1) - deviation can be up to 15 seconds!

For example, I see in my log file: first run was at 1467119934477 (of RTC time), second - at 1467120541683. Difference is 607_206 milliseconds, not 600_000, as it was planned!

What am I missing? What is a way to simulate behaviour of system alarm (it's the most close usecase that can describe my tack)?

PS. I use IntentService for PendingIntent = PendingIntent.getService(context, 0, myIntent, 0);

答:
You can call the method from support.v4:

```<code>AlarmManagerCompat.setExact(...);
</code>```

The internal implementation contains checks by sdk version.

Body:
I need to plan sheduled task every 10 minutes.

As in Lollipop and higher version setRepeating() is inexact, I use setExact() and (on alarm firing) I set new exact alarm in 10 minutes.

private void setAlarm(long triggerTime, PendingIntent pendingIntent) {
        int ALARM_TYPE = AlarmManager.ELAPSED_REALTIME_WAKEUP;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarmManager.setExact(ALARM_TYPE, triggerTime, pendingIntent);
        } else {
            alarmManager.set(ALARM_TYPE, triggerTime, pendingIntent);
        }
    }

triggerTime is calculated SystemClock.elapsedRealtime() + 600_000;

When alarm fires, firstly I plan new one, only after that I run my sheduled task.

setAlarm();
mySheduledTask;

I do have WAKE_LOCK permission in my manifest.

When I test this on Android 4 - it works perfect (deviation might be 12-15 milliseconds).

But when I run app on Xiaomi Redmi Note 3 Pro (5.1.1) - deviation can be up to 15 seconds!

For example, I see in my log file: first run was at 1467119934477 (of RTC time), second - at 1467120541683. Difference is 607_206 milliseconds, not 600_000, as it was planned!

What am I missing? What is a way to simulate behaviour of system alarm (it's the most close usecase that can describe my tack)?

PS. I use IntentService for PendingIntent = PendingIntent.getService(context, 0, myIntent, 0);

Body:
You can call the method from support.v4:

AlarmManagerCompat.setExact(...);

The internal implementation contains checks by sdk version.


问:
pandas groupby: TOP 3 values in each group and store in DataFrame
This is a followup to pandas groupby: TOP 3 values for each group
The solution described there is perfect if the number of rows in each group is at least 3, but it fails if at least one of the groups isn't big enough.

I propose here a new data set that requires another solution.

Some data are saved at random times and I need to find the highest 3 values for each hour:

```<code>                     VAL
TIME
2017-12-08 00:55:00   29
2017-12-08 01:10:00   56
2017-12-08 01:25:00   82
2017-12-08 01:40:00   13
2017-12-08 01:55:00   35
2017-12-08 02:10:00   53
2017-12-08 02:25:00   25
2017-12-08 02:40:00   23
2017-12-08 02:55:00   21
2017-12-08 03:10:00   12
2017-12-08 03:25:00   15
</code>```

it should return this DataFrame, without the time when a max was detected:

```<code>                     VAL1  VAL2  VAL3
TIME
2017-12-08 00:00:00   29   None  None
2017-12-08 01:00:00   82    56    35
2017-12-08 02:00:00   53    25    23
2017-12-08 03:00:00   15    12   None
</code>```

None are in groups where less than 3 rows are available.

The code to generate the data set is:

```<code>from datetime import *
import pandas as pd
import numpy as np

df = pd.DataFrame()

date_ref = datetime(2017,12,8,0,55,0)
days = pd.date_range(date_ref, date_ref + timedelta(0.11), freq='15min')

np.random.seed(seed=1111)
data1 = np.random.randint(1, high=100, size=len(days))

df = pd.DataFrame({'TIME': days, 'VAL': data1})
df = df.set_index('TIME')

# groupby
group1 = df.groupby(pd.Grouper(freq='1H'))
largest3 = pd.DataFrame(group1["VAL"].nlargest(3))
</code>```

My question is how is it possible to save these values into a new DataFrame, perhaps getting them from largest3:

```<code>                                         VAL
TIME                TIME
2017-12-08 00:00:00 2017-12-08 00:55:00   29
2017-12-08 01:00:00 2017-12-08 01:25:00   82
                    2017-12-08 01:10:00   56
                    2017-12-08 01:55:00   35
2017-12-08 02:00:00 2017-12-08 02:10:00   53
                    2017-12-08 02:25:00   25
                    2017-12-08 02:40:00   23
2017-12-08 03:00:00 2017-12-08 03:25:00   15
                    2017-12-08 03:10:00   12
</code>```

EDIT: Added reset_index

```<code>largest3 = pd.DataFrame(group1["VAL"].nlargest(3)).reset_index(level=1, drop=True)
</code>```

returns a better overview but I don't know how to move on from here:

```<code>                     VAL
TIME
2017-12-08 00:00:00   29
2017-12-08 01:00:00   82
2017-12-08 01:00:00   56
2017-12-08 01:00:00   35
2017-12-08 02:00:00   53
2017-12-08 02:00:00   25
2017-12-08 02:00:00   23
2017-12-08 03:00:00   15
2017-12-08 03:00:00   12
</code>```

答:
The trick is to create an index that is not based on set_index+modulus, and cumcount provides a progressive counter inside a group:

```<code>largest3 = (pd.DataFrame(group1["VAL"]
    .nlargest(3))
    .reset_index(level=1, drop=True))

largest3['index'] = largest3.groupby('TIME').cumcount()  # temporary index

largest3 = (largest3.set_index("index", append=True)['VAL']
    .unstack()
    .add_prefix('VAL'))
</code>```

The result is, as requested:

```<code>index                VAL0  VAL1  VAL2
TIME
2017-12-08 00:00:00  29.0   NaN   NaN
2017-12-08 01:00:00  82.0  56.0  35.0
2017-12-08 02:00:00  53.0  25.0  23.0
2017-12-08 03:00:00  15.0  12.0   NaN
</code>```

Body:
This is a followup to pandas groupby: TOP 3 values for each group
The solution described there is perfect if the number of rows in each group is at least 3, but it fails if at least one of the groups isn't big enough.

I propose here a new data set that requires another solution.

Some data are saved at random times and I need to find the highest 3 values for each hour:

                     VAL
TIME
2017-12-08 00:55:00   29
2017-12-08 01:10:00   56
2017-12-08 01:25:00   82
2017-12-08 01:40:00   13
2017-12-08 01:55:00   35
2017-12-08 02:10:00   53
2017-12-08 02:25:00   25
2017-12-08 02:40:00   23
2017-12-08 02:55:00   21
2017-12-08 03:10:00   12
2017-12-08 03:25:00   15

it should return this DataFrame, without the time when a max was detected:

                     VAL1  VAL2  VAL3
TIME
2017-12-08 00:00:00   29   None  None
2017-12-08 01:00:00   82    56    35
2017-12-08 02:00:00   53    25    23
2017-12-08 03:00:00   15    12   None

None are in groups where less than 3 rows are available.

The code to generate the data set is:

from datetime import *
import pandas as pd
import numpy as np

df = pd.DataFrame()

date_ref = datetime(2017,12,8,0,55,0)
days = pd.date_range(date_ref, date_ref + timedelta(0.11), freq='15min')

np.random.seed(seed=1111)
data1 = np.random.randint(1, high=100, size=len(days))

df = pd.DataFrame({'TIME': days, 'VAL': data1})
df = df.set_index('TIME')

# groupby
group1 = df.groupby(pd.Grouper(freq='1H'))
largest3 = pd.DataFrame(group1["VAL"].nlargest(3))

My question is how is it possible to save these values into a new DataFrame, perhaps getting them from largest3:

                                         VAL
TIME                TIME
2017-12-08 00:00:00 2017-12-08 00:55:00   29
2017-12-08 01:00:00 2017-12-08 01:25:00   82
                    2017-12-08 01:10:00   56
                    2017-12-08 01:55:00   35
2017-12-08 02:00:00 2017-12-08 02:10:00   53
                    2017-12-08 02:25:00   25
                    2017-12-08 02:40:00   23
2017-12-08 03:00:00 2017-12-08 03:25:00   15
                    2017-12-08 03:10:00   12

EDIT: Added reset_index

largest3 = pd.DataFrame(group1["VAL"].nlargest(3)).reset_index(level=1, drop=True)

returns a better overview but I don't know how to move on from here:

                     VAL
TIME
2017-12-08 00:00:00   29
2017-12-08 01:00:00   82
2017-12-08 01:00:00   56
2017-12-08 01:00:00   35
2017-12-08 02:00:00   53
2017-12-08 02:00:00   25
2017-12-08 02:00:00   23
2017-12-08 03:00:00   15
2017-12-08 03:00:00   12

Body:
The trick is to create an index that is not based on set_index+modulus, and cumcount provides a progressive counter inside a group:

largest3 = (pd.DataFrame(group1["VAL"]
    .nlargest(3))
    .reset_index(level=1, drop=True))

largest3['index'] = largest3.groupby('TIME').cumcount()  # temporary index

largest3 = (largest3.set_index("index", append=True)['VAL']
    .unstack()
    .add_prefix('VAL'))

The result is, as requested:

index                VAL0  VAL1  VAL2
TIME
2017-12-08 00:00:00  29.0   NaN   NaN
2017-12-08 01:00:00  82.0  56.0  35.0
2017-12-08 02:00:00  53.0  25.0  23.0
2017-12-08 03:00:00  15.0  12.0   NaN


问:
how to load fontawesome css only when an icon is used?
As it appears here: http://fontawesome.io/get-started/ I don't see any way I can have the min.css file loaded in the head only when an icon is used on the frontend.

I don't want to load that css file on all pages, maybe someone using my theme/plugin may not even use an icon at all! This means one more unnecessary server request. You think I can manage that with fontawesome?

Using WordPress by the way but I think it's the same with any CMS/project.

Thanks a lot!

答:
You can first check if there is any class available on the page, if not then exclude it if true then load. like this in jQuery:

```<code> if ( $('.fa').length > 0 ) { code here }
</code>```

I havent looked at the documentation but i think FontAwsome uses .fa as classname

Body:
You can first check if there is any class available on the page, if not then exclude it if true then load. like this in jQuery:

 if ( $('.fa').length > 0 ) { code here }

I havent looked at the documentation but i think FontAwsome uses .fa as classname


问:
Good uses for Apache CollectionUtils
I found the CollectionUtils class a year or so ago and a few of the methods like, collect, and transform seem really cool, however, I have yet to find a use where it would not by syntactically cleaner and\or easier to just write the logic with a simple loop.

Has any found a unique\useful use for these methods (transform, predicatedCollection, collect, etc) e.g. the methods that take a transformer or predicate as an argument?

答:
I think the key issue is designing/coding for flexibility.

If you have a single use case (e.g. selecting the members of a collection that satisfy some specific condition), then coding a relatively simple loop by hand works. On the other hand...

Suppose that the set of possible conditions grew large, or could even be composed on-the-fly at run-time (even dynamically, based on user input/interaction). Or suppose that there were a few very complex conditions which could be composed with operators (e.g. A and B, C and not D, etc.) into even more cases.

Suppose that, having made the selection, there was some other processing that was to be done on the resulting collection.

Now consider the structure of the code that might result from a brute-force, in-line approach to writing the above: an outer loop containing a complex decision process to determine which test(s) to perform, mixed together with code that does one or more things with the "surviving" members of the collection. Such code tends to be (and especially to become over time with maintenance) difficult to understand and difficult to modify without the risk of introducing defects.

So the point is to pursue a strategy in which each aspect:

basic "select something" process,

predicates that express elementary criteria,

combining operators that compose predicates, and

transformers that operate on values,

can be coded and tested independently, then snapped together as needed.

ContentLicense: CC BY-SA 2.5

Title: Good uses for Apache CollectionUtils


问:
Java String.matches regex with OR pipe
I am trying to make the following match, but it is not returning true as I would expect:

```<code>String attrs = "id|fullname|email|title";
String regex = "fullname|email";
return attrs.matches(regex);
</code>```

Instead it returns false.

Why is this? I expect the | pipe in attrs to be interpreted literally as an ASCII character, and the | pipe in regex to be interpreted according to regular expressions (i.e. OR).

The reason I ask is because I am writing an application where I let the user set the attributes in the format attr1|attr2|attr3|..., and I want to verify his/her input by matching it against the possible attribute values: attr1|attr2|attr3|...|attr[n].

Help appreciated,

ktm

Got it working by doing

```<code>String regex = "id.*|fullname.*|email.*|title.*";
String attrs = "fullname|email";
return attrs.matches(regex);
</code>```

答:
java String::matches() matches only whole strings. You need something like

try: regex =".*(fullname|email).*;

Or use the Pattern class

A better way of doing what you want is String[] rattrs = attrs.split("\\|") and then check each string.

Title: Java String.matches regex with OR pipe

Body:
I am trying to make the following match, but it is not returning true as I would expect:

String attrs = "id|fullname|email|title";
String regex = "fullname|email";
return attrs.matches(regex);

Instead it returns false.

Why is this? I expect the | pipe in attrs to be interpreted literally as an ASCII character, and the | pipe in regex to be interpreted according to regular expressions (i.e. OR).

The reason I ask is because I am writing an application where I let the user set the attributes in the format attr1|attr2|attr3|..., and I want to verify his/her input by matching it against the possible attribute values: attr1|attr2|attr3|...|attr[n].

Help appreciated,

ktm

Got it working by doing

String regex = "id.*|fullname.*|email.*|title.*";
String attrs = "fullname|email";
return attrs.matches(regex);


问:
In .net MVC Is there a better way to hide dt elements than adding display: none to each?
One of my views contains a dl element with a lot of the following structures repeated inside:

```<code><dt>
    <label>Accept this thing?</label>
</dt>
<dd>
    @Html.CheckBoxFor(model => model.ThisThingAccepted)
</dd>
</code>```

There are many such "things". I want the checkbox and label to disappear once the user has accepted the thing and posted the data back so it can be saved.

However, use of div and span elements inside a dl are disallowed, so the only HTML-legal way of doing this appears to be:

```<code><dt  @if (Model.ThisThingAccepted) { <text> style="display: none;" </text> }>
    <label>Accept this thing?</label>
</dt>
<dd @if (Model.ThisThingAccepted) { <text> style="display: none;" </text> }>
    @Html.CheckBoxFor(model => model.ThisThingAccepted)
</dd>
</code>```

Which is messy as all hell.

I know I could tidy it up a bit by using a custom display template, but is there a neater way to hide these elements?

答:
One of the ways to do this , by adding a property in your model

```<code>public class YourModel
{
public bool ThisThingAccepted{get;set;}
public string CssClass{get;set;}
}
</code>```

Creating a css class in your style sheet

```<code>.HideElements
{
 display:none;
}
</code>```

When you are binding your model populate the css property
like

```<code>Public ActionResult GetDetails()
{
var data  = getdatafromsomewhere();

var model = new YourModel();
model.ThisThingAccepted = data.ThisThingAccepted;
model.CssClass = data.ThisThingAccepted ? "HideElement" : string.Empty;

return View(model);
}
</code>```

On a side note you can use some other html elements here in place of dt,dl.
When you are rendering your view use the css class from model and assign it to elements where you want to use it.

Body:
One of my views contains a dl element with a lot of the following structures repeated inside:

    Accept this thing?

    @Html.CheckBoxFor(model => model.ThisThingAccepted)

There are many such "things". I want the checkbox and label to disappear once the user has accepted the thing and posted the data back so it can be saved.

However, use of div and span elements inside a dl are disallowed, so the only HTML-legal way of doing this appears to be:

<dt  @if (Model.ThisThingAccepted) { <text> style="display: none;" </text> }>
    Accept this thing?

<dd @if (Model.ThisThingAccepted) { <text> style="display: none;" </text> }>
    @Html.CheckBoxFor(model => model.ThisThingAccepted)

Which is messy as all hell.

I know I could tidy it up a bit by using a custom display template, but is there a neater way to hide these elements?

Body:
One of the ways to do this , by adding a property in your model

public class YourModel
{
public bool ThisThingAccepted{get;set;}
public string CssClass{get;set;}
}

Creating a css class in your style sheet

.HideElements
{
 display:none;
}

When you are binding your model populate the css property
like

Public ActionResult GetDetails()
{
var data  = getdatafromsomewhere();

var model = new YourModel();
model.ThisThingAccepted = data.ThisThingAccepted;
model.CssClass = data.ThisThingAccepted ? "HideElement" : string.Empty;

return View(model);
}

On a side note you can use some other html elements here in place of dt,dl.
When you are rendering your view use the css class from model and assign it to elements where you want to use it.


问:
Show popover upon hover on an icon in a datatable
I generate my datatable in an .ashx file:

```<code>(...)
//E.g. This is how I generate an icon which I put into one of the table cells
 comment = "<i class=\"fa fa-info\" id=\"popoverData\"aria-hidden=\"true\" data-placement=\"bottom\" data-original-title=\"Comments\" data-content=\"" + comments_text + "\"></i>";
(...)
var data = JsonConvert.SerializeObject(data);
var columns = JsonConvert.SerializeObject(columns);
context.Response.Write("{\"data\":" + data + ",\"columns\":" + columns + "}");
</code>```

The goal is to show a bootstrap popover upon hover on the above icon. My JavaScript:

```<code>    $(document).ready(function (){
       //this part should generate the bootstrap popover, but it's NOT
       $('#MyDataTable').on('mouseover', '#popoverData', function () {
         $('#popoverData').popover();
         //console log gets activated
         console.log("I am in the function");
     });
    getData();
    });

   function getData() {
     $('#MyDataTableDiv').html('<table id="MyDataTable" class="display" cellspacing="0" width="100%"></table>');

     $.ajax({
     "url": myUrl/getData.ashx',
     "success": function (json) {
        json.columnDefs = [
            { targets: '_all', defaultContent: "" },
            { targets: '_all', className: 'dt-body-left' }
        ];
        json.dom = 'Bfrtip';
        json.buttons = ['print', 'csv', 'copy'];

        $('#MyDataTable').dataTable(json);

    },
    "dataType": "json"
});
}
</code>```

The javascript mouseover event gets triggered, but the popover is not working. I've tried this too:

```<code>      $(document).ready(function (){
        $('#popoverData').popover();
        getData();
      });
</code>```

But in this case the popover shows up ONLY if the #popoverData element is outside the datatable.

How do I show popover upon hover on the icon?

答:
Please modify your code. </p>

```<code>   $('#MyDataTable').on('mouseover', '#popoverData', function () {
     $(this).popover('show');
 });
</code>```

<p>if this not worked then try </p>

```<code>$(document).on('mouseover', '#popoverData', function () {
$(this).popover('show');
});
</code>```

Body:
I generate my datatable in an .ashx file:

(...)
//E.g. This is how I generate an icon which I put into one of the table cells
 comment = "";
(...)
var data = JsonConvert.SerializeObject(data);
var columns = JsonConvert.SerializeObject(columns);
context.Response.Write("{\"data\":" + data + ",\"columns\":" + columns + "}");

The goal is to show a bootstrap popover upon hover on the above icon. My JavaScript:

    $(document).ready(function (){
       //this part should generate the bootstrap popover, but it's NOT
       $('#MyDataTable').on('mouseover', '#popoverData', function () {
         $('#popoverData').popover();
         //console log gets activated
         console.log("I am in the function");
     });
    getData();
    });

   function getData() {
     $('#MyDataTableDiv').html('

');

     $.ajax({
     "url": myUrl/getData.ashx',
     "success": function (json) {
        json.columnDefs = [
            { targets: '_all', defaultContent: "" },
            { targets: '_all', className: 'dt-body-left' }
        ];
        json.dom = 'Bfrtip';
        json.buttons = ['print', 'csv', 'copy'];

        $('#MyDataTable').dataTable(json);

    },
    "dataType": "json"
});
}

The javascript mouseover event gets triggered, but the popover is not working. I've tried this too:

      $(document).ready(function (){
        $('#popoverData').popover();
        getData();
      });

But in this case the popover shows up ONLY if the #popoverData element is outside the datatable.

How do I show popover upon hover on the icon?

Body:
Please modify your code.

   $('#MyDataTable').on('mouseover', '#popoverData', function () {
     $(this).popover('show');
 });

if this not worked then try

$(document).on('mouseover', '#popoverData', function () {
$(this).popover('show');
});


问:
Get ffmpeg png output as stream (not a png file)
In VB.NET I'm creating sound file waveform with ffmpeg

```<code>ffmpeg -i input -filter_complex "showwavespic=s=640x240:split_channels=1" -frames:v 1 output.png
</code>```

this code works good. But i have no write rights on pc at all and i can't create output.png anywhere. i must to get output.png as stream and put to picturebox as background image.

can someone help me please.

答:
Basic method is

```<code>ffmpeg -i input -filter_complex "..." -frames:v 1 -c:v png -f image2pipe -
</code>```

This will stream the result over stdout.

Body:
In VB.NET I'm creating sound file waveform with ffmpeg

ffmpeg -i input -filter_complex "showwavespic=s=640x240:split_channels=1" -frames:v 1 output.png

this code works good. But i have no write rights on pc at all and i can't create output.png anywhere. i must to get output.png as stream and put to picturebox as background image.

can someone help me please.

Body:
Basic method is

ffmpeg -i input -filter_complex "..." -frames:v 1 -c:v png -f image2pipe -

This will stream the result over stdout.


问:
Python application for updating an embedded device - is it feasible?
I am considering to write a tool for updating a WinCE based device. The update procedure consists of following steps:

get several files from two different zip-archives

start target and while it is booting send a command over serial interface RS232 (switch in bootstrap mode)

transfer WinCE-OS image and a flash-tool over FTP

connect via telnet and execute the flash-tool

reboot target

transfer customization files via FTP

Currently all this is done manually, which is very error prone and time consuming. Especially the step 6 is a pain in the a**, because FTP server on WinCE target often breaks.

I hope, Python could help me accomplish all these steps, the first look in the libraries showed, that there is everithing there: ziplib, ftplib, seriallib, telnetlib.

Does anyone have done something similar? What are hidden problems there?

Thank you for any hint!

EDIT:
There is not Python on target (and ihmo there is no need for).
Target provides telnetd, ftpd via ethernet connection and a boot-console via serial connection. The entire file system is exposed via telnet and ftp - so any file can be accessed through these protocols from the host.

答: You can use pyserial or python for windows extensions to send the serial command, telnetlib to send telnet commands and and ftplib for the FTP part. Eventually, you even can install Python on the WinCE device, but should should not need it.</p>


问:
ngrx effects calls http several times
I am using the latest versions of ngrx (4.1.1) and angular 4.4.4 and can't find the problem here and could need some help.

I am using an effect which calls the this.apiProvider.getLogisticsFolder() and works with the http response. As soon as my reducer returns the new state and everything is working as expected, my rest service is called a second time or even several times (the action/effect is only triggered once and so is the rest call getLogisticsFolder()).

What am I missing here?

```<code>@Effect()
syncFolders$ = this.actions$
    .ofType<LogisticsFolderActions.SyncFolders>(LogisticsFolderActions.SYNC_FOLDERS)
    .mergeMap(() => this.apiProvider.getLogisticsFolder()
        .withLatestFrom(this._store.select(state => state.logisticsFolders), this._store.select(state => state.settings))
        .map(([cloudLogisticsFolder, localLogisticsFolderState, settingsState]) =>
        {
            let tempLocalLogisticsFolder = localLogisticsFolderState.find(localLogisticsFolderState => localLogisticsFolderState.tenant === settingsState.baseURL);
            if (tempLocalLogisticsFolder)
            {
                //now check if the folder structure has been added, deleted or changed
                let updatedFolders = this.logisticsFolderProvider.checkAndProceedLogisticsFolderUpdate(cloudLogisticsFolder, tempLocalLogisticsFolder.logisticsFolders)
                this.logisticsFolderProvider.checkAndProceedTasksUpdate(cloudLogisticsFolder, updatedFolders)

                return new LogisticsFolderActions.SyncSuccess;
            } else
            {
                let logisticsFolderState = <LogisticsFolder.State>{};
                logisticsFolderState.tenant = settingsState.baseURL;
                logisticsFolderState.logisticsFolders = cloudLogisticsFolder;
                return new LogisticsFolderActions.SyncSuccess({ logisticsFolder: logisticsFolderState });
            }
        })
        .catch((error) =>
        {
            this._store.dispatch(new AppActions.UnexpectedError(error.json().message));
            return Observable.of(new LogisticsFolderActions.SyncFailed)
        })
    );
</code>```

Thanks for any help :)

答:
fixed...

I subscribed to the token which is assigned to this.token$ and as the state was updated a new value was executed and so we had several requests.

```<code>private oAuthRequest(options): Observable<any>
    {
        return this.token$.flatMap(token =>
        {
            options.headers = new Headers();
            options.headers.append('Content-Type', 'application/json');
            options.headers.append('Authorization', token);

            if (options.body && typeof options.body !== 'string')
            {
                options.body = JSON.stringify(options.body);
            }

            return this.http
                .request(new Request(options))
                .map((res: Response) =>
                {
                    if (res.text)
                    {
                        return res.json();
                    }
                    return res
                });
        }).take(1);

    }
</code>```

Title: ngrx effects calls http several times

Body:
I am using the latest versions of ngrx (4.1.1) and angular 4.4.4 and can't find the problem here and could need some help.

I am using an effect which calls the this.apiProvider.getLogisticsFolder() and works with the http response. As soon as my reducer returns the new state and everything is working as expected, my rest service is called a second time or even several times (the action/effect is only triggered once and so is the rest call getLogisticsFolder()).

What am I missing here?

@Effect()
syncFolders$ = this.actions$
    .ofType<LogisticsFolderActions.SyncFolders>(LogisticsFolderActions.SYNC_FOLDERS)
    .mergeMap(() => this.apiProvider.getLogisticsFolder()
        .withLatestFrom(this._store.select(state => state.logisticsFolders), this._store.select(state => state.settings))
        .map(([cloudLogisticsFolder, localLogisticsFolderState, settingsState]) =>
        {
            let tempLocalLogisticsFolder = localLogisticsFolderState.find(localLogisticsFolderState => localLogisticsFolderState.tenant === settingsState.baseURL);
            if (tempLocalLogisticsFolder)
            {
                //now check if the folder structure has been added, deleted or changed
                let updatedFolders = this.logisticsFolderProvider.checkAndProceedLogisticsFolderUpdate(cloudLogisticsFolder, tempLocalLogisticsFolder.logisticsFolders)
                this.logisticsFolderProvider.checkAndProceedTasksUpdate(cloudLogisticsFolder, updatedFolders)

                return new LogisticsFolderActions.SyncSuccess;
            } else
            {
                let logisticsFolderState = <LogisticsFolder.State>{};
                logisticsFolderState.tenant = settingsState.baseURL;
                logisticsFolderState.logisticsFolders = cloudLogisticsFolder;
                return new LogisticsFolderActions.SyncSuccess({ logisticsFolder: logisticsFolderState });
            }
        })
        .catch((error) =>
        {
            this._store.dispatch(new AppActions.UnexpectedError(error.json().message));
            return Observable.of(new LogisticsFolderActions.SyncFailed)
        })
    );

Thanks for any help :)

Body:
fixed...

I subscribed to the token which is assigned to this.token$ and as the state was updated a new value was executed and so we had several requests.

private oAuthRequest(options): Observable<any>
    {
        return this.token$.flatMap(token =>
        {
            options.headers = new Headers();
            options.headers.append('Content-Type', 'application/json');
            options.headers.append('Authorization', token);

            if (options.body && typeof options.body !== 'string')
            {
                options.body = JSON.stringify(options.body);
            }

            return this.http
                .request(new Request(options))
                .map((res: Response) =>
                {
                    if (res.text)
                    {
                        return res.json();
                    }
                    return res
                });
        }).take(1);

    }


问:
Return dataframe or vector from a function
I computed the model fits (AIC) from -LL inputs. I used a vectorized function and I want to return a data.frame or vector of all computed values for further analysis. The function works fine, but if I define an output vector, it doesn't return this vector.

Here's my function:

```<code>function.aic <- function(k,LL)   {
    aic <- (2*(LL)) + (2*k)
    m <-mean(aic)
    print(m)
    print(aic)
    aic_vector <- as.data.frame(aic) }
</code>```

Further, it would be great to save this vector in an object with the name of the input variable "LL" to have specific objects for each computation. But I just don't know how to do it, Google didn't really help.

答:
Seems like you are just missing a return statement. Also, to give named output, you could use deparse and substitute  to obtain the variable name. You could then create a list, and give the list element the name of your variable. For example:

```<code>function.aic <- function(k,LL)
{
  aic <- (2*(LL)) + (2*k)
  m <-mean(aic)
  print(m)
  print(aic)
  aic_vector <- as.data.frame(aic)

  mylist=list()
  mylist[[deparse(substitute(LL))]] = aic_vector
  return(mylist)
}

input_1 = 10
input_2 = 10

x = function.aic(input_1,input_2)
</code>```

x now is:

```<code>$input_2
  aic
1  40
</code>```

and so,  x$input_2 contains your AIC dataframe. Hope this helps!

Body:
I computed the model fits (AIC) from -LL inputs. I used a vectorized function and I want to return a data.frame or vector of all computed values for further analysis. The function works fine, but if I define an output vector, it doesn't return this vector.

Here's my function:

function.aic <- function(k,LL)   {
    aic <- (2*(LL)) + (2*k)
    m <-mean(aic)
    print(m)
    print(aic)
    aic_vector <- as.data.frame(aic) }

Further, it would be great to save this vector in an object with the name of the input variable "LL" to have specific objects for each computation. But I just don't know how to do it, Google didn't really help.

Body:
Seems like you are just missing a return statement. Also, to give named output, you could use deparse and substitute  to obtain the variable name. You could then create a list, and give the list element the name of your variable. For example:

function.aic <- function(k,LL)
{
  aic <- (2*(LL)) + (2*k)
  m <-mean(aic)
  print(m)
  print(aic)
  aic_vector <- as.data.frame(aic)

  mylist=list()
  mylist[[deparse(substitute(LL))]] = aic_vector
  return(mylist)
}

input_1 = 10
input_2 = 10

x = function.aic(input_1,input_2)

x now is:

$input_2
  aic
1  40

and so,  x$input_2 contains your AIC dataframe. Hope this helps!


问:
How do I attach a condition to a random choice?
I would like choice 5 to be presented if the child is on the naughty list, but choice 6 to be presented for nice list.  My problem is allocation to a list is a random choice of tuple values.</p>

```<code>import random, time # allowing use of random and delays
choice=[
'eddie',
'dan',
'erin',
'josh',
]

choices2=[
'naughty list',
'nice list'
]

choices3=[
'merry xmas anyhoooo!',
'cannot win them all!',
'have fun dude!',
'man\'s not got?',
]

choices4=[
'must have been when you pushed the granny over',
'could have been that cookie you stole?!',
'probably because you were cheeky to a teacher'
]

choices5=[
'must be because you are an angel',
'must be because you keep your room tidy',
'Santa just never saw you'
]
while True:
    input('\npress enter to check who is on the list')
    print('checking...')
    time.sleep(2)
    print(random.choice(choice))
    time.sleep(2)

    print(random.choice(choices2))
    if random.choice =='naughty list':
        print(random.choice(choices4))
    elif choices2=='nice list':
        print(random.choice(choices5))
    else:
        print('wrong')
    time.sleep(2)
    print(random.choice(choices3))
</code>```

答:
Updated code :

```<code> import random, time # allowing use of random and delays
choice1=[
'eddie',
'dan',
'erin',
'josh',
]

choices2=[
'naughty list',
'nice list'
]

choices3=[
'merry xmas anyhoooo!',
'cannot win them all!',
'have fun dude!',
'man\'s not got?',
]

choices4=[
'must have been when you pushed the granny over',
'could have been that cookie you stole?!',
'probably because you were cheeky to a teacher'
]

choices5=[
'must be because you are an angel',
'must be because you keep your room tidy',
'Santa just never saw you'
]
while True:
    input('\npress enter to check who is on the list')
    print('checking...')
    time.sleep(2)
    print(random.choice(choice1))
    time.sleep(2)

    list1 = random.choice(choices2)
    print(list1)
    if list1 =='naughty list':
        print(random.choice(choices4))
    elif list1=='nice list':
        print(random.choice(choices5))
    else:
        print('wrong')
    time.sleep(2)
    print(random.choice(choices3))
</code>```

Also, choice is a being used internally by the random function so changed the list name to choice1

Body:
I would like choice 5 to be presented if the child is on the naughty list, but choice 6 to be presented for nice list.  My problem is allocation to a list is a random choice of tuple values.

import random, time # allowing use of random and delays
choice=[
'eddie',
'dan',
'erin',
'josh',
]

choices2=[
'naughty list',
'nice list'
]

choices3=[
'merry xmas anyhoooo!',
'cannot win them all!',
'have fun dude!',
'man\'s not got?',
]

choices4=[
'must have been when you pushed the granny over',
'could have been that cookie you stole?!',
'probably because you were cheeky to a teacher'
]

choices5=[
'must be because you are an angel',
'must be because you keep your room tidy',
'Santa just never saw you'
]
while True:
    input('\npress enter to check who is on the list')
    print('checking...')
    time.sleep(2)
    print(random.choice(choice))
    time.sleep(2)

    print(random.choice(choices2))
    if random.choice =='naughty list':
        print(random.choice(choices4))
    elif choices2=='nice list':
        print(random.choice(choices5))
    else:
        print('wrong')
    time.sleep(2)
    print(random.choice(choices3))

Body:
Updated code :

 import random, time # allowing use of random and delays
choice1=[
'eddie',
'dan',
'erin',
'josh',
]

choices2=[
'naughty list',
'nice list'
]

choices3=[
'merry xmas anyhoooo!',
'cannot win them all!',
'have fun dude!',
'man\'s not got?',
]

choices4=[
'must have been when you pushed the granny over',
'could have been that cookie you stole?!',
'probably because you were cheeky to a teacher'
]

choices5=[
'must be because you are an angel',
'must be because you keep your room tidy',
'Santa just never saw you'
]
while True:
    input('\npress enter to check who is on the list')
    print('checking...')
    time.sleep(2)
    print(random.choice(choice1))
    time.sleep(2)

    list1 = random.choice(choices2)
    print(list1)
    if list1 =='naughty list':
        print(random.choice(choices4))
    elif list1=='nice list':
        print(random.choice(choices5))
    else:
        print('wrong')
    time.sleep(2)
    print(random.choice(choices3))

Also, choice is a being used internally by the random function so changed the list name to choice1


问:
Retrieving URL data when Content-Range is sent in PHP
There's many options available for downloading a URL in PHP - but I'm stuck.

I've looked through all the ones I know, but none seem to pay attention to partial content headers.

I'm trying to retrieve a URL that gives the following header:
HTTP/1.1 206 Partial Content
Content-Range:   bytes 0-100000/631723

As you can see it dishes out the file in 100,000 byte chunks.

Trouble is, when I use any method in PHP, ie file_get_contents, fopen, or even cURL, none of these continue on after receiving the first 100,000 bytes.

End result, I have a 100,000 byte file.

What I need is to get the PHP script to grab all the data, in the example above, all 631,723 bytes.

How can I do this?

答:
Try sending it with HTTP/1.0, which did not define content range requests (and other caching and proxy tohuwabohu). Thus you ensure receiving the complete file.

If you want to use file_get_contents for that, then set the protocol_version parameter via stream_context_create().


问:
Connectivity issues to mysql database from hybris
I was trying to setup hybris but when I tried to initialize from the CLI, the build failed due to Mysql connectivity issue.
However I am able to connect to mysql database from hybris node using mysql client.

Can any one help me on this ? Could it be some additional privileges required ?

Following is the error thrown at last when performing "ant initialize":

```<code> [java] ERROR [main] [DataSourceImpl] error connecting to DataSource having url jdbc:mysql://<mysql-ip>:3306/hybrisdatabase?useConfigs=maxPerformance&characterEncoding=utf8&useSSL=false: Unknown error 1045
</code>```

Full Error Logs

```<code>server:
     [echo]
     [echo] Configuring server at /ABC/hybris/bin/platform/tomcat
     [echo] Using config set at /ABC/hybris/config/tomcat
     [echo]
     [echo] copying from /ABC/hybris/config/tomcat to /ABC/hybris/bin/platform/tomcat
     [copy] Copying 9 files to /ABC/hybris/bin/platform/tomcat
     [copy] Copying 3 files to /ABC/hybris/bin/platform/tomcat
     [copy] Copying 2 files to /ABC/hybris/bin/platform/tomcat
     [copy] Copying 1 file to /ABC/hybris/bin/platform/tomcat/lib
     [echo]
     [echo] Embedded server does not seem to be running (no PID found). No restart necessary.
     [echo]

initialize:
    [input] skipping input as property tenant has already been set.
     [java] ---------------------------------------------------------------
     [java] Warning: you're using at least one deprecated extension!
     [java] Please note that they may not be available in future releases.
     [java]
     [java] Deprecated extensions: [liveeditaddon, sapcoreodata]
     [java] ---------------------------------------------------------------
     [java] ---------------------------------------------------------------
     [java] Warning: you're using at least one deprecated extension!
     [java] Please note that they may not be available in future releases.
     [java]
     [java] Deprecated extensions: [liveeditaddon, sapcoreodata]
     [java] ---------------------------------------------------------------
     [java] Exception in thread "main" java.lang.reflect.InvocationTargetException
     [java]     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
     [java]     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
     [java]     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
     [java]     at java.lang.reflect.Method.invoke(Method.java:498)
     [java]     at de.hybris.bootstrap.loader.Loader.execute(Loader.java:142)
     [java]     at de.hybris.bootstrap.loader.Loader.main(Loader.java:118)
     [java] Caused by: java.lang.RuntimeException: java.sql.SQLException: Unknown error 1045
     [java]     at de.hybris.platform.jdbcwrapper.DataSourceImpl.adjustDatabaseInfos(DataSourceImpl.java:647)
     [java]     at de.hybris.platform.jdbcwrapper.DataSourceImpl.<init>(DataSourceImpl.java:213)
     [java]     at de.hybris.platform.jdbcwrapper.DataSourceImpl.<init>(DataSourceImpl.java:149)
     [java]     at de.hybris.platform.core.DataSourceImplFactory.createDataSource(DataSourceImplFactory.java:51)
     [java]     at de.hybris.platform.core.AbstractTenant$HybrisDataSourceBuilder.createMasterDataSource(AbstractTenant.java:2869)
     [java]     at de.hybris.platform.core.AbstractTenant$HybrisDataSourceBuilder.buildMasterDataSourceOnce(AbstractTenant.java:2631)
     [java]     at de.hybris.platform.core.AbstractTenant$HybrisDataSourceBuilder.build(AbstractTenant.java:2577)
     [java]     at de.hybris.platform.core.AbstractTenant.doInitializeSafe(AbstractTenant.java:329)
     [java]     at de.hybris.platform.core.AbstractTenant.doInitialize(AbstractTenant.java:308)
     [java]     at de.hybris.platform.core.AbstractTenant.doStartUp(AbstractTenant.java:674)
     [java]     at de.hybris.platform.core.Registry.assureTenantStarted(Registry.java:648)
     [java]     at de.hybris.platform.core.Registry.activateTenant(Registry.java:709)
     [java]     at de.hybris.platform.core.Registry.setCurrentTenant(Registry.java:556)
     [java]     at de.hybris.platform.core.Registry.activateMasterTenantForInit(Registry.java:625)
     [java]     at de.hybris.platform.util.ClientExecuter.execute(ClientExecuter.java:39)
     [java]     ... 6 more
     [java] Caused by: java.sql.SQLException: Unknown error 1045
     [java]     at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964)
     [java]     at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3970)
     [java]     at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3906)
     [java]     at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:873)
     [java]     at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1710)
     [java]     at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1226)
     [java]     at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2253)
     [java]     at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2284)
     [java]     at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2083)
     [java]     at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:806)
     [java]     at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
     [java]     at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
     [java]     at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
     [java]     at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
     [java]     at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
     [java]     at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
     [java]     at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:410)
     [java]     at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:328)
     [java]     at de.hybris.platform.jdbcwrapper.JDBCConnectionFactory.createRawSQLConnection(JDBCConnectionFactory.java:189)
     [java]     at de.hybris.platform.jdbcwrapper.JDBCConnectionFactory.createSQLConnection(JDBCConnectionFactory.java:220)
     [java]     at de.hybris.platform.jdbcwrapper.JDBCConnectionFactory.makeObject(JDBCConnectionFactory.java:109)
     [java]     at org.apache.commons.pool2.impl.GenericObjectPool.create(GenericObjectPool.java:868)
     [java]     at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:435)
     [java]     at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:363)
     [java]     at de.hybris.platform.jdbcwrapper.JDBCConnectionPool.borrowConnection(JDBCConnectionPool.java:113)
     [java]     at de.hybris.platform.jdbcwrapper.ConnectionErrorCheckingJDBCConnectionPool.borrowConnection(ConnectionErrorCheckingJDBCConnectionPool.java:97)
     [java]     at de.hybris.platform.jdbcwrapper.DataSourceImpl.adjustDatabaseInfos(DataSourceImpl.java:629)
     [java]     ... 20 more
     [java] ERROR [main] [DataSourceImpl] error connecting to DataSource having url jdbc:mysql://10.43.4.168:3306/hemdevhybris?useConfigs=maxPerformance&characterEncoding=utf8&useSSL=false: Unknown error 1045
     [java] shutting down hybris registry..

BUILD FAILED
/TK/hybris/bin/platform/build.xml:123: The following error occurred while executing this line:
/ABC/hybris/bin/platform/resources/ant/antmacros.xml:1021: The following error occurred while executing this line:
/ABC/hybris/bin/platform/resources/ant/platformadministration.xml:51: The following error occurred while executing this line:
/ABC/hybris/bin/platform/resources/ant/antmacros.xml:878: Java returned: 1
</code>```

Hybris local.properties:

```<code>db.url=jdbc:mysql://<mysql-IP>:3306/hybrisdatabase?useConfigs=maxPerformance&characterEncoding=utf8&useSSL=false
db.driver=com.mysql.jdbc.Driver
db.username=hybris-user
db.password=*****
db.tableprefix=
mysql.optional.tabledefs=CHARSET=utf8 COLLATE=utf8_bin
mysql.tabletype=InnoDB
</code>```

Mysql connectivity from hybris node:

```<code>[hybris@****platform]$ mysql -h <mysql-ip> -u hybris-user -p'password'
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MySQL connection id is 2188
Server version: 5.7.20 MySQL Community Server (GPL)

Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MySQL [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| hybrisdatabase       |
+--------------------+
2 rows in set (0.01 sec)

MySQL [(none)]>  SHOW GRANTS FOR 'hybris-user'@'%';
+------------------------------------------------------------------+
| Grants for hybris-user@%                                      |
+------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'hybris-user'@'%'                       |
| GRANT ALL PRIVILEGES ON `hybrisdatabase`.* TO 'hybris-user'@'%' |
+------------------------------------------------------------------+
2 rows in set (0.00 sec)

MySQL [(none)]> use hybrisdatabase;
Database changed
MySQL [hybrisdatabase]> show tables;
Empty set (0.01 sec)
</code>```

答:
While creating the Mysql password, please avoid special characters and give the same password properly in Hybris local.properties file.
The "ant" command for Hybris initialization won't work well with MySql passwords with special characters such as  "-, +,#,:.".</p>

Body:
I was trying to setup hybris but when I tried to initialize from the CLI, the build failed due to Mysql connectivity issue.
However I am able to connect to mysql database from hybris node using mysql client.

Can any one help me on this ? Could it be some additional privileges required ?

Following is the error thrown at last when performing "ant initialize":

 [java] ERROR [main] [DataSourceImpl] error connecting to DataSource having url jdbc:mysql://<mysql-ip>:3306/hybrisdatabase?useConfigs=maxPerformance&characterEncoding=utf8&useSSL=false: Unknown error 1045

Full Error Logs

server:
     [echo]
     [echo] Configuring server at /ABC/hybris/bin/platform/tomcat
     [echo] Using config set at /ABC/hybris/config/tomcat
     [echo]
     [echo] copying from /ABC/hybris/config/tomcat to /ABC/hybris/bin/platform/tomcat
     [copy] Copying 9 files to /ABC/hybris/bin/platform/tomcat
     [copy] Copying 3 files to /ABC/hybris/bin/platform/tomcat
     [copy] Copying 2 files to /ABC/hybris/bin/platform/tomcat
     [copy] Copying 1 file to /ABC/hybris/bin/platform/tomcat/lib
     [echo]
     [echo] Embedded server does not seem to be running (no PID found). No restart necessary.
     [echo]

initialize:
    [input] skipping input as property tenant has already been set.
     [java] ---------------------------------------------------------------
     [java] Warning: you're using at least one deprecated extension!
     [java] Please note that they may not be available in future releases.
     [java]
     [java] Deprecated extensions: [liveeditaddon, sapcoreodata]
     [java] ---------------------------------------------------------------
     [java] ---------------------------------------------------------------
     [java] Warning: you're using at least one deprecated extension!
     [java] Please note that they may not be available in future releases.
     [java]
     [java] Deprecated extensions: [liveeditaddon, sapcoreodata]
     [java] ---------------------------------------------------------------
     [java] Exception in thread "main" java.lang.reflect.InvocationTargetException
     [java]     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
     [java]     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
     [java]     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
     [java]     at java.lang.reflect.Method.invoke(Method.java:498)
     [java]     at de.hybris.bootstrap.loader.Loader.execute(Loader.java:142)
     [java]     at de.hybris.bootstrap.loader.Loader.main(Loader.java:118)
     [java] Caused by: java.lang.RuntimeException: java.sql.SQLException: Unknown error 1045
     [java]     at de.hybris.platform.jdbcwrapper.DataSourceImpl.adjustDatabaseInfos(DataSourceImpl.java:647)
     [java]     at de.hybris.platform.jdbcwrapper.DataSourceImpl.<init>(DataSourceImpl.java:213)
     [java]     at de.hybris.platform.jdbcwrapper.DataSourceImpl.<init>(DataSourceImpl.java:149)
     [java]     at de.hybris.platform.core.DataSourceImplFactory.createDataSource(DataSourceImplFactory.java:51)
     [java]     at de.hybris.platform.core.AbstractTenant$HybrisDataSourceBuilder.createMasterDataSource(AbstractTenant.java:2869)
     [java]     at de.hybris.platform.core.AbstractTenant$HybrisDataSourceBuilder.buildMasterDataSourceOnce(AbstractTenant.java:2631)
     [java]     at de.hybris.platform.core.AbstractTenant$HybrisDataSourceBuilder.build(AbstractTenant.java:2577)
     [java]     at de.hybris.platform.core.AbstractTenant.doInitializeSafe(AbstractTenant.java:329)
     [java]     at de.hybris.platform.core.AbstractTenant.doInitialize(AbstractTenant.java:308)
     [java]     at de.hybris.platform.core.AbstractTenant.doStartUp(AbstractTenant.java:674)
     [java]     at de.hybris.platform.core.Registry.assureTenantStarted(Registry.java:648)
     [java]     at de.hybris.platform.core.Registry.activateTenant(Registry.java:709)
     [java]     at de.hybris.platform.core.Registry.setCurrentTenant(Registry.java:556)
     [java]     at de.hybris.platform.core.Registry.activateMasterTenantForInit(Registry.java:625)
     [java]     at de.hybris.platform.util.ClientExecuter.execute(ClientExecuter.java:39)
     [java]     ... 6 more
     [java] Caused by: java.sql.SQLException: Unknown error 1045
     [java]     at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964)
     [java]     at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3970)
     [java]     at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3906)
     [java]     at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:873)
     [java]     at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1710)
     [java]     at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1226)
     [java]     at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2253)
     [java]     at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2284)
     [java]     at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2083)
     [java]     at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:806)
     [java]     at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
     [java]     at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
     [java]     at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
     [java]     at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
     [java]     at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
     [java]     at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
     [java]     at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:410)
     [java]     at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:328)
     [java]     at de.hybris.platform.jdbcwrapper.JDBCConnectionFactory.createRawSQLConnection(JDBCConnectionFactory.java:189)
     [java]     at de.hybris.platform.jdbcwrapper.JDBCConnectionFactory.createSQLConnection(JDBCConnectionFactory.java:220)
     [java]     at de.hybris.platform.jdbcwrapper.JDBCConnectionFactory.makeObject(JDBCConnectionFactory.java:109)
     [java]     at org.apache.commons.pool2.impl.GenericObjectPool.create(GenericObjectPool.java:868)
     [java]     at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:435)
     [java]     at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:363)
     [java]     at de.hybris.platform.jdbcwrapper.JDBCConnectionPool.borrowConnection(JDBCConnectionPool.java:113)
     [java]     at de.hybris.platform.jdbcwrapper.ConnectionErrorCheckingJDBCConnectionPool.borrowConnection(ConnectionErrorCheckingJDBCConnectionPool.java:97)
     [java]     at de.hybris.platform.jdbcwrapper.DataSourceImpl.adjustDatabaseInfos(DataSourceImpl.java:629)
     [java]     ... 20 more
     [java] ERROR [main] [DataSourceImpl] error connecting to DataSource having url jdbc:mysql://10.43.4.168:3306/hemdevhybris?useConfigs=maxPerformance&characterEncoding=utf8&useSSL=false: Unknown error 1045
     [java] shutting down hybris registry..

BUILD FAILED
/TK/hybris/bin/platform/build.xml:123: The following error occurred while executing this line:
/ABC/hybris/bin/platform/resources/ant/antmacros.xml:1021: The following error occurred while executing this line:
/ABC/hybris/bin/platform/resources/ant/platformadministration.xml:51: The following error occurred while executing this line:
/ABC/hybris/bin/platform/resources/ant/antmacros.xml:878: Java returned: 1

Hybris local.properties:

db.url=jdbc:mysql://<mysql-IP>:3306/hybrisdatabase?useConfigs=maxPerformance&characterEncoding=utf8&useSSL=false
db.driver=com.mysql.jdbc.Driver
db.username=hybris-user
db.password=*****
db.tableprefix=
mysql.optional.tabledefs=CHARSET=utf8 COLLATE=utf8_bin
mysql.tabletype=InnoDB

Mysql connectivity from hybris node:

[hybris@****platform]$ mysql -h <mysql-ip> -u hybris-user -p'password'
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MySQL connection id is 2188
Server version: 5.7.20 MySQL Community Server (GPL)

Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MySQL [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| hybrisdatabase       |
+--------------------+
2 rows in set (0.01 sec)

MySQL [(none)]>  SHOW GRANTS FOR 'hybris-user'@'%';
+------------------------------------------------------------------+
| Grants for hybris-user@%                                      |
+------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'hybris-user'@'%'                       |
| GRANT ALL PRIVILEGES ON `hybrisdatabase`.* TO 'hybris-user'@'%' |
+------------------------------------------------------------------+
2 rows in set (0.00 sec)

MySQL [(none)]> use hybrisdatabase;
Database changed
MySQL [hybrisdatabase]> show tables;
Empty set (0.01 sec)


问:
Value equals to match_parent or fill_parent in dimens.xml?
Based on here on XML Attributes section I specify following in my dimens.xml:

```<code><dimen name="match_parent">-1dp</dimen>
<dimen name="main_left_menu_user_account_width">@dimen/match_parent</dimen>
<dimen name="main_left_menu_user_account_height">@dimen/match_parent</dimen>
</code>```

Then I use the both dimensions in my layout:

```<code><ImageView
    android:id="@+id/userAccountImage"
    android:background="@drawable/user_account"
    android:layout_width="@dimen/main_left_menu_user_account_width"
    android:layout_height="@dimen/main_left_menu_user_account_height" />
</code>```

Then, when I preview to Graphical Layout, it complains:

You must supply a layout_width attribute.

You must supply a layout_height attribute.

Actually can I define a value equals to match_parent in dimens.xml?

Update:

I also tried this but the preview still complains:

```<code><dimen name="main_left_menu_user_account_width">-1dp</dimen>
<dimen name="main_left_menu_user_account_height">-1dp</dimen>
</code>```

I successfully use wrap_content (the Graphical Layout doesn't complain at all):

```<code><dimen name="wrap_content">-2dp</dimen>

<dimen name="main_right_menu_width">@dimen/wrap_content</dimen>
<dimen name="main_right_menu_height">@dimen/wrap_content</dimen>
</code>```

答:
You can also achieve this using integers.xml file

integers.xml file:

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="match_parent">-1</integer>
    <integer name="wrap_content">-2</integer>
</resources>
</code>```

Use in dimens.xml:

```<code><dimen name="main_right_menu_width">@integer/wrap_content</dimen>
</code>```

You might also get lint warning, to suppress it use:

```<code><dimen name="main_right_menu_width" tools:ignore="ReferenceType">@integer/wrap_content</dimen>
</code>```

Body:
Based on here on XML Attributes section I specify following in my dimens.xml:

<dimen name="match_parent">-1dp</dimen>
<dimen name="main_left_menu_user_account_width">@dimen/match_parent</dimen>
<dimen name="main_left_menu_user_account_height">@dimen/match_parent</dimen>

Then I use the both dimensions in my layout:

<ImageView
    android:id="@+id/userAccountImage"
    android:background="@drawable/user_account"
    android:layout_width="@dimen/main_left_menu_user_account_width"
    android:layout_height="@dimen/main_left_menu_user_account_height" />

Then, when I preview to Graphical Layout, it complains:

You must supply a layout_width attribute.

You must supply a layout_height attribute.

Actually can I define a value equals to match_parent in dimens.xml?

Update:

I also tried this but the preview still complains:

<dimen name="main_left_menu_user_account_width">-1dp</dimen>
<dimen name="main_left_menu_user_account_height">-1dp</dimen>

I successfully use wrap_content (the Graphical Layout doesn't complain at all):

<dimen name="wrap_content">-2dp</dimen>

<dimen name="main_right_menu_width">@dimen/wrap_content</dimen>
<dimen name="main_right_menu_height">@dimen/wrap_content</dimen>

Body:
You can also achieve this using integers.xml file

integers.xml file:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="match_parent">-1</integer>
    <integer name="wrap_content">-2</integer>
</resources>

Use in dimens.xml:

<dimen name="main_right_menu_width">@integer/wrap_content</dimen>

You might also get lint warning, to suppress it use:

<dimen name="main_right_menu_width" tools:ignore="ReferenceType">@integer/wrap_content</dimen>


问:
C Recursive Function for prime number with just one parameter
Im trying to make a function to check if a number is prime number or not, using recursion. The best two examples are these two programs (one without recursion, one using recursion).

Using recursion:

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

int isPrime(int,int);

int main(){

    int num,prime;

    printf("Enter a positive number: ");
    scanf("%d",&num);

    prime = isPrime(num,num/2);

   if(prime==1)
        printf("%d is a prime number",num);
   else
      printf("%d is not a prime number",num);

   return 0;
}

int isPrime(int num,int i){

    if(i==1){
        return 1;
    }else{
       if(num%i==0)
         return 0;
       else
         isPrime(num,i-1);
    }
}
</code>```

Without using recursion:

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

int isPrime(int);

int main(){

    int num,prime;

    printf("Enter a positive number: ");
    scanf("%d",&num);

    prime = isPrime(num);

   if(prime==1)
        printf("%d is a prime number",num);
   else
      printf("%d is not a prime number",num);

   return 0;
}

int isPrime(int num){

    int i=2;

    while(i<=num/2){
         if(num%i==0)
             return 0;
         else
             i++;
    }

    return 1;
}
</code>```

My question is: Is it possible to make a function to check if a number is prime number or not, using recursion, but with just one parameter (like this: int isPrime(int num))?

Any help is appreciated

答:
```<code>float isPrime(float n) {
    if ((int)n == 2)
        return 1;
    if ((int)(1/(n - (int)n)) % (int)n == 0)
        return 0;
    if (n / (int)n == 1)
        return isPrime(n-1 + 1/n); // store original parameter to decimal places
    return isPrime(n-1);
}
</code>```

Usage:

```<code>if ((int)isPrime(n) == 1) {
    // do this if n is a prime number
}
</code>```

Body:
Im trying to make a function to check if a number is prime number or not, using recursion. The best two examples are these two programs (one without recursion, one using recursion).

Using recursion:

    #include<stdio.h>

int isPrime(int,int);

int main(){

    int num,prime;

    printf("Enter a positive number: ");
    scanf("%d",&num);

    prime = isPrime(num,num/2);

   if(prime==1)
        printf("%d is a prime number",num);
   else
      printf("%d is not a prime number",num);

   return 0;
}

int isPrime(int num,int i){

    if(i==1){
        return 1;
    }else{
       if(num%i==0)
         return 0;
       else
         isPrime(num,i-1);
    }
}

Without using recursion:

     #include<stdio.h>

int isPrime(int);

int main(){

    int num,prime;

    printf("Enter a positive number: ");
    scanf("%d",&num);

    prime = isPrime(num);

   if(prime==1)
        printf("%d is a prime number",num);
   else
      printf("%d is not a prime number",num);

   return 0;
}

int isPrime(int num){

    int i=2;

    while(i<=num/2){
         if(num%i==0)
             return 0;
         else
             i++;
    }

    return 1;
}

My question is: Is it possible to make a function to check if a number is prime number or not, using recursion, but with just one parameter (like this: int isPrime(int num))?

Any help is appreciated

Body:
float isPrime(float n) {
    if ((int)n == 2)
        return 1;
    if ((int)(1/(n - (int)n)) % (int)n == 0)
        return 0;
    if (n / (int)n == 1)
        return isPrime(n-1 + 1/n); // store original parameter to decimal places
    return isPrime(n-1);
}

Usage:

if ((int)isPrime(n) == 1) {
    // do this if n is a prime number
}


问:
How do I update a String value into MySQL Datetime in java code using PreparedStatement?
I have a date/time value in String form like "11/28/2017 4:00:49 PM" in my java code. Now how can I take this same value to MySQL column of type datetime?

Please note, I'm using PreparedStatement to insert the record in MySQL DB.

Here are the few ways I tried...

```<code>DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            DateFormat outputFormat = new SimpleDateFormat("MM-dd-yyyy KK:mm:ss a");
ps.setString(outputFormat.format(inputFormat.parse(rs.getString(1))));
</code>```

I used the above code and I'm getting the below exception...

```<code>com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value: '08-09-0017 02:46:57 AM' for column 'column_name' at row 1
</code>```

If I use the below code, I'm getting only Date but time with AM/PM is lost

```<code>ps.setDate(inputFormat.parse(rs.getString(1)));
</code>```

If I use the below code, I'm getting only Time but without AM/PM and Date

```<code>ps.setTime(inputFormat.parse(rs.getString(1).getTime()));
</code>```

If I use the below code, I get error

```<code>ps.setDate(1, (java.sql.Date) new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("11/28/2017 4:00:49 PM"));

java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Date
</code>```

答:
Since you want to parse into a Date your String, and that your problem is the AM/PM, you can see in the SimpleDateFormat documentation :

```<code>Letter  Date or Time Component  Presentation    Examples
a       Am/pm marker            Text            PM
</code>```

So this should be something like :

```<code>String s = "11/28/2017 4:00:49 PM";
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy k:mm:ss a");
java.util.Date myDate = sdf.parse(s);
System.out.println(myDate);
</code>```

Tue Nov 28 16:00:49 CET 2017

Note that in your code, you are not using a format that match at all

```<code>new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
              .parse("11/28/2017 4:00:49 PM"))
</code>```

For the way to use a java.util.Date in a PreparedStatement, I prefer to let you see that in the complete post : Using setDate in PreparedStatement

But basically, you just need to

```<code>ps.setDate(i, new java.sql.Date(myDate.getTime());
</code>```

or (not sur if Date manage the time part in mysql... it might depends on the jdbc version)

```<code>ps.setTimestamp(i, new java.sql.TimeStamp(myDate.getTime());
</code>```

Body:
I have a date/time value in String form like "11/28/2017 4:00:49 PM" in my java code. Now how can I take this same value to MySQL column of type datetime?

Please note, I'm using PreparedStatement to insert the record in MySQL DB.

Here are the few ways I tried...

DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            DateFormat outputFormat = new SimpleDateFormat("MM-dd-yyyy KK:mm:ss a");
ps.setString(outputFormat.format(inputFormat.parse(rs.getString(1))));

I used the above code and I'm getting the below exception...

com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value: '08-09-0017 02:46:57 AM' for column 'column_name' at row 1

If I use the below code, I'm getting only Date but time with AM/PM is lost

ps.setDate(inputFormat.parse(rs.getString(1)));

If I use the below code, I'm getting only Time but without AM/PM and Date

ps.setTime(inputFormat.parse(rs.getString(1).getTime()));

If I use the below code, I get error

ps.setDate(1, (java.sql.Date) new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("11/28/2017 4:00:49 PM"));

java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Date

Body:
Since you want to parse into a Date your String, and that your problem is the AM/PM, you can see in the SimpleDateFormat documentation :

Letter  Date or Time Component  Presentation    Examples
a       Am/pm marker            Text            PM

So this should be something like :

String s = "11/28/2017 4:00:49 PM";
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy k:mm:ss a");
java.util.Date myDate = sdf.parse(s);
System.out.println(myDate);

Tue Nov 28 16:00:49 CET 2017

Note that in your code, you are not using a format that match at all

new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
              .parse("11/28/2017 4:00:49 PM"))

For the way to use a java.util.Date in a PreparedStatement, I prefer to let you see that in the complete post : Using setDate in PreparedStatement

But basically, you just need to

ps.setDate(i, new java.sql.Date(myDate.getTime());

or (not sur if Date manage the time part in mysql... it might depends on the jdbc version)

ps.setTimestamp(i, new java.sql.TimeStamp(myDate.getTime());


问:
How to write a word at the end of a line with bash
I have a conf file like:

```<code>mon host = 1.1.1.1
cluster = test
</code>```

I want to write new ip end of "mon host" like:

```<code>mon host = 1.1.1.1, 2.2.2.2
cluster = test
</code>```

How can i do that?

答:
You can easily do it with sed:

```<code>sed '/^mon host =/ s/$/, 2.2.2.2/' your.conf
</code>```

Use -i to change the file instead of printing to STDOUT.

Body:
I have a conf file like:

mon host = 1.1.1.1
cluster = test

I want to write new ip end of "mon host" like:

mon host = 1.1.1.1, 2.2.2.2
cluster = test

How can i do that?

Body:
You can easily do it with sed:

sed '/^mon host =/ s/$/, 2.2.2.2/' your.conf

Use -i to change the file instead of printing to STDOUT.