Terminating app due to uncaught exception 'NSInvalidArgumentException', on deleting Row in UITableView

Question: I am getting the above error when executing the following code:
func tableView(_ tableView: UITableView,
                        commit editingStyle: UITableViewCellEditingStyle,
                        forRowAt indexPath: IndexPath) {
    let eventsOnArray = selectedRecipient?.events.allObjects  // crashes here

    guard let eventToRemove = eventsOnArray![indexPath.row] as? Event, editingStyle == .delete else {
                return
    }
        managedContext.delete(eventToRemove)
        do {
            try managedContext.save()
            getEvents()
            self.eventList.reloadData()
        } catch let error as NSError {
            print("Saving error: \(error), description: \(error.userInfo)")
        }

}

The detailed error is:
2018-03-11 12:20:49.732482-0400 Card Tracker[1516:29197] -[Recipient events]: unrecognized selector sent to instance 0x600000283840
2018-03-11 12:20:49.746477-0400 Card Tracker[1516:29197] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Recipient events]: unrecognized selector sent to instance 0x600000283840'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000010fe2f12b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x000000010ef76f41 objc_exception_throw + 48
    2   CoreFoundation                      0x000000010feb0024 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
    3   CoreFoundation                      0x000000010fdb1f78 ___forwarding___ + 1432
    4   CoreFoundation                      0x000000010fdb1958 _CF_forwarding_prep_0 + 120
    5   Card Tracker                        0x000000010e62b773 _T012Card_Tracker010ViewEventsC10ControllerC05tableC0ySo07UITableC0C_SC0gC16CellEditingStyleO6commit10Foundation9IndexPathV8forRowAttF + 195
    6   Card Tracker                        0x000000010e62c177 _T012Card_Tracker010ViewEventsC10ControllerC05tableC0ySo07UITableC0C_SC0gC16CellEditingStyleO6commit10Foundation9IndexPathV8forRowAttFTo + 119
    7   UIKit                               0x0000000110410a5f -[UITableView _animateDeletionOfRowAtIndexPath:] + 177
    8   UIKit                               0x0000000110419a59 __82-[UITableView _contextualActionForDeletingRowAtIndexPath:usingPresentationValues:]_block_invoke + 59
    9   UIKit                               0x0000000110953d67 -[UIContextualAction executeHandlerWithView:completionHandler:] + 174
    10  UIKit                               0x0000000110c41374 -[UISwipeOccurrence _performSwipeAction:inPullview:swipeInfo:] + 702
    11  UIKit                               0x0000000110c42bd1 -[UISwipeOccurrence swipeActionPullView:tappedAction:] + 112
    12  UIKit                               0x0000000110d25ed2 -[UISwipeActionPullView _tappedButton:] + 138
    13  UIKit                               0x00000001102ae972 -[UIApplication sendAction:to:from:forEvent:] + 83
    14  UIKit                               0x000000011042dc3c -[UIControl sendAction:to:forEvent:] + 67
    15  UIKit                               0x000000011042df59 -[UIControl _sendActionsForEvents:withEvent:] + 450
    16  UIKit                               0x000000011042ce86 -[UIControl touchesEnded:withEvent:] + 618
    17  UIKit                               0x000000011089ebad _UIGestureEnvironmentSortAndSendDelayedTouches + 5560
    18  UIKit                               0x0000000110898a4d _UIGestureEnvironmentUpdate + 1506
    19  UIKit                               0x000000011089841f -[UIGestureEnvironment _deliverEvent:toGestureRecognizers:usingBlock:] + 484
    20  UIKit                               0x00000001108974cb -[UIGestureEnvironment _updateGesturesForEvent:window:] + 288
    21  UIKit                               0x0000000110325f14 -[UIWindow sendEvent:] + 4102
    22  UIKit                               0x00000001102c9365 -[UIApplication sendEvent:] + 352
    23  UIKit                               0x000000012c2fe49d -[UIApplicationAccessibility sendEvent:] + 85
    24  UIKit                               0x0000000110c15a1d __dispatchPreprocessedEventFromEventQueue + 2809
    25  UIKit                               0x0000000110c18672 __handleEventQueueInternal + 5957
    26  CoreFoundation                      0x000000010fdd2101 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    27  CoreFoundation                      0x000000010fe71f71 __CFRunLoopDoSource0 + 81
    28  CoreFoundation                      0x000000010fdb6a19 __CFRunLoopDoSources0 + 185
    29  CoreFoundation                      0x000000010fdb5fff __CFRunLoopRun + 1279
    30  CoreFoundation                      0x000000010fdb5889 CFRunLoopRunSpecific + 409
    31  GraphicsServices                    0x00000001159789c6 GSEventRunModal + 62
    32  UIKit                               0x00000001102ad5d6 UIApplicationMain + 159
    33  Card Tracker                        0x000000010e606727 main + 55
    34  libdyld.dylib                       0x000000011436dd81 start + 1
    35  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

I am trying to delete a detail row in a Header-Detail based Entity.  The crash occurs in the debugger as soon as I leave the line let eventsOnArray.  I have placed a break point on that line, the code runs up until that point and then crashes when I use "Step Over".
getEvents:
 func getEvents () {
        // Now load all Events for this Receipient
        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Event")
        request.resultType = .dictionaryResultType

        do {
            events = try managedContext.fetch(request) as! [NSDictionary]
        } catch {
            print("Core Data  Fetch Failed:", error.localizedDescription)
        }
    }

Core Data Definition:
Comment: Isn't it the same issue like in [your previous question](https://stackoverflow.com/questions/49061018/unrecognized-selector-sent-to-instance-when-no-related-entities-found-in-core-da)? There is no property `events`, the relationship is called `card` – once again why singular `card` for a to-many relationship?
Comment: How is `selectedRecipient` defined and populated?  The error implies that there is no `events` property on the `Recipient` class.  But presumably the code compiles so the compiler thinks there is an `event` property.
Comment: selectedRecipient is passed in from the prior view controller.  events is the relationship between the Recipient and an event. Added the definition above
Comment: Your model shows that the relationship is named `card`, not `events`.  Try amending `selectedRecipient?.events.allObjects` to `selectedRecipient?.card.allObjects`.
Comment: problem between my model and the code it generated.. have cleared that out.. and change card to events
Answer: Chances are that selectedRecepient is not an instance of Recipient class (or at least ObjC runtime thinks so).
Try to examine its type:
print(type(of: selectedRecipient))

If it prints NSManagedObject then you should make sure that Recipient entity has its class set to Recipient in data model editor – this tells Core Data to cast instances of that entity to the corresponding class.
Comment: Optional is what it prints.  I get selectedRecepient passed in from the prior View Controller (it is the header record where there are one or more events attached to it.). It is defined as     var selectedRecipient: Recipient?  In the view controller class.   I load all the events related to selectedRecepient  in the getEvents() function:  Which I added above.
Comment: found issue with difference between model and generated code.


Pushing a View Controller from a Navigation Controller nested in a UITabBarController?

Question: Just as the title says, I have a UINavigationController nested in a UITabBarController. When the user taps on a table cell, I would like to push a view controller (which doesn't show the UITabBar). This is the behavior of the iPod app when you tap on "Now Playing."
How can this be done?
Answer: Just add this in the view controller you are pushing.
- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}

Comment: brilliant! had no idea it would be so simple :)
Answer: For example:
    OrderViewController *controller = [[OrderViewController alloc] init];
    controller.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentModalViewController:controller animated:YES];
    [controller release];

Or try to set property hidesBottomBarWhenPushed of self.tabBarController to YES.
Answer: Start with a UITabBarController project in Xcode, place a UINavigationController in each one of the tab view for the controller, and you're done! Hope that Helps!
Answer: I think hidesBottomBarWhenPushed is the way to go.  There's some gotchas to keep in mind.  Your setting this on the UIViewController that you're pushing, not on the tabBarController, or on the existing navigation controller.
Check here for more details: Setting hidesBottomBarWhenPushed leaves bottom bar missing after View Controller is popped
From that post, some sample code:
self.anotherViewController.hidesBottomBarWhenPushed = YES;
[self.navigationController pushViewController:self.anotherViewController animated:animated];


How to manage state transitions in INET

Question: I am trying to implement data acknowledgement in x-mac protocol. The algorithm is, after the packet transmission is over, the sending node will wait for an acknowledgement from the receiver. For that I added a new state WAIT_ACK. But during runtime, I can see the node cannot make state transition from WAIT_TX_DATA_OVER to WAIT_ACK. I am getting the following error.

<!> Undefined event of type 204 in state 7 (Radio state 2)! -- in module (inet::XMac1) SensorNetworkShowcaseA.sensor3.wlan[0].mac (id=181), at t=0.10677288732s, event #62

Note: XMAC1_DATA_TX_OVER = 204 and state 7 is WAIT_ACK
case SEND_DATA:

    if (msg->getKind() == XMAC1_STOP_PREAMBLES) {
        sendDataPacket();
        macState = WAIT_TX_DATA_OVER;
        return;
    }
    else if (msg->getKind() == XMAC1_SWITCHING_FINISHED) {
        sendDataPacket();
        macState = WAIT_TX_DATA_OVER;
        return;
    }
    else {
        return;
    }
    break;

case WAIT_TX_DATA_OVER:
     if (msg->getKind() == XMAC1_DATA_TX_OVER) {
        scheduleAt(simTime() + (slotDuration / 2), data_ack_timeout);
        macState = WAIT_ACK;
        radio->setRadioMode(IRadio::RADIO_MODE_RECEIVER);
        changeDisplayColor(GREEN);

    }
    break;
case WAIT_ACK:
    if (msg->getKind() == XMAC1_DATA_TX_OVER) {
        delete msg;
        return;
    }
   ...
   }

    break;

Update
In runtime, below is what I can see after the execution stops

