In my viewDidAppear, how do I know when it's being unwound by a child?

Question: When my child performs an unwind segue, my controller's viewDidAppear gets called.
In this method (and this method alone, I need to know whether it was from an unwind or not)
Note: the child is unwinding to the very first view controller, so this is an intermediate view controller, not the true root.
Comment: Anyway having some problems imagining the use case, if you want to unwind to the root view controller why should the intermediate controller appear? will viewDidAppear even be called?
Comment: Are you sure? From what I understand in the docs: https://developer.apple.com/library/ios/technotes/tn2298/_index.html this doesn't seem to be the case. It looks like it's a direct transition between source and destination controller. It also wouldn't really make sense to trigger viewWillAppear on the intermediate view controllers, as they will never "appear".
Comment: It will get `viewWillAppear:` and `viewDidAppear:`.
Comment: But how do I know it was from an unwind instead of something else?
Comment: I'm not really sure why you'd put these two things together.... They're more or less mutually exclusive other than the fact that the unwind segue is the one who initiates the unwind process. But to your question.... Technically yes. It's important to remember that `viewWillAppear:` and `viewDidAppear:` will be called whenever the view appears. Regardless if it was cased by an unwind segue.
Comment: Can't you just set a flag in unwind IBAction and access it in viewDidAppear?
Comment: It's important because I have something that's called in viewDidAppear (and I can't call it in viewDidLoad because it involves performSegue, and you can't call performSegue in viewDidLoad).
Comment: @lxx I updated my question :) this is actually an intermediate view controller, not the absolute root. The child is unwinding all the way to the absolute beginning of the universe.
Comment: Not sure if this works but you could trigger unwind first to your intermediate controller and then immediately another one to the root controller?
Comment: maybe it's easier to just use delegation or notification in your case ?
Comment: @lxx, yes, viewDidAppear will be called on B when C rewinds to A.
Comment: Actually it will call intermediate VC viewDidAppear.
Comment: Maybe using singleton to keep flag ? and access it in viewDidAppear ?
Comment: Can you not use the methods `isMovingFromParentViewController`, `isMovingToParentViewController`, `isBeingPresented` and `isBeingDismissed` to work out if the controller is being shown for the first time or exposed as a result of an unwind which really just results in a pop for nav controllers and a dismiss for modals? That is what they are for and what I use to detect returns from pushed controllers.
Answer: You should be able to use the following to detect in each controller if the exposure of the view controller was as a result of being pushed/presented, or as a result of being exposed as a result of pop/dismiss/unwind.
This may or may be enough for your needs.
- (void) viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];

    // Handle controller being exposed from push/present or pop/dismiss
    if (self.isMovingToParentViewController || self.isBeingPresented){
        // Controller is being pushed on or presented.
    }
    else{
        // Controller is being shown as result of pop/dismiss/unwind.
    }
}

If you want to know that viewDidAppear was called because of an unwind segue as being different from a conventional pop/dismiss being called, then you need to add some code to detect that an unwind happened. To do this you could do the following:
For any intermediate controller you want to detect purely an unwind in, add a property of the form:
/** BOOL property which when TRUE indicates an unwind occured. */
@property BOOL unwindSeguePerformed;

Then override the unwind segue method canPerformUnwindSegueAction:fromViewController:withSender: method as follows:
- (BOOL)canPerformUnwindSegueAction:(SEL)action
                 fromViewController:(UIViewController *)fromViewController
                         withSender:(id)sender{
  // Set the flag indicating an unwind segue was requested and then return
  // that we are not interested in performing the unwind action.
  self.unwindSeguePerformed = TRUE;

  // We are not interested in performing it, so return NO. The system will
  // then continue to look backwards through the view controllers for the
  // controller that will handle it.
  return NO;
}

Now you have a flag to detect an unwind and a means to detect the unwind just before it happens. Then adjust the viewDidAppear method to include this flag.
- (void) viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];

    // Handle controller being exposed from push/present or pop/dismiss
    // or an unwind
    if (self.isMovingToParentViewController || self.isBeingPresented){
        // Controller is being pushed on or presented.
        // Initialize the unwind segue tracking flag.
        self.unwindSeguePerformed = FALSE;
    }
    else if (self.unwindSeguePerformed){
        // Controller is being shown as a result of an unwind segue
    }
    else{
        // Controller is being shown as result of pop/dismiss.
    }
}

Hopefully this meets your requirement.
For docs on handling the unwind segue chain see: https://developer.apple.com/library/ios/technotes/tn2298/_index.html
Comment: This answer is incorrect. `self.isMovingToParentViewController || self.isBeingPresented` is true when the `viewDidAppear:` is called while popping the view controller. (yes, I'm sure it's the popping view controller, not the one behind)
Comment: Updated answer with full solution to include detecting unwind versus pop/dismiss.
Comment: Indeed, the answer is wrong. Seems like this has changed since it was written in 2015?
Answer: Here is a simple category on UIViewController that you can use to track whether your presented view controller is in the midst of an unwind segue.  I suppose it could be flushed out more but I believe this much works for your case.
To use it you need to register the unwind segue from your unwind action method on the destination view controller:
- (IBAction) prepareForUnwind:(UIStoryboardSegue *)segue
{
    [self ts_registerUnwindSegue: segue];
}

That's it.  From your intermediate view controller, you can test if you are in the midst of an unwind segue:
- (void) viewDidAppear:(BOOL)animated
{
    [super viewDidAppear: animated];

    BOOL unwinding = [self ts_isUnwinding];

    NSLog( @"%@:%@, unwinding: %@", self.title, NSStringFromSelector(_cmd), unwinding ? @"YES" : @"NO" );
}

There's no need to clean anything up; the segue will self-deregister when it ends.
Here's the full category:
@interface UIViewController (unwinding)

- (void) ts_registerUnwindSegue: (UIStoryboardSegue*) segue;
- (BOOL) ts_isUnwinding;

@end

static NSMapTable* g_viewControllerSegues;

@implementation UIViewController (unwinding)

- (void) ts_registerUnwindSegue: (UIStoryboardSegue*) segue
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        g_viewControllerSegues = [NSMapTable weakToWeakObjectsMapTable];
    });

    for ( UIViewController* vc = segue.sourceViewController ; vc != nil ; vc = vc.presentingViewController )
    {
        [g_viewControllerSegues setObject: segue forKey: vc];
    }
}

- (BOOL) ts_isUnwinding
{
    return [g_viewControllerSegues objectForKey: [self ts_topMostParentViewController]] != nil;
}

- (UIViewController *)ts_topMostParentViewController {
    UIViewController *viewController = self;
    while (viewController.parentViewController) {
        viewController = viewController.parentViewController;
    }
    return viewController;
}

@end

