Can an interrupt function call a regular function?

Question: If I want to create an interrupt and have it do something, can this 'something' be written in a regular function that I also use outside of the interrupt?
Answer: Yes, you can. You just have to make sure your function is reentrant.
If it accesses no memory beyond its parameters and (non static) local
variables, you should be fine. If it accesses global variables, hardware
registers, or static locals, it is unlikely to be, and only detailed
analysis will tell you for sure.
Beware also of the library functions you call: some of them are not
themselves reentrant and should therefore be avoided. See for example
the manual of strtok(), which explicitly addresses the
reentrancy problem.
Comment: In addition, if the function is only called by the one ISR, _and_ it will always run to completion (won't be interrupted and run another time before the previous call finishes), it doesn't need to be re-entrant.
Comment: @JRobert: The OP stated that the function would also be called from non-interrupt context. That other call would need to be inside a critical section if one wanted to ensure the function is never called while another call has not finished.
Comment: True enough, making my comment irrelevant here.
Answer: Yes you may.
Yet keep the function in question short, you don't want to spend too much time in interruption.
Another way is to set up a variable state in the interruption, and call the function in question in the normal cycle when the variable is in the desired state.
Answer: You can do that, but it will increase the complexity of your program.
Often when entering an interrupt service routine, the first thing you do is disabling interrupts - the make sure the callback completes reliably.
This is something you will have to consider if you want to use the same routine for a 'regular' scenario
Comment: You wrote: "_the first thing you do is disabling interrupts_": on AVRs at least, you don't. The hardware does it right before executing the interrupt vector.
Answer:
If I want to create an interrupt and have it do something, can this 'something' be written in a regular function that I also use outside of the interrupt?

The right answer is yes and no.
The issue here is reentrancy : whether a function can be interrupted while it's being called by another. Not all functions are re entrant so the safer assumption is that they are.
Another issue with calling a function from within the isr is overhead.
The typical solutions are:

Make sure that the function called from the isr is re entrant.
The simplest way to assure that is to a. Limit your calling of that from the isr. Or b. Create two versions of the same function. And call them separately.

Btw, I routinely call functions from within isr. In my case through function pointers.
Comment: You left out ***not*** at the end of  "Not all functions are re entrant so the safer assumption is that they are."


Interest Benefit on Home Loan for pre-construction period, if foreclosed before 3 years after posession

Question: I am living in India.
I want to know if I can claim tax benefit for the interest paid on my home loan under Section 24 for the pre construction period if I foreclose the loan before 3 years of possession.
I have given a detailed example to my problem:
Scenario Explanation:
A person 'P' has borrowed Home loan from a bank 'B' in the year April 2016. The house was under construction during that time. The EMI paid out was approx 20k per month.
The construction was complete and possession of the property was given in the year April 2019 - after 3 years since the loan started.
Now, as per Section 24 of the Income tax act, the interest paid during the period of pre-construction( 3 years in this case) is allowed to be shown as loss on property. This is supposed to be shown in equal parts for the next 3 years.
Lets say the interest paid in these 3 years is 3Lakhs. So, in the next 3 years, a tax benefit of 1 Lakh per annum can be claimed.

Now, the problem is that if the loan is foreclosed in the year August 2019. Am I still allowed to claim the tax benefit for the next 3 years?
Answer: In normal course of action if is carried over equally in next 5 years. There is no clarity on whether the loan needs to be active.  Consult a CA
Answer: The interest of the pre-construction period is allowed in equal parts in 5 years. Foreclosure of the loan later doesn't affect this.


Can tiny fruit bearing trees be grown in flower pots?

Question: Is it possible to grow a tiny tree in a flower pot that can produce fruits in house environment? Specifically, I'm interested in tangerines, pomegranates, bananas and lemons. How do I turn their fruits into growing plants? Even if some or all of them can't produce fruits in a flower pot, I'm still interested.
Answer: I grew potted citrus trees in Connecticut and it was very easy. I grew regular varieties, not dwarf or semi-dwarf. I kept up-sizing the pots on a yearly basis, but with yearly root pruning, you could keep them smaller. I also moved them outside in the summer months, which they appreciated since they really like sunshine. Some varieties, like key limes are smaller in stature.
Also, I grew ornamental bananas in pots. Banana plants are less well-suited to container culture in my opinion. Two problems come to mind. One, a non-dwarf variety will quickly outgrow the pot due to the baby "sucker" plants that come up around the base and aggressive root system. One could prune those off, but unlike a tree, a banana plant is somewhat unwieldy to be trying root pruning that frequently. Secondly, due to the thin leaf structure they seem to be somewhat susceptible to spider-mites in the dryer winter months.
Comment: Too bad, yet citrus will still do ok as long as they are right by a sunny window. They just won't grow as fast (which could be an advantage)
Comment: I live in an apartment, so moving plants outside is not an option :)
Answer: There are some dwarf varieties that can be grown in pots. One I've been looking into is a Meyer lemon. If you buy it old enough it will be able to fruit. I've read of people keeping it indoors all year round but most seem to bring it out during the summer. If indoors. It still needs adequate sunlight. I'm still looking into how much light is adequate. If you look around you should be able to find some other dwarf fruiting trees that can be grown in containers.
Comment: This is assuming growing lamps are used as opposed to natural sunlight from the windows, right? Are there any specific light amount minimums?
Comment: Do some searches on any varieties you're interested to find out more about what their light requirements. The meyere lemon tree I mentioned likes 8 hours of sunlight a day. If you can't provide that outdoors or through a window you can use artificial light.
Answer: Yes you will need a dwarf variety or dwarf rooting stock to keep them small and "pot sized".
You might also want to look at similar but more obscure plants. Eg. kumquats instead of oranges.
Finally, think you will be out of luck with bananas. These are technically herbs and not trees, so dwarf rooting stocks aren't available. They are large plants.
Comment: There are "super dwarf" Cavendish type (sweet) bananas that can be grown in five gallon pots and only grow 2-3 feet tall.  I grew a trio of these for a while, but unfortunately was never able to give them a long enough warm growing season to fruit properly.  (I lived in a city at a mile high elevation in the mountains of Idaho at the time.)  They grew happily, if unfruitfully every year, but never outgrew their 5-7 gallon pots.
Comment: Thanks for the info - you learn something every day. We have full size non-Cavendish here in Dallas and we had fruit last year - after a very mild winter. They're marginal here - no one else around here had seen fruit this far north. With the full size variety, the flower forms in the stem during/before winter. Frost will kill it.
Answer: I've successfully kept a calamondin tree indoors (which I bought when it was already at a fruiting stage). They look wonderful and the fruit tastes pretty good too.


Whitish film over mustard cake tea

Question: I had kept mustard oil cake dissolved in water in order to make fertiliser tea. But a whitish layer appeared over it after three days. Will it be safe to use that tea on my potted plants?
Comment: Have you finished making the tea yet, or do you mean its 3 days since  you put the mustard cake with water, before the next step of adding fungicide and more water in order to use it?
Comment: Three days after putting mustard cake with water
Answer: The agricultural industries are constantly looking for ways to make better use of their otherwise waste materials. Normally when we think of mustard/canola type cakes and meals we think in terms of their protein content and therefore their use as animal feed. After this kind of use the secondary waste product can be applied to horticultural and agricultural uses.
Research seems to indicate that great care is necessary when using oilseed cake/meal with plants. Any time you make tea, there is bound to be some separation of the meal components. Tea extraction could concentrate the more potent parts of the mix to the detriment of the soil, so great care in dilution is needed. North Carolina State University Extension did some experiments with meal from soybeans with mixed results. It seems that while it can be a source of N,P,K it can suppress germination of small seeds, which may be good in an already established potted plants. Also see this previous question related to compost teas.
The problem is that unlike using a well known categorized and analyzed product you are taking a risk applying such products directly to plants that you value. What is probably a safer route is to apply the tea as fertilizer to plants that you do not value and then compost those plants to mix in with the soil you grow your more valuable plants in.
Answer: The only way of making mustard cake tea for use as a fertilizer that I know about involves adding a fungicide powder after steeping the broken up mustard cake in water for 3 days; the formation of a white (presumably fungal) film on top prior to the addition of fungicide is likely not unusual, but the mixture should be kept for no longer than 4 days maximum prior to stirring well and mixing in the fungicide. Unfortunetely, I don't know the ratio of fungicide powder to the mixture, but there are a number of videos on this subject online, usually in languages other than English. My knowledge of this subject is otherwise non existent, never having used it myself, but searching on line for 'how to make mustard cake tea' should bring up some results.

Whitish film over mustard cake tea


How to simulate a slow internet connection on an Android phone

Question: I basically use internet using wifi which provides a very high speed internet and LAN connection. I would like to simulate a slow speed internet and LAN connection to understand how my web site works on slow speed. Is there any app that I can install on the android phone and simulate it?
Answer: There is no such setting on Android phones, but you can use the Emulator for this. Install the Android SDK from developer.android.com and launch it. On the DDMS view undet the Emulator control tab, you'll find the following options:

After you have created an emulator and ran it, you can set these values according to your preferences and test how different networks affect your site.
Answer: When using Emulator is not an option for testing certain functionality (frequently), our team hot-spots for physical Android devices with an iOS device and uses the Network Link Conditioner on that. Obviously, for some this isn't an option, but it works very well and is easy to implement.


How many blocks are there in blockchain as of today?

Question: I have currently downloaded 300,000 blocks and the last one is generated 1 year and 19 weeks ago. I wonder how many blocks are more to go, before I am up to date.
Comment: https://blockchain.info/q/getblockcount
Answer: There's a generic answer to this question that anyone can use, and an answer specific to users of Bitcoin Core (versions 0.10.0 or higher).
Generic version
Rather than directly answer your question with an answer that would become outdated within a few minutes as the next block was discovered, here's a general way you can look up the current number of blocks in the blockchain:

Go to this list of blockchain explorers.
Choose one (or choose several) and visit its website.
Almost all of them on their main page display the heights of recent blocks.
The height of a block is how many blocks there are before that block on the blockchain, so take the height of the highest block and add one—that's how many blocks there are on the blockchain.