INFO (XMac1)SensorNetworkShowcaseA.sensor3.wlan[0].mac: node 0A-AA-00-00-00-04 : State WAIT_TX_DATA_OVER, message XMAC_DATA_TX_OVER, new state  WAIT_ACK
INFO (ApskScalarRadio)SensorNetworkShowcaseA.sensor3.wlan[0].radio: SensorNetworkShowcaseA.sensor3.wlan[0].radio: Radio mode changed from TRANSMITTER to RECEIVER.
INFO (ApskScalarRadio)SensorNetworkShowcaseA.sensor3.wlan[0].radio: SensorNetworkShowcaseA.sensor3.wlan[0].radio: Changing radio reception state from UNDEFINED to IDLE.
INFO (ApskScalarRadio)SensorNetworkShowcaseA.sensor3.wlan[0].radio: SensorNetworkShowcaseA.sensor3.wlan[0].radio: Changing radio transmission state from IDLE to UNDEFINED.
<!> Undefined event of type 204 in state 7 (Radio state 2)! -- in module (inet::XMac1) SensorNetworkShowcaseA.sensor3.wlan[0].mac (id=181), at t=0.10677288732s, event #62
Answer: Based on the information you provided, this should not happen, so something in your assumptions are wrong. Most likely, you are NOT running this code. Make sure that this code is indeed executed (you may build a release version and run the debug version or something else). In these cases I often modify temporarily the error message in the code to see whether code changes are really compiled into the executable, just to be sure that I'm running the indeed the code I assume running.
Comment: Sure it shows that, because that was the line which printed the error. You should try to stop the execution with a breakpoint at the beginning of that method and step through. The interesting thing is how the execution got there. Start you simulation using Qtenv in a debugger then "Simulate/Run until..." event #62 and then choose "Simulate/Debug next event". Step into the handleMessage call and step through the code.
Comment: This is the code I am running. In my question, I have added the information I can see after the execution stops with error. As you suggested, I also tried by changing the code, then I can see the affect of code changes. Would you please suggest me if my code is wrong or there are other things I need to look at to fix this error? Thank you.
Comment: As far as I see, your code is correct. The error you are seeing is thrown at the end of the function and the execution should not reach that point as the function should return from inside the switch statement. Now this is clearly not the case, so you should debug and see the actual execution path in this event. That will show you why the WAIT_ACK case block is not executed.
Comment: Debugging shows a thread in ```throw cRuntimeError("Undefined event of type %d in state %d (Radio state %d)!", msg->getKind(), macState, radio->getRadioMode());```. This is the only thing that is showing from .cc file. I cannot even understand how to find out the main problem from it. Is there any way to debug this thread more? Thank you.

How to manage state transitions in INET


If you got hit by a bus, would your company be in trouble?

Question: At work, I'm the only IT guy (do it all, and do it now type guy) for the last 10 years.  If I ever got hit by a bus they would be totally screwed.  I've mentioned it several times to management/president type people, yet they ignore me.  Too bad for them.
What can I do to alleviate their pain?  (Or should I even care?)
(Yes, this should be a community wiki, but, I don't see the checkbox... maybe I don't have enough rep.)
Comment: I disagree, no1 would care if you die. if the company is in business only because of you than youre not only IT guy.
Answer: Document the heck out of everything.
There was a thread on Slashdot recently about starting documentation, which inspired me to write down my thoughts about documentation.
My key points were:
Principle #1: It Is Never Done
Documentation is an on-going effort that will always lag behind what is in production. Changes are made ad-hoc, things moved around or discontinued or put into service at random. Documentation will never catch up.
You have to sell the people paying the bills on the value of spending time (and therefore, money) on keeping the running documentation up to date. Frequently those conversations go like this: "remember when I had to spend $TIME figuring out how $THING was broken? Well when I was finished, there was this tech note detailing $THING, so that the next guy to come along won't have to figure it all out."
You have to do it, even though you will never finish.
Principle #2: The Only Thing Worse Than No Documentation Is Wrong Documentation
This is more of a truism than a principle. Documentation can lull you into the false sense that something is in a known state and that if something goes wrong you can therefore have a running start at fixing it.
It is important to acknowledge this problem.
Principle #3: You Are Writing Documentation For Your Successor
Odds are 95% of anything you do document you will never have to refer to again. Documentation is a collection of wisdom for the future, not for you. So you have to assume that your audience knows little or nothing about the specifics of how things are the way they are.
And there will be a successor. I don't know about you, but I don't plan to be in these specific environments for the rest of my life. Opportunities come and go, and when they come, sometimes you go. But life goes on behind you, and the smoother you can make life for your successor the better. Otherwise you might have a collection of former customers who quietly say unflattering things about you. I like to say that it is the same 50 guys working everywhere in IT in Ottawa because you keep running into them everywhere. Helping your successor might open doors for you in the future.
Now to a certain extent there is always a degree of "blame the previous guy" when trouble comes up. That is part of the business. I've done it myself. But on several occasions when I had blasted the previous guy as some kind of moron, I have learned otherwise that he really had his act together and knew more about what was going on than I did at the time.
Principle #4: "Why" is often more important than "How"
When looking at a system most of us start thinking thinks like why the hell is this like this? There are almost always very specific reasons for the configuration choices made. In these circumstances, the "Why" dictates the "How", and you have to make sure that the reader understands the specific problems being solved when examining the smoking remains of your solution.
Principle #5: It has to be easy or you won't do it
This means you have to be very aware of your tools as well as those who are going to use your tools.
Keeping things up-to-date has to be easy. If you have to make any kind of effort, then you will find excuses to avoid doing it when it is best done, which is immediately after a change.
If your tools are not easy for others to use, then they won't use it. This can be especially crippling in a team environment, since the larger the team gets the more likely you will encounter a team member who does not like your choice of tools.
Personally, I like a wiki for documents. However the problem is that a wiki does not force a structure on you, so the structure must be imposed from outside. This always leads to conflict somewhere as somebody else has a better/different idea.
In some places I've used Word and Visio documents "published" to PDF, with the "latest" PDF being considered authoritative. This is good in that you then have a collection that you can hand to your employer/successor. The PDFs, if properly dated, can provide a historical record of what happened, although one which is not easy to navigate through. It is bad in that I don't like Word or Visio and have been forced to get a basic understanding of these tools in order to effectively communicate the ideas.
My current employer is toying with the idea of Word documents in a Sharepoint portal. We'll just have to see how far we get there
Comment: Nice answer.  +1 if i could.
Comment: @roygbiv - Why can't you ? You got enough rep (>15)
Comment: @Idigas - At the time I made the comment, I didn't have enough rep. :)
Comment: Couldn't agree more with this answer. I like to use Word documents with a consistent style (some things grow into their own manual). Some people get concerned about loss of job security, but having documentation is not always enough. Need to have knowledge and skills to go with it, as one of my previous employers found out after they downsized me and my replacement didn't know enough about IT (he was primarly a programmer).
Comment: I agree, every job I take now I document the hell out of it not just for the sake of the company but for my sake. Sometimes you do somethings that you only do every once in a while and if you don't perform this as much you end up forgetting and having to figuring out how to do it again. I love that I just go to my folder where I keep this and re read my documents and remember how to do it.
Comment: +1 for the wiki (and use mediawiki and Pdf_Book extension), -1 for Sharepoint. I feel your pain (that you're about to feel :)
Comment: This is basically what all documentation should be like for Sys Admin. Especially if you're the only guy. I've been on the incoming side of things, where you walk into the shoes of the guy that left last week and it's hard. We had basically 10% of the infrastructure we have now and I was still finding out things the hard way 6 months into the job. Every time something else would break like that image processing cron job that someone who doesn't work here anymore setup in 1991... And the DECnet enabled SunOS 4.1 headless pizza box in the corner that runs it.
Comment: If "Document everything" sounds daunting, and it probably does if you've been going 10 years and haven't been documenting as you go along, then start with essentials. Think "what would a reasonably competent sysadmin need, bare minimum, to get started?" Then write it up, print two copies, store one copy on-site and one off-site, and email your management to inform them. And then schedule a recurring calendar task to update the essentials and add more detail.
Answer: Of course you should care. After all, any job worth doing is a job worth doing well.
1.) It's already been said but it needs repeating for reiteration. Document, document, document. Use excel spreadsheets, notepaper, quill and parchment if you have to. Several thousand mead notebooks like in the movie "Se7en" if need be. Either way, lay it out clear, concise and easy-to-read for whomever is going to have to replace you when you get hit by a meteor.
2.) Once you've begun documenting everything, you should be in the writing mood. Time to start a side project detailing the last few years' changes made on the servers. Start building a change-management process, but go through it historically. Make sure you note how often you've changed those disks on some of those finicky servers. How much they cost, etc. These provide great metrics for you to rely on anyway, even if that meteor misses you and takes out the neighbor's dog instead.
3.) Implement a monitoring system that monitors and emails critical failures. What's that, you say? You have one already? Sweet! Now document it. How it works, what you monitor, why you monitor it.
4.) You've got a responsibility to take it to your management types again. And again, and again. As many times as you can. Be polite. Be respectful, but come bearing what the cost to the business would be, if that meteor came down and you disappeared.
This is not a responsibility that you can blow off, it's an ethical requirement of your job and comisserate to the position you hold as the proverbial `keeper and guardian of the keys to the kingdom'.
Think of it this way. If you can avoid and forget worriyng about this and feel OK doing that, then why aren't you combing the accounting fileshares for company salaries to see what and how much more those management types are making than you. Why aren't you exploiting confidential corporate data for your own use? Why aren't you reading people's email?
Simply put, (and hopefully) you aren't doing these things because of a good solid sense of morals and ethics. You know, the whole right from wrong sort of thing. Thus follows, if you have that, then you know that it's clearly your responsibility to document and prepare countermeasures against the worst-case scenerio.
That being, your uninterrupted-by-work and relaxing vacation trip to Hawaii. :)
(Sans meteor, that is.)
Answer: Be careful crossing the street, look both ways, ensure there are no buses with Keanu Reeves and Sandra Bullock inside charging down the road.
Answer: If you want to lower the learning curve for your replacement, the best thing you can do is to write documentation of the set up and of your processes. Possibly the easiest way to do that is to set up a wiki system somewhere and just keep adding to it. Some of it will become out of date, but what isn't will be invaluable.
Answer: The many posts above regarding the importance of documentation are spot on, but there is one other aspect to being "the guy" at work that you want to look out for.
If you are the only person that knows how to operate everything, vacations/births/emergencies are difficult to handle, and you can never be promoted or learn other positions in the company (if that interests you).  If you are not able to grow and learn and expand your skills, you may end up in a position down the line where you are looking for a job, and your resume shows that you have spent 10 years as a COBOL/FORTRAN programmer or an OS\2/Novell/NT admin.
Growth and crosstraining are important to development as a sysadmin.  Instead of being "the guy" that the whole network depends on, be "the guy" that is always willing to show the new guy what to do and who is always interested in learning more about the business.
Comment: Hey Sean, totally agree.  However, just because I've been at one place for 10 years doesn't mean I'm behind the times.  On the contrary, I keep up with latest and greatest (as best I can.)
Answer: The key here is detailed and complete documentation.  This is something that is critical not only in case you are incapacitated but if they have a junior person come in and you want to go on vacation (or move on to greener pastures).  Having proper docs and references can be immensely useful for someone else to come up to speed on the network.
Answer: I try VERY HARD to ensure that we have no SPoF knowledge-wise, including my own. That attitude is more valuable than any local knowledge I might have kept to myself.
Answer: I took over this position (Sys Admin / Lead Dev) from a guy who had his own specific way of doing everything. The 17 servers we have are all set up slightly different. There are so many procedures and manual handling of issues here and hardly any of it was documented (documentation pretty much included a single line explanation of each server and its role). This has made me re-evaluate a lot of the processes in the office. Everytime I learn something, its added to the wiki. I also delegate some server work to other devs so they can at least learn minimal info about small jobs.
Documentation writing sucks, but think what it'd be like to come into your position without any.
Answer: Documentation is a huge deal. Where I'm at, I have the opposite problem as you really, we recently put in a new POS/Order Tracking system (we're an engraving and promotions company) and I'm have the problem of getting people to write in the system the information about the customization. Mainly low-level people, as the manager will do it to her orders, because she used to do it to all orders, putting it into a VERY OLD access database. I so want to go paperless, and it's entirely possible in our business, but I just can't get people to type the work order information in, dammit.
So, keep plugging away at getting authorization. Or if you're feeling nice, do it on your own time. It might be a good thing for your future at the company, not to mention your successor.
Comment: so, with the manager's backing, ensure that customisations are tracked... then some time later, find the person who did it and make then document it, when they've forgotten what they did. That usually drives home the reason for documenting it properly.
Comment: Problem is I've yet to get them to throw away the paper documentation, so your idea won't work. What I'm trying to work on is a simple as pie way to scan the signed proofs and such in and automatically save into a folder, only requiring the user to type in the order number, which then is the filename. I've yet to find a way to make this happen on OS X.
Answer: re: should I care?
Unless your office is 100% dysfunctional, people are going to notice that you make things work more smoothly.  That you care about the well-being of the company, and not just locking in your 'indispensibility'.  The company that banks on you never leaving / never getting a better offer isn't functioning very well.  It's someone's JOB to notice that you withhold that kind of thing from the company.
I personally LOVE working with people who document, and want the work they've finished to stand on its own, and not constantly require their involvement.  When you document and put the things you've already done behind you, you open up more time to work on future projects.
Answer: We have basically the same situation. That's why the director has hired me to add one more node of knowledge.
But honestly, it is not your place to care. It is the business of management to assess risks and address them.
Comment: Agreed.  It is important to make management aware of the problems that might arise if their only IT guy is not available, but it is not your job to nag them until they do what you want.  It's probably a good way to get yourself in hot water, actually.
Comment: -1 for "it is not your place to care". It's hard to make that judgment without seeing the org chart at the OP's company.
Comment: Plus the fact that he *does* care means he's anxious for the health and success of his company. Which is good.
Comment: @rotard The OP needn't nag -- writing up some "essentials" and storing two copies in secure places offsite and onsite, and then informing his management, will solve the problem without nagging.
Answer: I've found that the Getting Things Done approach helps get over the initial mental barrier preventing you from documenting your work properly. Rather than think of documentation as a monolithic task which will prevent you from doing "real" work, subdivide it into bite-sized chunks. Whenever you run across a tidbit of information that your successor should know, write it down. Then reserve an hour or two each week to review, clarify and categorize your knowledge.
Answer:
Documentation: Important
Your valuable job: Not as important as you think
Comment: Maybe I'm just terse about the subject, but I'd appreciate feedback with a downvote.
Comment: i did not downvote the answer as it is not that bad. They may have felt it was not helpful. No examples or explination may have prompted it. Again, I am guess like you.
Comment: guessing not guess. Sorry :)
Comment: Sure.  I didn't plan on writing a book, but if I did it'd be titled "Don't Be Pretentious".
Answer: Don't document. Don't share knowledge with others. By documenting things, you make yourself less valuable. You will get paid less. Your bonus will be less. Your job security will be decreased. Why would you do this?
The proper balance is where you don't get disturbed unnecessarily during sleep or vacation. Otherwise, you devalue yourself.
Comment: note to self. When hiring Sys Admins, ask if they have a username on serverfault. If they do ask them if they are chuck, if they are, don't hire him.
Comment: This is probably the most self-centered, egomaniacal advice I've ever read.
Comment: that is really good point, but i think he expect that after a few years the company will make IT department and he can be the boss of it(now hes the only IT guy). when he dies company will be just fine, because they will find guy just like him.
Comment: Depending on your company, this is either short-sighted or necessary for survival.  I suspect that it's more often the former.
Comment: You would choose to disobey your management, receive significantly lower pay for yourself, be perceived as less valuable and hard-working. In the long-term, receive sufficiently less income and have worse job security such that you impact the future of your family. All because you intend to force a company to do what is right for itself, even though the company has no similar love for you. I think you confuse how much the company respects and loves you if you're willing to sacrifice so greatly to give them something they think they don't want.
Comment: Sorry Matt, but I think most employers would rather find someone who does the job that his management wishes him to do, rather than takes it upon himself to be insubordinate and write documentation when asked to spend time on other tasks.
Comment: or if his name is carlito
Comment: Only in the most dysfunctional of companies would it be considered "insubordinate" for the lone IT guy to write documentation. Plus the OP never said his management directed him *not* to write documentation -- just that they have ignored inquiries about how they would handle an IT-guy-gets-hit-by-a-bus scenario.