Comment: vc.presentingViewController will be nil except for modal presentation or when some ancestor was presented as a modal.  e.g This will not work for NavRoot->A->PushB->PushC with unwind from C to A, detect at B as there is no `presentingViewController`. `ts_registerUnwindSegue` would need to use the same algorithm which the unwind segue search code uses to locate the target controller which would include searching children of the source controllers navigation controller, navigation parents, modals and combinations of each.
Comment: @RoryMcKinnel - IMO this question pertains to presented (modal) controllers, not controllers pushed onto a UINavigationController stack.  Why?  Because unwinding from a nav-stack doesn't invoke the intermediate controller's viewDidAppear methods.
Comment: Looking at this again, your assumption looks correct.
Comment: This is a good work around, thanks. However I tested it and the implementation is not correct imo. As all children of a given presentingViewController will also have viewDidAppear called as a side effect of its parent having it called on itself, any child controller of the presentingViewController won't be found by the category. I'll suggest a edit in your question to fix it as it won't fit in a comment and I don't think it is worth an answer as the logic is all yours.
Answer: Your question was really interesting to me, because I never used IB and segues before (don't judge me for that) and wanted to learn something new. As you described in your comments:

viewDidAppear will be called on B when C rewinds to A

So I come up with an easy custom solution to this:
protocol ViewControllerSingletonDelegate: class {

    func viewControllerWillUnwind(viewcontroller: UIViewController, toViewController: UIViewController)
}

class ViewControllerSingleton {

    static let sharedInstance = ViewControllerSingleton()

    private var delegates: [ViewControllerSingletonDelegate] = []

    func addDelegate(delegate: ViewControllerSingletonDelegate) {

        if !self.containsDelegate(delegate) {

            self.delegates.append(delegate)
        }
    }

    func removeDelegate(delegate: ViewControllerSingletonDelegate) {

        /* implement any other function by your self :) */
    }

    func containsDelegate(delegate: ViewControllerSingletonDelegate) -> Bool {

        for aDelegate in self.delegates {

            if aDelegate === delegate { return true }
        }

        return false
    }

    func forwardToDelegate(closure: (delegate: ViewControllerSingletonDelegate) -> Void) {

        for aDelegate in self.delegates { closure(delegate: aDelegate) }
    }
}

class SomeViewController: UIViewController, ViewControllerSingletonDelegate {

    let viewControllerSingleton = ViewControllerSingleton.sharedInstance

    func someFunction() { // some function where you'll set the delegate

        self.viewControllerSingleton.addDelegate(self)
    }

    /* I assume you have something like this in your code */
    @IBAction func unwindToSomeOtherController(unwindSegue: UIStoryboardSegue) {

        self.viewControllerSingleton.forwardToDelegate { (delegate) -> Void in

            delegate.viewControllerWillUnwind(unwindSegue.sourceViewController, toViewController: unwindSegue.destinationViewController)
        }

        /* do something here */
    }

    // MARK: - ViewControllerSingletonDelegate
    func viewControllerWillUnwind(viewcontroller: UIViewController, toViewController: UIViewController) {

        /* do something with the callback */
        /* set some flag for example inside your view controller so your viewDidAppear will know what to do */
    }
}

You also could modify the callback function to return something else, like controller identifier instead the controller itself.
I do everything programmatically, so please don't judge me for that too. ;)
If this code snippet won't help you, I'd still love to see some feedback.
Answer: Add  method in your parent view controller
@IBAction func unwindToParent(unwindSegue: UIStoryboardSegue) {
    if let childViewController = unwindSegue.sourceViewController as? ChildViewController {
        println("unwinding from child")
    }
}

As an exemple if the unwind segue is related to a button, in the storyboard link your button to it's view controller exit

It will propose to link to unwindToParent method

Then each time the unwind segue is performed, the unwindToParent method will be called
Answer: Suppose the segue navigation is ViewController -> FirstViewController -> SecondViewController. There is an unwind from SecondViewController to ViewController. You can add in the intermediary FirstViewController the following code to detect unwind actions.
import UIKit

class FirstViewController: UIViewController {

    var unwindAction:Bool = false
    override func viewDidAppear(animated: Bool) {
        if unwindAction {
            println("Unwind action")
            unwindAction = false
        }
    }
    override func viewControllerForUnwindSegueAction(action: Selector, fromViewController: UIViewController, withSender sender: AnyObject?) -> UIViewController? {
        self.unwindAction = true

         return super.viewControllerForUnwindSegueAction(action, fromViewController: fromViewController, withSender: sender)
    }

}

EDIT
After giving this some thought, I decided the solution to this depends on the kind of complexity that you are dealing with here. What exactly do you do when you do the unwind segue? The solutions given here are viable and they work -- only if you want to detect whether it is an unwind action. What if you want to pass the data between the point where the unwind is happening to the root? What if there is a complex set of preparations that you wanna do in one of the intermediate view controllers? What if you want to do both of these?
In such complex scenarios, I would immediately rule out overriding the unwind methods of the view controller. Doing such operations there will work, but it won't be clean. A method will be doing what it isn't supposed to do. Smell that? That's code smell.
What if, somehow a view controller could inform the next view controller in the hierarchy of the event happening? Better yet, how do we do this without tightly coupling these two?
Protocol.
Have a protocol definition something like:
protocol UnwindResponding {
    prepareForUnwindSegue(segue:UISegue , formViewController:UIViewController, withImportantInfo info:[String,AnyObject])
}

Using protocol you will keep the relationship between the objects -- the hierarchy of view controllers in this case -- explicit. At the point of occurrence of a particular event, you will delegate the call to the next controller in the hierarchy informing about the happening of a particular event in another view controller. Here is an example:
override func prepareForSegue(segue:UIStoryboardSegue, sender:AnyObject?) {

    if let unwindResponder = self.presentingViewController as? UnwindResponding where segue.identifier = "unwindSegue" {
        unwindResponder.prepareForUnwindSegue(segue:UISegue, fromViewController:self,info:info)
    }

}

In the intermediary view controller you can do something like:
extension IntermediaryViewController : UnwindResponding {
    prepareForUnwindSegue(segue:UISegue , fromViewController:UIViewController, withImportantInfo info:[String,AnyObject]) {
        if let unwindResponder =  self.presentingViewController {
            unwindResponder.prepareForUnwindSegue(segue,fromViewController:fromViewController, info:info)
        }
        unwindSegue = true
    }
}

Granted, you wouldn't wanna do this if you just want to detect unwind segues. Maybe you do, you'll never know what will happen in the future. Never hurts to keep your code clean.
Comment: I do not believe `viewControllerForUnwindSegueAction` will be called in FirstViewController in the case of Push->Push. The documetation states that this method is called on the controller which starts the unwind and for a controller pushed, this will return the parent which is the navigation controller. Then `canPerformUnwindSegueAction` is called on its children. The only reliable mechanism is to use `canPerformUnwindSegueAction` to detect the unwind in all controllers. See my answer.
Comment: All right. Yes. But why would you do an unwind segue in navigation controller systems? Seems like an overkill to me.
Comment: The important piece is that if you just pop to a controller, its harder to pass information back and you have to do all the code. Unwind segues give you a mechanism to pass information to the point you jump back to before the jump happens and its all done by IB. There are lots of examples where you might want to select an item which requires more than one controller push to reach: When selected you want to jump back to the controller which started the selection off. The other advantage is it also works across push and modal sequences without you having to write code.
Comment: I would prefer writing a lot of code especially since with the given approach there is tight coupling between the controllers. I would rather delegate with explicit relationship between root/descendant. But then again, this approach works for simple situations. +1, your answer. :)
Comment: I think the idea is the tight coupling is reduced to the use of proper unwind target methods: e.g. prepareForUnwindAsColorSelected, prepareForUnwindAsNameSelected etc... So I actually quite like that the coding is reduce to setting up the contract between unwind activation and appropriate unwind to points without needing any code added to the intermediate controllers. So I think that the relationship is explicit as long as you use a suitable naming scheme: same as you would have to do if doing it all by hand. Appreciate the +1 8^).
Comment: Establishing explicit relationship by mere naming scheme? Are you sure? I would rather use a protocol to make the relationships explicit.
Comment: Saw your update. Unfortunately `presentingViewController` is nil except if using modal presentation: or worse is set to the presenter of a modal ancestor which could skip some of the controllers in between. For a controller which is pushed, `self.navigationController` is the equivalent but then you need find the previous child by looking through its controller stack. This is actually what the unwind segue mechanism does as it hunts for the controller which has the right action method. See https://developer.apple.com/library/ios/technotes/tn2298/_index.html
Comment: The point is not that. The point is that it is very easy if you follow the protocol mechanism. You can make any class confirm to this protocol and have unwind messages sent there. The presentingViewController example taken here is just an example of this approach.
Comment: I got the idea. My point is that it is short circuiting the iOS unwind mechanism. The iOS unwind algorithm will end at the first instance which implements the protocol. Your protocol has now taken over the unwind process. This controller (which now knows the unwind has happened:tick)) now has to have code to find the next controller which implements the protocol which may or may not be the TRUE endpoint of the unwind segue. This means every intermediate when called has to code the full iOS unwind point search algorithm to get the next controller to retain the integrity of the unwind.
Answer: You can override the function unwindForSegue:towardsViewController:, which is called when the ViewController is on the path of an unwind segue. It's meant to be used to reconfigure the ViewController.
Swift example:
override func unwind(for unwindSegue: UIStoryboardSegue, towardsViewController subsequentVC: UIViewController) {
}

Comment: Unfortunately I don't see `unwindForSegue:towardsViewController:` being called on any of the view controllers in the path of an unwind (iOS 12.1).


TensorFlow output shape with Shape Function

Question: I am writing a custom TensorFlow Op in C++ and CUDA as per the guide and am confused about the setting of the ops output shape. I wish to be able to provide the desired output dimensions as an attribute and use this attribute to set the shape with SetShapeFn
My op code is very much a straight adaptation of the example linked above, however, I am not sure how to use the provided attribute in this way.
REGISTER_OP("GaussianProcess")
.Attr("output_dim: int") //This is the desired output dimension.
.Input("data_points: float32")
.Input("query_point: float32")
.Input("alpha: float32")
.Input("hyp: float32")
.Output("shape_descriptor: float32")
.SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) {
      /*
       Use attribute 'output_dim' here.
      */
});

For the above Op registration, how would one access the output_dim attribute in the lambda passed to SetShapeFn?
I need to be able to pass it to a call like so:
c->set_output(0, output_dim);

Answer: The InferenceContext allows getting attributes via the GetAttr method. So you can get output_dim like this:
int output_dim;
c->GetAttr("output_dim", &output_dim);

Hope that helps!


grub-efi-amd64-signed package post-installation script subprocess returned error exit status 127

Question: My dual boot laptop runs Ubuntu 18.04.3 as my main OS after an upgrade, also with Windows. Whenever I attempt to install or update apps I get this error:
Setting up grub-efi-amd64-signed (1.128+2.04-1ubuntu12) ...
dpkg: error processing package grub-efi-amd64-signed (--configure):
 installed grub-efi-amd64-signed package post-installation script subprocess ret
urned error exit status 127
Errors were encountered while processing:
 grub-efi-amd64-signed
E: Sub-process /usr/bin/dpkg returned an error code (1)

Now this happens with any interaction apt which is very inconvenient. I already attempted to update grub but did not have any solution with that.
Heres my dpkg and fstab if that can be any help.
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name                  Version              Architecture Description
+++-=====================-====================-============-===============================================================
un  grub                  <none>               <none>       (no description available)
un  grub-cloud-amd64      <none>               <none>       (no description available)
ii  grub-common           2.04-1ubuntu12       amd64        GRand Unified Bootloader (common files)
un  grub-coreboot         <none>               <none>       (no description available)
un  grub-doc              <none>               <none>       (no description available)
ii  grub-efi              2.04-1ubuntu12       amd64        GRand Unified Bootloader, version 2 (dummy package)
ii  grub-efi-amd64        2.04-1ubuntu12       amd64        GRand Unified Bootloader, version 2 (EFI-AMD64 version)
ii  grub-efi-amd64-bin    2.04-1ubuntu12       amd64        GRand Unified Bootloader, version 2 (EFI-AMD64 modules)
iF  grub-efi-amd64-signed 1.128+2.04-1ubuntu12 amd64        GRand Unified Bootloader, version 2 (EFI-AMD64 version, signed)
un  grub-efi-arm          <none>               <none>       (no description available)
un  grub-efi-arm64        <none>               <none>       (no description available)
un  grub-efi-ia32         <none>               <none>       (no description available)
un  grub-efi-ia64         <none>               <none>       (no description available)
un  grub-emu              <none>               <none>       (no description available)
un  grub-ieee1275         <none>               <none>       (no description available)
un  grub-legacy           <none>               <none>       (no description available)
un  grub-legacy-doc       <none>               <none>       (no description available)
un  grub-linuxbios        <none>               <none>       (no description available)
un  grub-pc               <none>               <none>       (no description available)
un  grub-uboot            <none>               <none>       (no description available)
un  grub-xen              <none>               <none>       (no description available)
un  grub-yeeloong         <none>               <none>       (no description available)
un  grub2                 <none>               <none>       (no description available)
ii  grub2-common          2.04-1ubuntu12       amd64        GRand Unified Bootloader (common files for version 2)

fstab
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
/dev/mapper/ubuntu--vg-root /               ext4    errors=remount-ro 0       1
# /boot was on /dev/nvme0n1p2 during installation
UUID=d5d23cc4-21a5-4c06-bf9a-9a74d76d315b /boot           ext4    defaults        0       2
# /boot/efi was on /dev/nvme0n1p1 during installation
UUID=93E0-B2F2  /boot/efi       vfat    umask=0077      0       1
/dev/mapper/ubuntu--vg-swap_1 none            swap    sw              0       0