Please note that it's not uncommon for blockchain explorers to be wrong about various facts, including the height of the highest valid block.  Visiting several sites decreases your risk of getting bad information without realizing it—if different sites disagree about the height by more than a single block, you'll know something is wrong.
For Bitcoin Core users
The getblockchaininfo RPC includes both the height of the highest downloaded block and the height of the highest valid-looking downloaded header.  On a fast connection, Bitcoin Core will typically download all the headers within two minutes of the time it is first started, so this number of headers is usually the total number of blocks on the best blockchain (minus one, since counting starts from zero).
{
  "chain": "main",
  "blocks": 381466,
  "headers": 381466,

The first few lines of getblockchaininfo on a fully-synced node
It's important to node that the headers count can conceivably go down if Bitcoin Core discovers the blocks that are supposed to be attached to those headers are invalid.  This most recently happened during the 4 July 2015 fork (although 0.10.0 and later Bitcoin Core nodes were unaffected) and it could also happen if there's a hard fork attempt that has the support of the majority of the network hash rate.
In Bitcoin Core GUI (Bitcoin-Qt), you can run the getblockchaininfo RPC by going to Help menu -> Debug item -> Console tab, and then typing in:
getblockchaininfo

Comment: Just in general I'm not sure querying multiple block explorers really decreases your chance of them being wrong, simply comparing the "balance" field for a given address will more than likely give you completely unique results on most of them.
Comment: @Bitcoin True.  I clarified that section; doing that made me realize that there's a simpler method possible using just Bitcoin Core, so I added that to the answer.  Thanks!
Answer: As of October 31, 2015, 6:48 PM UTC, there are 381435 blocks.
Answer: As of September 20, 2016. 10:16PM CST. There are 430756 blocks.
Comment: -1 Jimmy's answer was somewhat useful, as it directly addressed the asker's question when the question was asked. This answer now is just already outdated two hours later.


Sticky faucet handle of unrecognized faucet

Question: Does anyone recognize the brand of the faucet in the image below, so that I can attempt to disassemble and inspect parts? Secondly, the right-hand handle sticks; is hard to turn off completely, and leaves water leaking from the spout.  Any advice on how to fix this problem?
Comment: there may be labels attached to the pipes underneath ... you have said what type of valves you have (compression or washerless) (washreless would be 1/4 or 1/2 turn with hard stops)
Comment: Tommie, you can discontinue the practice of adding the comment notice at the top of your questions. That goes without saying on SE networks. :)
Answer: It looks much like this one--wow ... not cheap--found by doing a web image search for "antique brass faucet".
This is the install document. Item 16 is a setscrew that you loosen so that you can remove the handle, and expose the cartridge assembly. Then I guess that you would loosen a retaining ring and pull up on the cartridge assembly.
Do not forget to shut off the water before doing this.
Here is the manufacturer. You could email them.
Here is a search for info.
Comment: Could you offer any advice on part two of the question (how to disassemble, inspect, and clean these faucets)?  - I'm a novice in this area but I'm handy and learn quick.
Comment: This answer addresses the critical points of disassembly. Cleaning of a faucet mostly involves dissolving calcium buildup. However, cartridge-type faucets generally don't need much cleaning if the cartridges are being replaced. There's plenty to be found on that with a search.


should I create a new class for a specific piece of business logic?

Question: I have a Request class based on the same Entity in my Domain.   It currently only has property definitions.  I'd like to add a method for checking a duplicate Request which I'll call from my controller.  Should I add a method called CheckDuplicate in the Request class?  Would I be violating the SRP?  The method will need to access a database context to check already existing requests.  I'm thinking creating another class altogether for this logic that accepts a datacontext as part of its constructor.  But creating a whole new class for just one method seems like a waste too.  Any advice?
Comment: If I had my way, all classes would have only one method unless that class was a container for logical groups of methods. But I'm a little extreme ;).
Answer: I'd go ahead and create it.
As you mentioned, adding a new responsibility to what's currently a DTO would violate the SRP.  The question arises, what happens when the next requirement comes along?  Would you add another method?  What happens when you add a new attribute to the DTO?  Would that necessary change add the risk of messing up your duplicate checking logic?  Part of the idea of the SRP is that there should only be one reason to modify your class.
Moreover, a DuplicateChecker may turn out to be useful for other domain classes as you move forward.
It's not like classes are particularly expensive.
Answer: As per the question, you just need to validate if the entry is a duplicate? If thats the case that is like validation, so you can go ahead and create a method isValid() or isDuplicate() which would return a boolean value on checking the validations that you have.
Comment: not necessarily.  I only need to check when a certain class of users are about to begin requesting.  So the request isn't even complete yet.  This is not being checked at submission of request.
Comment: @Riz Yes true, what I mean is, if you have this validation for certain users, then you call the isValid() method only for those users and if it is true, then proceed further.


Need a cli to check the sha256 hash of a file

Question: To check the sha1 of a file I would use openssl sha1 <file> I'm not sure what to use to check the sha256 hash of the file however, what would you recommend?
Answer: You can use
openssl dgst -sha256 <file>

Tested on LibreSSL 2.6.4 on macOS 10.14 (Mojave).

Prior to Mojave you can use openssl sha -sha256 <file> or openssl sha256 <file>.
To check command line options for the openssl sha command: openssl sha -help.
Comment: This is also portable and runs on ubuntu.
Comment: "Prior to Mojave" - `openssl sha256 ` still works, on MacOS Catalina, as of Nov. 2020.
Comment: You may need to use `/usr/bin/openssl` explicitly
Answer: OS X ships with a shasum command.
> which shasum
/usr/bin/shasum

You can use:
> shasum -a 256 <file>

More details:
> shasum --help
Usage: shasum [OPTION]... [FILE]...
Print or check SHA checksums.
With no FILE, or when FILE is -, read standard input.

  -a, --algorithm   1 (default), 224, 256, 384, 512, 512224, 512256
  -b, --binary      read in binary mode
  -c, --check       read SHA sums from the FILEs and check them
  -t, --text        read in text mode (default)
  -p, --portable    read in portable mode
                        produces same digest on Windows/Unix/Mac
  -0, --01          read in BITS mode
                        ASCII '0' interpreted as 0-bit,
                        ASCII '1' interpreted as 1-bit,
                        all other characters ignored

The following two options are useful only when verifying checksums:
  -s, --status      don't output anything, status code shows success
  -w, --warn        warn about improperly formatted checksum lines

  -h, --help        display this help and exit
  -v, --version     output version information and exit

When verifying SHA-512/224 or SHA-512/256 checksums, indicate the
algorithm explicitly using the -a option, e.g.

  shasum -a 512224 -c checksumfile