batch if exist command

Question: I am trying to save a game and it will just get stuck. When I press ENTER it will leave a blank spot. Does anybody see a mistake in my script here?
@echo off
:saveload
title player movement
color 0f
cls
set /a health=10
if exist saves.txt (
    < saves.txt (
        set /p weapon=
        set /p armorh=
        set /p armorc=
        set /p armorl=
        set /p armorf=
        set /p bow=
        set /p gold=
        set /p dmgweapon=
        set /p dmgbow=
        set /p prtah=
        set /p prtac=
        set /p prtal=
        set /p prtaf=
        set /p name=
    )
    goto :varsetup
) else (
    echo to first begin we need to get your name!
    set /p name=What is your name?:
    (
        set /p armorh=n/a
        set /p armorc=n/a
        set /p armorl=n/a
        set /p armorf=n/a
        set /p bow=n/a
        set /p gold=10
        set /p dmgweapon=1
        set /p dmgbow=0
        set /p prtah=0
        set /p prtac=0
        set /p prtal=0
        set /p prtaf=0
        set /p name=%name%
    ) > saves.txt
    goto :saved
)
:saved

Comment: You need a blank line between normal text and the code block. Anyway, in your `else` branch after `set /p name=`, instead of `set /p foo=bar` you need to state `echo bar`, as far as I got your intention; `if exist` should not be the problem here...
Comment: hmm it seems to be that my comment does not contain proper code i did include four spaces but it won't work if someone can fix that i'd really appreciate that
Answer:
In your else branch after set /p name=, instead of set /p foo=bar you need to state echo bar, as far as I got your intention. if exist should not be the problem here. Here is the fixed code:
@echo off
:saveload
title player movement
color 0f
cls
set /a health=10
if exist "saves.txt" (
    < "saves.txt" (
        set /p weapon=
        set /p armorh=
        set /p armorc=
        set /p armorl=
        set /p armorf=
        set /p bow=
        set /p gold=
        set /p dmgweapon=
        set /p dmgbow=
        set /p prtah=
        set /p prtac=
        set /p prtal=
        set /p prtaf=
        set /p name=
    )
    goto :varsetup
) else (
    echo to first begin we need to get your name!
    set /p name=What is your name?:
    (
        echo n/a
        echo n/a
        echo n/a
        echo n/a
        echo n/a
        echo 10
        echo 1
        echo 0
        echo 0
        echo 0
        echo 0
        echo 0
        echo %name%
    ) > "saves.txt"
    goto :saved
)
:saved

batch if exist command


How to prevent a synchronized tremolo bridge from lifting

Question: I recently changed the strings on my Ibanez GIO GRG170DX and I noticed that after tuning the guitar, the bridge was lifting up (no longer flat with the body). I don't think it was like this before restringing, but I can't figure out what to do to fix it.
I watched a youtube video which recommended that I loosen the screws on the front of the bridge, but when I did that it didn't really seem to help.
How can I prevent my synchronized tremolo bridge from lifting?
Answer: Turn the guitar over so the bottom is visible. There should be a plastic panel held on with screws. Undo the screws and take the panel off. Inside, there should be springs that connect the bridge and tremolo to a metal bracket that is like a claw.
The metal bracket should have screws in it also that go through the bracket and into the body of the guitar. Tighten the screws to pull the springs tighter and lower the bridge again.
Be sure to loosen the strings before you tighten the bracket screws to prevent the strings from breaking. You probably have to go back and forth loosening the strings and tightening the screws and then tune the strings up and see if the bridge is where you want.
Replace the plastic panel on the back and screw it back into place.
Comment: @KevinJohnson Ah yes. A lot of guitars come with a third spring not installed for use with thicker strings. I should edit that in. It wasn't clear from your question that you had changed string gauges.
Comment: I tried this but wasn't able to screw in the screws enough to make a difference, so I ended up bringing it to a shop to get it repaired. It turned out that the guitar was missing a spring and when I changed string gauges the spring tension of just the 2 springs simply wasn't enough.
Answer: Changing strings on a floating trem bridge requires never changing gauge, and changing stings fully one by one, not taking them all off. It's pretty limiting if you want to deviate then you will have to go through all these steps:

blocking the trem
changing strings one by one
adjusting trem counter pressure


StandardScaler with make_pipeline

Question: If I use make_pipeline, do I still need to use fit and transform functions to fit my model and transform or it will perform these functions itself?

Also, does StandardScaler also perform the normalization or only the scaling?

Explaining the code: I want to apply PCA and later applying normalization with svm.

pca = PCA(n_components=4).fit(X)
X = pca.transform(X)

# training a linear SVM classifier 5-fold
from sklearn.svm import SVC
from sklearn.model_selection import cross_val_score

clf = make_pipeline(preprocessing.StandardScaler(), SVC(kernel = 'linear'))
   scores = cross_val_score(clf, X, y, cv=5)

Also abit confused what happens if I don't use the fit function in the below code:

from sklearn.svm import SVC
from sklearn.model_selection import cross_val_score