Comment: Try running: `sudo dpkg --configure -a` and if you need to, you can post the output at paste.ubuntu.com and then post a link in the comments here.
Comment: Oh well, try installing `mokutil` this may be a problem with a [missing dependency](https://bugs.launchpad.net/ubuntu/+source/grub2/+bug/1814187).
Answer: According to this bug report, you need to install mokutil to fix the problem.
It seems that this package is a missing dependency.
Answer: if you have shim-signed installed remove it.

This package provides a minimalist boot loader which allows verifying
signatures of other UEFI binaries against either the Secure Boot DB/DBX or
against a built-in signature database.  Its purpose is to allow a small,
infrequently-changing binary to be signed by the UEFI CA, while allowing
an OS distributor to revision their main bootloader independently of the
CA.
This package contains the version of the bootloader binary signed by the
Microsoft UEFI CA.

Then remove grub-efi-amd64-signed.
Comment: This is a good way to render someone's system unbootable.


Can I build a gravel driveway over sand?

Question: There is a large quantity of sand where I would like to build a gravel drive. The sand is not super deep, only an inch or two at its deepest points, but I cannot find any quick way to remove it. Much of it is compacted as well. I was considering just dumping 4 inches of #8 gravel on top of this sand base, which like I said, seems quite stable even in the rain. My big questions are:
Will dumping this gravel over the sand weight it down and stop the sand from blowing around when it gets windy? I'm trying to keep sand from getting all over my cars.
Are there any inherent problems with doing this? (Note: I don't need this driveway to last forever, a couple years of life would be just fine)
Any other suggestions?
Thanks for any assistance!
Comment: Why is there sand? And what is under that sand?
Comment: The rock will probably work its way down and some of the sand will move up over time. The sand may help to lock the rock together, The question I would ask is how deep is "not super deep".
Comment: If you use #8 it will never stop settling. Use 3/4" crushed stone. If the stones have rounded edges, you're looking at the wrong pile.
Answer: For me living in the desert a sand yard is pretty common.   Putting gravel on top of the sand here to add a bit of firmness is also common.
So as previously commented how much sand and what is under it will affect success and how long it lasts before sand comes through (if it does).   The gravel will work into the sand, but this is not bad at all (concrete is sand, gravel and a cement, 2 out of the 3).
Two factors on how long it lasts before the sand does appear on top again will depend on water content, how much gravel is laid, how thick the sand is and compaction.
To start your effort, water the sand well and give it a day or so to soak and harden.  If a compaction machine is available compact it when damp.
Lay your gravel on top, wet and compact it.
Answer: You could use crushed Oyster shells.
The shell are very compatible with the sand and will blend in with the sand to make a drive almost as hard as cement.
Comment: I like the idea but oyster shells in my neck of the woods would be more expensive than asphalt or concrete.
Answer: Have you heard of or considered crushed bluestone? Fairly inexpensive, gives a locking effect and stays put such as the edge/end.
I have a farmer friend who would disc his driveway (roughly 100'x30') after every rainy season and this turned the soil to a fine sand.
He wanted something that would form to his slightly rolling grade, drain properly, easy to walk on and maintain, and be somewhat quite. Concrete was not an option (rolling grade) and he didn't like asphalt.
He used bluestone gravel. SO far no maintenance required, no sinkage, same color as when purchased, quite, pretty and very comfortable to walk on even with thin sandals. I was very surprised, almost amazed and wondered why it is not used more often.
Roughly 2 1/2" -  3' depth is what he used.

NOTE: Bluestone is one of only a couple crushed stones that meets code for Wheelchair Accessibility.


using vba to close messagebox

Question: I am using a for loop in VBA to open a series of files.
If the given file is already open, a message box will appear asking if I want to save the file.
How do I select "dont save" without specifying file names in my code?
I do not want to specify file names because they change through each iteration of the for loop
Thank you
Comment: Does this help? http://stackoverflow.com/q/11220537/2258
Comment: showing code is always beneficial
Answer: Turn off the alerts by putting this line before the Workbook.Open method:
Application.DisplayAlerts = False

Be sure to turn on the alerts back by adding this after Workbook.Open method:
Application.DisplayAlerts = True

using vba to close messagebox


Number of rotations to superpose

Question: Two lines A and B of same length both center at the origin in 3D space.
Suppose A and B are not the same.
What is the number of matrices that directly rotates A to B?
Comment: What do you mean by "directly"  rotating $A$ to $B$? Can you give an example of a non-direct rotation?
Comment: Why quartic equations ?
Comment: You can *always* map $A$ to $B$ by reflecting across a plane, no ifs or buts.
Comment: Direct rotation: $R_{1}a = b$. More than one rotation: $R_{1}R_{2}a = b$
Answer: By the definition of "direct rotation" that you've given in comments to the question, there is an infinite number of such rotations. You can rotate $A$ about any axis that lies in the angle bisector of $A$ and $B$ to bring it onto $B$. Taking $A\times B$ as the rotation axis will minimize the rotation angle.
Answer: You can work out the problem using complex numbers. You are asking for the number of solutions of
$$b=ra$$ where $a,b,r$ have unit length.
This is a linear equation, that has a single solution
$$r=\frac ba.$$
If the lines are unoriented, there can be two mappings,
$$r=\pm\frac ba.$$
Comment: nvm. just have to find the plane that contains the two lines.
Comment: ok. i get this now. so this works for 2D? For 3D, I need quaternions? Sorry I didn't mention it is in 3D space.
Comment: no... it is not the same. 4 rotations can work if a plane contains A and B in 3D. Clockwise/counter clockwise 180 degree along axis 1 or 2. Since a plane can always contain any two intersecting line, the answer is always 4 unless A = B. There are always 4 real solutions for the quartic.
Comment: @rxu: maybe, but does that correspond to different matrices ?
Comment: There are two axis of rotations. For an X (two lines), the horizontal and vertical axes both can work.
Comment: @rxu: forget about angles, think in terms of matrices.
Comment: 4 unique solutions. Draw X on paper. Two axes of rotation on the paper with angle 180 degree. Since +180 and -180 degree gives the same matrix, this totally gives two unique rotation matrices. Third axis of rotation is perpendicular to paper with +theta and 180+theta angles. That gives two unique rotation matrices.
Answer: 4 unique rotation matrices in 3D if $A \ne B$

Find plane containing the two lines.
This plane contains two axes of rotations. Rotating 180 degree around one of these two axes transforms A to B. -180 degree gives the same rotation matrices. For an X (two lines) on paper, the rotation axes are the vertical and horizontal axes.
Third axis of rotation is perpendicular to the plane. Rotation $+\theta$ degree and $180 + \theta$ degree around this axis gives two rotation matrices.
Comment: Actually, there's an infinite number of "direct" rotations. For every axis in the angle bisector of the two lines, there's a corresponding rotation that takes $A$ to $B$.
Comment: meh. so i need to get the largest root from the characteristic polynomial.
Answer: Actually, there are continuum many such rotations.  Let $a$ and $b$ be endpoints of $A$ and $B$, respectively, and let $S$ be the set of points that are equdistant from $a$ and $b$. It follows from the assumptions that $a\neq b$, so $S$ is the perpendicular bisector plane of the segment $ab$. Moreover, $S$ contains the origin. Let $L$ be a line contained in $S$ and passing through the origin. Now $L$ intersects the segments $A$ and $B$ at the same angle at the same point, so there is a rotation whose axis is $L$ and which maps $A$ to $B$. There are continuum many choices for $L$ and hence continuum many rotations.
Comment: Thanks that explains a bug I see when I am superimposing line segments.

Number of rotations to superpose


How to rename order status in frontend in magento?

Question: I need to rename order status in magento only for customers.
For exmaple:
Customer`s order has a status "fraud". In frontend(for cusntomer) it should be displayed as "Open", but in backand it should stay "Suspected fraud"
I use Magento 1.7. Thanks
Answer: Go to System->Order statuses, edit the Suspected fraud status and you should have a separate field for each store view where you can input the translation for the status. Write Open for all of them (except admin - Status Label).


Android setTheme() not changing ActionBar and Status Bar

Question: I have an ActionBarActivity which has fragments for a navigation drawer. When an item in the navigation drawer is pressed, it starts the corresponding fragment.
In each of these fragments, the onCreate() method looks like this:
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getActivity().setTheme(R.style.AppTheme);

    setHasOptionsMenu(true);
}

The theme that is applied is different for each of these fragments however.
I noticed that the setTheme() method does not appear to change the colour of the ActionBar or status bar as declared in the styles.xml from which I am referencing:

Again, there are different styles with different colorPrimary and colorPrimaryDark attributes for the different fragments in my activity.
So, the setTheme() method does not change the colour of the ActionBar or status bar, but it does change some things like the colour of the pullback feature in a listview, for example.
Am I missing something, or is there something I need to do for setTheme() to change the ActionBar and status bar colour?
UPDATE:
I tried the solution posted here but it gives me exactly the same result as what I had tried before (using setTheme()).
Comment: Check this, for changing theme from Fragment: http://stackoverflow.com/a/15496425/3736955
Comment: Are you trying to implement material theme in your app ?
Comment: @Radix Yes, I'm trying to implement material themes.
Answer: You need to call setTheme(..) before super.onCreate(..),and It works for me:
setTheme(R.style.YourThemeName);
super.onCreate(savedInstanceState);

Answer: You can change background color , text color of the action bar via defining a custom style.
Edit your styles.xml file in your project
<resources>

</resources>

and then use the setTheme() to set the CustomActionBarTheme
for more info check here
Also if you are trying to implement material theme, do the below and it applies to the places as mentioned in the image you commented with

where my application uses the AppTheme (..usually specified in the manifest..as below )
    <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:screenOrientation="portrait"
    ..
    android:theme="@style/AppTheme">

Comment: That could work, but I thought that the `colorPrimary` and `colorPrimaryDark` attributes would change the ActionBar as shown in the [diagram from the developer website](https://developer.android.com/training/material/images/ThemeColors.png). Also, I don't think this would change the status bar colour.
Answer: I decided to use the following method to solve my issue:
private void updateActionBar(int title, int actionBarColor, int statusBarColor) {
    if (title != 0) {
        getSupportActionBar().setTitle(getString(title));
        getSupportActionBar().setSubtitle(null);
    }

    if (actionBarColor != 0) {
        getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(actionBarColor)));
    }

    if (statusBarColor != 0) {
        if (Build.VERSION.SDK_INT >= 21) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().setStatusBarColor(getResources().getColor(statusBarColor));
        }
    }

}

I have been calling this method before changing the Fragment, but have also kept using getActivity().setTheme(R.style.AppTheme); or getActivity().setTheme(R.style.AppTheme_colourTwo); in the onCreate method of the Fragment.


Select On Change not working correct

Question: I have a select option that calls a function that needs to be triggered on change. But now it's triggered when  the page is loaded and on change. See below:
$(function () {

$('select[id^="iZondagbegin_"]').on('change', uren("Zondag"));
$('select[id^="iZondageinde_"]').on('change', uren("Zondag"));
$('select[id^="iMaandagBegin_"]').on('change', uren("Maandag"));
$('select[id^="iMaandageinde_"]').on('change', uren("Maandag"));
$('select[id^="iDinsdagbegin_"]').on('change', uren("Dinsdag"));
$('select[id^="iDinsdageinde_"]').on('change', uren("Dinsdag"));
$('select[id^="iWoensdagbegin_"]').on('change', uren("Woensdag"));
$('select[id^="iWoensdageinde_"]').on('change', uren("Woensdag"));
$('select[id^="iDonderdagbegin_"]').on('change', uren("Donderdag"));
$('select[id^="iDonderdageinde_"]').on('change', uren("Donderdag"));
$('select[id^="iVrijdagbegin_"]').on('change', uren("Vrijdag"));
$('select[id^="iVrijdageinde_"]').on('change', uren("Vrijdag"));
$('select[id^="iZaterdagbegin_"]').on('change', uren("Zaterdag"));
$('select[id^="iZaterdageinde_"]').on('change', uren("Zaterdag"));

function uren(dag) {

    var vandaag = datumvandaag();
    var pauze = ($('[title="Pauze"]').val());
    var error;

    $('input[id^="i' + dag + '_"]').val("");

    //get values
    var tijdStart = ($('select[id^="i' + dag + 'begin_"]').val());
    var uurStartControle = +($('select[id^="i' + dag + 'begin_"]').val());
    tijdStart += ":" + ($('select[id^="i' + dag + 'begin_"]').filter("[id$='_$DateTimeFieldDateMinutes']").val());
    var minutenStartControle = +($('select[id^="i' + dag +'begin_"]').filter("[id$='_$DateTimeFieldDateMinutes']").val());

    //var datezondagstart = new Date(vandaag + tijdstart + ":00");

    var tijdStop = ($('select[id^="i' + dag + 'einde_"]').val());
    var uurStopControle = +($('select[id^="i' + dag + 'einde_"]').val());
    tijdStop += ":" + ($('select[id^="i' + dag + 'einde_"]').filter("[id$='_$DateTimeFieldDateMinutes']").val());
    var minutenStopControle = +($('select[id^="i' + dag + 'einde_"]').filter("[id$='_$DateTimeFieldDateMinutes']").val());

    if (uurStartControle >= uurStopControle && minutenStartControle >= minutenStopControle || uurStopControle <= uurStartControle) {
        alert("Tijd is ongeldig!");
        error = 1;

    }

    if (error != 1) {
        var totaleTijd = tijdsverschil(tijdStart, tijdStop, pauze);
        if (totaleTijd != '00:00') {
            $('input[id^="i' + dag + 'uren_"]').val(totaleTijd);
        }
        else{
            alert("Tijd is ongeldig!");
        }
    }
}

});

Any one have an idea what i'm doing wrong? I'm i call it the wrong way?
Comment: You firstly should refactorize this code and logic to use a more generic way
Answer: Currently You are calling uren function when you are using uren("Zondag"). You should use an anonymous function as event handler and call uren function.
Use it like
$('select[id^="iZondagbegin_"]').on('change', uren("Zondag"));

To:
$('select[id^="iZondagbegin_"]').on('change', function () {
    uren("Zondag");
});

I would recommend, You to use data-* attributes to store what need to be passed to change event handler.
Example:
HTML, Here Added a cooom class mySelect
<select class="mySelect" id="iZondagbegin_1" data-value="Zondag"> .... </select>
<select class="mySelect" id="iMaandagBegin_" data-value="Maandag"> .... </select>

Script
$('.mySelect').on('change', function () {
    uren($(this).data('value'));
});

Answer: Please change all lines like:
$('select[id^="iZondagbegin_"]').on('change', uren("Zondag"));

To:
$('select[id^="iZondagbegin_"]').on('change', uren);

and:
<select id="iZondagbegin_...." data-value="Zondag">.....</select>

and:
function uren() {
     var value = $(this).data('value');
     //.....
}

Or better still, use a common class, .myclass say, on all the select elements and do the binding with one statement.
$('select.myclass').on('change', uren);
.....
<select id="iZondagbegin_...." data-value="Zondag" class="myclass">.....</select>
.....
function uren() {
     var value = $(this).data('value');
     //.....
}

When you pass arguments like that or when you provide (), the function will be invoked immediately. You don't want that.
Comment: still need to pass argument
Answer: There's already two answers that point out your issue; an alternative solution is to let jQuery handle contexts with $.proxy:
$('select[id^="iZondagbegin_"]').on('change', $.proxy(uren, null, "Zondag");

More info here

Select On Change not working correct


Path of exile - party tanker build

Question: Due to my group having too many aggressive builds, I thought it might help if I instead use a more tanky build that can withstand damage and draw the enemies to me and let them focus on dealing damage. But I am facing a few problems:

Bosses seems to be immune to taunting, in fact they seemed to attack those that deals more damage resulting in my character being mostly ignored by bosses.
Potion recharge by killing, my character lacks damage and therefore unable to charge back potions needed.
Evasion tanking is not reliable at all, regardless which base character I attempt it ends up focusing on armour/energy shield instead.

I have searched around for suggested Tank builds but those builds focus on being able to survive while hitting the boss and not what I have in mind.
Is there any way to build a tanker that can effectively draw attacks(especially from bosses) to let the damage dealers of the party focus more on doing damage?
Answer: I would suggest trying an Empire's Grasp reverse knockback build to drag enemies where you want them and hold them there instead of taunting. This will at least have the effect of keeping your ranged party members safe from their melee attacks.
Some builds to try that can include reverse knockback are dual shockwave totems, RAT nuke, molten strike Mjölner, or a fast attacking cyclone build.
Combining reverse knockback with auras, curses, vigilant strike with The Vigil jewel, and ascendencies which can affect your allies such as Guardian, Champion, or Necromancer can let you fulfil a tanky support role.
Guardian's abilities are especially well suited to buffing party members defensively, whereas Necromancer's are a huge boost to offense, even after the recent nerf.
Comment: Nice idea! But how would it fare against bosses that have movement modifiers like lightning warp or leap? Can it still contain them effectively?
Comment: Sadly it will not work vs lightning warp as that is an actual teleport, but it might work vs leap slams if you hit them fast enough. RAT nuke probably has the attack speed to keep leapers contained. Molten strike Mjolner may do the job as well with enough extra projectiles (GMP and life gain on hit are your friends there). Cyclone will hold them with enough attack speed and some AoE increases I think, but it's been a year or three since I last did a reverse knockback cycloner, and that was with CoC pre-several-nerfs.
Answer: You can generally taunt bosses. Only the Shaper and his guardians are immune to taunt. It may not stop the bosses hitting your team mates at all but they will take less 10% damage when attacked by an enemy that you've taunted. Make sure they're not taunting enemies themselves which they might be doing if they are using any war cries.
Probably the best way to protect your team mates is to use the defensive auras (grace, determination, discipline and purities) and focus on improving aura effectiveness as well as aura area. It is possible to use all of these if you get some passive skills and items that reduce mana reservation. Focusing your own character around energy shield also allows you to use some auras by reserving life using blood magic (particularly with the Prism Guardian unique shield). This will ensure that all of your team mates can tank the boss and deal lots of damage at the same time.
The ascendancy classes Necromancer and Guardian reward for granting auras to your allies. Guardian in particular is good for a defensive support character as it can also grant a lot of bonus energy shield and damage reduction. Champion gives extra bonuses for taunting.
It would also be effective to focus on cursing enemies. Bosses take less penalties from curses but you can increase curse effectiveness with some passive skills. You can also get a passive skill and some items that allow you to apply more than one curse to an enemy. A highly effective temporal chains and enfeeble will massively weaken a boss.
If you get endurance charges then you could get the Conduit keystone passive which will share your endurance charges with enemies.
Another option to stop bosses would be to focus on making hits that stun enemies. Look for things that give increased stun duration and, particularly, enemy stun threshold reduction. Maces are probably best for this as they have implicit properties that improve stun and lots of mace passive skills also help. It's fairly easy to get some good stuns on bosses playing solo, but it may be difficult with a team unless you really go all out.
Another thing you could try would be to chill bosses. Chill has a base duration of 2s which can be improved with increased chill duration. Increased chill and ailment effectiveness will make the chill slow the subject more. Like stun, you would probably need to really focus your character on this. There are also some abilities that let you maim enemies, slowing them even further.
Answer: You are better off not as a tank but rather a support through curse and aura use.
Curses go a long way to reducing boss damage output. Combine enfeeble with temporal chains for example. You can also add in other damage boosting curses like elemental weakness and vulnerability.
Using auras like determination, discipline and grace you can boost the party members defenses. Add in Heralds that party members aren't already using and get all of the aura mana reserved reductions and effect/radius boosts to increase these effects.
Some unique items are tailored towards being a supportive character. The Victario's items come to mind. Victario's Influence boosts auras as well as significantly decreasing their reservation cost. Arguably the most useful unique for a support character. Victario's Charity Allows you to generate charges for allies and boosts aura radius. Lochtonial Caress generates charges and gives you Conduit which shares charges with party members.
Since these items and other abilities usually gives charges on kill you can link a damaging skill to culling strike to get kills without needing much damage. Of course it won't work when your party members are 1-shotting so you are usually better off focusing on cursing and auras.
Comment: I accepted this answer for the suggestion to use culling strike as means to kill and recharge potions. That solved one big problem I am facing.

Path of exile - party tanker build


Duplicate rows in Python Pygame Tetris clone

Question: I've been looking at this problem for awhile now and have draw a blank so would appreciate some help.
I'm making a simple Tetris clone using Python and Pygame. The problem is that the process of detecting completed rows sometimes adds a cloned row to the new GRID so anything effecting the original also effects the cloned row too.
here is the code for removing completed rows:
# create an empty grid
newGRID = []

fullRowsCount = 0
for row in reversed(GRID):
    # count number of non-zero blocks in row
    rowBlockCount = sum(col > 0 for col in row)

    # if number of non-zero blocks is less than the width of grid then copy to newGRID
    if rowBlockCount < GRID_SIZE.width:

        # insert non-full row into newGRID
        newGRID.insert(0, row)

    else:
        # increment this counter in order to know number of blank rows to add to top of newGRID
        fullRowsCount += 1

# if there are any full rows then they're not included in newGRID so blank rows need adding to the top
if fullRowsCount:
    newGRID = [[0] * GRID_SIZE.width] * fullRowsCount + newGRID
    # update GRID to the newGRID
    GRID = newGRID

Thank you for your time :)
Comment: Basically there's a 2D list called GRID which contains the stack data. By stack I mean once a shape has stopped it's data is added to the GRID so basic collision detection can take place.

Even if newGRID.insert(0, row[:]) is used wouldn't that still be creating a clone albeit not entangled with the orignal?
Comment: This is the full code https://pastebin.com/W1xXjMCU. The code above starts at line 362
Answer: The statement
newGRID = [[0] * GRID_SIZE.width] * fullRowsCount + newGRID

does not do what you expect. It creates 1 column, which is shared by all rows in the grid.
Note, the output of the following code
newGRID = [[0] * 3] * 3
newGRID[0][0] = 1
print(newGRID)

is

[[1, 0, 0], [1, 0, 0], [1, 0, 0]]

You have to create a new column for each row:
newGRID = [[0] * GRID_SIZE.width for _ in range(fullRowsCount + newGRID)]


Printing a crystal report in landscape to a specifc printer

Question: I have a couple of reports that are designed in landscape mode which work fine when previewing and printing via the VB6 Crystal control.
I was recently asked to allow the printer to be changed so added code to enumerate the printers, and set the control's PrinterDriver, PrinterName and PrinterPort properties.
While this works well for the portrait reports, specifying anything other than the default printer causes the report viewer to force the report into the default orientation for the selected printer.
Setting Printer.Orientation to vbPRORLandscape has no effect on crystal as it uses its own printing surface.
The Crystal viewer also has no way to specify an orientation (it's set to landscape in the designer)
Microsoft KB198901 has sample code to change the default orientation (after changing to use PRINTER_ACCESS_USE) but this effects anything else that would access that printer until it's changed back again.
Is there any way to print to a specific printer AND keep the report's landscape orientation without temporarily changing the printer's system wide configuration to landscape for the duration of the control's use?
The reports are designed in Crystal 4.6 and is printed by the Crystal 8.0 viewer control.
Comment: I'd be interested in a better answer than "cache the settings and restore after use" myself.  However I believe these settings are stored and used at the print spooler level, which is global (one set per printer for the entire PC).  I'd be glad to be shown this is incorrect though!
Answer: I guess you are setting CRAXDRT.Report's PrinterDriver, PrinterName and PrinterPort properties. The same object has PaperSize and PaperOrientation properties. Did you try to set them ?
Comment: I'm using the older VB6 `Crystal.CrystalReport` control, not `CRAXDRT.Report`. It does not seem to expose any orientation properties.
Comment: What is Crystal.CrystalReport control ? Is this CrystalViewer ?  Sorry, I used Crystal 8 long time ago.
Comment: It's the viewer control provided (or compatable) with VB6.


Pasting text into dplyr mutate

Question: Id like to be able to pass a string of variables to lag into the dplyr mutate function but am having some trouble. For example, this works fine:
 text <- "lag(depth)"
 diamonds %>% mutate_(text)

But this doesn't and gives an error:
 text <- "lag(depth), lag(table)"
 diamonds %>% mutate_(text)

Error in parse(text = x) : <text>:1:11: unexpected ','
1: lag(depth),

This feels like it should be possible. Any help would be greatly appreciated.
Comment: Use `strsplit` to split the string first, i.e. `diamonds %>% mutate_(.dots = unlist(strsplit(text, ', ')))`
Comment: `.dots` is the way to go, I had found this also: `diamonds %>% reduce(strsplit(text,", ")[[1]],mutate_,.init=.)`
Answer: You have to concatenate your text:
text <- c("lag(depth)", "lag(table)")

And then use .dots to parse your text:
library(dplyr)

diamonds %>%
  mutate_(.dots = text)

## A tibble: 53,940 x 12
#   carat cut     color clarity depth table price     x     y     z `lag(depth)`
#   <dbl> <ord>   <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>        <dbl>
# 1 0.23  Ideal   E     SI2      61.5    55   326  3.95  3.98  2.43         NA
# 2 0.21  Premium E     SI1      59.8    61   326  3.89  3.84  2.31         61.5
# 3 0.23  Good    E     VS1      56.9    65   327  4.05  4.07  2.31         59.8
# 4 0.290 Premium I     VS2      62.4    58   334  4.2   4.23  2.63         56.9
# 5 0.31  Good    J     SI2      63.3    58   335  4.34  4.35  2.75         62.4
# 6 0.24  Very G~ J     VVS2     62.8    57   336  3.94  3.96  2.48         63.3
# 7 0.24  Very G~ I     VVS1     62.3    57   336  3.95  3.98  2.47         62.8
# 8 0.26  Very G~ H     SI1      61.9    55   337  4.07  4.11  2.53         62.3
# 9 0.22  Fair    E     VS2      65.1    61   337  3.87  3.78  2.49         61.9
#10 0.23  Very G~ H     VS1      59.4    61   338  4     4.05  2.39         65.1
## ... with 53,930 more rows, and 1 more variable: `lag(table)` <dbl>

Answer: We could do this with parse_exprs from rlang
library(tidyverse)
library(rlang)
text <- "lag(depth); lag(table)" #note the `;` separation
diamonds %>%
     mutate(!!! parse_exprs(text))
# A tibble: 53,940 x 12
#   carat cut     color clarity depth table price     x     y     z `lag(depth)`
#   <dbl> <ord>   <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>        <dbl>
# 1 0.23  Ideal   E     SI2      61.5    55   326  3.95  3.98  2.43         NA
# 2 0.21  Premium E     SI1      59.8    61   326  3.89  3.84  2.31         61.5
# 3 0.23  Good    E     VS1      56.9    65   327  4.05  4.07  2.31         59.8
# 4 0.290 Premium I     VS2      62.4    58   334  4.2   4.23  2.63         56.9
# 5 0.31  Good    J     SI2      63.3    58   335  4.34  4.35  2.75         62.4
# 6 0.24  Very G… J     VVS2     62.8    57   336  3.94  3.96  2.48         63.3
# 7 0.24  Very G… I     VVS1     62.3    57   336  3.95  3.98  2.47         62.8
# 8 0.26  Very G… H     SI1      61.9    55   337  4.07  4.11  2.53         62.3
# 9 0.22  Fair    E     VS2      65.1    61   337  3.87  3.78  2.49         61.9
#10 0.23  Very G… H     VS1      59.4    61   338  4     4.05  2.39         65.1
# ... with 53,930 more rows, and 1 more variable: `lag(table)` <dbl>

Comment: Note that `text` is separated with comas ;)
Comment: @patL Not a problem.  You can change collapse it `text <- paste(text, collapse=";")` if it is vector or if it is a string use `text <- gsub(",", ";", text)`
Answer: as an alternative solution you can try to use mutate_at. The function lag must be duplicated using this approach.
library(tidyverse)
a <- unlist(stringi::stri_extract_all_words(text))
diamonds %>%
  mutate_at(.vars = a[a %in% colnames(diamonds)], .funs = c(lag=a[duplicated(a)]))
# A tibble: 53,940 x 12
   carat cut       color clarity depth table price     x     y     z depth_lag table_lag
   <dbl> <ord>     <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>     <dbl>     <dbl>
 1 0.23  Ideal     E     SI2      61.5    55   326  3.95  3.98  2.43      NA          NA
 2 0.21  Premium   E     SI1      59.8    61   326  3.89  3.84  2.31      61.5        55
 3 0.23  Good      E     VS1      56.9    65   327  4.05  4.07  2.31      59.8        61
 4 0.290 Premium   I     VS2      62.4    58   334  4.2   4.23  2.63      56.9        65
 5 0.31  Good      J     SI2      63.3    58   335  4.34  4.35  2.75      62.4        58
 6 0.24  Very Good J     VVS2     62.8    57   336  3.94  3.96  2.48      63.3        58
 7 0.24  Very Good I     VVS1     62.3    57   336  3.95  3.98  2.47      62.8        57
 8 0.26  Very Good H     SI1      61.9    55   337  4.07  4.11  2.53      62.3        57
 9 0.22  Fair      E     VS2      65.1    61   337  3.87  3.78  2.49      61.9        55
10 0.23  Very Good H     VS1      59.4    61   338  4     4.05  2.39      65.1        61

Comment: I think you're missing the point of the question, OP wants to know what to do if he's stuck with strings to begin with.
Comment: @Moody_Mudskipper yes thanks. Made some chages to my answer.

Pasting text into dplyr mutate


How can I find self-charging gear?

Question: The only way I've seen to find self-charging gear in Heat Signature is to hope that a "liberator" character eventually shows up with something. Is there a way normal characters can find self-charging gear? There are various personal missions that are all but impossible without that kind of kit, but I haven't found any in all my travels (and I feel like I'm pretty late-game).
Answer: They're still rare, but my strategy has been spending all my money on "Overpriced Mystery Crate" from the Miscellaneous Shop (and the Liberation Mission eventually).

I've unlocked a few of those items for sale; but overpriced mystery crate is always there.
An example of all the loot on a character I had when I loaded the game:

Basically I just spend all my money on the cases and then sell all the junk and keep anything better than current inventory.

How can I find self-charging gear?


Update Apk automatically on update found from google play

Question: I want to implement auto update on my android app, but i don`t know how to do it. Can you please help me, I have searched the web but i cant find it.
I have tired ,
The code in
Force update android app when new version available.
But it didn't work at all.
Comment: Check this link carefully it's working answers..
Comment: dude it woks ya know
Answer: Hey Guys I have found the answer I am currently using javiersantos AppUpdater


Is there a way to run a transaction multiple time at once?

Question: First, I would like to apologize in advance. I just started learning this a few months ago, so I need stuff broken down completely. I have a project using python and datajoint (makes sql code shorter to write) where I need to create an airport that has at least 7 airports, different planes and what not. Then I need to populate the tables with passenger reservations. Here is what I have so far.
        @schema
        class Seat(dj.Lookup):
            definition = """
            aircraft_seat : varchar(25)
            """
            contents = [["F_Airbus_1A"],["F_Airbus_1B"],["F_Airbus_2A"],["F_Airbus_2B"],["F_Airbus_3A"],
            ["F_Airbus_3B"],["F_Airbus_4A"],["F_Airbus_4B"],["F_Airbus_5A"],["F_Airbus_5B"],
            ["B_Airbus_6A"],["B_Airbus_6B"],["B_Airbus_6C"],["B_Airbus_6D"],["B_Airbus_7A"],
            ["B_Airbus_7B"],["B_Airbus_7C"],["B_Airbus_7D"],["B_Airbus_8A"],["B_Airbus_8B"],
            ["B_Airbus_8C"],["B_Airbus_8D"],["B_Airbus_9A"],["B_Airbus_9B"],

This keeps going leaving me with a total of 144 seats on each plane.
        @schema
        class Flight(dj.Manual):
            definition = """
            flight_no  : int
            ---
            economy_price : decimal(6,2)
            departure : datetime
            arrival : datetime
            ---
            origin_code : int
            dest_code : int
            """
        @schema
        class Passenger(dj.Manual):
            definition = """
            passenger_id : int
            ---
            full_name : varchar(40)
            ssn : varchar(20)
            """
        @schema
        class Reservation(dj.Manual):
            definition = """
            -> Flight
            -> Seat
            ---
            -> Passenger

            """

Then I populate flights and passengers:
        Flight.insert((dict(flight_no = i,
                    economy_price = round(random.randint(100, 1000), 2),
                    departure = faker.date_time_this_month(),
                    arrival = faker.date_time_this_month(),
                    origin_code = random.randint(1,7),
                    dest_code = random.randint(1,7)))
             for i in range(315))
        Passenger.insert(((dict(passenger_id=i, full_name=faker.name(),
                   ssn = faker.ssn()))
             for i in range(10000)), skip_duplicates = True)

Lastly I create the transaction:
        def reserve(passenger_id, origin_code, dest_code, departure):
            with dj.conn().transaction:
             available_seats = ((Seat * Flight - Reservation) & Passenger &
             {'passenger_id':passenger_id}).fetch(as_dict=True)
        try:
            choice = random.choice(available_seats)
        except IndexError:
            raise IndexError(f'Sorry, no seats available for {departure}')
        name = (Passenger & {'passenger_id': passenger_id}).fetch1('full_name')
        print('Success. Reserving seat {aircraft_seat} at ticket_price {economy_price} for
        {name}'.format(name=name, **choice))
        Reservation.insert1(dict(choice, passenger_id=passenger_id), ignore_extra_fields=True)

       reserve(random.randint(1,1000), random.randint(1,7),
       random.randint(1,7),random.choice('departure'))

       Output[]: Success. Reserving seat E_Yak242_24A at ticket_price 410.00 for Cynthia Erickson

       Reservation()
       Output[]: flight_no      aircraft_seat      passenger_id

             66           B_Yak242_7A           441

So I am required to have 10.5 flights a day with the planes at least 75% full which leaves me needing over 30000 reservations. Is there a way to do this like 50 at a time? I have been searching for an answer and have not been able to find a solution. Thank you.
Comment: The most efficient way to do this would be to use multi-threading, but it is a rather complex topic that cannot be included in just a single answer. Maybe you can start by looking the [multiprocessing](https://docs.python.org/3/library/multiprocessing.html) module first, the idea would be you initialize multiple processes, that each will process a transaction at once.
Answer: One of the maintainers for DataJoint here. First off, I'd like to say thanks for trying out DataJoint; curious as to how you found out about the project.
Forewarning, this will be a long post but I feel it is a good opportunity to clear up a few things. Regarding the problem in question, not sure if I fully understand the nature of your problem but let me follow on several points. I recommend reading this answer in its entirety before determining how best to proceed for your case.
TL;DR: Compute tables are your friend.
Multi-threading
Since it has come up in the comments it is worth addressing that as of 2021-01-06, DataJoint is not completely thread-safe (at least from the perspective of sharing connections). It is unfortunate but it is mainly due to a standing issue with PyMySQL which is a principal dependency of DataJoint. That said, if you initiate a new connection on each thread or process you should not run into any issues. However, this is an expensive workaround and can't be combined with transactions since they require that operations be conducted within a single connection. Speaking of which...
Compute Tables and Job Reservation
Compute tables is one noticeable omission from your above attempt at a solution. Compute tables provide a mechanism to associate its entities to those in an upstream parent table with addional processing prior to insert (defined in a make method in your Compute table class) where it may be inoked by calling the populate method which calls the make method for each new entry. Calls to your make method are transaction-constrained and should achieve what you are looking for. See here in the docs for more details in its use.
Also, for additional performance gains, there is another feature called Job Reservation which provides a means to pool together multiple workers to process large data sets (using populate) in an organized, distributed manner. I don't feel it is required here but worth mentioning and ultimately up to how you view the results below. You may find out more on this feature here in our docs.
Schema Design
Based on my understanding of your initial design, I have some suggestions how we can improve the flow of the data to increase clarity, performance, and also to provide specific examples on how we can use the power of Compute tables. Running as illustrated below on my local setup, I was able to process your requirement of 30k reservations in 29m54s with 2 different plane model types, 7 airports, 10k possible passengers, 550 available flights. Minimum 75% seating capacity was not verified only because I didn't see you attempt this yet, though if you see how I am assigning seats you will notice that it is almost there. :)
Disclaimer: I should note that the below design is still a large oversimplification of the actual real-world challenge to orchestrate proper travel reservations. Considerable assumptions were taken mainly for the benefit of education as opposed to submitting a full, drop-in solution. As such, I have explicitly chosen to avoid using longblob for the below solution so that it is easier to follow along. In reality, a proper solution would likely include more advanced topics for further performance gains e.g. longblob, _update, etc.
That said, let's begin by considering the following:
import datajoint as dj # conda install -c conda-forge datajoint or pip install datajoint
import random
from faker import Faker # pip install Faker
faker = Faker()
Faker.seed(0) # Pin down randomizer between runs

schema = dj.Schema('commercial_airtravel') # instantiate a workable database

@schema
class Plane(dj.Lookup):
    definition = """
    # Defines manufacturable plane model types
    plane_type    : varchar(25) # Name of plane model
    ---
    plane_rows    : int         # Number of rows in plane model i.e. range(1, plane_rows + 1)
    plane_columns : int         # Number of columns in plane model; to extract letter we will need these indices
    """
    contents = [('B_Airbus', 37, 4), ('F_Airbus', 40, 5)] # Since new entries to this table should happen infrequently, this is a good candidate for a Lookup table

@schema
class Airport(dj.Lookup):
    definition = """
    # Defines airport locations that can serve as origin or destination
    airport_code : int         # Airport's unique identifier
    ---
    airport_city : varchar(25) # Airport's city
    """
    contents = [(i, faker.city()) for i in range(1, 8)] # Also a good candidate for Lookup table

@schema
class Passenger(dj.Manual):
    definition = """
    # Defines users who have registered accounts with airline i.e. passenger
    passenger_id : serial      # Passenger's unique identifier; serial simply means an auto-incremented, unsigned bigint
    ---
    full_name    : varchar(40) # Passenger's full name
    ssn          : varchar(20) # Passenger's Social Security Number
    """

Passenger.insert((dict(full_name=faker.name(),
                       ssn = faker.ssn()) for _ in range(10000))) # Insert a random set of passengers

@schema
class Flight(dj.Manual):
    definition = """
    # Defines specific planes assigned to a route
    flight_id            : serial                      # Flight's unique identifier
    ---
    -> Plane                                           # Flight's plane model specs; this will simply create a relation to Plane table but not have the constraint of uniqueness
    flight_economy_price : decimal(6,2)                # Flight's fare price
    flight_departure     : datetime                    # Flight's departure time
    flight_arrival       : datetime                    # Flight's arrival time
    -> Airport.proj(flight_origin_code='airport_code') # Flight's origin; by using proj in this way we may rename the relation in this table
    -> Airport.proj(flight_dest_code='airport_code')   # Flight's destination
    """

plane_types = Plane().fetch('plane_type') # Fetch available plane model types
Flight.insert((dict(plane_type = random.choice(plane_types),
                    flight_economy_price = round(random.randint(100, 1000), 2),
                    flight_departure = faker.date_time_this_month(),
                    flight_arrival = faker.date_time_this_month(),
                    flight_origin_code = random.randint(1, 7),
                    flight_dest_code = random.randint(1, 7))
               for _ in range(550))) # Insert a random set of flights; for simplicity we are not verifying that flight_departure < flight_arrival

@schema
class BookingRequest(dj.Manual):
    definition = """
    # Defines one-way booking requests initiated by passengers
    booking_id : serial                                # Booking Request's unique identifier
    ---
    -> Passenger                                       # Passenger who made request
    -> Airport.proj(flight_origin_code='airport_code') # Booking Request's desired origin
    -> Airport.proj(flight_dest_code='airport_code')   # Booking Request's desired destination
    """

BookingRequest.insert((dict(passenger_id = random.randint(1, 10000),
                            flight_origin_code = random.randint(1, 7),
                            flight_dest_code = random.randint(1, 7))
                       for i in range(30000))) # Insert a random set of booking requests

@schema
class Reservation(dj.Computed):
    definition = """
    # Defines booked reservations
    -> BookingRequest              # Association to booking request
    ---
    flight_id        : int         # Flight's unique identifier
    reservation_seat : varchar(25) # Reservation's assigned seat
    """
    def make(self, key):
        # Determine booking request's details
        full_name, flight_origin_code, flight_dest_code = (BookingRequest * Passenger & key).fetch1('full_name',
                                                                                'flight_origin_code',
                                                                                'flight_dest_code')
        # Determine possible flights to satisfy booking
        possible_flights = (Flight * Plane *
                            Airport.proj(flight_dest_city='airport_city',
                                         flight_dest_code='airport_code') &
                            dict(flight_origin_code=flight_origin_code,
                                 flight_dest_code=flight_dest_code)).fetch('flight_id',
                                                                           'plane_rows',
                                                                           'plane_columns',
                                                                           'flight_economy_price',
                                                                           'flight_dest_city',
                                                                           as_dict=True)
        # Iterate until we find a vacant flight and extract details
        for flight_meta in possible_flights:
            # Determine seat capacity
            all_seats = set((f'{r}{l}' for rows, letters in zip(*[[[n if i==0 else chr(n + 64)
                                                                    for n in range(1, el + 1)]]
                                                                  for i, el in enumerate((flight_meta['plane_rows'],
                                                                                flight_meta['plane_columns']))])
                             for r in rows
                             for l in letters))
            # Determine unavailable seats
            taken_seats = set((Reservation & dict(flight_id=flight_meta['flight_id'])).fetch('reservation_seat'))
            try:
                # Randomly choose one of the available seats
                reserved_seat = random.choice(list(all_seats - taken_seats))
                # You may uncomment the below line if you wish to print the success message per processed record
                # print(f'Success. Reserving seat {reserved_seat} at ticket_price {flight_meta["flight_economy_price"]} for {full_name}.')
                # Insert new reservation
                self.insert1(dict(key, flight_id=flight_meta['flight_id'], reservation_seat=reserved_seat))
                return
            except IndexError:
                pass
        raise IndexError(f'Sorry, no seats available departing to {flight_meta["flight_dest_city"]}')

Reservation.populate(display_progress=True) # This is how we process new booking requests to assign a reservation; you may invoke this as often as necessary

Syntax and Convention Nits
Lastly, just some minor feedback in your provided code. Regarding table definitions, you should only use --- once in the definition to identify a clear distinction between primary key attributes and secondary attributes  (See your Flight table). Unexpectedly, this did not throw an error in your case but should have done so. I will file an issue since this appears to be a bug.
Though transaction is exposed on dj.conn(), it is quite rare to need to invoke it directly. DataJoint provides the benefit of handling this internally to reduce the management overhead of this from the user. However, the option is still available should it be needed for corner-cases. For your case, I would avoid invoking it directly and reccomend using Computed (or also Imported) tables instead.


How to get sorting complete/finished event of jsgrid

Question: I have 2 different jsGrid table.I have to update the other table data after finishing sorting event of 1st table.I searched the documentation but i couldn't find any complete/finished event for sorting.I found onDataLoaded event,but it does not fire after filtering.
How would i find the completion of sorting event.
Answer: I found out the event which gets fired as the data of a grid changes - onRefreshed. Link - documentation link It gives out the grid instance as a argument.
Inside that I used var sorting = $("#grid").jsGrid("getSorting");
to get the sorting which gives -
{
    field,      // the name of the field by which grid is sorted
    order       // 'asc' or 'desc' depending on sort order
}.
If the table has been sorted the object will have the details - {field:'A',order:'asc'} if not then {field:undefined,order:undefined}.
onRefreshed: function (args) {
var sorting = $("#jsgrid").jsGrid("getSorting");
}


Reduce Required Root Certificate List For Constrained Devices

Question: I'm developing a memory constrained IoT device and would like to connect it to Google IoT Core via MQTT. The list of required root certificates that must be trusted to allow for server TLS certificate validation is very long. I am seeking a smaller list that is appropriate for limited-resource IoT devices but won't suddenly stop working. Is there a way to safely reduce this list of required certificates?
From the online documentation (https://cloud.google.com/iot/docs/concepts/device-security) under the Device Security Recommendations section it states:
'Use TLS 1.2 when communicating with mqtt.googleapis.com:8883 (or :443), and verify that the server certificate is valid using root certificate authorities. Read this security note for detailed TLS requirements and future compatibility.'
From the security note (https://security.googleblog.com/2015/09/disabling-sslv3-and-rc4.html) it states:
'At least the certificates in https://pki.google.com/roots.pem must be trusted.'
I can clearly see that the documentation states the full list is required but this doesn't seem acceptable for memory constrained IoT devices. As an example AWS requires only a single certificate - depending on the TLS cipher selected. See the AWS documentation under Server Authentication (https://docs.aws.amazon.com/iot/latest/developerguide/managing-device-certs.html)
Any help on understanding ways that the list of root certificates can be reduced - such as elemination based on ECC-based validation vs RSA-based validation - would be helpful.
Answer: Thanks to a helpful Google engineer on Github who answered the Issue Clarify how trusted_RootCA_certs were chosen in the Google provided iot-device-sdk-embedded-c project, the solution is to use a long-term support (LTS) domain.
From the documentation, the special domain "mqtt.2030.ltsapis.goog" can be used instead of "mqtt.googleapis.com" allowing the need of only two root CA certs w/ small ECC 256 public keys instead of the entire root.pem package (128KB).
These root CA certs are fixed through year 2030.
The required root CAs are:

GTS LTSR as primary
GS Root R4 as backup

Note other requirement and features for embedded devices in the long-term support (LTS) domain documentation.
Comment: If I am planning to use the LTS domain from a Raspberry Pi, will it work? If yes then can you please mention how?


webservices test on JMeter

Question: In J.meter I need to test multiple web-services in single scenario like, after successful execution of service one it will gives session-Id and this session id will take by other services and check it and complete the scenario as per business logic?
Answer: It is classic question regarding "correlation" in JMeter. Correlation stands for the process of extracting dynamic data from previous response and passing it to the next request.

Add a JSON Extractor as a child of the first request and define a JSON Path query to extract the session-Id value and and store it into a Jmeter Variable.
Use the aforementioned JMeter Variable as the session-Id for the subsequent requests.

See API Testing With JMeter and the JSON Extractor article for comprehensive instructions.
Comment: Can you attach Screen shoot in above procedure what you have mentioned?

webservices test on JMeter


Ubuntu occasionally downgrades Tomcat to the version from apt repository

Question: I'm using Tomcat 9 on Ubuntu 20.04.
The apt installs Tomcat 9.0.31 which has a HTTPS-related bug preventing our web application from working well.
To fix the issue, I am manually updating Tomcat to a newer release (9.0.40), by downloading a ZIP archive from the Tomcat website and replacing the binary files of the older version in /usr/share/tomcat.
This approach worked until recently. Since March 2022 (approximately), I'm observing occasional downgrades of the installed Tomcat from 9.0.40 to 9.0.31!
I wonder how could I prevent that? Why the OS ever downgrades the software without any consent?
Answer: There are different ways of holding back packages: with dpkg, apt, dselect, aptitude or Synaptic.
dpkg
Put a package on hold:
echo "<package-name> hold" | sudo dpkg --set-selections

Remove the hold:
echo "<package-name> install" | sudo dpkg --set-selections

Display the status of all your packages:
dpkg --get-selections

Display the status of a single package:
dpkg --get-selections <package-name>

Show all packages on hold:
dpkg --get-selections | grep "\<hold$"

apt
Hold a package:
sudo apt-mark hold <package-name>

Remove the hold:
sudo apt-mark unhold <package-name>

Show all packages on hold:
sudo apt-mark showhold

dselect
With dselect, enter the [S]elect screen, find the package you wish to hold in its present state and press = or H. The changes will take effect immediately after exiting the [S]elect screen.
The following approaches are limited in that locking/holding a package within aptitude or synaptic doesn't affect apt-get/apt.
aptitude
Hold a package:
sudo aptitude hold <package-name>

Remove the hold:
sudo aptitude unhold <package-name>

Locking with Synaptic Package Manager
Go to Synaptic Package Manager (System > Administration > Synaptic Package Manager).
Click the search button and type the package name.
When you find the package, select it and go to the Package menu and select Lock Version.
That package will now not show in the update manager and will not be updated.


Puppet create link with timestamp only after Exec

Question: I am working on a module to deploy tar file into directories on client. So whenever the tar file changes it deploys in to a new directory with datetime stamp like '20150204130312' . It works fine till this point. I am generating that date time stamp for directory in module.
Whenever the module runs the date and time are generated every time but the directory is only created if tar file updates which is fine. After this i want to create a link to that folder in which tar was extracted. I want that link to be created only if the tar file is extracted. But right now whenever puppet runs since the date and time stamp changes everytime the link is updated even if the tar was not extracted.
I tried using notify in exec and require on file resource but that doesnt work.
$dir have the timestamp generated on module using
$rel_dir= "/data/agrod/releases";
$dir= generate('/bin/date', '+%Y%m%d%H%M%S')
exec { "untar $targz":
    command => "/bin/mkdir -p $rel_dir/$dir/; /bin/tar xzvf /tmp/$targz -C $rel_dir/$dir",
    refreshonly => true,
    require => File["/tmp/$targz"],
   notify => File["/data/agrod/current"],    }

file { "/data/agrod/current":
 ensure => 'link',
 target => "/data/agrod/$dir",
 require => Exec["untar $targz"],
}

How should i create the dependency so that link only gets created when tar file is extracted in exec. I dont want to use exec for creating links. I don't know if this is possible.
Answer: Instead of require use subscribe:
exec { "untar ${targz}":
  command => "/bin/mkdir -p $rel_dir/$dir/; /bin/tar xzvf /tmp/$targz -C $rel_dir/$dir",
  refreshonly => true,
  subscribe => File["/tmp/${targz}"],
  notify => File["/data/agrod/current"]
}

The subscribe parameter will assume require automatically and will ensure the exec is only executed if the File["/tmp/${targz}"] resource changes.
Hope this helps


Is there a sign for 'per decem'?

Question: There are signs for per cent (%), per mille (‰), per myriad (‱) et cetera, but is there a sign representing one part per ten, or 'per decem'?
If so, how does it look like? If not, why not?
Comment: For what its worth, you can easily get away with only using percent signs and never use any of the others your whole life.  I don't see the benefit a perdecem sign would bring.  It would just make one more symbol to remember and have a chance of mistaking for something else if reading quickly.  I, for one, am glad to not know of any such symbol.
Comment: [Google](https://www.google.com/search?q='per+decem') only seems to show actual Latin (*per decem annos*: for ten years). If nobody uses it the way you are thinking and $^0\!/$ looks weird, then perhaps you have an answer.  There are units which are tenths, such as *decibels* (dB) and in some countries *deciliters* (dl), so perhaps the symbol is "d-".
Comment: To give you a perspective – I've created a plot where I had to scale a variable to parts per ten for readibility and I wanted to showcase this unit in the legend like this – Variable name (%) – without having to write it out.

@ JMoravitz Following your logic one would also not need percent, because one could use permille.

@Henry I was thinking about ⁰⁄  too, that would only be logical. And it seems one can easily create it out of the unicode symbols U+2070 and U+2044
Comment: I would write "/10" after the number and call it a day.
Answer: Since 'ppt' is already used for 'parts per trillion', I'd settle for the sign ⁰⁄  that was proposed.

Is there a sign for 'per decem'?


Spring Batch limits number of concurrent threads to 10

Question: I've got Spring Boot application with Spring Batch framework. My goal is simple - run certain job concurrently. I want to be able to, let's say, run 15 threads in the same time and reject every excessive one. Here's my configuration class:
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.JobRegistry;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.support.JobRegistryBeanPostProcessor;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.launch.support.SimpleJobLauncher;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
@EnableBatchProcessing
public class GeneratingReportJobConfiguration {

    @Autowired
    private GeneratingReportTask task;

    @Autowired
    private JobRepository jobRepository;

    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Bean
    public JobRegistryBeanPostProcessor jobRegistryBeanPostProcessor(JobRegistry jobRegistry) {
        JobRegistryBeanPostProcessor jobRegistryBeanPostProcessor = new JobRegistryBeanPostProcessor();
        jobRegistryBeanPostProcessor.setJobRegistry(jobRegistry);
        return jobRegistryBeanPostProcessor;
    }

    @Bean
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(15);
        taskExecutor.setMaxPoolSize(15);
        taskExecutor.setQueueCapacity(0);
        return taskExecutor;
    }

    @Bean
    public JobLauncher jobLauncher(TaskExecutor taskExecutor) {
        SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
        jobLauncher.setJobRepository(jobRepository);
        jobLauncher.setTaskExecutor(taskExecutor);
        return jobLauncher;
    }

    @Bean
    public Job job() {
        return jobBuilderFactory.get("generatingReportJob")
                .start(step())
                .build();
    }

    @Bean
    public Step step() {
        return stepBuilderFactory.get("generatingReportTask")
                .tasklet(task)
                .build();
    }
}

The thing is, whatever I'm trying to do - application runs at most 10 jobs at the same time. I've tried experimenting with TaskExecutor - my first logical choice was SimpleAsyncTaskExecutor, which appeared to stash
every excessive request and then run them in a random order which is not intended.
So later I've tried to manipulate that limit and, as you can see in the code, I've started using ThreadPoolTaskExecutor, which allowed me to set the limit to 5, for example, and it worked as expected - at most 5 threads could run at the same time and next ones were being rejected while these 5 were running. However, setting the limit to 15 resulted in behaviour similar to the previous one. Still, 11th request was being queued, whereas 16th was being rejected. This is almost my intended behaviour, however I need to be able to fully control thread execution.
Jobs are being invoked via @RestController using jobLauncher.run(). Every excessive request results in browser loading until being able to start execution. Seems like, program is being frozen somewhere inside jobLauncher.run() (when able to start job execution it just exits - that's how async run works).
Comment: I tried that as well and I'm able to run up to 15 jobs concurrently: https://gist.github.com/benas/fb729bd25c75667c8dc24c9c4d9d6b1d. In that case, I'm not sure why you are limited to 10..
Comment: I'm studiying a little bit the argument cause is interesting :) when you say: "setting the limit to 15 resulted in behaviour similar to the previous " do you mean the core or max pool size?
Comment: I see nothing wrong with your configuration. You should be able to run more than 10 jobs concurrently (up to 15 according to your example). Probably your job is consuming a lot of resources and you have a hardware limit? (ie your JVM is not able to spawn more than 10 threads?).
Comment: @rick both of them. you can see this in my code preview under `taskExecutor()` method
Comment: @MahmoudBenHassine well, job is just `Thread.sleep()` for 30 seconds, so I suppose it can't be the matter
Comment: Do you have an example on Git so I can pull and take look the issue?
Comment: @dominikbrandon I faced similar issue and solved by setting throttle limit as core pool size
Answer: Bit late but try to check if you are using HikariCP which has a default 10 simultaneous DB connexions limit
Just faced similar issue and resolved by increasing spring.datasource.hikari.maximum-pool-size
See: Number of parallel threads processing is capped to 10 with Spring Batch
Comment: You may be right, but I can't verify if this works anymore. Anyway, thanks for your answer.


Reducing time in C# Forms Control.set_Text(string) function

Question: Hoping for a quick answer (which SO seems to be pretty good for)...
I just ran a performance analysis with VS2010 on my app, and it turns out that I'm spending about 20% of my time in the Control.set_Text(string) function, as I'm updating labels in quite a few places in my app.
The window has a timer object (Forms timer, not Threading timer) that has a timer1_Tick callback, which updates one label every tick (to give a stop-watch sort of effect), and updates about 15 labels once each second.
Does anyone have quick suggestions for how to reduce the amount of time spent updating text on a form, other than increasing the update interval?  Are there other structures or functions I should be using?
Answer: I ran into this issue myself, and ended up creating my own simple Label control.
.Net's Label control is a surprisingly complicated beast, and is therefore slower than we'd like.
You can make a class that inherits Control, call SetStyle in the constructor to make it double-buffered and user-painted, then override the OnPaint method to call e.Graphics.DrawString and draw the Text property.
Finally, override Text or TextChanged and call Invalidate.
As long as you don't need AutoSize, this will be substantially faster than the standard Label control.
Here is my implementation:  (Currently in use in production)
///A simple but extremely fast control.
///<remarks>Believe it or not, a regular label isn't fast enough, even double-buffered.</remarks>
class FastLabel : Control {
    public FastLabel() {
        SetStyle(ControlStyles.AllPaintingInWmPaint
               | ControlStyles.CacheText
               | ControlStyles.OptimizedDoubleBuffer
               | ControlStyles.ResizeRedraw
               | ControlStyles.UserPaint, true);
    }
    protected override void OnTextChanged(EventArgs e) { base.OnTextChanged(e); Invalidate(); }
    protected override void OnFontChanged(EventArgs e) { base.OnFontChanged(e); Invalidate(); }

    static readonly StringFormat format = new StringFormat {
        Alignment = StringAlignment.Center,
        LineAlignment = StringAlignment.Center
    };
    protected override void OnPaint(PaintEventArgs e) {
        e.Graphics.DrawString(Text, Font, SystemBrushes.ControlText, ClientRectangle, format);
    }
}

If you don't want centering, you can get rid of, or change, the StringFormat.
Comment: This is pretty close to what I need, but I noticed a couple things - my font looks funny now, and all the labels need to be resized to accommodate that change.  Also, now I'm spending 30% of my time in the DrawString function, which doesn't seem to have sped up my form's responsiveness.  Any thoughts?
Comment: I'm not sure why that would happen.  What exactly does the font look like?
Comment: The letters and letter spacing look slightly wider - in both cases it's MS Sans Serif 8.25 pt, but the FastLabel is just wider.
Answer: Well, assigning the Text property takes about 0.6 nanoseconds, give or take.  It is the side effects that are expensive.  You've probably got the AutoSize property turned on for the labels.  So it needs to create the font handle, render the text in a temporary device context, measure the resulting string, taking account for side-effects due to TrueType hinting that artificially stretches the letter shape so it coincides with a pixel on the monitor, also adjusting for the modified ABC metrics to make ClearType work.  Then tell the native Windows control that it needs to change its window size.  Which will produce paint events for the label as well as the container control that's the parent of the label control.  Which goes through the same routine again, now actually drawing pixels.  Which, when Aero is enabled, changes bytes in a memory device context which needs to be blitted to the video device driver that actually updates the video memory so that the user can see the result.
Yeah, that takes time.
Speed it up by writing your own code instead of Windows Forms doing it for you.  Override the OnPaint event, use TextRender.DrawText to draw the labels.  Quick win there, it is easily 50 times faster.  Minus the point-and-click convenience of the designer though.
Comment: I tried using this methodology quickly, but I'm guessing I need to do a bit more than just create a simple `class MyFastLabel : Label` that overrides the OnPaint method?  With only that function and the TextRenderer.DrawText() method, anything that's a MyFastLabel doesn't show up.  What else should be included?
Comment: I don't think that inheriting label will provide any speed benefits, except for double-buffering.
Comment: @slaks: you completely missed the point.  A form or a panel can draw anything that a label would.
Comment: I was referring to his comment.


what difference between direct pointer and indirect pointer?

Question: pointer to a struct
code that can not work
struct node
{
    /* data */
    int data;
};

void addnode(struct node* n)
{
    n = (struct node*)malloc(sizeof(struct node));
    printf("value of pointer n = %p",&n);
    (*n).data = 9;
}
int main()
{
    struct node * n1 = NULL;
    addnode(n1);
    printf("data is %d\n",n1->data);
}

but the code below is fine
struct node
{
    /* data */
    int data;
};

void addnode(struct node ** n1)
{
    // the address of struct
    *n1 = (struct node*)malloc(sizeof(struct node));
    printf("address of pointer &n1 = %p\n",&n1);
    printf("address of pointer *n1 = %p\n",*n1);
    (*n1)->data = 99;
}
int main()
{
    struct node * n1 = NULL;
    //pass the address of pointer instead of value of it
    addnode(&n1);
    printf("address of pointer &n1 = %p\n",&n1); // self address
    printf("address of pointer *n1 = %p\n",&(*n1)); // the address of struct
    printf("data is %d\n",n1->data);
}

what makes me confused is why the indirect pointer as a parameter is working, instead of the direct pointer.
Comment: @T.J.Crowder Indeed, I once made one as community wiki, see the linked duplicate. A list of good dupe targets can be found in the [C tag wiki](https://stackoverflow.com/tags/c/info) below FAQ.
Comment: In the first version, you just passed the value of `n1` to a function, so `n` just got assigned `NULL` at the beginning. Afterwards you did `n = ... malloc`, which is an unrelated address to the original `n1`.  The second version `*n1 =....` writes into the address of what you passed. Also note that your function don't change `&n1` even though it's changed `n1` . So, it's the same value as before you did `addnode(&n1)`, till the very end of the `main`. So: First version: you passed n1 =>  you can't change n1 from the function
Second version: you passed &n1 => you can't change &n1 inside of it
Answer: The 'indirect' pointer, as you called it, is actually 'a pointer to your pointer variable'.
If you inspect the value of n1 in your debugger, you will see, in your first example, that it will remain NULL (because you did not assign a new value to it).
In the second example however, you assign a value to the variable by accessing it's address.
Your first code can work too if it looks like this:
struct node
{
    /* data */
    int data;
};

struct node* addnode()
{
    struct node* n = (struct node*)malloc(sizeof(struct node));
    printf("value of pointer n = %p",&n);
    n->data = 9;
    return n;
}
int main()
{
    struct node * n1 = NULL;
    n1 = addnode();
    printf("data is %d\n",n1->data);
}

Comment: I will have a try.thanks folks