The sums are computed as described in FIPS-180-4.  When checking, the
input should be a former output of this program.  The default mode is to
print a line with checksum, a character indicating type (`*' for binary,
` ' for text, `?' for portable, `^' for BITS), and name for each FILE.

Report shasum bugs to email@example.com

Comment: @erikvold You know what? I bet I got with the Xcode Command Line tools. Argh. I really wish Apple wouldn't pollute `/usr/bin` with optional stuff. I'll have to verify this is the case later today. Will update answer if it indeed came from the XCL install.
Comment: `shasum` returns a different hash than `openssl sha -sha256 `(with the latter being the correct hash). Any idea why?
Comment: @ws6079 `shasum` is a perl script, uses `Digest::SHA` to compute the hash value. For the same file I get the exact same SHA using either `shasum` or `openssl` for a `SHA-256` hash computation. See: https://gist.github.com/ianchesal/82a064b8971eb5e717ce84f3ded6dbfd
Comment: Hmm I don't seem to have it on osx 10.11.3. `which shashum` outputs nothing
Comment: shahsum is working great for me today.
Answer: To clarify @John's useful answer - which allows you to compare a given hash with its file in one command:
Enter shasum -a 256 -c <<<,
followed by an optional space,
followed by a single tick ('),
followed by the hash to compare,
followed by a space,
followed by a mode character, based on how the initial hash was generated:

nothing, if the hash was created with -t or no option (text mode, which is the default)

asterisk (*), if the hash was created with -b (binary mode)

question mark (?), if the hash was created with -p (portable mode)

caret (^), if the hash was created with -0 (bits mode)

followed by the path to the file,
followed by a closing single tick (').
Like the following breakdown, with delineating parens around the hash and filepath parts, and square brackets around the optional "mode character" part. (Don't include the parens or brackets in real life - they're just here to make the parts easy to see!)
shasum -a 256 -c <<< '(hashToCompare) [mode character](filepath)'

Broken down:
The actual shasum command is shasum -a 256 -c

-a 256 tells shasum to use sha256.

-c tells shasum to "check" the provided input.

The <<< is a Unix/Linux special character set, called a "redirection" operator. It's for feeding something into a prior command. By using it, we're saying we're going to provide a string of information for the shasum command to use as input.
The string of input information must have opening and closing single ticks, such as 'some string here', or in this case, the hash, mode character, and filepath to be checked.

The hash part inside the string doesn't need anything special - but it must be followed by a space.

The mode character part can be nothing, an asterisk (*), a question mark (?), or a caret (^). This tells shasum the mode with which the hash was generated. (Note: no character at all, representing text mode, is shasum's default.)

The filepath part, is the actual path to the file to be checked.

So, here's a real-life example checking a particular MAMP download file against it's purported SHA-256 value. The * mode character was required for this check to work:
shasum -a 256 -c <<< 'f05ede012b8a5d0e7c9cf17fee0fa1eb5cd8131f3c703ed14ea347f25be11a28 *MAMP_MAMP_PRO_5.2.pkg'

Note: the result of this command (for my example file) is either -
OK:

MAMP_MAMP_PRO_5.2.pkg: OK

or
FAILED:

MAMP_MAMP_PRO_5.2.pkg: FAILED
shasum: WARNING: 1 computed checksum did NOT match

Update: I recently had to do something similar, but with a file containing the hash value/filename string. Here is an alternative for that situation:
cat <text-file-containing-string> | shasum -a <shasum-value> -c

For example:
cat qemu-w64-setup-20230822.sha512 | shasum -a 512 -c

Comment: Does the presence of the asterisk indicate that the checksum used as input in the example was generated in binary mode ( with `--binary` option)? From the man page:  "When checking, the input should be a former output of this program.  The default mode is to print a line with checksum, a character indicating type (`*` for binary, ` ` for text, `U` for UNIVERSAL, `^` for BITS,`?` for portable), and name for each FILE." So, the characters between the checksum and filename depend on the mode set when the checksum was created?
Comment: So clarify, whether you need an asterisk (or mode character other than default) correlates to the file. Text files can omit the character because the default mode is text. Leaving it out for an ISO will error "shasum: standard input: no properly formatted SHA checksum lines found". Binary file, so the asterisk (binary mode) will be needed.
Comment: For me this works without the asterisk before the filename (as well as with the asterisk).
Comment: `shasum -c <<< '7cb77378a0749f2a9b7e09ea62ffb13febf3759f  *sample.txt'` returns the message `*sample.txt: FAILED open or read`. Without the asterisk, `sample.txt: OK`. I haven't been able to find the basis of the asterisk's use elsewhere yet. Could you clarify?
Comment: @SoFarther: yes, you're right. After some experimentation to prove that idea, I have updated my post to clarify the "mode" aspect.
Answer: I would use this command.
shasum -a 256 -c <<<'_paste hash to compare here_ *_path to file goes here_'

Example:
shasum -a 256 -c <<< '0d2ea6de4f2cbd960abb6a6e020bf6637423c07242512596691960fcfae67206 */Users/USERNAME/Downloads/someprogram.dmg'


Can a grounding issue with newly installed light fixtures cause a short circuit/blown fuse?

Question: I have installed three lights (60 Watt Bulbs) on the same line (wire) connected to one light switch.   The fuse blew when I hit the switch.  I've connected all of the white to white and black to black.  I believe the problem may be with the ground.  I've grounded each light fixture.  I believe that I was just supposed to pig tail the ground to the ground in each light fixtures and only affix the actual ground wire in the switch box to the green ground nut.  Is that correct?  An informed response would be greatly appreciated!
Comment: A blown fuse doesn't necessarily mean a short circuit. It only means there is too much current for the fuse, and cable to handle. This **may** be because of a short circuit, or just too much load.
Answer: Unless you connected a hot to ground, it probably is not related to the ground.  Without seeing some pictures or diagrams, my best guess is that one of your white wires is actually a hot (and someone didn't mark it as so), so by connecting the whites (which are supposed to be neutral) together, you've created a short.
Sometimes with switches, when the power comes into the ceiling box first, there will be one cable to the switch from the ceiling box. In this configuration you will find a black and white wire, but both are actually hot since the switch only interrupts the hot wire.  Take a look at the switch wiring - are both wires black, or is one black and one white? If one black and one white, then one of your white wires is actually hot and should not be connected to the rest of the white (neutral) wires.
I would start by disconnecting your work, verifying the fuse doesn't blow in this configuration and then start connecting the lights back up at one at a time.
Remember that electricity is dangerous and there's nothing wrong with calling an electrician if you are in over your head!
Answer: Following up on what @Steven mentioned. I am not entirely sure of your level of proficciency however i have included two diagrams that illustrate the point he was making and two of the ways it can be wired. The first is how i assume it would be wired however in older houses you can easily find that it is wired too the light first as is shown in second image

And here we have the second example which is more common in older dwellings
Comment: White switch wire should be on the light side (neutral potential when "off"), connection 4. black wire should be on L1 side, connection 1 (always hot). Also white wire should be "flagged" with either black or red tape indicating it is now a hot leg.
Answer: Typically the ground is never involved unless there is a problem!    The only exception is something like a one wire circuit that USES the ground instead of a nuetral!  Ony find this on things like and occupancy sensor switch designed to be installed on switch locations that are ONLY a switched leg with no nuetral in switch box (VERY COMMON) an exception is made for these devices because it is teensy control circuit only...no significant amperage goes through the ground...other than that?  You can not even have a ground in most circuits and aside from being dangerous?  It will all work just fine...but the problem with no ground is that IF part of circuit touches metal (ground) it will "short" to ground with electricity running THROUGH your ungrounded device or equipment!  You would not even know because the circuit breaker probably won't care/won't trip and so?  You grab metal ungrounded energized part and it just like grabbing LIVE electrical conductor beause it HAS BECOME a conductor!  YOU become a a conductor and maybe your heart stops and you DIE of "electrocution"   which is just a long answer that NO the ground is not what was causing your problem ...in all likely hood it is an "open" rather than a "short" ...an "open" is where current carrying part is not connected for some reason...a blown fuse for example is most typical...
Comment: connecting all the whites to white and blacks to black in a switch loop causes a dead short on a switch loop and will trip the breaker.


Diagnostic connector broken; wires corroded and pulled out of the housing

Question: 1990 f150, XLT Lariat. Has been having idling issues, and the check engine light flicked on. I went to try and pull codes off, and realized that the wires inside the diagnostic connector had corroded. I can't seem to find a replacement part, or a method to reconnect the wires. The housing itself is shattered on one side too, which is probably how moisture got in there in the first place.
Answer: Honestly, your best bet is to go to a wrecking yard where you can pull your own parts, find one in a Ford vehicle (F150 would probably work the best). Pull the data link connector (DLC) from the truck along with several inches (6" or more) from the wiring harness. Take it home and splice it into where your DLC is at now. This will allow you access back into your computer. The only reason why I suggest another Ford truck around the same age is the color indicators of the wires should be the same and should make it easier for you to match them up.
Comment: Cut and splice one wire at a time!  Don't want to mix anything up.


Power an op amp when having only higher supplies

Question: I have a +-24 V supply and I want to power an op amp. I initially tried an LM324 using a single +24V supply, but I then discovered that I want the op amp to be allowed to output negative voltages too (which the 324 can't). I could not find an op amp that can take e.g. max +-25 V so that I can connect it immediately to my supply. Would just a voltage divider do?
Comment: http://www.ti.com/lsds/ti/amplifiers-linear/operational-amplifier-op-amp-products.page#p1261max=48;100
Comment: You could get some +/- 15 Volt three terminal regulators and cut the voltage down.
Answer: If you're trying to output a signal moving a few volts either side of 0V, then you could produce +ve & -ve rails from your +/-24V using a positive and negative regulator, then power any old op-amp of those.
If you want enormous voltage swings on the output, then you could use a high-voltage op-amp which you can power directly off the +/-24V rails.  Don't do this if you're going to put the output in something which can't take such large voltages though.
Or if you're doing AC-only (audio, for example), you can couple the signal via a capacitor and bias things up off you 0V rail.
"High-voltage op amp" in google found me this: LM143 http://www.ti.com/lit/an/snva516/snva516.pdf which will take +/- 40V supplies.
Never used it, don't know what it's like, but there are clearly suitable products around.
You should say something about the type of signal you're trying to handle.
Answer: Using just a pair of voltage dividers to produce the supply rails for the op amp is a bad idea as the supply current drawn by the op amp will vary and will result in varying voltage supplies.  You should use a pair of linear regulators instead such as the 7812 for the positive rail and 7912 for the negative rail. (More modern equivalents also exist).
Or as mentioned by Will Dean, if you want to be able to produce large output voltage swings, use a special purpose high-voltage op amp IC.
Answer: Here are 1000+ op-amps on digikey that can do ±24V rails
Alternatively you could bias the opamp to halfway between your power supply (12V) to have a similar effect. In this scenario "negative" values of output would be on one side of 12V and "positive" values on the opposite.
Finally, no you do not want to use a voltage divider for a power rail to an IC for a variety of reasons. Fluctuations in current consumption will cause the supply to dip or rise and the chip won't operate properly.
Answer: A LM324 can handle up to 32 V supply, so ±15 V would work and give you most of the voltage swing a LM324 can have.  A opamp takes relatively little current, so basic linear regulators will do.  You've got plenty of headroom, so the 78xx series will be fine.  You can use a 7815 to make +15 V from the +24 V supply, and a 7915 to make -15 V from the -24 V supply.
Answer: You can use a resistor and a zener diode to provide a limited voltage version of your 24 volt rails, maybe +/- 15 volts. It won't be as rock-steady as a linear regulator but would certainly suit most applications. Most op-amps only need a few milli amps or less so 1k resistors to 15 volt zeners can supply up to 9mA. In fact that will be the current going into the zener when not connected to an opamp. If space is an issue and leaded components are the only option this might be a decent solution.


Why was this post closed

Question: https://alcohol.stackexchange.com/questions/2168/most-popular-beer-by-country
I think this should be reopened as Community question as the only question Country wise to check for their respective specialities of beer brands
Answer: @BeerFreezer. Thanks for participating in the meta as well as the main site.
As discussed elsewhere in the meta, the consensus at Beer.SE is, unlike other stack exchanges, to allow regional questions as long as they are sufficiently constrained. There are hundreds of countries that produce beer, and therefore, although I think it's indeed a useful question, I agreed (with whoever cast the first close vote) that the question was [too broad].
Take a look at this question: What does AngularJS do better than jQuery? [closed].
Try to remember that questions aren't closed because they're not useful, but rather because they don't fit certain site guidelines. Even if I don't personally agree with site guidelines (I'm actually closer to your side than you might think), as a moderator I am somewhat obligated to enforce the guidelines as set by the community. You'll still get reputation for upvotes of course—you just won't be seeing any new answers, since, it's been decreed the question covers too much ground and lacks specificity.
That said, you've reminded me of this question of mine: Local beers to try at airports (major airports only). To give you some context, at the time, the site was very young and I was trying to increase community participation by asking a "fun" question—a question any of us might remember the next time we're at a brewery in an airport. Some users commented immediately that the question wasn't well-suited for an SE site; I shared their sentiments and agreed to a motion to close. However, one might argue users aren't willing to act "against" a moderator. (Though, personally, I don't see close votes as antagonistic, at all. Also, I try to respect users by believing in their willingness to express honest thoughts; similarly I hope I have users' respect in trusting me to be able to handle said thoughts.) Now, the above question, I attempted to "constrain" by defining a "minimum enplanements" threshold. However, since I'm also allowing 1 airport per country regardless off that criterion, clearly my question is even less constrained than yours! And especially since the site has grown and there's less of a need for the original purpose I sought to fulfill (fun, immediate participation), I will be consistent in my judgments and close my own question.
Please don't hesitate to speak up about things like this in the future.
If you still disagree with my judgment, that's okay! If you believe your question would be valid as a community wiki, then please find a meta.stackexchange.com post that helps substantiate your reasoning. (I'm placing the burden of proof on you, since the community has already voted according to its established system.)

Why was this post closed


safety of carbon fiber bonded to aluminum fork crown

Question: I recently experienced the failure of the carbon fork on my 2001 K2 Mod3 road bike at 20 miles per hour. Yes, I was injured. My question is the bonding agent that secures the carbon fiber fork to the aluminum fork as strong and durable as the carbon fiber or the aluminum. Also I have been told by a bicycle manufacturer that the workable lifespan of "high performance bikes to be less than 10yrs, which seems to not agree with the article on lifespan of carbon fiber bikes that gives them an unlimited lifespan. I have some concern because I like to purchase my bikes slightly used thinking I can afford a much nicer bike. Example, I just purchased a Serotta Legend Ti with carbon forks & seat stays, hardly used for $3000 but am now somewhat nervous about material failure. Whats one to do to know if a bike is safe?
Comment: One question at a time and not enough information.  How did the fork fail?  A manufacturer - which manufacture?   What article?
Answer: Carbon fiber is a bit tougher to determine the safety of than steel or aluminum (where a thorough visual inspection normally reveals the serious flaws, along with checks of headset tightness and what not) - aside from a thorough visual inspection for cracks and damage all around, you really need a professional evaluation. Bikeradar has some tips for inspecting carbon fiber bikes - key points are bonding areas and essentially places where stress builds up and making sure the bike hasn't been crashed before. There are plenty of guides on buying used bicycles online and safety checks to perform on them.
As for lifetime, especially in the case of a high end carbon fiber bike, the lifetime is a function of how much it has been used. A crash can do a lot more damage to a high end carbon fiber bike than to a lower end steel/aluminum bike (due to likely higher speeds and weight savings). There was a previous question here which highlighted the lifetime of carbon fiber bikes (especially forks), which you should read. In particular, the article by Zinn is useful.
Answer: You can do a thorough inspection of the bike and components, including a tear down.  I have only ever bought one bike used.  After I did, I tore it apart down to the frame and inspected everything.  I ended up replacing a wheel because of cracks around a spoke hole on that rig.
As far as mixed material forks, that is a pretty common practice.  I don't have any specific numbers to support this, but I haven't ever heard of the failure rates for such forks being different than all carbon forks.
As far as "carbon" is concerned, there is as much variation out there in the market as there is with anything.  Years ago, the first carbon frames were assumed to be a bit more disposable and mainly for the elite race crowd who were replacing their bikes every other year or so anyway.  There are currently companies making downhill race bikes from extremely thick and durable carbon that will take the same beating an aluminum frame would and last just as long.  I'd say a place to look is at the company's warranty.  Many companies are now offering lifetime frame warranties, even on their carbon frames.
Comment: A lifetime warranty is usually until the product reaches it's end of life through use, which if they state a workable life of 10 years and you get 13 (as per the question) you're warranty will have run it's course.
Answer: I should quickly define a few words to avoid ambiguity in what follows:
Strong ==  Force / Cross-Section Area.
Durable == Strain (deformation) energy in the material before failure.
Endurance Limit ==  Asymptote where alternating stress does not decrease with additional load cycles

To your question:  Bonding Agent
The bonding agent is (in theory) as strong as the carbon fiber epoxy, but structurally, it is the weakest over-all material in the joint.
Carbon Fiber  >>  Aluminum  >>>  Bonding Agent or Epoxy
Remember, carbon fiber is composed a the cloth-like carbon fiber soaked in an epoxy (another bonding agent), effectively gluing carbon sheets together. At the macro scale, the carbon fibers transfer most of the force and the epoxy is just there to hold the carbon fibers together.  At the micro scale, only the epoxy and
bonding agent are bonded. I cant speak with respect to specific bonding agents or bike makers, but from an engineering perspective, the bonding agent should be as strong and durable as the carbon fiber epoxy, though weaker than individual carbon fibers or aluminum.
While the bonding agent and epoxy are close in strength, the bonded area/agent is the weakest material in the joint: At the micro scale, this is where deformations (strain) and stress are largest and failure begins at the macro scale.

To your next question:  Life Span
Materials with an endurance limit have an unlimited fatigue life (for a max rider weight) in theory.  Carbon fiber and Steel have an infinite fatigue life... In theory.  If stresses are below the endurance limit, the material does not weaken and can undergo theoretically infinite stress/load cycles.  Other non-ferrous alloys like Aluminum do not have an endurance limit, the material continues to weaken with additional stress/load cycles; eventually they are destined to fail- bike makers design aluminum frames to last far in excess of the what someone might ride during the bikes useful life.

In reality, many things affect fatigue life and strength in materials.  Scratches (even small ones) are a Very common cause for significant failures to develop/propagate in all materials.  Alloy frames suffer from incomplete welds or poor heat treatments during manufacture as possible causes of failure; typically alloy failures are not catastrophic (and safer) because the metal bends (giving obvious and ample warning) before breaking in half.
Carbon fiber is increasingly sensitive to impacts.  Where alloys bend, carbon is brittle and might crack or de-laminate (where layers separate, first at the micro scale, leading to macro scale cracks and failure.  As cracks develop, surrounding areas take more load, causing the existing crack to widen.  Carbon (and composite failures in general) are more catastrophic in nature because carbon is more brittle and there is little warning or time before the carbon breaks in half.  Voids (small air pockets trapped in between carbon layers) during manufacture, if present, are likely causes of failure.  UV radiation and extreme heat, or oils and solvents can degrade the epoxy/bonding agent.
In practice, normal bike use leads to failures - ie. Handling the frame with dirt and sand on it, A rock kicked up from a tire impacts the frame, You fall, The frame gets scratches in the car or on the rack, Take your pick.  So while the materials themselves have an infinite fatigue life, life happens and failures
happen; bike makers continually tweak their designs and techniques to avoid real-life failures but they happen.

In buying a used bike, inspect it in person, and gain trust that the owner took good care of it.  I bought my bike used as well - personally, I think thats the way to go - but there is some level of unavoidable risk.
Answer: The answer here is not about the strength of carbon vs aluminium but with bonding.  I worked with (aftermarket) K2 Carbon mountain bikes in the late 1990's and they had aluminium dropouts at the rear (to hold the rear wheel on) bonded to layered carbon rear swingarm.
During testing for one of my products we mounted disk brakes to the dropout but suffered failures where the dropout would unbond from the carbon - this was due to excessive heat from the disk brake that weakened the "glue" bonding the carbon to aluminium. We redesigned the product to prevent heat transfer.
So answering the question: the bonding agent for layered carbon to aluminium has a time and heat based weakness - however, the good news is that they can be rebonded so long as they survived the crash.


What is the difference between axial compressor blades and centrifugal compressor blades?

Question: Is there a particular difference?  The way they're overhauled is the same ? (I mean do we use the same overhauling methods ?)
Answer: The blades are shaped completely differently. Typically a centrifugal compressor is one solid piece that looks like a turbocharger and an axial compressor is a flat disk that looks like a fan with individually manufactured blades inserted, though axial compressor disks with integral blades "blisk" is starting to be used. Here are compressor pics that show how they are used:
Two stage radial/centrifugal compressor circled (with a three stage axial turbine following)

Fifteen stage axial compressor

A radial compressor can usually generate higher pressure in a single stage so it's usually simpler, while an axial compressor is easier to stack in multiple stages to get much higher pressure ratios.
Answer: The main difference is in how they operate, vs how they are maintained. Flow through a centrifugal compressor is turned perpendicular to the axis of rotation, while air in an axial compressor flows parallel to the axis of rotation.
Answer: Axial blades are airfoils that compress air by forcing it aft into a converging space via downwash the same as a wing generates lift by downwash.  Efficient, but sensitive to angle of attack and aerodynamic stall, like a regular wing, so therefore sensitive to flow disruptions.
A centrifugal compressor is spinning duct that forces air into a converging space purely by centrifugal force imparted to air within it as it spins.  Less efficient, but relatively insensitive to flow disruptions and way easier to make.
Comment: Axial blades do not have to be airfoils.
Comment: Do you know of a turbine engine with flat ones?


Is there a tool that tells me if my transfer has been used by others in a ring signature?

Question: Is there a tool that, given a tx hash and/or a specific output, can search through the blockchain to see if it's been used as input in other transfers? This would preferably not be a web service but something I run offline on my own copy of the blockchain.
Answer: You can search the blockchain for your outputs with a given address and view key, but I'm not sure if you can actually determine if a given output has been used in other transactions.
Here are some useful tools.

lmdbcpp-monero
transactions-export


How to randomly pick instanced instances in Geometry Nodes

Question: I'm making a procedural building with geometry nodes where the walls are instanced on a generated profile from a grid and those instanced walls are being instanced vertically along a mesh line. While the 1st instance on points node is able to randomly pick mesh from a collection that contains more than 1 wall mesh, I can't find a way to randomize the walls being picked in the 2nd instance on points node which dictates the height of the building. I would also like to avoid using the realize instances node. Any help would be appreciated.
Comment: pls show us your nodes tree or upload blend file...thanks.
Answer: Basically, you would only have to pass a random value when instantiating the objects in the individual floors, so that the objects from your collection are selected in different order.
What I do in this example:

First I create a floor from single points of a subdivided quadrilateral curve.

I multiply this floor with Instance on Points along a mesh line in the height and realize the points with Realize Instances (The Realize Instances node is used here only to achieve the points for instantiation, but not to transform the individual objects to be instantiated).

Then I create a selection/mask with which I can separate the lowest floor from the upper floors.

When instantiating the upper floors with the node Instance on Points, I select the objects from the collection using a random value.

Here is the blend file:
Comment: I've tested it and it works quite well.


How can I extend existing 8 x 8 pilings?

Question: I am converting a deck to a boat lift. I have 8x8 sqaure pilings built at deck height, 2.5 ft above water.  I knew it might get converted into a boat lift so they are all in the correct location. But I need to splice/add appx 12' vertical to the existing pilings.  The joint will be below the deck height and will not show so asthetics are not an issue. Current choice is cut both pieces as flat as possiible and bolt metal plates on the outside.  But I have also considered dowels (which would need to be 2" dia.) or would be interested in some other type of joint.  Realize as far as tools go, that any joint will have to be cut into existing pilings about 1.5 ft above water level.
Comment: Is all the load vertical with the lift between two pilings, or is the lift cantilevered out?
Answer: Maybe a timber post extender would work.
That, or steel plates bolted to the outside like you suggested.


2.4Ghz microwaves have a 12cm wavelength. How do microwave ovens leak radiation, since any gap in the shielding is much smaller than that wavelength?

Question: I've read (I think on wikipedia, but I can't find the reference) that microwave oven leakage is often due to faulty seals on the door. Given that any gap in the door is going to be far smaller than 10% of the wavelength, how is it possible for the microwaves to leak through? Shouldn't the Faraday cage function perfectly?
Comment: related: http://physics.stackexchange.com/questions/141562/diffraction-by-small-holes/141713
Answer: Two things are going on. First - the conductivity of the shielding of the microwave oven is "only so good": the skin effect in particular results in the electrical currents running in only a very superficial layer of the conductor, and this means there is some phase lag (and incomplete reflection, i.e. some transmission of power).
Second, gaps do occur. In a well designed microwave the gaps have compliant conductive seals; but if these lose their springiness I can see how currents flowing around the gap will result in re-emission of microwave energy. You don't need a 2D opening: just a gap that is "long and thin" is sufficient to act as an antenna. Where "long" is a few cm (1/4 of a wavelength). See for example this diagram:

from http://www.interferencetechnology.com/in-situ-emc-testing-using-surface-current-sense-wires-1/ which describes some of the techniques behind using such an "antenna".
Comment: Any estimate of transmission due to non-infinite skin loss? My guess is that that's completely negligible compared to radiation from apertures.
Comment: @DanielSank there is a fairly comprehensive study of transmission through perforated plates at http://ipnpr.jpl.nasa.gov/progress_report2/II/IIO.PDF - this probably would help answer your question. "It's pretty small" as you expected, but depends on many factors.
Answer: The gap in the door is smaller than a wavelength - but the length of the door is conveniently a few wavelengths. So the sharp metal edge of the door re-radiates the energy, like an antenna, through the gap.
Microwave ovens have some special structure on the door edge to create a reflection in the wave and block and leakage - sorry don't know the details, was never into antenna design
Answer: The edge of the doors and area around the door on the microwave oven side when closed during operation act like microwave notch filter. The notch filter is tuned for 2450 Mhz.
Any deformation of the door by a dent of a insignificant amount could cause the microwave to leak rf energy as it changes the notch frequency. If you are in front of it at the time...God help you. A notch filter blocks a small range of frequencies but passes frequencies above or below.
One experiment you can try that is pretty cool. Put a DECT 6.0 cordless phone inside the oven (without turning on the microwave obviously).  Use the base unit to find the phone ...it will ring inside the closed microwave oven. The DECT 6.0 phones operate in the 1.924 GHz range..


Mongodb crash after WiredTiger Cannot allocate memory error

Question: I am using MongoDB (3.2.6) as storage for my application and since a couple of weeks MongoDB started to crash usually every 1 or 2 weeks. The crash seems to come from an issue during WiredTiger memory allocation here is the full stacktrace of the last crash:
2016-10-09T18:25:36.389+0200 E STORAGE  [thread1] WiredTiger (12) [1476030336:325695][993:0x7f559c19a700], file:index-1108-8065571460375661294.wt, WT_SESSION.checkpoint: memory allocation of 18624 bytes failed: Cannot allocate memory
2016-10-09T18:25:36.547+0200 E STORAGE  [thread1] WiredTiger (12) [1476030336:422567][993:0x7f559c19a700], file:index-1108-8065571460375661294.wt, WT_SESSION.checkpoint: checkpoints cannot be dropped when in-use: Cannot allocate memory
2016-10-09T18:25:37.347+0200 I COMMAND  [conn10793] command admin.$cmd command: ping { ping: 1 } keyUpdates:0 writeConflicts:0 numYields:0 reslen:37 locks:{} protocol:op_query 208ms
2016-10-09T18:25:37.386+0200 E STORAGE  [thread1] WiredTiger (12) [1476030337:254969][993:0x7f559c19a700], checkpoint-server: checkpoint server error: Cannot allocate memory
2016-10-09T18:25:38.448+0200 E STORAGE  [thread1] WiredTiger (-31804) [1476030337:484838][993:0x7f559c19a700], checkpoint-server: the process must exit and restart: WT_PANIC: WiredTiger library panic
2016-10-09T18:25:38.677+0200 I -        [conn10894] Fatal Assertion 28559
2016-10-09T18:25:38.994+0200 I -        [WTJournalFlusher] Fatal Assertion 28559
2016-10-09T18:25:38.994+0200 I -        [TTLMonitor] Fatal Assertion 28559
2016-10-09T18:25:40.978+0200 I -        [thread1] Fatal Assertion 28558
2016-10-09T18:25:41.207+0200 I -        [thread1]

The server it's running on has 7Gb RAM and is exclusively used for Mongo.
free -m
             total       used       free     shared    buffers     cached
Mem:          6811       6140        670          0         28        634
-/+ buffers/cache:       5478       1332
Swap:         2047       1009       1038

Several dbs are running on it with a total size around 925MB while WiredTiger cache status is :
db.serverStatus().wiredTiger.cache
"bytes currently in the cache" : 969927022,
"bytes read into cache" : 800513540,
"bytes written from cache" : 1349774879,
"maximum bytes configured" : 3221225472,
[...]

According to the documentation, WiredTiger should use by default

60% of RAM minus 1 GB, or [...] https://docs.mongodb.com/manual/faq/storage/#to-what-size-should-i-set-the-wiredtiger-cache

Based on 7GB RAM we get ~ 3.2Gb so it seems good.
Now how can 925Mb databases can bust a 3.2Gb cache ? I know that we have to take the indexes into account but even by indexing every fields (which is not the case) it should not fill the 2+ Gb remaining ? Last crashed occurred yesterday so the provided stats are just after a fresh restart. Could it be that the way I'm using Mongo a memory leak occurs somewhere slowly increasing the memory consumption ? I may completely miss the point as I am new to Mongo so any leading advice or article would be a relief.
I found this issue : https://jira.mongodb.org/browse/SERVER-24408 but it does not provide any further explanations.
EDIT 12/10:
3 days later the cache status is the following :
"bytes currently in the cache" : 1319874144,
"bytes read into cache" : 1054001990,
"bytes written from cache" : 8936911271,

Comment: What's the `SHMMAX` set to on the server?
Comment: From ipcs -lm > max total shared memory (kbytes) = 8388608
Comment: @DessDess We are having this issue, did you find any solution or workaround?
Comment: @Orgil Unfortunatelly no, I ended up scaling up the server and the crashes disappeared, so it was definitely a memory issue but the reason remains a mistery
Answer: Potentially the unix box is forking the process from your application and causing a duplicate process to try to allocate the same amount of memory but crashing when it does so.


What can motivate people to write and share their personal stories?

Question: I want to motivate people, who do not already write, to write about their lives and publish their stories on my new web site. What would motivate someone to write and share their personal stories?
Comment: Would you anonymize the stories? The Internet being forever this would be highly desirable.
Answer: A pitch
An editor of the resource writes an article on some topic, a topic that resonates well with the readers, so everybody is eager to share his/her own experience. This approach is good for very short stories, but not as good if you want your contributors to write multiple pages.
Answer: The biggest motivator is going to be example. If you have stories of your own, or stories other people have told you (and are willing for you to circulate), others are more likely to participate.
You could also try creating a prompt to encourage people to write the sort of stories you're looking for. Look at the way other websites do this (including the writing challenge on the Meta of this SE).
It's going to be difficult - near impossible - to motivate people to be the first or second contributor on a new website, particularly one involving personal stories. But if there's already a "gang", new people are going to be more inclined to join.
Answer:
I want to motivate people, who do not already write, to write about
  their lives and publish their stories on my new web site. What would
  motivate someone to write and share their personal stories?

Money. Publicity. Connections. A platform.
If you are promoting yourself, you will have a bit of trouble with your stated goal. If you are hoping to promote others, they will write for you.
Answer: "What do people care about?" People will always share stories about what they love, care about, or have strong feelings toward/against.
"Can they relate?" Sad and/or very personal stories have a weird way of drawing out stories from others. Some people want to show you that you're not alone, and others feel safe enough to release a burden of their own by confessing their own story.
"Does your experience confirm/reject a bias that people tend to have?" People will always want to jump in and tell an opposite story or a confirming story that they've experienced, either to support or correct.


darcs help breaks my shell

Question: I have just installed darcs 220.127.116.11. When I type darcs help, sth less-like shows up. When I dismiss it with q it goes away but I don't get prompt and can't execute any commands. C-c doesn't work either. I am using bash on gentoo.
Answer: I have no idea what darcs is, but when bash fails to return to the prompt that some command as part of a pipeline is still running.  For instance if you ran:
<code>cmd | less
</code>
And exited less, but cmd did not die from a broken pipe, then cmd would continue to run and bash would continue to wait until it exited.  It also might not respond to signals and keypresses if it didn't have access to the tty.
You will need a second terminal to check and see if any processes are hanging around after trying to dismiss darcs.  Sometimes Ctrl-Z or Ctrl-\ will work where Ctrl-C doesn't. There is probably no fix other than to look at darcs and figure out why it is not dimissing like it should.  If it is really launching less, then maybe typing ">" before "q" will make it exit properly.
Answer: In this situation (terminal messed up, can't see what you're typing) the "reset" command will often fix things.
I would try again with a newer darcs, eg version 2.3 released today. If the problem still happens, you can probably change this behaviour - see the darcs manual. Otherwise, folks on the #darcs irc channel will be able to help.

darcs help breaks my shell


Check a program/script is active and running properly

Question: I can't find guidance anywhere on how, if you're running a (say python) script permanently in Raspbian on a headless RPi, to check periodically it's running ok.  I've researched reporting on running scripts using ps, but feel like I'm just reinventing the wheel badly.  Grateful for advice on anyone who has addressed this effectively.  I'm guessing a separate python script run periodically with cron should work, but I don't know how to confirm if a specific other script is running or might have crashed but somehow remained open..  Very grateful for advice.
Comment: I've started a discussion in [raspberrypi.org](http://www.raspberrypi.org/forum/viewtopic.php?f=37&t=72927) about this - there are a couple of other possible solutions there.
Answer: Supervisor may be of help . You can start it at init time and declare which processes you want to monitor. Given that it's written in python you may find it easier to use than, say, daemontools.
Answer: AFAIK there is no way to know if a process is running ok or just hung but still there using existing tools.
I guess you have to find a way to check it, you can write down a log with the last time the process did something, then you check this log from an external program (lets use cron) and if the last time stamp is too old, you know something is wrong.
You can also make your program open a socket and respond to some sort of ping, then again from an external program you try to ping it from time to time.
If you want to try a ping-able program in python you can try this simple snippet:
# Echo server program
import socket

HOST = ''                 # Symbolic name meaning the local host
PORT = 50007              # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #create the socket
s.bind((HOST, PORT))        #bind socket to port
s.listen(1)                 # start listening
conn, addr = s.accept()     # if someone connects
print 'Connected by', addr
while 1:
    data = conn.recv(1024)  # whenever they send data (up to 1024 bytes)
    if not data: break
    conn.send(data)         # send through the same socket what they send (make echo)
conn.close()

Then the client to ping it should look like the following (this is the program you should call from a cron job)
# Echo client program
import socket

HOST = '127.0.0.1'        # The remote host (in this case local)
PORT = 50007              # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send('Hello, world')    # we send some text
data = s.recv(1024)       # and we should receive the same text
s.close()
print 'Received', repr(data)

Extracted from HERE
Comment: Making a script ping responsive sounds useful. How would this be achieved.
Comment: @geotheory : edited my answer


Currency exchange (USD to NTD and HKD) in San Francisco

Question: Where can I buy NTD/TWD and/or HKD in San Francisco, preferably around Union Square? If there are such places at all. And is it more reasonable to do so rather than exchanging USD to NTD/TWD in TPE airport and also exchanging USD to HKD somewhere in Taipei?
Comment: Currency exchange in the US is generally terrible, you'll get better rates in Taipei & Hong Kong.
Comment: See https://travel.stackexchange.com/q/1911/11491 and https://travel.stackexchange.com/q/10/11491
Answer: You can probably order those from your bank. My bank, the Bank of America, for example, offers same-day shipping of foreign currency if you order before 2pm, which you could then pick up in the closest BoA financial center.
If you have an account at a major bank, it is likely that you'd be able to order HKD and NTD and have them delivered on the same or the next day. Also, banks usually have better rates than currency exchange stores. (Since you're asking here, I assume you're not in a hurry, right?)
Comment: In most banks exchange rates for cash are terrible.
Comment: @jpatokal The right answer is definitely "don't do it", but if the OP insists (or has some special needs)...


Can deleted answers be down-voted?

Question: An answer I deleted immediately after posting has been down-voted.  Is this possible, or did the down-vote occur in the split-second before I deleted it?
Answer: No
If a user that can see deleted posts tries to downvote one, they will get the message:

This post has been deleted; deleted posts can't be voted on

However, due to a known bug horrible design choice in the system, the system will sometimes automatically give downvotes, which is what probably happened here.
TL;DR

If you post a very short answer with no explanation, there's a good chance a system bot will flag it as "potentially low quality" for users to review.
if that flag is marked helpful, the system will cast a downvote on the post.
When your answer was deleted, the system went "Ha! That answer was deleted. Clearly I was right about the flag." And marked it as helpful.

Soooo... I guess don't delete posts immediately after posting them? It's also a good idea to add an explanation along with your answer to avoid having it marked as low quality.
Ideally, you shouldn't need to worry about that, but that feature was designed with Stack Overflow in mind (where it makes more sense), and the chances of us having it fixed to be non-stupid for this site are slim to none.
Comment: OK, that sounds plausible.
Comment: @SmileAndNod still, the fact that they're using smartphones to post a question/answer doesn't mean that they should get a free pass from quality check...
Comment: @AndrewT.  I deleted that comment because I guess it was unclear. My point was that "deleting a post and editing it while deleted" is one of the few online/incloud options I know of for drafting a high-quality post. Time and accessibility issues such as eye-sight and keyboarding ability are sometimes factors.

Can deleted answers be down-voted?


Grey mushroom cream sauce - why so dark?

Question: I've attempted making an Alfredo sauce many times in the past: With flour+butter, without, many different recipes that none have achieved an actual white color. The mushrooms and onion tint the whole sauce in this grey shade which isn't very appetizing. Any tips or tricks for a sauce that's actually white?
Thanks.
Comment: Are you cooking your mushrooms in advance of adding them to the sauce?
Answer: You don't say how you prepare the sauce, and Alfredo does not contain mushrooms (or flour, or onions). But if you are simply pureeing button mushrooms, then no, there is no way to make it any other color. The mushrooms have black gills, and they will color the whole white sauce.
In theory, you could try removing the gills from button mushrooms before cooking a sauce. In practice, you will probably have enough pieces remaining to give the sauce a light greyish tint.
You can use a different type of mushroom, one without black gills. Porcini should work. Of course, you'll end up with a different taste, and porcini are not a staple in every supermarket. But if you insist on a white sauce, this is the way to go.
Another option is to just eat it as it is. Humans need some time to get accustomed to visual stimuli which are not expected in a given context. But a sauce made with mushrooms, onions and cream is super tasty. After you have eaten it a few times, you can learn to associate it with "good", not "unappetizing". But I guess the success of this method will vary between people.
Comment: Could she remove the gills? I asked if she was pre-cooking the mushrooms because I though that doing so would let the moisture leach out and then be reabsorbed into the mushrooms so that, when added to the cream sauce, it wouldn't color it... or, in fact, the browning of the mushrooms would give the gravy a browner color, which is more "normal" for gravy.
Answer: What I have done to not get the gray colour is:

Fry your button mushrooms in butter, until soft adding a bit of salt and pepper.
make a Béchamelsauce with butter (1 Tablespoon),flour (1 Tablespoon) and milk (1 Cup)
Once your sauce is done, take it off the stove and stir/fold in the mushrooms

Depending on the amount of butter you used for the mushrooms you might get a slight colour change, but it should be minimal. If you really feel like it, you could first pat the mushrooms dry to minimize the colour transfer.
Béchamelsauce has the ability to intensify any ingredient extremely well, but does not keep it's nice saucy look well for very long, so the secret here is make it right before you eat.


Can I convert multiple point loads into a single uniform distributed load?

Question: I have a beam that has a given limit of 1690 lbs uniform load for a 24" span. I will be subjecting this beam to multiple point loads at different locations on the beam. In order to determine if the loads will exceed the beam allowable limit (1690 lbs) I was wondering if I could add up all these point loads into a single uniform load to compare to the load allowable. Is this possible?
Answer: An easy way is to back-calculate the S, section modulus of the beam, and its bending strength then you can verify if it will support your set of loads or any other load.
$$M = S*\sigma_{b .max} = wL^2/8=1960*2^2/8 = 980lbs.ft$$
Therefore you calculate the combined moment of say n point loads P1, P2, P3...Pn separately and add their moments to check if it adds up to less than 980lbsft.
For each individual load, F, the moment is
$$M_{n \max} = F_{n}ab / L  $$
Where a and b are the distance of force Fn from the supports.
And sum of all these moments must be less than your beam's max allowed bending moment.
$$\sigma M= M1 +M2+ ..+Mn <980 $$
Comment: Thanks for the response. So here's what I did. The beam is a 24 in cantilever. I used the max moment equation for a cantilever with distributed load: (wL^2)/2 to find the limiting value. I obtained 486720 lbs-in.  I then added up individual max moments using the formula: wL. The moments sum up to 1533.88 lbs-in. The process above makes sense but the moment I get seems so far below the allowable, its odd. Additionally the max moment is given by the manufacturer as 5070 lbs-in. What do you think might be the discrepancy?
Comment: @Ryan C, my be they based the bending strength of the beam on other criteria such as connection limit. how is it connected. or my by it is suppoeted by a post or some plate. can you draw a sketch?
Answer: Your design is governed by the moment, the equivalent uniformly distributed load, $$ W = \frac{2*M}{L^2} = 17.6 lb/in$$
If you want to place multiple point loads on the beam, you should sum all moments due to the point loads, then compare it with the limit given by the manufacturer.


Finding minimum in PRAM model

Question: Show that the minimum of $n$ elements stored in an array can be found in a time in $O(\log(n))$ using $O(n/\log(n))$ processors assuming an EREW-PRAM machine is given.
Comment: Can you tell us why you reversed [xskxzr's changes](https://cs.stackexchange.com/posts/117152/revisions)?  They look useful to me.  Was that unintentional?
Answer: Let us start with a solution using $n$ processors and then we optimize the solution to use $O(n/\log n)$ of them.
Assume first that $n$ is a power of $2$, i.e. $2^k$ for some $k \in \mathbb{Z}$. Imagine a perfect binary tree where the leaves are the elements of the array. In each step we will process one level of the tree in a bottom up manner, where for each node in the tree we will compute the minimum of all elements contained in the leaves of its subtree and write this minimum in the node.
In the first step each node represent one element and hence is the minimum of it self. Now in each further step we go one level up in the tree, half of the processors retire and the other half, each will be responsible for one node. Note that the minimum of leaves in a subtree rooted at some node, is the minimum between the minimum of elements in its right subtree and the minimum of elements in its left subtree. Hence, a processor responsible for a node $M$, it only compares the numbers written on the left child and the right child of this node and write the minimum between them in this node.
When we reach the top of the tree, we will have exactly one processor that will compare the values written in both children of the root and write the minimum of them in the root.
Since the depth of a perfect binary tree of $2^k$ leaves is exactly $k$, the algorithm finishes in $\log n$ steps. Since we started with $n$ processors and the number of used processors kept cutting down, $n$ processors are enough for the whole job.
Now assuming $n$ is not a power of two, then there is a $k$ such that $n < 2^k < 2n$. Try to prove this claim as an exercise. Now using this claim, given an array of $n$ elements, we can use $2n$ processors to build an array of $2^k$ elements in constant time by adding very large numbers to the array (adding numbers equal to the first number of the array suffice since we are looking for the minimum) and run the algorithm as described above.
Now we optimize the number of processors using a preprocessing technique. Assuming we started with $c \cdot n/ \log n$ processors for some constant $c$ (2 is enough here). Let us start by completing the array into a power of two as above and cut the array into chunks, each of size $\log n$. We will have at most $O(n / \log n)$ of them. Each processor can find the minimum in a chunk sequentially in $O(\log n)$ time. Let us build a new array $A'$ of length $O(n / \log n)$, where the processor responsible for the $i$-th chunk writes the minimum in the $i$-th position of the array. We end up with an array of size $O(n / \log n)$ and with $c \cdot n / \log n$ processors we can proceed as above in $O(\log(n/\log n) = O(\log n)$ steps.
In total we get an algorithm with $O(\log n)$ time and $O(n / \log n)$ processors.

Finding minimum in PRAM model


Older gas stove is hot to the touch

Question: My new apartment has an older gas stove--I'm guessing its from the 70s? All the markings are gone. Anyway, on the stove top there are two hot spots where the pilot lights are underneath. It's hot to the point where you cant hold your hand there for more than a second or so. The pilot lights are not huge, I'm estimating a half inch tall, but there is zero insulation. There is just a thin metal piece in between the stove top and the pilot. I'm assuming standards were a little more lax 50 or so years ago. It seems like a fire hazard to me. What do you guys think?
Comment: What I would wonder about is if this old stove has a heat sensor on one or both of the pilot lights that shuts off the gas inside the stove if a pilot light ever goes out. Does this stove have such a protective system? Gas fired water heaters have this, but I am not sure stoves do. It could be that since stoves are operated manually, the assumption is that should one or both pilots go out, the operator would notice. An unlit pilot may have such a low flow rate that gas levels cannot accumulate. We have cooked on an electric range since the mid 1970s; don't remember how gas stoves used to work.
Answer: This is not an improper fire hazard. In operation the stove top near a burner will get a lot hotter than that.
You are not supposed to lay flammable materials on top of the stove, but I doubt it would start a piece of paper on fire. You could place a 1 inch square of paper towel over the hot spot and see if it would ignite.
EDIT
AFIK modern gas stoves have electronic spark igniters (they do not have standing pilot lights) so one cannot compare modern stoves to old ones which do have a standing pilot light. I don't think a hot spot over a standing pilot light is an out of specification condition.
Comment: In the past all gas stove tops had standing pilots. Yes they get hot over the pilot. Is this normal yes. You would create the same amount of heat with a match, thin metal will quickly heat up above the match will it be two hot to hold your hand on yes this was the norm for many decades prior to electronic ignightors.
Comment: I think the question is more than just "is this an imminent hazard?" but rather "Is this **normal** for this type of stove?"
Comment: That is my understanding about modern gas stoves as well, Jim. It makes sense to me that there should be warm spots above the pilots but hot enough to where you can't touch it seems a bit much.
Answer: It is not a hazard, the complete top of the range is considered a cooking surface and that would be totally normal if the length of the standing pilot flame is as you posted and the actual cap is intact on the burner assy. UL is who determines what acceptable temp ranges are for products. From what you described, that is the standard for the front and rear burner assy with a standing pilot.

Older gas stove is hot to the touch


Is there a manual/tutorial describing how to automate baker payouts when using kiln?

Question: I can't seem to find any good documentation on working with and troubleshooting payment automation.
Comment: Nobody can help....
Answer: Kiln is currently the easiest approach to running your own baker in the Tezos ecosystem. It is early in it's development and iterating quickly. But the focus clearly is to help people bake for themselves; as such there is no real need to automate baker payouts to others.
If you are using Kiln to run your own delegation service you will likely need to find a separate solution for payouts for the foreseeable future. Some example solutions can be found in the answers to
Looking for a payout script or software
Comment: I want to learn how to use the script but don't have time :(
Comment: Got my baker running via command line finally! the tezos gitlab website is really outdated...


Changing WPA supplicant configuration on dd-wrt

Question: I installed dd-wrt on my Fonera (old model), and I'm trying to use it as an ethernet-wlan adapter for a PC without WiFi (using it in client-mode).
I've configured everything following a step-by-step tutorial, and it didn't work. After that I entered with ssh, and found the configuration file (in /tmp).
If I change the wpa_supplicant configuration (remove most lines, leave only the SSID and WPA-PSK), it works. The "wrong" configuration seems to be the first line of the configuration file: "ap_scan=2".
The problem is: when I reboot it, it reads the old configuration, and I have to ssh again, and change the temporary configuration.
So, what I'm trying to do now (without success so far) is one of the three:

change the non-volatile configuration, and make it persistent.
find a way to configure WPA2 security in the web interface without writing extra lines in the config file
use some kind of script on system start (after everything else), which kills wpa_supplicant, writes the right config file, and starts it again.

I can't write to /etc because it's read-only, and I can't simply remount it read-write. I've read something about enabilng JFFS but I couldn't really understand how it works.
Any idea?
Answer: You can simply put your script in Administration → Commands → Save Startup Scripts


Applying Lowpass (LPF) and Highpass (HPF) Filters to an Image in Frequency Domain in MATLAB

Question: What I want is simply to apply low pass and highpass filters to an image in the frequency domain. Does MATLAB image processing toolbox have any commands for this?
Comment: Did you take a look into imfilter?
Comment: Is it a requirement that you use the image processing toolbox? You can always just zeropad --> fft --> multiply --> ifft.
Comment: conv2 can also be helpful
Answer: You can use spatial Methods using Convolution (conv2 and imfilter).
You can do it in Frequency Domain using the Convolution Theorem property using fft.
Usually, In Image Processing, all filters are built using Gaussian Kernel.
High Pass is basically subtracting Low Pass filtered image from the original image.
You can create the Gaussian Kernel manually or using fspecial.
For fast implementation, have a look here - Fast Gaussian Blur.
P.S.
For people who use conv, be aware that conv is using conv2 and you can reduce the overhead by using it directly.
Answer: I spatial domain, simply convolve masks like averaging, or guassian with image to get low pass filtering:

LowpassMask=(1/9)*ones(3,3); % Averaging mask of size 3*3
  Filtered=conv2(image,LowpassMask);

for high pass filtering, either convolve it with a differntiator mask like sobel or subtract already low passed image from the original image:

Sobel=[-1 0 1];
  Filtered=conv2(image,Sobel);

However, since you mentioned frequency domain filtering, I explain it a little bit also. In frequency domain you can take 2D FFT of the image and then mask part of it based on low-pass or high-pass filter you desire, to get the 2D FFT of the image use, fft2, then mask central parts for low pass filtering or corners for high-passing filtering.


What are some of the best books on complex systems and emergence?

Question: I'm rather interested in getting my feet wet at the interface of complex systems and emergence. Can anybody give me references to some good books on these topics? I'm looking for very introductory technical books.
Comment: @Dilaton. Perhaps it would be better to create one post for book recommendations _of complex systems,_ and a separate post for book recommendations of _information theory?_ It might not be constructive to keep them together. Also please crosscheck with the book recommendation topics that Phys.SE (and sister sites) already have.
Comment: Do note: http://physics.stackexchange.com/review/suggested-edits/4609
Answer: Maybe these three lectures about emergence could be interesting to get a first overview of the topic. Therein Prof. De Deo explains for example that emergence has a lot to to with what new phenomena can occurre when coarse graining (or renormalizing) microscopic degrees of freedom of a large system to obtain an effective (possibly including emergent phenomena) macroscopic description.
Background material to understand and deepen the wisdom about the concepts presented in these lectures can be found here. Among these resources is this book titled "Statistical Physics: Statics, Dynamics and Renormalization". It explains not only the statistical mechanics basics, but from the authors "interdisciplinery" point of view it includes topics such as renormalization, self-organized criticality complexity, and other things which are useful and important to understand emergence (as explained in the video lectures).
I've just read some chapters of this book, it is slightly technical and very accessible, and the style of writing makes me wanting to read the whole thing.
Comment: Hello, could you give a new link for the "here" link? (The second one)
Answer: I like the book Energy Landscapes by David Wales. It deals with various classes of complex systems (clusters, glasses, proteins) in the context of chemistry.
I want to add - emergence is fraught with flaky ideas; a lot of appeals to ignorance are rooted from the idea of irreducible complexity. So because we can't, say, predict the weather from $F=ma$, this means that God makes it happen.
If you're interested in something "bigger" than the chemistry of complex systems, I like the work of David Bohn (say, The Undivided Universe).
Answer: An Introduction to Complex Systems is a recently published (2019) book by Tranquillo that has been very well reviewed in the Nov. 2019 Physics Today issue:

The text provides a useful overview of complex systems, with enough detail to allow a reader unfamiliar with the topic to understand the basics. The book stands out for its comprehensiveness and approachability. It will be particularly useful as a text for introductory physics courses.
  [...]
  Tranquillo has written a thorough textbook that gives a useful introduction to complex adaptive systems as a whole field. It can also serve as a quick reference for seasoned practitioners who need a refresher on a particular subject.

Which also points out that:

math is well-integrated into the text, a reader could skim over the equations and focus instead on the prose without losing much. Tranquillo's presentation will allow math-phobes to be slowly exposed to equations—alongside good explanations—without being forced to read through proofs line by line; thus the book is a useful text for mixed-population undergraduate courses.

Which seems to make it fit very well into the "very introductory technical books" category.
Answer:
This answer contains some additional resources that may be useful. Please note that answers which simply list resources but provide no details are strongly discouraged by the site's policy on resource recommendation questions. This answer is left here to contain additional links that do not yet have commentary.

James P. Sethna is one of the leading figure in this area.
You can refer to his book without any doubt.
http://www.lassp.cornell.edu/sethna/
Answer: As how it's titled, Complexity: A guided tour is a guided tour to complexity sciences. There is no formula in the book, but it does discuss many results and give you pointers. The author is a student of Douglas Hofstadter. She has a talk here
FYI: @Chris Aldrich also shares many helpful links in Are there any theories using thermodynamics/statistical mechanics or information theory principles to modelling in ecology?


Matthew 1:19, Divorce, and Virginity

Question: In light of Joseph being called a righteous man in Matthew 1:19, does this mean that divorce because one of the two was not a virgin at the time of marriage is biblically valid?
Comment: Are you assuming Mary wasn't a virgin? The question reads that way...
Comment: I think he's assuming that *Joseph thought* Mary wasn't a virgin.
Comment: @DJClayworth Did he think that? Or did he just think others would think that?
Answer: I know of no doctrine held by any Christian tradition based on this passages that speaks to virginity at the time of marriage in relation to possible divorce. It is simply not the subject matter of the passage and drawing such a conclusion from it would be bad hermeneutics. You would need to find other teachings on previous relationships or extra-marital relationships in order to address that issue in a Biblical fashion.
If you look at other Biblical passages, you will note that basically the only valid grounds for divorce is the case of adultery. Even then it is not prescribed / required, only possible allowed.
If you look into the marriage traditions of the time, you will find that the issue of divorce was as relevant to Betrothal (engagement of sorts) as it was to marriage. A betrothal could not just be broken off for any reason, it was as good as a marriage vow as far as being binding on the parties, but the relationship was not to be consummated until after the wedding.
Mary getting pregnant during the betrothal was (barring the supernatural) obvious proof of adultery. Having committed herself to marry and be faithful to one man and entering a binding contract with him, Joseph would know he hadn't slept with her so she must have slept with another man.
With this understanding, we see that the only thing this passage could teach us about divorce is to reinforce the teaching that says adultery is possible grounds for divorce, but that it is not unlawful to NOT divorce even cases of adultery.
Comment: I like this, but you have to remember also that Joseph is basing his decision on pre-Christian rules. What he did, or what he thought was right, is not binding on Christians
Comment: @DJClayworth The entire point of my answer is that if the event speaks to anything, it is to a different topic than the one the OP was trying to apply it to. However Biblical examples both positive and negative should not be so easily dismissed for being before Christ. Christ himself and the Apostles clearly taught that the OT scriptures were relevant and binding on life for NT Christians. Certainly what we learn about God's character and what pleases or displeases him is relevant no matter what era it's from.
Answer: This is a good question.  Joseph and Mary had entered into the covenant of betrothal for marriage.  The terms of that covenant were that each would maintain purity until their wedding.  When it was found that Mary was pregnant, Joseph knew quite well that the child was not his.  The conclusion was that Mary had been unfaithful to him, even though this turned out to be an invalid conclusion.
So, the issue was that Mary was thought to have broken the covenant of marriage by being unfaithful--not necessarily that she was no longer a virgin.  Indeed, Boaz married Ruth, who had already been the wife of another.  David married Bathsheba, who had been the wife of Urriah.
So, again, virginity was not the issue per se, but unfaithfulness was.
Comment: @warren: That example would make sense and perhaps add something to the argument. The other example seems to detract from it more than build it up.
Comment: I agree with your conclusion, but before he married her David also committed adultery with Bathsheba so I fail to see how that whole situation adds any relevant veneration.
Comment: @Caleb That's true.
Comment: @Caleb - it could just as easily have been pointed-out that David married Abigail who, before he died, was Nabal's wife.
Answer: Two possible answers:

Mt 1:18 says "his mother Mary was espoused to Joseph" (KJV), which indicates they were betrothed/engaged, but not yet legally married. "Divorce" then is referring, not to a literal divorce, but to breaking off an engagement. So this passage is not relevant to the question of divorce, just to a breaking of an engagement, which everyone must agree is a matter of much greater freedom than divorce is
Until the angel appears to Joseph (v. 20), Joseph must have assumed, that if his fiance was pregnant, and knowing that he himself had not slept with her, that she must have been with another man. And yet, while other men would become enraged and make a public scene about this apparent discovery, Joseph is mindful to end things quietly - that is his righteousness - when he thinks another has wronged him severely, he nonetheless seeks to deal with matters calmly and mercifully. And his righteousness is rewarded with the revelation that the perceived slight in fact was not

So I don't think this passage tells us anything about virginity as a grounds for divorce. It seems to be about breaking off a betrothal rather than divorce proper. And even if it is about divorce proper, Joseph had good reason to suspect unfaithfulness since the engagement or marriage or relationship had begun, while a mere lack of virginity might long predate you having ever met your marital partner.
If a person had falsely presented themselves as a virgin and you married them, that might be valid grounds for divorce. But if they never presented themselves as such (either through openly admitting such a previous sexual relationship, or if they never said but you never asked), then I don't see how that is any better grounds for divorce than simply "I'm tired of you" or "I found someone who I think is better"
Comment: betrothals were not akin to our modern concept of engagement - they were as legally important as marriage, but the relationship would not be consummated until after the wedding
Comment: Your #1 is arguably misleading since it equates betrothal with engagement, and you apply our modern idea of "greater freedom" to a concept that was treated with utmost gravity and no freedom at all. This is not a valid parallel and therefore any conclusions drawn from it are also invalid. I think your second point is spot on as far as why his actions were considered righteous. I suggest you [edit] this answer to focus on that point.
Comment: A betrothal is simply a contract to get married - it may be terminated by the mutual agreement of the parties to the contract (whether we understand that to mean the couple to be married, or in biblical times it would have been their respective families.) Following the standard of Matthew 19, marriage is a morally much more serious affair, with much more strenuous moral and legal requirements around its termination.

Matthew 1:19, Divorce, and Virginity


Can E=MC2 be used when thinking about human strength

Question: As we know just because a person has more mass that doesn't mean they can lift more weight or punch harder as those actions are more about training your technique.
My story is a martial arts / superhero type and I have seen "power ratings" or rough measurements of spiritual energy like chi and chakras being used in other stories.
I was wondering if E=MC2 or other equations could be used to measure a fighters potential, not their resting energy but their max capability for single or short bursts of action .
Comment: No, $e = mc^2$ is not applicable to chemical reactions, which is what powers animal muscles. (The energy absorbed or released in chemical reactions is so small that mass is constant for all practical purposes.) As for *"or other equations"*, this is the definition of "too broad".
Comment: @AlexP Actually, E=mc2 *is* applicable (it's always applicable), but you're absolutely right that it's wrong to invoke it in the OP's context since the *m* in the equation has *noting at all* to do with the person's mass, but with the (really really tiny) change in mass in the chemical reactions involved.
Comment: @MarkOlson: There's applicable and applicable. While the equation does indeed *hold* for chemical reactions, actually applying it to compute anything useful is quite impractical.
Comment: Only if your martial arts / superhero type can convert mass into energy as part of their fighting.This will make them effectively nuclear-powered. Considering super-strength requires more energy than can be extracted from chemical reactions involved in metabolism. If there was a mechanism to convert ting amounts of matter into a power source for superhuman fighting, and do so safely, then this could provide a hypothetical basis for a martial arts superhero. As long as they don't explode!
Comment: @AlexP: Agreed!
Comment: what are u trying to hit? antimatter?
Answer: Well, maybe. Sort of.
The idea would be that when acting as a superhero your protagonist's actions are powered not by his mundane physiology, but by tapping into the (chi, etc) spiritual energy produced by his body. Probably the closest approach to this is the Star Wars midichlorian bodies, which while biological also allow tapping into the field that is The Force.
Of course, relating this to body mass has its problems. First, the unit of energy production would presumably be the cell, and not all cells have the same mass. Second, this would require assuming that every cell in all magic users has the same efficiency in producing Chi energy. Otherwise, you can get someone like Luke Skywalker who has a very high density of midichlorians and much stronger Force than others of the same size.
Alternatively, your "midichlorians" might work by actually converting the mass of the cell it inhabits to effects such as powering a fist, with a conversion rate of energy to mass consumed being some factor of the e = mc^2 equation. Since individual cells in the body are not immortal, a certain amount of early cell death due to using superpowers would be acceptable, similar to the cellular damage incurred during heavy exercise. Note that, since you are invoking "spiritual" force, the rules do not need to be exactly the same as for mere material processes.
Answer: Not really
If you know the mass of (e.g.) your arm, you can apply the equation and discover what energy would be released if the mass of that arm were converted entirely to energy.  But what's the point?  It has nothing to do with the force applied swinging that arm.  Therefore, you have a measure that's no more valuable than simply reporting the arm's mass and yet a whole lot more confusing because no one would know what you meant.
Your arm, for example, is accelerated via muscle contraction.  After that acceleration has completed, (i.e., after you know the final acceleration of the arm) you could then apply the equation for force (F = mA) to derive an energy value.  The same is true for legs, head butts, etc.
Which is what people do using tools like accelerometers to measure force-of-impact.  (See our sister site, Martial Arts.SE, where a question about measuring force-of-impact was posted and the answers include ways to do it from cell phones to professional equipment.)
But even this is used only as a basic measure.  Arms and legs are usually still accelerating when they impact the opponent.  This means you can't measure the delivered energy without tracking the acceleration of the arm moment-by-moment.  Each impact would be (and will be) different based on the circumstances of the blow.
In the end, F=mA is the basis used today to do specifically what you're talking about, but the data is aquired in far more practical ways: like hitting the bag attached to a tool designed specifically to measure the impact force.
And remember that it's force, not energy, that you really want to measure.
Comment: Minor point:E= mc^2 is not the kinetic energy of an object with mass m moving at the speed of light. For objects with mass moving at near the speed of light, you need to use the relativistic kinetic energy equation, which approaches infinity at near-lightspeed velocities for objects with mass.
Comment: @notovny, that's a good point and a good catch.  I'll update the answer.  Thanks!