clf = SVC(kernel = 'linear', C = 1)
scores = cross_val_score(clf, X, y, cv=5)
Answer: StandardScaler does both normalization and scaling.
cross_val_score() will fit (transform) your data set for you, so you don't need to call it explicitly.
A bit more common approach would be to put all steps (StandardScale, PCA, SVC) in one pipeline and use GridSearchCV for tuning hyperparameters and chosing best parameters (estimators).
Demo:
pipe = Pipeline([
        ('scale, StandardScaler()),
        ('reduce_dims', PCA(n_components=4)),
        ('clf', SVC(kernel = 'linear', C = 1))
])

param_grid = dict(reduce_dims__n_components=[4,6,8],
                  clf__C=np.logspace(-4, 1, 6),
                  clf__kernel=['rbf','linear'])

grid = GridSearchCV(pipe, param_grid=param_grid, cv=3, n_jobs=1, verbose=2)
grid.fit(X_train, y_train)
print(grid.score(X_test, y_test))

Comment: If you use `StandardScaler` in the pipeline like this, doesn't the `grid.score` function with `X_test` use `X_test` to fit the `StandardScaler` (again) and transform `X_test` with that fit? Usually we want `X_test` to be transformed by the `StandardScaler` fit with the `X_train`. Can this be achieved with `Pipeline`?

StandardScaler with make_pipeline


Ubuntu Server: Acquire an IP from a newly connected DHCP server automatically

Question: I know how to request that a machine to acquire a new IP address, however I've got a slightly different scenario.
I have configured a box locally on my network which has DHCP.  Therefore, it acquired an IP address.  I want to ship it to somebody on a different network which also has DHCP.  Ideally, they would plug in their Ethernet cable before starting up their machine; in reality, they will just plug in cables as fast as they can.
The problem I've seen:  they plug in the power first, and then the Ethernet.  The machine doesn't automatically acquire an IP address using the new DHCP server unless we have them restart the box (or, if we had them log in, by restarting networking or forcing DHCP to release/renew).
Is there a way to configure an Ubuntu server (10.04 LTS) to automatically try to release/renew any time that an Ethernet cable is connected?
Comment: What version of ubuntu ... it _should_ already be doing this as part of the ifup scripts
Comment: 10.04 LTS.  I can't say for sure that nobody has changed that file.  Is there a setting in the ifup scripts that I can look at?
Comment: FWIW, I'm encountering this same in Ubuntu Server 14.04, pretty much stock installation.
Answer: It looks like one common way to handle this is to add a udev rules file.  I believe this gets installed by some package on a desktop system, but I cannot find it on any of my Ubuntu or Debian servers.
Here is a blog that seems to have some details.
The blog suggests adding a udev rules like this.
/etc/udev/rules.d/85-ifupdown.rules
# This file causes network devices to be brought up or down as a result
# of hardware being added or removed, including that which isn't ordinarily
# removable.
# See udev(7) for syntax.

SUBSYSTEM=="net", GOTO="net_start"
GOTO="net_end"

LABEL="net_start"

# Bring devices up and down only if they're marked auto.
# Use start-stop-daemon so we don't wait on dhcp
ACTION=="add",          RUN+="/sbin/start-stop-daemon --start --background --pidfile /var/run/network/bogus --startas /sbin/ifup -- --allow hotplug $env{INTERFACE}"

ACTION=="remove",       RUN+="/sbin/start-stop-daemon --start --background --pidfile /var/run/network/bogus --startas /sbin/ifdown -- --allow hotplug $env{INTERFACE}"

LABEL="net_end"

If you look at the ifup command being used you will notice that it only applies to hotplug interfaces.  So be sure to use allow-hotplug instead of auto in your network interfaces file.
Comment: Interesting, I'm attempting this on an Intel i3 NUC and when I `sudo udevadm monitor` I don't get any events when plugging or unplugging the ethernet cable.  However it looks like simply changing `auto eth0` to `allow-hotplug eth0` causes a dhcp lease to occur when the ethernet cable is connected.


Pass variables to ansible playbooks

Question: I need to pull a build from S3 on my target machine. Therefore I need to pass the S3 key and secret to the ansible playbook somehow.
I know that I could define them in

the inventory
the playbook itself

but I really don't want to store credentials there.
Can I use environment variables from the local machine (or something similar) in an ansible playbook?
Answer: $ENV(SOMEVAR) or {{ lookup('env', 'SOMEVAR') }} (1.1+) should work. You could also use vars_prompt to request it at playbook runtime.
Answer: Check out ansible-vault  it allows you to encrypt variables into a file and then "unlock" that file at run-time.
Failing that, you can also specify extra variables at runtime with the -e "" flag:

ansible-playbook -i inv/production myplaybook.yml -e "s3_key=<value here> s3_secret=<secret here>"

Pass variables to ansible playbooks


Nagios: Service dependency on same host for an entire hostgroup

Question: I have a Nagios system with a large number of hosts categorised in different hostgroups. Each of these hosts has two services monitored on it, one of which is intended to be dependent on the other - if service1 is WARNING or CRITICAL, service2 on that server should not give an alert as well. service2 is intended more for statistic collection, while service1 is a simple availability check - as such, I always want service2 checking, but not  alerting if service1 is reporting as down.
This is my services.cfg entry:
<code>define servicedependency{
    hostgroup                       example-servers
    #host_name                       host1.example.com,host2.example.com
    service_description             service1
    dependent_service_description   service2
    execution_failure_criteria      n
    notification_failure_criteria   u,w,c,o
}
</code>
I have tried both specifying it via a hostgroup and as a list of individual servers. Ideally, I would do it for the entire hostgroup in one rather than have to constantly maintain a list.
However, this does not seem to work, either way. If service1 is down, service2 also shows a CRITICAL status in the problems screen and on host details.
Answer: From the Nagios manual for "execution_failure_criteria": "If you specify n (none) as an option, the execution dependency will never fail and checks of the dependent service will always be actively checked (if other conditions allow for it to be)."
Sounds like you should be using "u,c" instead (don't check if server1 is UNKNOWN or CRITICAL).  Or perhaps "w,u,c" IF a WARNING state from service1 should also cause service2 not to execute.
Comment: I'd like the check to be made in any case (for performance data), but only to send notifications if service1 is not warning/critical.
Answer: If you specify "execution_failure_criteria      n" then service2 will always be checked. If is is checked and is in a warning or critical state the user interface will show that state. You can't prevent that (afaik), but you can prevent it sending notifications, e.g "notification_failure_criteria   u,w,c".
I think you can either have "execution_failure_criteria" set as it is (i.e. "n"), and live with the status showing service2 as critical when it can't be reached, or change it to "c".
You probably don't want to suppress notifications if service1 is OK, which is what you are doing with the "o" in "notification_failure_criteria   u,w,c,o".


How to bundle a custom Directive with External HTML Template in AngularJS?

Question: See my project structure below
project
-Lib
    -MyCustomDirective(which i will use across multiple application)
      -customDir.js
      -customDirTmpl.html
-app
   -js
      -myfirstcontroller.js
      -main.js
   -partials
      -myfirstview.html
   -index.html

So , i am planning to create a custom directive, which i want to use across multiple projects. The issue here is, I want keep the template for my directive in separate html file. When my directive is loaded, my app is trying to find the "customDirTmpl.html" respective to the current application not respective to my "MyCustomDirective" folder.
I want to keep the templateUrl of my directive same across all project, i dont want to change it respective to any particular project.
Sample code of "customDir.js"
var myDir = function () {
    return {
        restrict: 'E',
        //I want this to be constant accross which ever project i use this directive
        templateUrl: 'customDirTmpl.html',
        link: function(scope){
            //to do something
        }
    };
};

app.directive("MyCustomDir", [myDir]);

Comment: You can programatically add directive into templateCache, so it will be fetched by templateUrl. Or introduce distribution building process, where directive source is built into single JS file you can use in different projects.
Answer: A good way to do this is to have a utility in your directive library project that handles these needs.
Writing up an example will be quite tedious, so here is an example from the ng-grid project that demonstrates this.
Take a look at the getTemplate function property.
And here is it's example usage from the same project.
Notice the use of gridUtil for fetching the template.


how do I get xstream to combine mouse events?

Question: I'm experimenting with drag-and-drop using cyclejs in a codepen. The standard drag methods supported by HTML 5 don't seem to support constraints on the movement of the dragged object so I went with standard mousedown/mousemove/mouseup. It works, but not consistently. The combine() operation doesn't seem to trigger even when the debug() calls show that mousedown and mousemove events have been received and sometimes the mouseup is missed. Perhaps my understanding of the operation is incomplete or incorrect. A direct link to the codepen is provided at the bottom of this post. Any help appreciated!
const xs = xstream.default;
const { run } = Cycle;
const { div, svg, makeDOMDriver } = CycleDOM;

function DragBox(sources) {
  const COMPONENT_NAME = `DragBox`;

  const intent = function({ DOM }) {
    return {
      mousedown$: DOM.select(`#${COMPONENT_NAME}`)
        .events("mousedown")
        .map(function(ev) {
          return ev;
        })
        .debug("mousedown"),
      mousemove$: DOM.select(`#${COMPONENT_NAME}`)
        .events("mousemove")
        .map(function(ev) {
          return ev;
        })
        .debug("mousemove"),
      mouseup$: DOM.select("#container")
        .events("mouseup")
        .map(function(ev) {
          return ev;
        })
        .debug("mouseup")
    };
  };

  const between = (first, second) => {
    return source => first.mapTo(source.endWhen(second)).flatten();
  };

  const model = function({ mousedown$, mousemove$, mouseup$ }) {
    return xs
      .combine(mousedown$, mousemove$)
      .debug("combine")
      .map(([mousedown, mousemove]) => ({
        x: mousemove.pageX - mousedown.layerX,
        y: mousemove.pageY - mousedown.layerY
      }))
      .compose(between(mousedown$, mouseup$))
      .startWith({
        x: 0,
        y: 0
      })
      .debug("model");
  };

  const getStyle = left => top => {
    return {
      style: {
        position: "absolute",
        left: left + "px",
        top: top + "px",
        backgroundColor: "#333",
        cursor: "move"
      }
    };
  };

  const view = function(state$) {
    return state$.map(value =>
      div("#container", { style: { height: "100vh" } }, [
        div(`#${COMPONENT_NAME}`, getStyle(value.x)(value.y), "Move Me!")
      ])
    );
  };

  const actions = intent(sources);
  const state$ = model(actions);
  const vTree$ = view(state$);

  return {
    DOM: vTree$
  };
}

function main(sources) {
  const dragBox = DragBox(sources);

  const sinks = {
    DOM: dragBox.DOM
  };

  return sinks;
}

Cycle.run(main, {
  DOM: makeDOMDriver("#app")
});

https://codepen.io/velociflapter/pen/bvqMGp?editors=1111
Comment: a debug() placed on the mapTo() stream produces output, but flatten() only produces output sporadically. When it does, the element is dragged. https://codepen.io/velociflapter/pen/YaRqYM
Answer: Testing your code shows that combine is not getting the first mousedown event, apparently due to the between operator subscribing to mousedown$ after the first mousedown event. Adding remember to the mousedown$ sends that first mousedown event to the between operator subscription.
mousedown$: DOM.select(`#${COMPONENT_NAME}`)
  .events("mousedown").remember()

Codepen.io remember example.
Codesandbox.io testing between

Here's another CycleJS/xstream Drag and Drop approach (taking inspiration from this RxJS Drag and Drop example) I think is more straight forward. Everything else in your code is essentially the same but the model function is this:
const model = function({ mousedown$, mousemove$, mouseup$ }) {
  return mousedown$.map(md => {
    let startX = md.offsetX, startY = md.offsetY
    return mousemove$.map(mm => {
      mm.preventDefault()
      return {
        x: mm.clientX - startX,
        y: mm.clientY - startY
      }
    }).endWhen(mouseup$)
  }).flatten().startWith({x:0,y:0})
};

Here's a Codepen.io example.
Comment: @JamesFremen A nights sleep helped me realize adding `remember` to the `mousedown$` preserves that initial mousedown event for the `between` operator.
Comment: thanks knuckles.. yes - I'm not sure if you saw my later comment but I also suspect a problem due to between(). It puzzling because, at least on my system, sometimes it works. I've looked at the xstream code but it's written for speed/compactness so I may not be able to understand it well enough to get a fix in this time. Thanks for your answer!
Comment: I can reproduce your fix in my environment, too. That's good to know going forward - thanks again! Rather subtle if you're unused to a stream approach. It does seem reasonable in retrospect, though - the previous operators are consuming events.


Método Sort não está ordenando corretamente

Question: Tenho o seguinte código:
#include <bits/stdc++.h>

using namespace std;

int main()
{
int n, cases = 1, a[3];
cin >> n;
while(cases != n + 1)
{
    cin >> a[0] >> a[1] >> a[2];

    sort(a, a + 2);

    cout << "Sorted array: " << a[0] << " " << a[1] << " " << a[2] << endl;

    cout << "Case " << cases << ": " << a[1] << endl;

    cases++;
}
return 0;
}

Para casos com as entradas: 30 25 15, o array fica: 25 30 15.
Isso seria um bug, ou fui quem implementou de forma errada?
Answer: Tem vários erros. Esse código é basicamente C e não C++. Usar bits/stdc++.h não é recomendado, é um desperdício de recurso.
A lógica é bem esquisita. Não está enviando o início e fim do array corretamente, não está pegando o último elemento. Só corrigi esse erro que é o que faz a maior diferença.
#include <iostream>
#include <bits/stdc++.h>
using namespace std;

int main() {
    int n, cases = 1, a[3];
    cin >> n;
    while (cases != n + 1) {
        cin >> a[0] >> a[1] >> a[2];
        sort(a, a + 3);
        cout << "Sorted array: " << a[0] << " " << a[1] << " " << a[2] << endl;
        cout << "Case " << cases << ": " << a[1] << endl;
        cases++;
    }
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: Entendi, usei a + 2, pois, pensei que funcionasse da seguinte maneira:
a + 0 -> primeira posição
a + 1 -> segundo posição
a + 2 -> terceira posição

Costumo escrever códigos nesse estilo C, pois conheço pouco C++, mas meu objetivo é escrever códigos mais rápidos (para maratonas de programação), tem alguma dica para eu melhorar meus códigos?
Obrigado!
Comment: Aí você tem que fazer perguntas específicas.
Answer: Realmente você não está pedindo para ordenar o último parâmetro.
Seu array tem tamanho 3 e ao chamar o sort, você precisa passar o tamanho 3 para que ele ordene não só as duas primeiras posições, mas também a última.
...

sort(a, a + 3);

...


How to configure postfix to force From: field but leave Reply-To: alone

Question: I need to configure postfix on a localhost as a relay to an smtp server.
This external smtp server requires From: header to be consistent with the authenticated user name.
I want to fixup the From: header for all the messages originating on this local machine to say email@example.com
I tried the following:

sender_canonical_maps
The problem is: it seems to be overwriting the Reply-To: header as well, I don't need this, on the contrary, I want to use it extensively.

How I checked this:

Put sender_canonical_maps = regexp:/etc/postfix/sender_canonical in main.cf
REPLYTO="email@example.com" mail firstname.lastname@example.com
Actual results: received message has overwritten Reply-To to firstname.lastname@example.com

Vs:

Remove sender_canonical_maps from main.cf
REPLYTO="email@example.com" mail -r firstname.lastname@example.com email@example.com
Actual results: received message has correct Reply-To

The problem is this doesn't work without -r firstname.lastname@example.com.

header_checks: apparently doesn't work for From: fields (http://www.postfix.org/header_checks.5.html see Bugs: section)

How can I simply force the From: header on all outgoing mail, but leave Reply-To: alone for local users to specify?
Comment: What is the mail client you are using, you can achieve this easily with mail clients.
Comment: This is for automatically sending mail from different scripts running on the machine, I want to configure this once and for all and not bother checking every script/mail client for correct configuration.
Comment: Yes absolutely, There is a mail client **mutt** which does this precisely. You can create automated scripts and send mail. Plus there is a muttrc file in which you can set variables(To:, From:, Reply-To:, et al).

Hope this helps!
Comment: I know how I could solve this problem if I started from scratch, this is not the point of this question. I already have some processes which send mail via local postfix, I just want to migrate to another smtp relay which has additional restrictions. What I need here is an answer to precisely the question: how to do this apparently simple thing in postfix.
Comment: Well as I asked in my first comment "what is your e-mail client", which you chose not to answer. Now **apparently** the thing you want is the job of an MUA(mail client) and not an MTA(postfix). Refer the [link](https://wiki.list.org/DOC/What%20is%20an%20MTA%3F%20What%20is%20an%20MUA%3F%20What%20is%20an%20MDA%20or%20LDA%3F) to know the difference. The rewrite option you tried is for cleaning up not for what you are trying to achieve. I am here only to help you if you let me.
Comment: What is your upstream mta?  Sounds like you are trying to send stuff via gmail as a smarthost and have replies go back to the origin.
Comment: Does it really matter? Let's say this is kind of "ok I spent ours on this and now I want to know how it's supposed to be done". I really can do this whole stuff without those postfix hacks. It's just unbelievable that this kind of behaviour is so hard to achive.
Answer: Forcing the from address when postfix relays over smtp
/etc/postfix/main.cf:
smtp_header_checks = regexp:/etc/postfix/header_check

/etc/postfix/header_check:
/^From:.*/ REPLACE From: firstname.lastname@example.com

Tested with:
mail -s test -a 'Reply-To: email@example.com' email@example.com <<< test

Header on client side:
From: email@example.com
Reply-To: firstname.lastname@example.com
To: <firstname.lastname@example.com>

In syslog you then see
Nov  1 17:20:50 huuu postfix/smtp[4716]: 1B65481FAB18: replace: header From: root@huuu (root): From: firstname.lastname@example.com

Comment: Very weird, it didn't work for me as stated in the question. I'll give it a second try
Comment: Tested on Debian Jessie. Postfix version 2.11.3-1. I have added log message I see in syslog to the answer.
Comment: For others who found this, note that the default header check file (at least on CentOS 7 Postfix 2.10.1) is `/etc/postfix/header_checks`, i.e., plural.
Answer: Check out the "Generic mapping for outgoing SMTP mail" at: http://www.postfix.org/ADDRESS_REWRITING_README.html
Grt. R.
Comment: Hi. Thanks for this link. But I have already read it (just wasn't able to solve my problem). Here on stackexchange  actual answers to the question are very valuable (i.e. add such and such lines to your configs etc), not just RTFM links :)
Comment: To me it seems the answer to your problem. if you send to whatever email adres on the internet with, the smtp_generic_maps can map your local address to  your email@example.com address.


How to calculate the distance a square corner adds to the diameter of a circle?

Question: What is the formula for finding the distance a square corner adds to the diameter of a circle?
In the drawing, if I know the diameter (5.0") of the circle, how much do I add to find the total distance of its furthest point from the corner?
Comment: From the centre of the circle, draw a radius up and another radius to the left, to each of the two tangent points. The required distance is the diagonal length of the new smaller square, plus one radius of the circle.
Comment: Hint. The pythagorean theorem tells you the distance from the center of the circle to the corner point.
Answer: Okay, I figured it out. 5" x square root of 2 will give the diagonal center-line of a square that tightly encompasses a circle of 5" diameter. Then, simply subtract the 5-inch diameter of the circle and divide the remaining portion by two to get the extra length of just one corner. Add the corner length back to the circle's diameter to arrive at 6.0355 inches.
The formula for the square's diagonal comes from the Pythagorean formula. Because a diagonal of a square would create mirrored right triangles, each with 45-degree corners, the diagonal is their hypotenuse. Using the Pythagorean formula, a^2 + b^2 = c^2, with a and b each lengths equal to the diameter of a circle that would fit inside, the formula for a square's diagonal is derived.
Since I want "usable" fractions that can be found on an American tape measure, with +/-16th of an inch being an acceptable tolerance, I take an extra step of multiplying the decimal fraction by 16, which gives me a half a sixteenth. Not enough to matter, so, my answer is approximately 6 inches.


Spring boot batch : How to run job with job parameters

Question: I had to set jobparemeters on spring batch but with spring boot batch there is no way to do that easily.
I need to rerun job but if parameters are the same, spring-batch won't run again a job. So I decided to add a timestamp as parameter.
Comment: You can add the timestamp at launch time. See my comment on your answer.
Answer: I found a way and put my solution on stackoverflow for those that might be interested.
First you need to add this property on your application.properties / application.yml :
<code>spring.batch.job.enabled: false
</code>
With that property spring boot doesn't run the job automatically.
Next, on your configuration file, you have to add a bean which runs your job and where you can put jobparameters :
<code>@Bean
@Autowired
public JobExecution run(Job job, JobLauncher jobLauncher) {
    JobExecution jobExecution = null;
    try {
        JobParameters jobParameters = new JobParametersBuilder()
                .addLong("time", System.currentTimeMillis()).toJobParameters();

        jobExecution = jobLauncher.run(job, jobParameters);
        logger.info("Exit Status : " + jobExecution.getStatus());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return jobExecution;
}
</code>
If you have a better way, let me know.
Comment: What about `java -jar myjob.jar param1=value1 param2=value2 time=$(date)` for example? With this, you don't need the code above.
Comment: In my case I think it works. But implementation depends of my OS. I will try.
Comment: Sure `$(date)` is for unix/linux, but you got the idea. You can do the same with a similar command of your OS to add the timestamp as a parameter in the command without the need to write the code above.


How to add custom Jquery in drupal module?

Question: I have created a custom module in drupal 7. The module creates a form for user and store the  form's data into database. The module is working fine. But I want to add a custom jquery for the page. I searched Google and find the result for adding custom JQuery for theme not for modules. I guessed and add the following in my module's  info file
;scripts
scripts[] = js/test.js

Just alert a "hello" word while the module will load. But nothing is happened. Is this possible to add custom Jquery for a module or I am doing wrong? Please help.
Comment: It should be worked if you put your code in "test.js" file in "js" directory in your current theme and then clear cache.
Comment: I did what you said and it worked. Thanks man... :)
Comment: Since it was just a problem of clearing the cache, I am going to close this question.
Answer: There are several ways of adding JS to your module, you can check them here https://www.drupal.org/node/756722
Your attempt should work fine, just don't forget to clear the caches after editing module's .info file.
Cheers!
Comment: As for reference for future answers, answers that are just links are not considered answers, on Stack Exchange. You should quote the relevant parts in the answer itself, which should not rely on an external link.
Answer: with the drupal_add_js function you can add your own javascript file, it is best to call in hook_init
Example
/**
 * Implements hook_init().
 */
function mymodule_init(){
  drupal_add_js(drupal_get_path('module', 'mymodule') . '/js/mymodule.script.js', array('scope' => 'footer'));
}

drupal_add_js
hook_init
This hook is not run on cached pages.
To add JS that should be present on all pages, modules should not implement this hook, but declare these files in their .info file.
scripts[] = js/script.js

Comment: It's done in my comment, Thx Beebee
Comment: From hook_init docs page: "This hook is not run on cached pages.

To add CSS or JS that should be present on all pages, modules should not implement this hook, but declare these files in their .info file."
Answer: You can add any no of js files and css files from your .info file.
This is as simple as you modify your modulename.info file with:
scripts[] = js/jsfilename.js
stylesheets[all][] = css/cssfilename.css
stylesheets['specify_name'][] = css/cssfilename.css


Do you perform cross validation on bootstrap samples?

Question: Let's say that I have to chose the best model to predict a variable but my sample size is small. I would like to resample my data using the bootstrap, run each model and evaluate its prediction error with cross validation on each bootstrap sample. In the end I will chose the model with the lowest average prediction error.
Is this a acceptable procedure? If yes is there something I should be aware of while using this procedure?
Answer:
is there something I should be aware of while using this procedure?

You should be aware of the fact that prediction error estimates are subject to bias and variance. With small sample sizes, the variance is the problem.
To get a first idea of the variance of your prediction error estimates, look at the variance of prediction error within and between bootstrapped models that are built using the same input variables. While this can underestimate the true variance, it will give you a first idea of what is going on.
For this, you can e.g. look at the model built using all available input variables, or a model built with input variables that you as an expert for the application think will be a good choice.
Next, comparing prediction errors is basically a statistical test. Fortunately, you can use paired tests if all competing (surrogate) models were tested using the same test samples. Unfortunately, comparing many models means that you have a massive problem of multiple comparison.
From the results of the variance estimation above, calculate how much better a  model needs to be so you can recognize the improvement. Is that something that you can realistically expect? If not,

you either need larger sample sizes or
you better stick to the first model and report that the available sample size does not allow any further optimization.

Whenever you do data-driven model optimization$^*$ you need to test the final model with a new independent test data set.
In other words, you need to apply double or nested cross validation (or out-of-bootstrap).
$^*$i.e. tune something [here: which variables to include] by test results.

You may also want to have a look at a similar recent discussion: Grid search on k-fold cross validation
Answer: The way the bootstrap is applied to estimate prediction error rate is to use the bootstrap samples to estimate the bias of the resubstitution estimate of error rate and adjust it.  Various bootstrap estimators have been devised and shown to work better than the leave-one-out version of cross-validation.  For most population distributions the version called 632+ is the best.  Details about the methods and the literature on it can be found in my book Bootstrap Methods or this book by McLachlan.  This started with Efron 1983 JASA paper "Estimating the error rate of a prediction rule: Improvements on Cross-validation ".
This approach is preferable to the method you have planned.
Comment: I have already found something on the web something referring to the boostrap estimators 632+ but unfortunately my mathematical background doesn't allow me to understand it clearly from the papers. Is there a way to explain it easly ? And subject to the fact that bootstrap estimator 632 is a better approach i would like to know which are the problems that affect my solution?
Comment: @frin Exactly why 632 works so well is not so easy to understand. I try to explain it by saying that it gives the appropriate coefficients to a linear combination of two estimated to keep the variance and bias both small. It keeps the bias small because it weights the apparent error rate and e0 in a way that nearly cancels their opposing biases. Understanding 632 requires soMe knowledge of the bootstrap e0 estimate and the apparent error rate (the former is a little diffucult to undersatnd and the latter rather easy).
Comment: I'd have said that a bit of optimistically biased resubstitution is mixed into the independent out-of-boostrap estimate in order to hopefully correct the pessimistic bias... As I deal with data where the resubstitution is often heavily overoptimistic (e.g. underestimating the true error by factor 3 - >10), I directly go for out-of-bootstrap.


How to view SQLite database which is present in bluestacks ?

Question: Hi I am using Blue Stacks in Debuggable mode with eclipse to run mt development build.
On checking Data in file explorer of DDMS tab i cannot goto database in blue stacks? Any tips?
Comment: No you can't see DB in BlueStcks but you Export this Programmatically.
Comment: one more thing, i connected my android mobile phone and checked, but still the same result
Comment: and after some googling i found an emulator called genymotion, almost functions likes bluestacks and we can view its database via data/data/package/databases cool, i shifted to geny now
Answer: Try this way
File f=new File("/data/data/YOURAPPPACKAGENAME/databases/YOURDATABASENAME");
                    FileInputStream fis=null;
                    FileOutputStream fos=null;

                    try
                    {
                      fis=new FileInputStream(f);
                      fos=new FileOutputStream("YOURSDCARDFOLDERPATH"+"/YOUREXPORTDDATBASENAME");
                      while(true)
                      {
                        int i=fis.read();
                        if(i!=-1)
                        {fos.write(i);}
                        else
                        {break;}
                      }
                      fos.flush();
                      Toast.makeText(context, "DB dump OK", Toast.LENGTH_LONG).show();
                    }
                    catch(Exception e)
                    {
                      e.printStackTrace();
                      Toast.makeText(context, "DB dump ERROR", Toast.LENGTH_LONG).show();
                    }
                    finally
                    {
                      try
                      {
                        fos.close();
                        fis.close();
                      }
                      catch(Exception ioe)
                      {}
                    }

And add permission into your manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

You must add sdcard read and write permission into your manifest.xml file and after database successfully exported open using SQLite Manager.
Comment: @user3244439 now you got DB into your specify path
Comment: but how to pull and push db files using bluestack?


Which datatype in Django model to be used to save HTML5 type "month" in database

Question: I have a HTML form with field which takes input as month
<input type='month' name="last_appraisal" id='txtLastAppraisal' value='2013-12' />

In my Django model this field is defined as
last_appraisal = models.DateField(blank=True, null=True)

When I try to save this value (received from request.POST) in database then I get format error.
last_appraisal = request.POST.get('last_appraisal','')
if last_appraisal != '':
    mymodel.last_appraisal = last_appraisal
    mymodel.save()

ERROR: raise exceptions.ValidationError(msg)
    ValidationError: [u"'2013-01' value has an invalid date format. It must be in YYYY-MM-DD format."]

I know I can achieve this by adding a default day(maybe 01) to this input month and then save into the database. And while fetching back this value I can re-format it like "YYYY-MM" and send it back to template.
But I want to know if there's any better way to achieve this. I am using Django 1.5.1 and Python 2.7.
EDITED:
After reading all the responses it is clear that Django doesn't have built-in support for this format. Now I have few choices

My way to add day into date field.
As suggested by @Odif to take database field as 'CharField'
As suggested by @Ghopper21 to create a Custom Django field

My preference will be the choice1 because using this

I don't have to write some extra complex code compare to choice3.
I get the flexibility to use this field in table searches like 'find all candidates who got their appraisal in Jun 2013' which I loose if I go for chioce2.

Don't know whether my choice is good or bad but considering the size of project and time to complete it I think this will be the best choice. Please comment if you think this is absolutely rubbish or if you are in favor of this approach.
Comment: maybe you should consider writing your own field type by overriding DateField
Answer: There are two issues here: Django doesn't have a built-in way to deal with month/year-only dates, and nor does Python.
If you are ok with a convenient way to translate the month/year-only dates into full dates with the day set to 1, but just don't want to have to do this manually in your view code every time, you can encapsulate that logic in a custom Django widget, which is a component for translating between the Django field representation (in this case a DateField) and the HTML input field.
If you need to have the underlying Python representation of the date to be month/year-only in a first class way, I'd suggest looking into the excellent Python library dateutil's relativedelta class -- which allows you to specify things like relativedelta(year=2013, month=12). If you want to use that, you'd then have to create a custom Django model field that translates between relativedelta instances and database storage via serialization. You'd then still need a custom widget for the HTML side of things.
Comment: I am not using Django forms, is it possible to use custom Django widget without forms?
Comment: Sure, look up the widget documentation. You can create a widget a use the `render` and `value_from_datadict methods yourself. But at that point you are just essentially creating two translation functions, which you can do however you like if you aren't using a Django form.
Answer: Use models.CharField. DateField and DateTimeField expect date and datetime object respectively. Since '2013-01' cannot be coerced into either, then use CharField. Or use integerfield and just post month.
Comment: Yes I can do this.. but this is also a workaround. If I use 'CharField' then i will loose all the benefits of using 'DateField' like  adding two dates, getting difference etc.
Comment: Yes, but you are not using dates anyway.


What are wild card standings in NHL?

Question: I have noticed that on the NHL website, starting from this year, there are not only standings in league,
conferences and
divisions (which used to be there last year, too), but also some kind of ranking which is called wild card.
What are this standings for? How are teams divided there?
Comment: Yes, you did. (I usually wait a few days before accepting an answer, just in case someone else would want to write something more about it. IF this is the reason you are asking.)
Comment: Did I answer your question Martin?
Answer: After the realignment, the league now consists of 2 conferences with 2 divisions in each conference. NHL playoffs consist of 16 teams fighting for the last two spots to compete in the Stanley Cup Final
The way the new playoff structure works is as follows...

The top three teams in each division will make-up the first 12 teams in the playoffs.
The remaining 4 teams (Adding up to 16 teams) will be made up by the next two highest-placed finishers in each conference. Two teams per conference.

This means that the the 2 wild card spots in the Eastern Conference can consist of one of the following:

Two teams from the Atlantic Division
Two teams from the Metropolitan Division
One team from the Atlantic and one team from the Metropolitan.

The way the seeding now works is...

The division winner with the most points in the conference will be matched against the wild-card team with the fewest points
The division winner with the second-most points in the conference will play the wild-card team with the second fewest points.

Here's an example
In the picture below showing the current standings of the Eastern Conference, you can see that the top 2 rows consist of 3 teams for each division. If the season ended today, these 6 teams (3 from the Atlantic Division and 3 from the Metropolitan Division) will make the playoffs.
In the third row, you see a list of every other team in the conference. The top 2 teams in this list are "Wild Card" teams and will also make the playoffs.
The playoff seedings would look like this:
#1 Toronto vs. #8 Boston
(Boston is the wild card team with the least amount of points and will face the team with the most points in the conference which is Toronto)
#2 Pittsburg vs. #7 Tampa Bay
(Tampa Bay is the wild card team with the most amount of points and will face the team with the 2nd most points in the conference)

Source
Comment: During the first and second round, teams play other teams in their divisions (Apart from the first round where wild card teams can play against teams in the other division).
Comment: Just to clarify: The remaining pairs in the play off would consist of 2nd team from one division and 3rd team from the other one? (In your example Detroit-Islanders, Carolina-Montreal.) Or are the rules different?
Comment: Ok, so now I found [this link](http://www.nhl.com/ice/standings.htm?season=20132014&type=PLA), showing the pairings in the playoffs based on the table at the moment. I see that the second and third team from *the same division* play against each other.

What are wild card standings in NHL?


Building an odd predictive model

Question: So I've perused this site and others, and have a question that I can't seem to find the answer to (possibly because I'm unsure how to even word it).
Here goes:
So I'm coming from an ecological stats background, and have done modeling, stepwise regression, etc, but have an interesting problem right now.
I am working on a project where there is scoring done, and it is basically binomial (either they have a response or they don't), but the scores are weighted differently, so one could be 0 or 9 and the next could be 0 or 4.  There is one variable that is discrete, but the rest are in that fashion.
What I want to do is to use the very small sample of responses we have (about 150 out of 40000) to test and validate a model that will tell us what variables are most important.
The hard part is that the weights are going to probably be half stats based, half based on the requirements of the business people in my group.  They have set the scores, and have some flexibility, but it wouldn't work for me to tell them that the model is most significant in a certain way if that didn't line up with their business definitions.
What I've done is created a model that was fully binomial, and started with that.  However, I want to incorporate their scoring, or at least be able to get to a place where we can add in the scoring element while staying in the middle between completely numbers driven and completely business driven.
My long winded question is this: What is the best way to approach this modelwise? Letting them define weights and then just going from there? Or is there a way where I can really just meet them in the middle?
Answer: The solution you are looking for is called Bayesian decision theory.  It constructs the Bayesian posterior density function as you would for any purely statistical question, but then minimizes a cost function over that posterior density to find the lowest cost point solution.  You could treat different models as parameters themselves and solve for the probabilities that the models are good models, and then over that space, which would be discrete, impose a cost so that if you had two models that were close in probability but vastly different in cost you could allow the interaction of costs and probabilities to decide your model.
The model could then be used predictively, again with a cost function, and then scored based on the cost of the prediction being wrong.
Parmigiani produces a good book on introductory Bayesian and Pearson-Neyman decision theory.  Its ISBN-13 is 9780471496571.
This may cause your business office to rethink their costing as well.  When you impose discipline and structure on the decision making, people start talking about their hidden assumptions.  It does happen, from time to time, that when people talk about things out loud with others a better model appears.

Building an odd predictive model


some substitute of TV distance in compact metric space

Question: Could anyone help me to understand the following excerpts from an article which is not available online though,
''In the Markov process theory, it is common to show convergence to invariant measure in total variance distance. However, we have no hope for such as we can always choose the initial distribution such that the process does not converge. We could choose the initial distribution to be singular with regard to Lebesgue measure if the invariant measure is absolutely continuous and vice-versa. We can avoid this problem by using a weaker metric which is known as Kantarovich metric.....''
Q: Why it is common? what're the benefits of TV norm over others? Why he has no hope of convergence? (asking because he didn't give counterexample at all, which might be easy to understand for a probabilist but I am very new to Markov chain on Metric space topic). I also do not understand his remedy of singular measure etc. Thanks for the explanation. How the weaker metric is helping?
Thanks!
Comment: Even if the article is not available online, you can still do the author the courtesy of giving a full citation.
Answer: Without knowing the article in question, it is somewhat difficult to answer, but here are some facts that the paper in question seems to be using:
Total variation of probability measures is always 1 so that is not particularly important. (This is almost definitional; it is easy to show that it would be upper bounded by 1 and you can refine partitions in your sample space until you get arbitrarily close to 1 I think)
1) TV distance is a nice distance because it is bounded by 1. It is also relatively easy to compute if the measures have densities since it has a nice explicit form. It is also very interpretable: how can you couple two random variables with the given distribution such that they return the same value in some set of events? It is also easy to visualize if your measures have densities w.r.t. the same measure. (Look at the area between your densities; best done if they have densities w.r.t. Lebesgue measure)
2) TV distance between a continuous distribution and a discrete one is, however, always 1, so that is not useful. So, for instance, if you add i.i.d. discrete random variables (think of Bernoulli), and renormalize, by central limit theorem, you know that it will converge to a normal distribution in distribution, but in total variation, it will not converge, which is a problem.
Instead, one can look at the Wasserstein distance between the two measures, which is given by essentially a transportation map: Let's say that it costs me $c(x,y)$ to move one unit of mass from x to y; how much will my transportation cost if I want to make my measure $\mu $ look like $\nu $? This is well-defined between mixture distributions, and indeed, you can prove many convergence arguments this way. (Also, convergence in Wasserstein implies convergence in distribution)
Comment: Thank you very much for your intuitive answer.
Comment: Wasserstein distance is also bounded by $1$?


Acessar objeto javascript no formulario html

Question: Olá,
estou enfrentando uma dificuldade com meu código javascript, pois não consigo imaginar uma forma em que seja possível acessar as funções do construtor do meu objeto JavaScrip no formulário HTML.
Gostaria de saber se existe uma forma de fazer isso que estou querendo.
Abaixo segue em anexo o código HTML e JavaScript, respectivamente.
HTML:

<!DOCTYPE html>

 <title>Calculadora</title>
 <meta charset="UTF-8">

 <form id="formulario">

Digite o primeiro número

  <input type="text" name="valor1" value="0">

Digite o segundo número

  <input type="text" name="valor2" value="0">

Resultado

  <input type="text" name="resultado" disabled="disabled">

Operações

    SOMAR
    SUBTRAIR

    MULTIPLICAR
    DIVIDIR

 </form>

JavaScript:

function Calculadora(){

 this.setValor1 = function(numero1){
  this.valor1 = +document.getElementById('formulario').valor1.value;
 }

 this.setValor2 = function(numero2){
  this.valor2 = +document.getElementById('formulario').valor2.value;
 }

 this.getSoma = function soma(){
  resultado = this.valor1 + this.valor2;

  document.getElementById('formulario').resultado.innerHTML = resultado;
 }

 this.getSubtracao = function subtracao(){
  resultado = this.valor1 - this.valor2;

  document.getElementById('formulario').resultado.innerHTML = resultado;
 }

 this.getMultiplicacao = function multiplicacao(){
  resultado = this.valor1 * this.valor2;

  document.getElementById('formulario').resultado.innerHTML = resultado;
 }

 this.getDivisao = function divisao(){
  resultado = this.valor1 / this.valor2;

  document.getElementById('formulario').resultado.innerHTML = resultado;
 }

}

Desde já, obrigado.
Comment: Porque não faz o onclick no javascript?
Answer: Isso seria possivel se fizesses algo como
var Calculadora = new _Calculadora();

onde _Calculadora é a função construtora, e Calculadora é uma variável global instância criada quando a página carrega.
Podem creio quer seria mais limpo fazer no JavaScript em vêz de ter chamadas inline no HTML. Poderia ser algo assim:

function Calculadora() {

    this.init = function(id) {
        this.formulario = document.getElementById(id);
        this.valor1 = this.formulario.valor1;
        this.valor2 = this.formulario.valor2;
        this.resultado = this.formulario.resultado;
        var acoes = this.formulario.querySelectorAll('table th a');
        for (var i = 0; i < acoes.length; i++) {
            acoes[i].addEventListener('click', this.doAction.bind(this));
        }
    }

    this.doAction = function(e) {
        var el = e.target;
        var action = el.dataset.onclick;
        this[action]();
    }

    this.getValues = function() {
        return [this.valor1.value, this.valor2.value].map(Number);
    }

    this.getSoma = function soma() {
        var val = this.getValues();
        this.escreve(val[0] + val[1])
    }

    this.getSubtracao = function subtracao() {
        var val = this.getValues();
        this.escreve(val[0] - val[1])
    }

    this.getMultiplicacao = function multiplicacao() {
        var val = this.getValues();
        this.escreve(val[0] * val[1])
    }

    this.getDivisao = function divisao() {
        var val = this.getValues();
        this.escreve(val[0] / val[1])
    }
    this.escreve = function(txt) {
        this.resultado.value = txt;
    }
}

new Calculadora().init('formulario');
<form id="formulario">

Digite o primeiro número

    <input type="text" name="valor1" value="0">

Digite o segundo número

    <input type="text" name="valor2" value="0">

Resultado

    <input type="text" name="resultado" disabled="disabled">

Operações

            SOMAR
            SUBTRAIR

            MULTIPLICAR
            DIVIDIR

</form>

jsFiddle: https://jsfiddle.net/b884xjce/1/


Projecting a matrix unto a uncorrelated matrix

Question: If $\mathbb{E}[\epsilon|Z] = 0,\ Var[\epsilon|Z] = \sigma^2I$,
and $\mathbb{E}[\epsilon|X] \ne 0 $
then is the following true?
$\mathbb{E}[\epsilon|Z(Z^TZ)^{-1}Z^TX] = 0$, $Var[\epsilon|Z(Z^TZ)^{-1}Z^TX] = \sigma^2I$
Assuming $Z$ and $X$ are full col rank.
$Z_{(n\times m)}$ and $X_{(n\times k)}$ are random matrices, and $\epsilon_{k\times 1}$ is a random vector. $ m \ge k$
$Z$ is highly correlated with $X$. Essentially $Z$ is the instrumental variable to $X$.
Comment: Could you provide more information, like is there any relation between' Z' & 'X'?
Comment: Hint: consider the possibility $Z(Z^\prime Z)^{-1}Z^\prime X=X.$
Comment: @whuber I don't think that should be a possibility since $\mathbb{E}[\epsilon|Z] \implies \mathbb{E}[Z\epsilon] = 0$ which will mean that the projected matrix will be that also? I need some reference material for this.
Comment: @Nizam, the assumption is that $X$ and $Z$ are highly correlated i.e $Z$ is an instrumental variable
Comment: Because you haven't made any assumptions about $X$ and $Z$ in your question--you haven't even specified whether they are random variables or not--the possibility I mentioned is certainly plausible.  For instance, take $Z$ to be a constant vector. As a counterexample, it answers your question, at least in the vague and general form in which it is stated.  If you need to include more information, as suggested by your comments, then please edit your post accordingly.
Answer: Here's a counterexample.  Let $Z$ be a $1\times 1$ random matrix (or a constant, for that matter) with $\Pr(Z=0)=0$ and $\epsilon$ a zero-mean random variable independent of $Z.$  Suppose as in the question that $X$ is a random variable with $E[\epsilon\mid X] \ne 0.$ Assuming what you like about the correlation between $X$ and $Z,$ it is always the case that
$$E[\epsilon\mid Z (Z^\prime Z)^{-1} Z^\prime X] = E[\epsilon\mid X] \ne 0.$$
The existence of this counterexample is not due to the simplicity of the situation: similar counterexamples exist for $n\times m$ matrices $Z$ (random or not); they're just a little more complicated to compute.


Show $\lim_\limits{x\to\infty} x(1-\frac{\ln (x -1)}{\ln x})=0$

Question: The following expression came up in a proof I was reading, where it is said "It is easily shown: $$\lim_{x\to\infty} x(1-\frac{\ln (x-1)}{\ln x})=0."$$
Unfortunately I'm not having an easy time showing it. I guess it should come down to showing that the ratio $\frac{\ln (x-1)}{\ln x}$ converges to 1 superlinearly, which seems intuitive but I don't know how to prove it formally. Any tips?
Edit: original question had an implicit typo - I had $\ln x - 1$ rather than the intended $\ln(x-1)$.
Comment: That's not right. $x(1-\frac{\ln x-1}{\ln x})=x(1-(1-\frac{1}{\ln x}))=\frac{x}{\ln x}\to\infty$ as $x\to\infty$.
Comment: Did you mean by chance $\ln(x-1)=\ln(x)+\ln(1-\frac1x)$ in the numerator?
Comment: first of all, simplify limit. The use the L'Hopitals rule and you will get the right result(Your limit does not equal to zero)
Comment: Heed my warning, young pup: The path to the dark side starts with "it is easily shown"
Comment: @LutzL That's a good question and half the answer, both in one.
Comment: Yup, sorry - sloppy on my part. Needed parentheses, as LutzL guessed
Answer: Well it's false :
$$x\biggl(1-\frac{\ln x-1}{\ln x}\biggr)=\frac x{\ln x}\to+\infty. $$
Answer: Your question only makes sense if it was posed as
$$
\lim_{x\to\infty}x\left(1-\frac{\ln(x-1)}{\ln x}\right)
$$
which can easily be transformed into
$$
\lim_{x\to\infty}\frac{-x\ln(1-\frac1x)}{\ln x}=\lim_{x\to\infty}\frac{1+O(\frac1x)}{\ln x}=0
$$
Comment: Perhaps an easier way: substitute $x=\frac{1}{h}$ to obtain $\frac{\log(1-h)}{h \log(h)}$, and use L'Hopital.
Comment: Your answer is the correct one.
Comment: Thanks for your answer, but I'm still missing a piece conceptually. How do you get the asymptotics for $\ln(1-1/x)$ in the numerator?
Comment: This is the logarithm series, as in $-\ln(1-h)=h+\frac12h^2+\frac13h^3+…$ which converges and gives $-\ln(1-h)=h+O(h^2)$ for $|h|<1$.


Can I repost unanswered questions from Stack Overflow?

Question: I have several questions on Stack Overflow which were never closed, but never received an answer. Would I be allowed to repost the same question here (as long as it's Magento related)?
If so, would the SO version have to be closed?
Answer: Treat Magento.SE and Stack Overflow as two separate sites.
Because, uh, they are.
If it's your question, and you honestly do want an answer to it, go ahead and ask it here. Heck, you can do that even if it already has an answer on SO and you simply want a better one.
What you want to avoid is "mechanical migration" - re-posting questions you don't need answers to here and then copying answers in from SO, just to pad the numbers. That doesn't allow anyone to demonstrate their Magento expertise, and creates an artificial sense of progress when nothing's actually happening.


Suggestion for a Lyapunov function

Question:
Consider the differential system $$ x'=x+y $$ $$y'=x-y+xy$$
What would be a Lyapunov function for this system at $(0,0)$?

I have considered functions $V(x,y)=ax^{2n}+by^{2m}$ but none of them seems to be Lyapunov.
Comment: @Mattos No, no, you are right, I guess I am talking too much to people using a relaxed definition of Lyapunov function. Thanks for putting me back in the right path. :-)
Comment: As far as I'm aware, you construct a Lyapunov function to show that a critical point is _stable_ when _linearising the system doesn't work_. If a critical point is unstable, then you won't _ever_ be able to find a Lyapunov function, so you _can't_ investigate the critical point in the manner you want to. You can use the second derivative test (Hessian) to determine whether $\frac{d}{dt}L \le 0$ though.
Comment: @Did The function $L(x,y) = x^{2} - y^{2}$ doesn't satisfy the condition that $L(x,y) > 0, \ \forall (x,y) \ne (0,0)$. For example, choose $\lvert x \rvert < \lvert y \rvert \implies x^{2} - y^{2} < 0$. Or am I forgetting something?
Comment: Yes $(0,0)$ is unstable solution but I want to investigate it by LF .
Comment: @Mattos The critical point $(0,0)$ is unstable for the system $x'=-(x^2+y^2)x$, $y'=(x^2+y^2)y$, which admits the Lyapunov function $L:(x,y)\mapsto x^2-y^2$.
Answer: As it is indicated in comments Lyapunov function is usually used to infer the stability of the equilibrium. There is a useful theorem by Chetaev, which allows one to build a function (often called Chetaev's function in Russian-language literature) to prove instability. In your case you can take
$$
V(x,y)=xy,
$$
which is positive in the first quadrant, zero on its boundary, and the origin also belong to the boundary.
I have
$$
\dot V=y^2+x^2+x^2y>0,
$$
for $x,y>0$. Hence, by the aforementioned theorem, the origin is unstable.
Comment: Nice theorem! I'll have to remember that one.
Answer: We refer to Liapunov's technique to determine the stability only when the linearized system is not hyperbolic at the equilibrium point.
Now ,bearing this in mind, let's just check the linearized system, which can be derived by simply dropping the non-linear terms :
$\left(
  \begin{array}{cc}
    1 & 1 \\
    1 & -1 \\
  \end{array}
\right)$
This system has a positive eigenvalue ($\sqrt{2}$) and a negative one ($-\sqrt{2}$), so it's hyperbolic, and from the linearization we can state that the origin is a saddle (hence not stable).
Bottom line, search for a Liapunov function only when the equilibrium is not hyperbolic. If it is hyperbolic, such as your case, then you're a lucky boy! (or a lucky girl if you're a girl)
;)

Suggestion for a Lyapunov function


Built-in Generic Types

Question: I read somewhere that EventHandler is a built-in generic type. Why is that so? Could somebody explain me ways to distinguish between generic and non-generic types?
Thanks,
Abhi.
================
I am reading Microsoft .NET Framework Application Development Foundation 2nd edition to prepare for MCTS. In the first chapter, there was a question as below:-
Which of the following are examples of built-in generic types? (Choose all that
apply.)
A. Nullable
B. Boolean
C. EventHandler
D. System.Drawing.Point
The answer of the question is A and C as per the book. Option A is alright, but wasn't sure about option C. Can somebody please explain?
Comment: "EventHandler is a built-in generic type" - in what language?
Comment: What programming language? What did you read?
Comment: Tim/Peter, I have updated my original post. The language is C#.
Comment: How can I not choose more than one answer as accepted answer? Most of you have answered my answer in your own way and I want to mark at least 2 of them as accepted answer!! Is there any way?
Answer: There are two types: EventHandler and EventHandler<TEventArgs>. Obviously the first isn't generic, and the second is.
Comment: There is a [third EventHandler](http://java.sun.com/javase/6/docs/api/java/beans/EventHandler.html) as well :) Less related to generics though.
Comment: By looking at , I can say that it is generic, but if you see the question that I have posted in my original post (updated a few minutes ago), it doesn't mention . Is it that the quesion was not asked properly or is it that just by the name of type, we can make out whether it is generic or not?
Comment: @user366436: Both Nullable and EventHandler exist in generic and non-generic forms. It seems to me it's just a bad question.
Answer: T is the type of EventArgs the eventhanlder handles (so T : EventArgs)
Answer: In C# (but it applies to Java too), you can recognize generics by the presence of Type Parameters, usually indicated between <> brackets.
For example, the generic type of EventHandler in C# is declared as:
public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e);

The type TEventArgs that parameterises the delegate is used to have static typing inside the event handler function, without the need for casts or to define multiple delegate types for each type of argument you need passed to the handler.
Say you have 2 different events, one generating objects of type T1, one of type T2.
You will have two different handlers:
void HandleEvent1(object sender, T1 args) {...}
void HandleEvent2(object sender, T2 args) {...}

In C# 1.0 (no generics) you would create your own delegate types for the 2 events:
delegate void Event1Handler(object sender, T1 e);
delegate void Event2Handler(object sender, T2 e);

And use them to bind your event with the handlers.
From C# 2.0 there's no need to create new delegate types, since both handlers are captured by the generic EventHandler<> type (TEventArgs = T1 or TEventArgs = T2).
See here and here for an intro on generics.
Answer: To answer the question you ultimately need to look up each type name in the MSDN index. Nullable appears as Nullable<T>. EventHandler shows up twice, with and without the <T> suffix. These are in fact separate types.
Comment: Nullable also exists without the ``: http://msdn.microsoft.com/en-us/library/system.nullable.aspx
Answer: The question is badly phrased, but is asking which of the types are generic (or have generic versions). The answer is EventHandler and Nullable, since Boolean and Point do not have generic equivalents.

Built-in Generic Types